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
fix: review findings across the daemon, tools and docs (#37)
Qinghe Licf04a8ef24e1
diff --git a/.env.example b/.env.exampleindex 7875f2e..628ab34 100644--- a/.env.example+++ b/.env.example@@ -15,6 +15,8 @@ IPHONE_CONTROL_LANG=# 开发者工具:设为 1 时 MCP 服务多出日志、崩溃报告、安装和卸载 App、网页检查(Web Inspector)六个工具(默认关闭,免得 agent 多读工具说明)# Developer tools: 1 adds six MCP tools for logs, crash reports, installing and removing apps, and web pages (Web Inspector) (off by default).+# 从源码运行和在 macOS 上这个文件只有守护进程读,语言和开发者工具要写进 MCP 的配置,见文档的「配置」一页。+# For a source install and on macOS only the daemon reads this file; set the language and developer tools in the MCP configuration too (see the Configuration page).IPHONE_CONTROL_DEV_TOOLS=# 固定控制哪台设备,设了就不能切换。留空为自动选:正在控制的那台一直用到它断开;diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f1ba1b0..73a9b0a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,16 +8,18 @@ All notable changes to this project are documented here. The format is based on### Added-- 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.-- Developer tools, opt-in with `IPHONE_CONTROL_DEV_TOOLS=1`: `iphone_app_logs` (the phone's unified log, filtered by app or process, text and time), `iphone_crash_reports`, `iphone_install_app` and `iphone_uninstall_app` (both marked destructive; uninstalling the WebDriverAgent runner is refused). Without the switch the tool list is unchanged.-- Web Inspector, part of the developer tools: `iphone_web_targets` lists inspectable web pages and WebViews (Safari tabs, debug builds of hybrid apps), and `iphone_web_eval` runs JavaScript in one and returns the result as JSON. A new crate, `ictl-webinspector`, implements the client for the phone's Web Inspector service.+- English: `IPHONE_CONTROL_LANG=en` switches tool descriptions and results, CLI output and help, `status`/`doctor`, logs and notifications to English. The default stays Simplified Chinese, and older clients still get Chinese.+- `iphone-control viewer [--port]`: watch and control the phone live in a browser (opt-in, 127.0.0.1:8200 by default). Other local users can reach the port, so stop it when done.+- Developer tools, opt-in with `IPHONE_CONTROL_DEV_TOOLS=1`: `iphone_app_logs`, `iphone_crash_reports`, `iphone_install_app`, `iphone_uninstall_app`, `iphone_web_targets` and `iphone_web_eval`. Without the switch the tool list is unchanged.### Fixed-- Scroll bars are dropped from element lists in every system language, not only Chinese and English: they are recognised by their percentage value and thin shape instead of their label. On a German iPhone, for example, lines like `Other "Vertikaler Rollbalken, 1 Seite"` no longer appear.+- Scroll bars are dropped from element lists in every system language, not only Chinese and English.+- `iphone_uninstall_app` only accepts a bundle ID or the full display name; empty, partial or ambiguous names are refused and the candidates are listed.+- App installs and re-signing wait for each other instead of uploading to the phone at the same time.+- A daemon that gets stuck exits by itself, so systemd or Docker can restart it.+- Memory no longer grows while the HID fallback is in use.+- `usbmuxd.log` is rotated when it gets too large.## [0.1.4] - 2026-11-07diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex 26d3b8e..d1bc406 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -8,16 +8,18 @@### 新增-- 英文界面:设 `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`;本机其他用户能连上这个端口,用完就停。-- 开发者工具,设 `IPHONE_CONTROL_DEV_TOOLS=1` 开启:`iphone_app_logs`(手机的系统日志,可按 App 或进程、文字、时间筛选)、`iphone_crash_reports`、`iphone_install_app` 和 `iphone_uninstall_app`(后两个标为破坏性操作;拒绝卸载 WebDriverAgent)。不设就和原来一样,工具列表不变。-- Web Inspector,属于开发者工具:`iphone_web_targets` 列出可检查的网页和 WebView(Safari 标签页、混合 App 的调试构建),`iphone_web_eval` 在其中执行 JavaScript 并以 JSON 返回结果。新的 `ictl-webinspector` crate 实现了手机 Web Inspector 服务的客户端。+- 英文界面:设 `IPHONE_CONTROL_LANG=en` 后,工具说明和结果、命令行输出和帮助、`status`/`doctor`、日志、通知都改成英文。默认仍是简体中文,旧版本客户端照旧得到中文。+- `iphone-control viewer [--port]`:在浏览器里看实时画面并操作手机(默认 127.0.0.1:8200,显式开启)。本机其他用户能连上这个端口,用完就停。+- 开发者工具,设 `IPHONE_CONTROL_DEV_TOOLS=1` 开启:`iphone_app_logs`、`iphone_crash_reports`、`iphone_install_app`、`iphone_uninstall_app`、`iphone_web_targets`、`iphone_web_eval`。不设时工具列表不变。### 修复-- 任何系统语言下元素列表都会去掉滚动条,不再只认中文和英文:改按百分比的值和细长的形状认,不看标签。例如德语 iPhone 上不再出现 `Other "Vertikaler Rollbalken, 1 Seite"` 这样的行。+- 任何系统语言下元素列表都会去掉滚动条,不再只认中文和英文。+- `iphone_uninstall_app` 只接受 Bundle ID 或完整的显示名;空的、不完整的、对应多个 App 的名字都拒绝,并列出候选。+- 安装 App 和重签互相排队,不再同时往手机上传。+- 守护进程卡死时会自己退出,由 systemd 或 Docker 重启。+- HID 后备期间内存不再增长。+- `usbmuxd.log` 过大时会轮转。## [0.1.4] - 2026-11-07diff --git a/README.md b/README.mdindex 0c04e11..3fcb6bc 100644--- a/README.md+++ b/README.md@@ -110,6 +110,8 @@ More: [step-by-step guide](https://derrors.github.io/iphone-control/en/guide/get| `iphone_list_devices` | Every iPhone/iPad on USB; marks the one being controlled || `iphone_select_device` | Switch to another device, or back to automatic choice |+`IPHONE_CONTROL_DEV_TOOLS=1` adds six opt-in [developer tools](docs/tools.md#developer-tools-opt-in): logs, crash reports, installing and removing apps, and two for Web Inspector (list web pages, run JavaScript in them). They are off by default; read the [security notes](SECURITY.md#developer-tools) before turning them on.+Action tools accept `then: "elements" | "screenshot"` to return the screen after the action. Screenshot pixels are tap coordinates, so the agent can tap what it sees. Games, maps and video players draw their own UI and have no element tree — use screenshots and coordinates there. Full parameters: [docs/tools.md](docs/tools.md).Tool texts, results, CLI output and logs are in Simplified Chinese by default; set `IPHONE_CONTROL_LANG=en` for English ([configuration](https://derrors.github.io/iphone-control/en/guide/configuration)).diff --git a/README.zh-CN.md b/README.zh-CN.mdindex c798534..92ed03a 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -110,6 +110,8 @@ iphone-control mcp-config # 打印 `claude mcp add` 命令,复制运行| `iphone_list_devices` | 列出 USB 上接着的 iPhone/iPad,标出正在控制哪台 || `iphone_select_device` | 改为控制另一台,或改回自动选 |+设 `IPHONE_CONTROL_DEV_TOOLS=1` 增加 6 个[开发者工具](docs/tools.md#developer-tools-opt-in)(英文):日志、崩溃报告、安装和卸载 App,以及 Web Inspector 的两个工具(列出网页、在网页里执行 JavaScript)。默认关闭,开启前先看[安全说明](SECURITY.md#developer-tools)(英文)。+操作类工具可以带 `then: "elements" | "screenshot"`,顺带返回操作后的界面。截图的像素就是点击坐标,agent 看到哪里就能点哪里。游戏、地图、视频自己绘制界面,没有元素树,只能看截图按坐标操作。完整参数见 [docs/tools.md](docs/tools.md)(英文)。工具说明和结果、命令行输出、日志默认是简体中文;设 `IPHONE_CONTROL_LANG=en` 改成英文(见[配置](https://derrors.github.io/iphone-control/guide/configuration))。diff --git a/SECURITY.md b/SECURITY.mdindex a5a5c55..e11b117 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -14,6 +14,7 @@ iphone-control is, by design, a remote control for a phone. Anyone who can talk|---|---|---|| Phone control (taps, typing, screenshots, apps) | Control socket: `/run/iphone-control/ctl.sock` inside the container, `$XDG_RUNTIME_DIR/iphone-control/ctl.sock` for a source install on Linux, `~/.local/share/iphone-control/ctl.sock` on macOS; mode 0600 | Root on the host; anyone who can `docker exec` into the container; the user running a source install or the macOS binary || WebDriverAgent (no authentication) | On the phone, reached through usbmuxd; nothing listens on the network unless you run `wda-bridge` | With `wda-bridge`: **every local user** on the host, because the container uses host networking. Browsers are blocked by a Host-header check (DNS rebinding), other local processes are not |+| Live viewer (`iphone-control viewer`, opt-in) | A page on `127.0.0.1` (port 8200 by default); nothing listens unless you run it. Bound to the device controlled when it starts | **Every local user** on the host can watch the screen and control the phone through the port: it has no login. Other web pages in a browser are blocked by the `Host`, `Origin` and JSON checks, other local processes are not || Apple ID session tokens, development signing key and certificate | `account/` in the data directory (0700, key 0600) | Whoever can read the data directory. The Apple ID password itself is never stored || Pairing records | `lockdown/` in the data directory (container), the system's `/var/lib/lockdown` (source install on Linux) or `/var/db/lockdown` (macOS, shared with Finder) | Root on the host. A pairing record lets its holder talk to the phone over USB without another *Trust* prompt || Lock-screen passcodes | `secrets/passcodes/<UDID>` in the data directory (0600), one file per device, **plain text**, only if you ran `passcode set`. A `secrets/passcode` file from an older version is moved to the device's file when exactly one device is connected, and stays where it is until then | Whoever can read the data directory |@@ -23,7 +24,7 @@ The data directory is `./data` next to `compose.yaml` for the container (root-ow## Design choices that limit exposure-- No network listener by default. WebDriverAgent is reached through usbmuxd; `wda-bridge` only binds 127.0.0.1, only forwards requests whose Host header is a loopback name, and is meant to be stopped after use.+- No network listener by default. WebDriverAgent is reached through usbmuxd. `wda-bridge` and `viewer` are opt-in and bind 127.0.0.1 only, and both are meant to be stopped after use. `wda-bridge` only forwards requests whose Host header is a loopback name. `viewer` checks the Host header the same way; its actions also need an `Origin` of the viewer page itself and a JSON body, so other web pages can't act through it, and each action carries the UDID of the device the viewer was started for, so the daemon refuses it once another device is controlled.- The control socket is a Unix socket with mode 0600, not TCP.- The container is not `privileged`: it is only allowed USB character devices (major 189), and the tunnel to the phone uses a user-space TCP stack, so no network interface or routing changes on the host.- Auto-unlock is off by default. When enabled, it stops for good after a single wrong attempt (it writes a stop marker, `logs/UNLOCK-DISABLED`, before entering the second digit) and sends a notification; it never retries a passcode that might be wrong. The marker is global: a failure on one device stops auto-unlock on all of them until you run `unlock-reset`. It does not work before the first unlock after a reboot (BFU) — that always needs a person.@@ -38,6 +39,16 @@ The data directory is `./data` next to `compose.yaml` for the container (root-ow- **Agents act with your hands.** An agent with these tools can send messages, make purchases and change settings. The MCP server tells agents to ask before paying, deleting, sending messages or changing account or privacy settings, but that is an instruction, not an enforcement mechanism. Use a phone and accounts you are comfortable automating.- **Back up the data directory securely**, and never commit it. `.gitignore` and `.dockerignore` exclude `data/`, `.env` and key material, so they don't end up in git or in image layers.+## Developer tools++`IPHONE_CONTROL_DEV_TOOLS=1` adds six MCP tools that reach well beyond the screen. They are off by default; turn them on for the work that needs them and off again afterwards.++- **`iphone_web_eval` runs arbitrary JavaScript** in any inspectable page, including Safari tabs. A script can read cookies that aren't HttpOnly and `localStorage`, and submit forms or send requests as the logged-in user.+- **`iphone_install_app` accepts any path on the machine that runs the daemon.** In the container the daemon is root.+- **`iphone_app_logs` reads the system log of every process**, and `iphone_crash_reports` returns full crash reports. Both end up in the agent's context and can contain private data.+- **`iphone_uninstall_app` deletes an app and its data.** It refuses the WebDriverAgent runner and only accepts a bundle ID or the app's exact display name.+- **The switch is not a permission boundary.** `IPHONE_CONTROL_DEV_TOOLS` only decides whether the MCP server offers these tools. The daemon always accepts the requests, so anyone who can reach the control socket (mode 0600, so the same user or root) can use them with the switch off.+## Developer Disk Image and WebDriverAgent sources- The Developer Disk Image is downloaded at runtime from a community-maintained mirror (the same source pymobiledevice3 uses) unless you set `ICTL_DDI_URL` or `ICTL_DDI_DIR`. The phone verifies Apple's signature through personalization (TSS), so a tampered image will not mount.diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex b0538e2..b8c75f4 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -839,13 +839,17 @@ async fn wda_bridge(socket: &Path, port: u16) -> anyhow::Result<()> {"Note: every user on this machine can control the phone through this port (WDA has no authentication); stop it when you're done."));+ let slots = std::sync::Arc::new(tokio::sync::Semaphore::new(MAX_CONNECTIONS));loop {let (client, _) = listener.accept().await?;+ // 连接太多就不接新的(见 MAX_CONNECTIONS)+ let Ok(slot) = slots.clone().try_acquire_owned() else { continue };let device = device.clone();tokio::spawn(async move {if let Err(e) = bridge_conn(client, &device).await {tracing::warn!("{}", ictl_l10n::log_trf!("桥接连接出错:{e}", "Bridge connection error: {e}"));}+ drop(slot);});}}@@ -853,29 +857,46 @@ async fn wda_bridge(socket: &Path, port: u16) -> anyhow::Result<()> {/// 先读到第一个请求的头部,Host 必须是本机回环地址才转发:恶意网页借 DNS rebinding 发到 127.0.0.1 的请求,/// Host 头是它自己的域名async fn bridge_conn(mut client: tokio::net::TcpStream, device: &ictl_device::Device) -> anyhow::Result<()> {- use tokio::io::{AsyncReadExt, AsyncWriteExt};- let mut head = Vec::new();- let mut buf = [0u8; 4096];- while !head.windows(4).any(|w| w == b"\r\n\r\n") {- if head.len() > 64 * 1024 {- bail!("{}", ictl_l10n::tr!("请求头太长", "request headers too long"));- }- let n = client.read(&mut buf).await?;- if n == 0 {- return Ok(());- }- head.extend_from_slice(&buf[..n]);- }+ use tokio::io::AsyncWriteExt;+ let (head, body) = read_head(&mut client).await?;if !host_is_loopback(&head) {client.write_all(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await?;return Ok(());}let mut remote = device.connect_port(8100).await?;remote.write_all(&head).await?;+ remote.write_all(&body).await?;tokio::io::copy_bidirectional(&mut client, &mut remote).await?;Ok(())}+/// 本机端口(`wda-bridge`、`viewer`)同时接的连接数上限,满了新连接直接断开(比如开了太多标签页)+const MAX_CONNECTIONS: usize = 32;+const MAX_HEAD: usize = 16 * 1024;+/// 客户端发请求头、请求体时单次读的等待上限:连上不发的连接不能一直占着名额+const READ_TIMEOUT: Duration = Duration::from_secs(10);++/// 读到请求头结束;返回头部和跟着一起到的那部分请求体+async fn read_head(client: &mut tokio::net::TcpStream) -> anyhow::Result<(Vec<u8>, Vec<u8>)> {+ use tokio::io::AsyncReadExt;+ 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!("{}", ictl_l10n::tr!("请求头太长", "request headers too long"));+ }+ let n = tokio::time::timeout(READ_TIMEOUT, client.read(&mut buf)).await??;+ if n == 0 {+ bail!("{}", ictl_l10n::tr!("连接已关闭", "connection closed"));+ }+ data.extend_from_slice(&buf[..n]);+ }+}+/// HTTP 请求头里的 Host 是不是 localhost / 127.0.0.1 / [::1](端口不限)fn host_is_loopback(head: &[u8]) -> bool {let text = String::from_utf8_lossy(head);diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rsindex 159d462..0e1ada6 100644--- a/apps/iphone-control/src/viewer.rs+++ b/apps/iphone-control/src/viewer.rs@@ -28,12 +28,7 @@ use tokio::net::TcpStream;const PAGE: &str = include_str!("viewer.html");/// WDA's MJPEG server on the phoneconst 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;@@ -54,7 +49,7 @@ pub async fn run(socket: &Path, port: u16) -> anyhow::Result<()> {"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));+ let slots = std::sync::Arc::new(tokio::sync::Semaphore::new(crate::MAX_CONNECTIONS));loop {let (client, _) = listener.accept().await?;// too many open connections (for example many tabs): drop the new one@@ -71,7 +66,7 @@ pub async fn run(socket: &Path, port: u16) -> anyhow::Result<()> {/// One request per connection (`Connection: close`), which keeps the parser smallasync fn serve(mut client: TcpStream, udid: &str, socket: &Path, port: u16) -> anyhow::Result<()> {- let (head, mut body) = read_head(&mut client).await?;+ let (head, mut body) = crate::read_head(&mut client).await?;let Some(req) = Head::parse(&head) else {return reply(&mut client, 400, "text/plain", b"bad request").await;};@@ -106,7 +101,7 @@ async fn serve(mut client: TcpStream, udid: &str, socket: &Path, port: u16) -> a}while body.len() < len {let mut buf = [0u8; 4096];- let n = tokio::time::timeout(READ_TIMEOUT, client.read(&mut buf)).await??;+ let n = tokio::time::timeout(crate::READ_TIMEOUT, client.read(&mut buf)).await??;if n == 0 {bail!("body cut off");}@@ -123,26 +118,6 @@ async fn serve(mut client: TcpStream, udid: &str, socket: &Path, port: u16) -> a}}-/// 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",diff --git a/compose.yaml b/compose.yamlindex 5645ece..71bacca 100644--- a/compose.yaml+++ b/compose.yaml@@ -20,6 +20,19 @@ services:# WDA 经 usbmuxd 直连手机,本机不监听任何端口;host 网络只为了用宿主机上的代理network_mode: hostrestart: unless-stopped+ # status 连不上控制接口就算不健康;卡死时守护进程自己退出,由上面的 restart 拉起+ healthcheck:+ test: ["CMD", "iphone-control", "status"]+ interval: 60s+ timeout: 15s+ retries: 3+ start_period: 30s+ # stdout/stderr 的上限;logs 目录里的日志由守护进程自己轮转+ logging:+ driver: json-file+ options:+ max-size: 10m+ max-file: "3"env_file:- path: .envrequired: falsediff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex 4a87280..269e266 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -26,6 +26,7 @@ use crate::machine::{Backoff, DeviceState, Misses, MuxWatch};use crate::notify::{self, Dedup, Event};use crate::protocol::{Request, Response};use crate::supervise::StartOutcome;+use crate::watchdog::Heartbeat;pub const TICK: Duration = Duration::from_secs(10);/// 改变手机状态的请求排队超过这么久就放弃@@ -106,8 +107,14 @@ impl Persisted {}pub(crate) fn save(&self, path: &Path) {+ use std::io::Write;let tmp = path.with_extension("json.tmp");- let r = std::fs::write(&tmp, serde_json::to_vec_pretty(self).unwrap_or_default())+ // sync before the rename, or a power cut can leave state.json empty+ let r = std::fs::File::create(&tmp)+ .and_then(|mut f| {+ f.write_all(&serde_json::to_vec_pretty(self).unwrap_or_default())?;+ f.sync_all()+ }).and_then(|_| std::fs::rename(&tmp, path));if let Err(e) = r {tracing::warn!("{}", ictl_l10n::log_trf!("保存 state.json 失败:{e}", "Saving state.json failed: {e}"));@@ -201,10 +208,26 @@ pub struct Snapshot {pub log_tail: Vec<String>,}+/// What is known about the device being controlled. Replaced as a whole when that device goes away or changes+/// ([`Daemon::forget_device`]), so a new field can't be left holding the previous device's value+#[derive(Default)]+pub(crate) struct PerDevice {+ /// 这台手机上的 WDA 描述文件+ pub device_profile: DeviceProfile,+ /// WDA 最近一次报的界面旋转及读取时间。只在短暂掉线时给 HID 使用,不持久化+ pub wda_rotation: Option<(Instant, Rotation)>,+ /// 开发者镜像连续挂载失败次数,到 3 次清缓存重新下载+ pub ddi_failures: u32,+ /// 最近一次经本进程锁屏的时间(自动解锁要等锁屏过渡走完,见 [`crate::tools::LOCK_SETTLE`])+ pub last_lock: Option<Instant>,+ pub apps: HashMap<bool, Vec<AppInfo>>,+ /// Log capture for `AppLogs` (developer tools), started by the first request+ pub log_capture: Option<crate::devtools::Capture>,+}+pub(crate) struct Inner {pub persisted: Persisted,- /// 当前这台手机上的 WDA 描述文件;换连接、离线时清成 NotChecked- pub device_profile: DeviceProfile,+ pub dev: PerDevice,pub state: DeviceState,pub device: Option<Device>,pub info: Option<DeviceInfo>,@@ -214,14 +237,10 @@ pub(crate) struct Inner {pub infos: HashMap<String, DeviceInfo>,/// HID 和截图用的隧道(HID 会话归它所有)pub tunnel: Option<Tunnel>,- /// WDA 最近一次报的界面旋转及读取时间。只在短暂掉线时给 HID 使用,不持久化;换设备时清掉- pub wda_rotation: Option<(Instant, Rotation)>,pub runner: Option<WdaRunner>,pub wda: Option<WdaClient<DeviceTransport>>,/// 后台启动 WDA 的任务(含挂开发者镜像),巡检里收结果pub starting: Option<JoinHandle<StartOutcome>>,- /// 开发者镜像连续挂载失败次数,到 3 次清缓存重新下载- pub ddi_failures: u32,pub resigning: bool,pub wda_misses: Misses,pub backoff: Backoff,@@ -234,18 +253,15 @@ pub(crate) struct Inner {/// 连续列不出设备的次数(usbmuxd 抖一下不立刻当成离线)pub list_errors: u32,pub offline_since: Option<Instant>,- /// 最近一次经本进程锁屏的时间(自动解锁要等锁屏过渡走完,见 [`crate::tools::LOCK_SETTLE`])- pub last_lock: Option<Instant>,/// HID 会话最近一次使用的时间;空闲超过 [`crate::supervise::HID_IDLE`] 就关掉(它持有屏幕媒体流)pub hid_used: Option<Instant>,/// 最近一次读到的元素树。只在调用方允许(max_age_ms)时复用;改变界面的操作做完就清掉pub elements_cache: Option<(Instant, ictl_wda::elements::Tree)>,+ /// 滑动等列表停下时最后读到的树([`crate::tools`] 的 `settle` 拿来当比较的起点)+ pub swiped_tree: Option<(Instant, ictl_wda::elements::Tree)>,pub dedup: Dedup,pub next_resign: Instant,pub next_session_check: Instant,- pub apps: HashMap<bool, Vec<AppInfo>>,- /// Log capture for `AppLogs` (developer tools), started by the first request- pub log_capture: Option<crate::devtools::Capture>,}pub struct Daemon {@@ -256,6 +272,7 @@ pub struct Daemon {/// The kept Web Inspector connection (developer tools), separate from `inner` so a slow page doesn't hold up/// taps and screenshots; see [`crate::web`]pub(crate) web: Mutex<Option<crate::web::WebConn>>,+ pub(crate) heartbeat: crate::watchdog::Heartbeat,}/// 停掉 HID 会话(屏幕媒体流),隧道保留。媒体流不停的话手机一直以为「配对的电脑」在看屏幕:@@ -324,18 +341,16 @@ impl Daemon {let now = Instant::now();let inner = Inner {persisted,- device_profile: DeviceProfile::NotChecked,+ dev: PerDevice::default(),state: DeviceState::Absent,device: None,info: None,connected: Vec::new(),infos: HashMap::new(),tunnel: None,- wda_rotation: None,runner: None,wda: None,starting: None,- ddi_failures: 0,resigning: false,wda_misses: Misses::default(),backoff: Backoff::default(),@@ -346,15 +361,13 @@ impl Daemon {usbmuxd_delay: Duration::ZERO,list_errors: 0,offline_since: Some(now),- last_lock: None,hid_used: None,elements_cache: None,+ swiped_tree: None,dedup: Dedup::default(),// 启动一分钟后再做第一次重签检查和会话验证,先让设备就绪next_resign: now + Duration::from_secs(60),next_session_check: now + Duration::from_secs(90),- apps: HashMap::new(),- log_capture: None,};let first = Snapshot {state: DeviceState::Absent,@@ -370,7 +383,7 @@ impl Daemon {log_tail: Vec::new(),};let (snap, _) = watch::channel(first);- Arc::new(Self { cfg, log, inner: Mutex::new(inner), snap, web: Mutex::new(None) })+ Arc::new(Self { cfg, log, inner: Mutex::new(inner), snap, web: Mutex::new(None), heartbeat: Heartbeat::new() })}/// 自动解锁配置:用设备 `udid` 自己的密码。没接设备时密码文件不存在(自动解锁不可用)@@ -444,14 +457,14 @@ impl Daemon {/// 重读这台手机上的 WDA 描述文件(misagent,一次约几十毫秒)pub(crate) async fn refresh_device_profile(&self, g: &mut Inner) {let Some(d) = g.device.clone() else {- g.device_profile = DeviceProfile::NotChecked;+ g.dev.device_profile = DeviceProfile::NotChecked;return;};let Some(bundle) = g.persisted.wda_bundle.clone() else {- g.device_profile = DeviceProfile::Missing;+ g.dev.device_profile = DeviceProfile::Missing;return;};- g.device_profile = match d.installed_profiles().await {+ g.dev.device_profile = match d.installed_profiles().await {Ok(ps) => match wda_profile_expiry(&ps, g.persisted.team_id.as_deref(), &bundle, &d.udid) {Some(t) => DeviceProfile::Expires(t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()),None => DeviceProfile::Missing,@@ -479,6 +492,7 @@ impl Daemon {}g.wda = None;g.elements_cache = None;+ g.swiped_tree = None;drop_tunnel(g).await;g.wda_misses.reset();}@@ -494,6 +508,12 @@ impl Daemon {Ok(g.tunnel.as_mut().expect("刚建好"))}+ /// 不再控制当前这台(断开、重新接入、换设备):停掉它的会话,清掉关于它的一切+ pub(crate) async fn forget_device(&self, g: &mut Inner) {+ self.drop_session(g).await;+ g.dev = PerDevice::default();+ }+/// WDA 可用就返回客户端(本进程 runner 存活)pub(crate) fn wda<'a>(&self, g: &'a mut Inner) -> Option<&'a mut WdaClient<DeviceTransport>> {if g.runner.as_ref().is_some_and(|r| r.alive()) { g.wda.as_mut() } else { None }@@ -510,6 +530,7 @@ impl Daemon {/// 发布快照给不拿锁的读者(`status`)。日志尾巴在读的时候再取pub(crate) fn publish(&self, g: &Inner) {+ self.heartbeat.beat();let unlock = self.unlock_cfg(g.device.as_ref().map(|d| d.udid.as_str()));let pinned = self.pinned(g);self.snap.send_replace(Snapshot {@@ -519,7 +540,7 @@ impl Daemon {pinned,pinned_by_env: self.cfg.udid.is_some(),persisted: g.persisted.clone(),- device_profile: g.device_profile.clone(),+ device_profile: g.dev.device_profile.clone(),auto_unlock: unlock.enabled(),unlock_disabled: unlock.disabled_by_failure(),notify_configured: self.cfg.notify.any(),@@ -530,75 +551,79 @@ impl Daemon {// ------------------------------------------------------------------ 请求处理/// 处理一个控制请求。`queued_at`:请求到达的时间,用来放弃排队太久的操作- pub async fn handle(self: &Arc<Self>, req: Request, queued_at: Instant, ctx: CallCtx) -> Response {+ pub async fn handle(self: &Arc<Self>, req: Request, queued_at: Instant, mut ctx: CallCtx) -> Response {// 不需要设备锁的请求- match req {- Request::Daemon => {- let mut s = self.snap.borrow().clone();- let unlock = self.unlock_cfg(s.device.as_ref().map(|d| d.udid.as_str()));- s.unlock_disabled = unlock.disabled_by_failure();- s.auto_unlock = unlock.enabled();- s.log_tail = self.log.tail(15);- return Response::text(serde_json::to_string_pretty(&s).unwrap_or_default());- }+ if matches!(req, Request::Daemon) {+ let mut s = self.snap.borrow().clone();+ let unlock = self.unlock_cfg(s.device.as_ref().map(|d| d.udid.as_str()));+ s.unlock_disabled = unlock.disabled_by_failure();+ s.auto_unlock = unlock.enabled();+ s.log_tail = self.log.tail(15);+ return Response::text(serde_json::to_string_pretty(&s).unwrap_or_default());+ }+ if let Err(e) = check_request(&req) {+ return Response::error(e);+ }+ let text = |r: Result<String, String>| {+ r.map(|t| Response::text_with(t, crate::protocol::Outcome::default())).unwrap_or_else(Response::error)+ };+ match lane(&req) {+ Lane::Snapshot => unreachable!("handled above"),// 重签自己分段持锁:签名、安装要几十秒,期间不挡住别的请求- Request::Resign { force } => {+ Lane::Resign => {+ let Request::Resign { force } = req else { unreachable!("lane") };return self.resign_now(force).await.map(Response::text).unwrap_or_else(Response::error);}- // Web Inspector requests talk to the page, not to WDA; they only take the lock to find the device- Request::WebTargets => return self.web_targets().await.map(Response::text).unwrap_or_else(Response::error),- Request::WebEval { target, expression, timeout_ms } => {- if expression.trim().is_empty() || timeout_ms > MAX_WEB_EVAL_MS {- return Response::error(ictl_l10n::trf!(- "expression 不能为空,timeout 最多 {} 秒",- "expression can't be empty, and timeout can be at most {} seconds",- MAX_WEB_EVAL_MS / 1000- ));+ // Web Inspector talks to the page, not to WDA: its own lock, the device lock only to look up the device+ Lane::Web => {+ let mut slot = match acquire(&self.web, &mut ctx.gone).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ let device = self.inner.lock().await.device.clone();+ if let Err(r) = admit(&req, queued_at, &ctx, device.as_ref().map(|d| d.udid.as_str())) {+ return r;}- return self- .web_eval(&target, &expression, Duration::from_millis(timeout_ms))- .await- .map(Response::text)- .unwrap_or_else(Response::error);+ let Some(device) = device else {+ return Response::error(ictl_l10n::tr!("手机未连接", "Phone not connected"));+ };+ return text(match req {+ Request::WebTargets => self.web_targets(&mut slot, &device).await,+ Request::WebEval { target, expression, timeout_ms } => {+ self.web_eval(&mut slot, &device, &target, &expression, Duration::from_millis(timeout_ms)).await+ }+ _ => unreachable!("lane"),+ });}- // an install can take minutes; it doesn't hold the lock meanwhile- Request::InstallApp { path } => {- return self.install_app(&path).await.map(Response::text).unwrap_or_else(Response::error);+ // an install can take minutes and doesn't hold the device lock; installs queue among themselves+ Lane::Install => {+ if ctx.gone.as_mut().is_some_and(|g| g.try_recv().is_ok()) {+ return cancelled();+ }+ let device = self.inner.lock().await.device.clone();+ if let Err(r) = admit(&req, queued_at, &ctx, device.as_ref().map(|d| d.udid.as_str())) {+ return r;+ }+ let Some(device) = device else {+ return Response::error(ictl_l10n::tr!("手机未连接", "Phone not connected"));+ };+ let Request::InstallApp { path } = req else { unreachable!("lane") };+ let r = self.install_app(&device, &path).await;+ if r.is_ok() {+ self.inner.lock().await.dev.apps.clear();+ }+ return text(r);}- _ => {}- }- if let Err(e) = check_request(&req) {- return Response::error(e);+ Lane::Device => {}}- let mut g = match ctx.gone {- Some(mut gone) => tokio::select! {- biased;- g = self.inner.lock() => g,- Ok(()) = &mut gone => return Response::error(ictl_l10n::tr!("调用方已取消,请求没有执行", "The caller cancelled; the request was not carried out")),- },- None => self.inner.lock().await,+ let mut g = match acquire(&self.inner, &mut ctx.gone).await {+ Ok(g) => g,+ Err(r) => return r,};let g = &mut *g;- if let Some(want) = &ctx.expect_udid {- let now = g.device.as_ref().map(|d| d.udid.as_str());- if now != Some(want.as_str()) {- return Response::error(ictl_l10n::trf!(- "正在控制的设备变了(原来是 {want},现在{}),没有执行;先用 iphone_list_devices 确认",- "The controlled device changed (it was {want}, now {}); not carried out. Check with iphone_list_devices first",- now.map_or(ictl_l10n::tr!("没有设备", "there is no device").into(), |u| ictl_l10n::trf!(- "是 {u}",- "it is {u}"- ))- ));- }- }- if req.is_device_action() && queued_at.elapsed() > STALE {- return Response::error(ictl_l10n::trf!(- "守护进程正忙,这个操作排队超过 {} 秒,已放弃执行(以免落到已经变化的屏幕上);先截图看看再重试",- "The daemon is busy and this action waited in the queue for more than {} seconds, so it was dropped (it could have landed on a changed screen); take a screenshot and try again",- STALE.as_secs()- ));+ if let Err(r) = admit(&req, queued_at, &ctx, g.device.as_ref().map(|d| d.udid.as_str())) {+ return r;}// 改变界面的操作做完后缓存的元素树就作废;只有调用方声明「不改变布局」的按名字点击(max_age_ms > 0)保留let keeps_cache = matches!(req, Request::TapElement { max_age_ms, .. } if max_age_ms > 0);@@ -659,7 +684,7 @@ impl Daemon {| Request::Resign { .. }| Request::InstallApp { .. }| Request::WebTargets- | Request::WebEval { .. } => unreachable!("上面已处理"),+ | Request::WebEval { .. } => unreachable!("other lanes"),};if invalidates {g.elements_cache = None;@@ -674,14 +699,125 @@ impl Daemon {// 先停 HID 媒体流、runner(经 usbmuxd),再停 usbmuxdself.drop_session(&mut g).await;if let Some(mut c) = g.usbmuxd.take() {- let _ = c.kill().await;+ stop_child(&mut c).await;}}}+/// Kills a child and waits for it, but not forever: a process stuck in the kernel (a USB call that never returns)+/// doesn't exit on SIGKILL, and whoever is stopping it holds the device lock+pub(crate) async fn stop_child(child: &mut tokio::process::Child) {+ let _ = child.start_kill();+ let _ = tokio::time::timeout(Duration::from_secs(5), child.wait()).await;+}+/// 参数检查(与设备无关,不必拿锁)+/// Which path a request takes through [`Daemon::handle`]. Every variant is listed (no `_`), so a new request type+/// doesn't compile until it is given a lane; a lane decides the lock, and every lane but the snapshot and re-signing+/// goes through [`admit`] (cancelled callers, stale actions, the expected device)+enum Lane {+ /// `status`'s snapshot: no lock+ Snapshot,+ /// re-signing takes the device lock in short steps+ Resign,+ /// the Web Inspector connection's own lock+ Web,+ /// no device lock; installs queue among themselves+ Install,+ /// the device lock+ Device,+}++fn lane(req: &Request) -> Lane {+ match req {+ Request::Daemon => Lane::Snapshot,+ Request::Resign { .. } => Lane::Resign,+ Request::WebTargets | Request::WebEval { .. } => Lane::Web,+ Request::InstallApp { .. } => Lane::Install,+ Request::Status+ | Request::Screenshot { .. }+ | Request::ListElements { .. }+ | Request::Tap { .. }+ | Request::TapElement { .. }+ | Request::LongPress { .. }+ | Request::Swipe { .. }+ | Request::TypeText { .. }+ | Request::PressButton { .. }+ | Request::ListApps { .. }+ | Request::LaunchApp { .. }+ | Request::TerminateApp { .. }+ | Request::OpenUrl { .. }+ | Request::Settle { .. }+ | Request::AlertCheck+ | Request::WaitFor { .. }+ | Request::Doctor+ | Request::UnlockReset+ | Request::ListDevices+ | Request::SelectDevice { .. }+ | Request::AppLogs { .. }+ | Request::CrashReports { .. }+ | Request::UninstallApp { .. } => Lane::Device,+ }+}++fn cancelled() -> Response {+ Response::error(ictl_l10n::tr!(+ "调用方已取消,请求没有执行",+ "The caller cancelled; the request was not carried out"+ ))+}++/// Takes `lock`, unless the caller goes away first (see [`CallCtx::gone`])+async fn acquire<'a, T>(+ lock: &'a Mutex<T>,+ gone: &mut Option<tokio::sync::oneshot::Receiver<()>>,+) -> Result<tokio::sync::MutexGuard<'a, T>, Response> {+ match gone {+ Some(gone) => tokio::select! {+ biased;+ g = lock.lock() => Ok(g),+ Ok(()) = &mut *gone => Err(cancelled()),+ },+ None => Ok(lock.lock().await),+ }+}++/// Checks done once a request got its lock: the caller's expected device ([`CallCtx::expect_udid`]) and, for actions,+/// how long it queued ([`STALE`])+fn admit(req: &Request, queued_at: Instant, ctx: &CallCtx, controlled: Option<&str>) -> Result<(), Response> {+ if let Some(want) = &ctx.expect_udid+ && controlled != Some(want.as_str())+ {+ return Err(Response::error(ictl_l10n::trf!(+ "正在控制的设备变了(原来是 {want},现在{}),没有执行;先用 iphone_list_devices 确认",+ "The controlled device changed (it was {want}, now {}); not carried out. Check with iphone_list_devices first",+ controlled.map_or(ictl_l10n::tr!("没有设备", "there is no device").into(), |u| ictl_l10n::trf!(+ "是 {u}",+ "it is {u}"+ ))+ )));+ }+ if req.is_device_action() && queued_at.elapsed() > STALE {+ return Err(Response::error(ictl_l10n::trf!(+ "守护进程正忙,这个操作排队超过 {} 秒,已放弃执行(以免落到已经变化的屏幕上);先截图看看再重试",+ "The daemon is busy and this action waited in the queue for more than {} seconds, so it was dropped (it could have landed on a changed screen); take a screenshot and try again",+ STALE.as_secs()+ )));+ }+ Ok(())+}+fn check_request(req: &Request) -> Result<(), String> {match req {+ Request::WebEval { expression, timeout_ms, .. }+ if expression.trim().is_empty() || *timeout_ms > MAX_WEB_EVAL_MS =>+ {+ return Err(ictl_l10n::trf!(+ "expression 不能为空,timeout 最多 {} 秒",+ "expression can't be empty, and timeout can be at most {} seconds",+ MAX_WEB_EVAL_MS / 1000+ ));+ }Request::Settle { max_ms } if *max_ms > MAX_WAIT_MS => {return Err(ictl_l10n::trf!("max_ms 不能超过 {MAX_WAIT_MS}", "max_ms can't exceed {MAX_WAIT_MS}"));}diff --git a/crates/ictl-daemon/src/devices.rs b/crates/ictl-daemon/src/devices.rsindex a2c754f..8ca5a61 100644--- a/crates/ictl-daemon/src/devices.rs+++ b/crates/ictl-daemon/src/devices.rs@@ -146,8 +146,6 @@ impl Daemon {.find(|d| d.udid == target.udid).cloned().ok_or(ictl_l10n::tr!("设备刚刚断开了", "the device just disconnected"))?;- // 上一台的锁屏时间不能拿来等这一台- g.last_lock = None;self.online(g, &usb).await;let pin = if self.cfg.passcode_file_for(&target.udid).is_file() {""diff --git a/crates/ictl-daemon/src/devtools.rs b/crates/ictl-daemon/src/devtools.rsindex ec3b484..fd4e0cd 100644--- a/crates/ictl-daemon/src/devtools.rs+++ b/crates/ictl-daemon/src/devtools.rs@@ -5,8 +5,11 @@//! Logs come from os_trace_relay. It only streams what happens from now on, so the first `AppLogs` request//! starts a capture into a ring buffer (at most [`MAX_LINES`]); later requests read from it, which is what makes//! `since` work. The capture follows the controlled device: it stops when the daemon switches to another device or-//! the device goes offline, and by itself after [`IDLE`] without a request, so a session that used the tool once-//! doesn't keep a log stream running.+//! the device goes offline, and after [`IDLE`] without a request (checked by the health check, see+//! [`Daemon::log_housekeeping`]), so a session that used the tool once doesn't keep a log stream running.+//!+//! The reader task only ever awaits the next entry: an entry is several reads, and cancelling one half-way (as a+//! `select!` against a timer would) leaves the stream out of step.//!//! The stream leaves out debug and info messages (see `ictl_device::Device::log_stream`: asking for them slows the//! phone). It is still every process, tens of lines a second, so the buffer is bounded by size as well as by count@@ -18,7 +21,7 @@ use std::collections::VecDeque;use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};-use ictl_device::{LogEntry, LogLevel};+use ictl_device::{AppInfo, LogEntry, LogLevel};use tokio::task::JoinHandle;use crate::core::{Daemon, Inner};@@ -30,12 +33,14 @@ const IDLE: Duration = Duration::from_secs(15 * 60);/// Longest crash report text returned; the start holds the exception, the crashed thread and the app versionconst MAX_REPORT_CHARS: usize = 40_000;const MAX_LINE_CHARS: usize = 600;+/// The first line arrives a moment after recording starts; a gap larger than this means older lines were dropped+const DROPPED_MARGIN: u64 = 3;pub(crate) struct Capture {udid: String,started: Instant,buf: Arc<Mutex<Buffer>>,- last_query: Arc<Mutex<Instant>>,+ last_query: Instant,task: JoinHandle<()>,}@@ -56,36 +61,27 @@ impl Daemon {errors_only: bool,) -> Result<String, String> {let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;- let running = g.log_capture.as_ref().is_some_and(|c| c.udid == device.udid && !c.task.is_finished());+ let running = g.dev.log_capture.as_ref().is_some_and(|c| c.udid == device.udid && !c.task.is_finished());if !running {let mut stream = device.log_stream().await.map_err(|e| e.to_string())?;let buf = Arc::new(Mutex::new(Buffer::default()));- let last_query = Arc::new(Mutex::new(Instant::now()));- let (b, q) = (buf.clone(), last_query.clone());+ let b = buf.clone();let task = tokio::spawn(async move {- let mut check = tokio::time::interval(Duration::from_secs(30));- loop {- tokio::select! {- e = stream.next() => {- let Ok(e) = e else { return };- b.lock().unwrap_or_else(|p| p.into_inner()).push(Instant::now(), compact(e));- }- _ = check.tick() => {- if q.lock().unwrap_or_else(|p| p.into_inner()).elapsed() > IDLE {- return;- }- }- }+ // never cancelled mid-entry (see the module docs); stopped by aborting the task+ while let Ok(e) = stream.next().await {+ b.lock().unwrap_or_else(|p| p.into_inner()).push(Instant::now(), compact(e));}});- g.log_capture = Some(Capture { udid: device.udid.clone(), started: Instant::now(), buf, last_query, task });+ let now = Instant::now();+ g.dev.log_capture = Some(Capture { udid: device.udid.clone(), started: now, buf, last_query: now, task });+ }+ if let Some(c) = g.dev.log_capture.as_mut() {+ c.last_query = Instant::now();}- let c = g.log_capture.as_ref().expect("set above");- *c.last_query.lock().unwrap_or_else(|p| p.into_inner()) = Instant::now();// an app's name or bundle ID → the process it runs as; anything else is taken as a process namelet wanted = if process.is_empty() { None } else { Some(self.process_name(g, process).await) };- let c = g.log_capture.as_ref().expect("set above");+ let c = g.dev.log_capture.as_ref().expect("set above");let filter = LogFilter { process: wanted.as_deref(), grep, errors_only };let from = Instant::now().checked_sub(since);let (lines, oldest) = {@@ -121,7 +117,9 @@ impl Daemon {out += ictl_l10n::tr!(" 没有。", " none.");}// the buffer may reach back less far than `since`: say how far, so a missing line isn't taken as "didn't happen"- if running && let Some(o) = oldest.filter(|o| *o < since.as_secs()) {+ // (only when lines were really dropped: right after the start the first sentence already says how far it goes)+ let recording_for = c.started.elapsed().as_secs();+ if running && let Some(o) = oldest.filter(|o| *o < since.as_secs() && o + DROPPED_MARGIN < recording_for) {out += &ictl_l10n::trf!("\n(缓冲里最早一行是 {o} 秒前,更早的已经挤出去了)","\n(the oldest line in the buffer is from {o} s ago; earlier lines have been dropped)"@@ -134,6 +132,14 @@ impl Daemon {Ok(out)}+ /// Stops the log capture after [`IDLE`] without a request, or once its stream has ended. Called from the health+ /// check, which holds the daemon lock+ pub(crate) fn log_housekeeping(g: &mut Inner) {+ if g.dev.log_capture.as_ref().is_some_and(|c| c.last_query.elapsed() > IDLE || c.task.is_finished()) {+ g.dev.log_capture = None;+ }+ }+/// The executable name of an installed app given by name or bundle ID, or `process` itselfasync fn process_name(&self, g: &mut Inner, process: &str) -> String {for system in [false, true] {@@ -188,9 +194,8 @@ impl Daemon {}/// Runs without holding the daemon lock (an install can take minutes), like re-signing- pub(crate) async fn install_app(&self, path: &str) -> Result<String, String> {- let device =- self.inner.lock().await.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;+ /// Installs are queued one at a time inside `Device::install` (they share one upload path on the phone)+ pub(crate) async fn install_app(&self, device: &ictl_device::Device, path: &str) -> Result<String, String> {let p = std::path::Path::new(path);if !p.exists() {return Err(ictl_l10n::trf!(@@ -199,12 +204,17 @@ impl Daemon {));}device.install(p).await.map_err(|e| e.to_string())?;- self.inner.lock().await.apps.clear();+ self.inner.lock().await.dev.apps.clear();Ok(ictl_l10n::trf!("已安装 {path}", "Installed {path}"))}+ /// Uninstalling deletes the app's data, so unlike launching, the name must match exactly: a bundle ID or the+ /// whole display name. The app lists are read again first, so an app installed a moment ago is foundpub(crate) async fn uninstall_app(&self, g: &mut Inner, app: &str) -> Result<String, String> {- let bid = self.resolve_app(g, app).await?;+ g.dev.apps.clear();+ let mut all = self.list_apps(g, false).await?;+ all.extend(self.list_apps(g, true).await?);+ let bid = uninstall_target(app, &all)?;if is_wda_runner(&bid, g.persisted.wda_bundle.as_deref()) {return Err(ictl_l10n::trf!("{bid} 是 WebDriverAgent,iphone-control 靠它控制手机,不能卸载",@@ -213,7 +223,7 @@ impl Daemon {}let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;device.uninstall(&bid).await.map_err(|e| e.to_string())?;- g.apps.clear();+ g.dev.apps.clear();Ok(ictl_l10n::trf!("已卸载 {bid}", "Uninstalled {bid}"))}}@@ -256,6 +266,46 @@ fn compact(mut e: LogEntry) -> LogEntry {e}+/// The bundle ID to uninstall: `app` is an installed bundle ID, or exactly one app's display name (ignoring case).+/// Anything else is refused, listing similar names, since a wrong guess deletes an app with its data+fn uninstall_target(app: &str, apps: &[AppInfo]) -> Result<String, String> {+ let app = app.trim();+ if app.is_empty() {+ return Err(ictl_l10n::tr!("app 不能为空", "app can't be empty").into());+ }+ if let Some(a) = apps.iter().find(|a| a.bundle_id.eq_ignore_ascii_case(app)) {+ return Ok(a.bundle_id.clone());+ }+ let exact: Vec<&AppInfo> = apps.iter().filter(|a| a.name.eq_ignore_ascii_case(app)).collect();+ let line = |a: &&AppInfo| format!("{}\t{}", a.name, a.bundle_id);+ match exact.as_slice() {+ [one] => Ok(one.bundle_id.clone()),+ [] => {+ let needle = app.to_lowercase();+ let similar: Vec<String> =+ apps.iter().filter(|a| a.name.to_lowercase().contains(&needle)).take(5).map(|a| line(&a)).collect();+ Err(if similar.is_empty() {+ ictl_l10n::trf!(+ "没有装 \"{app}\"(卸载要用 Bundle ID 或完整的 App 名字),用 iphone_list_apps 查看",+ "\"{app}\" is not installed (uninstalling needs the bundle ID or the full app name); see iphone_list_apps"+ )+ } else {+ ictl_l10n::trf!(+ "没有名字正好是 \"{app}\" 的 App,没有卸载;卸载要用 Bundle ID 或完整的名字。相近的:\n{}",+ "No app is named exactly \"{app}\", nothing uninstalled; uninstalling needs the bundle ID or the full name. Similar:\n{}",+ similar.join("\n")+ )+ })+ }+ many => Err(ictl_l10n::trf!(+ "有 {} 个 App 叫 \"{app}\",没有卸载;用 Bundle ID 指定:\n{}",+ "{} apps are named \"{app}\", nothing uninstalled; pass the bundle ID:\n{}",+ many.len(),+ many.iter().map(line).collect::<Vec<_>>().join("\n")+ )),+ }+}+/// The WDA runner this daemon signed, or any other WebDriverAgent buildfn is_wda_runner(bid: &str, signed: Option<&str>) -> bool {signed.is_some_and(|s| s.eq_ignore_ascii_case(bid)) || bid.to_ascii_lowercase().contains("webdriveragentrunner")@@ -322,20 +372,23 @@ fn crash_list(names: Vec<String>, filter: &str) -> Vec<String> {v}-/// `MyApp-2026-11-08-120000.ips` → `2026-11-08-120000`, for sorting by date across apps+/// `MyApp-2026-11-08-120000.ips` → `2026-11-08-120000`, for sorting by date across apps. Searched in the whole name:+/// process names can contain dots (`com.apple.WebKit.WebContent-2026-….ips`, `Foo.cpu_resource-….ips`)fn report_date(name: &str) -> &str {- let stem = name.split('.').next().unwrap_or(name);- let b = stem.as_bytes();+ let b = name.as_bytes();+ let digits = |r: std::ops::Range<usize>| b[r].iter().all(u8::is_ascii_digit);(0..b.len().saturating_sub(16)).rev().find(|&i| {- b[i..].len() >= 17- && b[i..i + 4].iter().all(u8::is_ascii_digit)+ digits(i..i + 4)&& b[i + 4] == b'-'+ && digits(i + 5..i + 7)&& b[i + 7] == b'-'+ && digits(i + 8..i + 10)&& b[i + 10] == b'-'+ && digits(i + 11..i + 17)})- .map_or("", |i| &stem[i..])+ .map_or("", |i| &name[i..i + 17])}#[cfg(test)]@@ -352,6 +405,25 @@ mod tests {}}+ #[test]+ fn uninstall_needs_an_exact_name() {+ let app = |n: &str, b: &str| AppInfo { name: n.into(), bundle_id: b.into(), executable: String::new() };+ let apps = [+ app("Test Flight", "com.apple.TestFlight"),+ app("MyTest", "com.example.mytest"),+ app("Notes", "com.apple.mobilenotes"),+ app("Notes", "com.other.notes"),+ ];+ assert!(uninstall_target("", &apps).is_err(), "empty must not match the first app");+ assert!(uninstall_target(" ", &apps).is_err());+ assert_eq!(uninstall_target("com.example.MyTest", &apps).as_deref(), Ok("com.example.mytest"));+ assert_eq!(uninstall_target("mytest", &apps).as_deref(), Ok("com.example.mytest"));+ let e = uninstall_target("Test", &apps).unwrap_err();+ assert!(e.contains("com.apple.TestFlight") && e.contains("com.example.mytest"), "{e}");+ assert!(uninstall_target("Notes", &apps).unwrap_err().contains("com.other.notes"), "ambiguous");+ assert!(uninstall_target("com.not.installed", &apps).is_err());+ }+#[test]fn wda_runner_cannot_be_uninstalled() {let signed = Some("com.facebook.WebDriverAgentRunner.xctrunner.ABC123");@@ -413,5 +485,10 @@ mod tests {assert_eq!(crash_list(names, "myapp").len(), 2);assert_eq!(report_date("JetsamEvent-2026-11-08-101500.ips"), "2026-11-08-101500");assert_eq!(report_date("weird.ips"), "");+ assert_eq!(report_date("com.apple.WebKit.WebContent-2026-11-09-101500.ips"), "2026-11-09-101500");+ assert_eq!(report_date("Foo.cpu_resource-2026-11-01-080000.ips.synced"), "2026-11-01-080000");+ let names =+ vec!["Old-2026-11-01-080000.ips".into(), "com.apple.WebKit.WebContent-2026-11-09-101500.ips".into()];+ assert_eq!(crash_list(names, "")[0], "com.apple.WebKit.WebContent-2026-11-09-101500.ips");}}diff --git a/crates/ictl-daemon/src/doctor.rs b/crates/ictl-daemon/src/doctor.rsindex f4cebbf..2aea478 100644--- a/crates/ictl-daemon/src/doctor.rs+++ b/crates/ictl-daemon/src/doctor.rs@@ -120,7 +120,7 @@ impl Daemon {if g.device.is_some() {self.refresh_device_profile(g).await;}- let whose = match &g.device_profile {+ let whose = match &g.dev.device_profile {DeviceProfile::Expires(_) => {ictl_l10n::tr!("这台手机上的描述文件", "The provisioning profile on this phone")}@@ -130,8 +130,8 @@ impl Daemon {}_ => ictl_l10n::tr!("描述文件", "The provisioning profile"),};- match g.device_profile.left(&g.persisted) {- _ if g.device_profile == DeviceProfile::Missing => {+ match g.dev.device_profile.left(&g.persisted) {+ _ if g.dev.device_profile == DeviceProfile::Missing => {out.push(ictl_l10n::tr!("❌ 这台手机上没有装当前 Apple ID 签的 WDA\n → iphone-control setup(会把这台手机注册到 Apple ID 并装上 WDA)", "❌ No WDA signed by the current Apple ID on this phone\n → iphone-control setup (registers this phone with the Apple ID and installs WDA)").into(),diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rsindex 884c6d8..1299efa 100644--- a/crates/ictl-daemon/src/lib.rs+++ b/crates/ictl-daemon/src/lib.rs@@ -16,6 +16,7 @@ pub mod machine;pub mod notify;mod supervise;mod tools;+mod watchdog;mod wda_pkg;mod web;@@ -64,6 +65,7 @@ pub async fn run(cfg: Config) -> anyhow::Result<()> {async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::Result<()> {let daemon = Daemon::new(cfg);daemon.log.log(ictl_l10n::log_tr!("守护进程启动", "Daemon started"));+ watchdog::spawn(daemon.heartbeat.clone(), daemon.log.clone());let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;let mut tick = tokio::time::interval(core::TICK);@@ -80,7 +82,11 @@ async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::ResulOk((stream, _)) => {conns.spawn_local(serve_conn(daemon.clone(), stream));}- Err(e) => tracing::warn!("{}", ictl_l10n::log_trf!("控制接口 accept 失败:{e}", "Accepting on the control socket failed: {e}")),+ Err(e) => {+ tracing::warn!("{}", ictl_l10n::log_trf!("控制接口 accept 失败:{e}", "Accepting on the control socket failed: {e}"));+ // 比如文件描述符用完:立刻重试只会空转+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }},Some(_) = conns.join_next(), if !conns.is_empty() => {}_ = tick.tick() => {diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rsindex 893683b..7e38859 100644--- a/crates/ictl-daemon/src/supervise.rs+++ b/crates/ictl-daemon/src/supervise.rs@@ -83,9 +83,11 @@ impl Daemon {// 经旧 usbmuxd 建立的连接(隧道、runner、WDA)都要失效:先停 HID 媒体流(还要经它),再停它self.drop_session(g).await;if let Some(mut c) = g.usbmuxd.take() {- let _ = c.kill().await;+ crate::core::stop_child(&mut c).await;}- let log = std::fs::OpenOptions::new().create(true).append(true).open(self.cfg.logs().join("usbmuxd.log"));+ let log_path = self.cfg.logs().join("usbmuxd.log");+ rotate_before_append(&log_path, crate::eventlog::MAX_BYTES);+ let log = std::fs::OpenOptions::new().create(true).append(true).open(log_path);let mut cmd = tokio::process::Command::new(&self.cfg.usbmuxd_bin);cmd.args(["-U", "root", "-f"]).kill_on_drop(true);if let Ok(f) = log@@ -192,22 +194,18 @@ impl Daemon {tokio::task::spawn_local(self.clone().check_session());}self.web_housekeeping(g.device.as_ref().map(|d| d.udid.as_str()));+ Self::log_housekeeping(g);self.publish(g);}async fn offline(&self, g: &mut Inner) {let now = Instant::now();- g.device_profile = DeviceProfile::NotChecked;- g.wda_rotation = None;if g.device.take().is_some() {self.log.log(ictl_l10n::log_tr!("手机离线", "Phone offline"));// 名字、型号、iOS 版本是这台的:留着的话状态、提示文字会把它当成还在控制的设备g.info = None;- self.drop_session(g).await;+ self.forget_device(g).await;g.offline_since = Some(now);- g.apps.clear();- // 日志采集属于那台设备:不再控制它就停掉,不让旧设备的日志流再跑到闲置超时- g.log_capture = None;}self.set_state(g, DeviceState::Absent);let since = *g.offline_since.get_or_insert(now);@@ -236,13 +234,8 @@ impl Daemon {)),None => {}}- self.drop_session(g).await;- g.device_profile = DeviceProfile::NotChecked;- // App 列表是上一台的(同一台重新接入也重读,便宜)- g.apps.clear();- // 日志采集属于那台设备:不再控制它就停掉,不让旧设备的日志流再跑到闲置超时- g.log_capture = None;- g.wda_rotation = None;+ // 同一台重新接入也清(App 列表重读很便宜,日志流经的旧连接已经断了)+ self.forget_device(g).await;let d = Device::from_usb(seen);g.info = d.info().await.ok();if let Some(i) = &g.info {@@ -265,7 +258,7 @@ impl Daemon {match device.paired().await {Ok(true) => {- if g.device_profile == DeviceProfile::NotChecked {+ if g.dev.device_profile == DeviceProfile::NotChecked {self.refresh_device_profile(g).await;}}@@ -379,12 +372,16 @@ impl Daemon {StartOutcome::Wda(WdaError::StartFailed(ictl_l10n::trf!("启动任务异常:{e}", "Start task failed: {e}")))});match outcome {- StartOutcome::Ready { runner, client, mounted } => {+ StartOutcome::Ready { runner, mut client, mounted } => {if let Some(v) = mounted {self.log.log(&ictl_l10n::log_trf!("开发者镜像已挂载 {v}", "Developer disk image mounted {v}"));}- g.ddi_failures = 0;+ g.dev.ddi_failures = 0;g.runner = Some(runner);+ // verified on an iPhone only; iPads keep what they did+ if g.info.as_ref().is_some_and(|i| i.product_type.starts_with("iPhone")) {+ client.keep_stream_upright();+ }g.wda = Some(client);// 状态在下面 online() 的健康检查里变成 Ready}@@ -396,11 +393,11 @@ impl Daemon {StartOutcome::Ddi { error: e, mount_failed } => {// 只有挂载失败才可能是缓存坏了;ICTL_DDI_DIR 是用户自己的文件,从不删if mount_failed && self.cfg.ddi_dir.is_none() {- g.ddi_failures += 1;- if g.ddi_failures >= DDI_FAILURES_INVALIDATE {- self.log.log(&ictl_l10n::log_trf!("开发者镜像连续 {} 次挂载失败,清掉缓存,下次重新下载", "Mounting the developer disk image failed {} times in a row, clearing the cache to download it again", g.ddi_failures));+ g.dev.ddi_failures += 1;+ if g.dev.ddi_failures >= DDI_FAILURES_INVALIDATE {+ self.log.log(&ictl_l10n::log_trf!("开发者镜像连续 {} 次挂载失败,清掉缓存,下次重新下载", "Mounting the developer disk image failed {} times in a row, clearing the cache to download it again", g.dev.ddi_failures));ictl_device::ddi::invalidate(&self.cfg.ddi_cache());- g.ddi_failures = 0;+ g.dev.ddi_failures = 0;}}g.backoff.failed(Instant::now());@@ -465,13 +462,13 @@ impl Daemon {// 看这台手机上装的那份,不看最近一次签名:给别的手机签过之后,这台装的还是更早签的、更早到期if !force && g.persisted.wda_bundle.is_some() {self.refresh_device_profile(g).await;- if g.device_profile == DeviceProfile::Missing {+ if g.dev.device_profile == DeviceProfile::Missing {// 自动重签不替没装过的手机注册设备(占 Apple ID 的设备名额),交给用户决定return Ok(ictl_l10n::tr!("这台手机上没有装当前 Apple ID 签的 WDA,不自动重签;要装就运行 iphone-control setup", "No WDA signed by the current Apple ID on this phone, not re-signing automatically; run iphone-control setup to install it").into());}- if let Some(left) = g.device_profile.left(&g.persisted)+ if let Some(left) = g.dev.device_profile.left(&g.persisted)&& left > self.cfg.resign_min{return Ok(ictl_l10n::trf!(@@ -584,6 +581,13 @@ impl Daemon {}}+/// Keeps a log that a child appends to from growing without end. Only safe while nothing has it open+fn rotate_before_append(path: &Path, max: u64) {+ if std::fs::metadata(path).is_ok_and(|m| m.len() >= max) {+ let _ = std::fs::rename(path, path.with_extension("log.1"));+ }+}+fn now_secs() -> u64 {std::time::SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()}diff --git a/crates/ictl-daemon/src/tools.rs b/crates/ictl-daemon/src/tools.rsindex 724a23d..6cf10a9 100644--- a/crates/ictl-daemon/src/tools.rs+++ b/crates/ictl-daemon/src/tools.rs@@ -28,6 +28,8 @@ const LOCAL_MOTION: f64 = 4.0;const STILL_TOLERANCE: i64 = 3;/// 滑动后最多等这么久让列表停下(快速滑动的惯性滚动约 2 秒)const SCROLL_SETTLE: Duration = Duration::from_millis(2500);+/// 滑动时读到的树这么久之内还能当 settle 比较的起点+const SWIPED_TREE_FRESH: Duration = Duration::from_secs(1);/// WDA 不可用时 status 里说明哪些功能用不了const NEEDS_WDA: &str = "读界面元素、按名字点击、启动 App、输入中文要等 WDA 恢复";const NEEDS_WDA_EN: &str =@@ -41,7 +43,7 @@ impl Daemon {/// 配置了密码就在锁屏时自动解锁;没配置而手机锁着则报错(与 toolkit 一致)pub(crate) async fn ensure_unlocked(&self, g: &mut Inner) -> Result<(), String> {let cfg = self.unlock_cfg(g.device.as_ref().map(|d| d.udid.as_str()));- if let Some(left) = g.last_lock.and_then(|t| LOCK_SETTLE.checked_sub(t.elapsed())) {+ if let Some(left) = g.dev.last_lock.and_then(|t| LOCK_SETTLE.checked_sub(t.elapsed())) {tokio::time::sleep(left).await;}let Some(wda) = self.wda(g) else { return Ok(()) };@@ -84,7 +86,7 @@ impl Daemon {if let Some(w) = self.wda(g)&& let Ok(r) = w.rotation().await{- g.wda_rotation = Some((Instant::now(), r));+ g.dev.wda_rotation = Some((Instant::now(), r));}}@@ -100,7 +102,7 @@ impl Daemon {})?;let (w, h) = imaging::png_size(&png).ok_or(ictl_l10n::tr!("无法读取截图尺寸,没有发送触摸", "Can't read the screenshot size, no touch sent"))?;- let known = g.wda_rotation.map(|(at, r)| (at.elapsed(), r));+ let known = g.dev.wda_rotation.map(|(at, r)| (at.elapsed(), r));hid_rotation(w, h, known)}@@ -335,30 +337,28 @@ impl Daemon {/// 屏幕上有弹窗时在结果里提醒(读树时顺带看,不多花时间)pub(crate) async fn settle(&self, g: &mut Inner, max: Duration) -> Result<String, String> {let t0 = Instant::now();+ // 刚滑完读到的树:只作比较的起点,是不是真稳定还要看下一次读到的+ let seed = g.swiped_tree.take().filter(|(at, _)| at.elapsed() < SWIPED_TREE_FRESH).map(|(_, t)| t);let Some(w) = self.wda(g) else {tokio::time::sleep(max.min(Duration::from_millis(500))).await;return Ok(ictl_l10n::tr!("WDA 不可用,等了 0.5 秒", "WDA unavailable, waited 0.5 s").into());};w.begin_polling().await.map_err(|e| e.to_string())?;- let r = poll_stable(w, t0, max).await;+ let r = poll_stable(w, t0, max, seed).await;w.end_polling().await;- let (first, polled) = r?;- let Some((msg, tree)) = polled else {- // 元素很少:改看画面- let note = alert_note(&first);- return Ok(self.settle_visually(g, t0, max).await? + ¬e);+ let (msg, settled, tree) = match r? {+ Polled::FewElements(first) => {+ // 元素很少:改看画面+ let note = alert_note(&first);+ return Ok(self.settle_visually(g, t0, max).await? + ¬e);+ }+ Polled::Done { msg, settled, tree } => (msg, settled, tree),};let note = alert_note(&tree);// 自己画的加载圈(不是 ActivityIndicator)不在树里,树稳定了页面可能还在加载。// 加载中的页面中间是空的:只在这种时候多看一眼画面(约 0.5 秒),平常不多花时间let screen = self.screen(g).await?;- let msg = if msg.starts_with(ictl_l10n::tr!("界面已稳定", "Screen settled"))- && middle_is_empty(&tree, screen.height)- {- msg + &self.motion_note(g).await- } else {- msg- };+ let msg = if settled && middle_is_empty(&tree, screen.height) { msg + &self.motion_note(g).await } else { msg };// 紧接着的 then=elements 直接用这棵树g.elements_cache = Some((Instant::now(), tree));Ok(msg + ¬e)@@ -566,12 +566,14 @@ impl Daemon {self.ensure_unlocked(g).await?;let desc = format!("({},{}) → ({},{})", fmt_g(from.0), fmt_g(from.1), fmt_g(to.0), fmt_g(to.1));if let Some(w) = self.wda(g) {- match w.swipe(from, to, (seconds * 1000.0) as u64).await {+ match w.swipe_into_polling(from, to, (seconds * 1000.0) as u64).await {// 滑动请求不等惯性滚动(等的话设置不对能卡十几秒),这里等列表停下再返回:// 列表还在滚时下一次点击只会让它停住,点不到东西Ok(()) => {let vertical = (to.1 - from.1).abs() >= (to.0 - from.0).abs();- return Ok(ictl_l10n::trf!("已滑动 {desc}{}", "Swiped {desc}{}", wait_scrolled(w, vertical).await));+ let (note, tree) = wait_scrolled(w, vertical).await;+ g.swiped_tree = tree.map(|t| (Instant::now(), t));+ return Ok(ictl_l10n::trf!("已滑动 {desc}{note}", "Swiped {desc}{note}"));}Err(WdaError::Unavailable(_)) => {}Err(e) => return Err(e.to_string()),@@ -707,22 +709,22 @@ impl Daemon {}};if locked {- g.last_lock = Some(Instant::now());+ g.dev.last_lock = Some(Instant::now());return Ok(ictl_l10n::tr!("已锁屏", "Locked").into());}}self.hid_do(g, |h| Box::pin(h.press(Button::Lock))).await?;- g.last_lock = Some(Instant::now());+ g.dev.last_lock = Some(Instant::now());Ok(ictl_l10n::tr!("已锁屏", "Locked").into())}pub(crate) async fn list_apps(&self, g: &mut Inner, include_system: bool) -> Result<Vec<AppInfo>, String> {- if let Some(a) = g.apps.get(&include_system) {+ if let Some(a) = g.dev.apps.get(&include_system) {return Ok(a.clone());}let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;let a = device.list_apps(include_system).await.map_err(|e| e.to_string())?;- g.apps.insert(include_system, a.clone());+ g.dev.apps.insert(include_system, a.clone());Ok(a)}@@ -734,7 +736,7 @@ impl Daemon {return Ok(b);}// 守护进程启动后新装的 App 不在缓存里:刷新一次再找- g.apps.clear();+ g.dev.apps.clear();self.resolve_cached(g, app).await?.ok_or_else(|| {ictl_l10n::trf!("找不到名为 \"{app}\" 的 App,用 iphone_list_apps 查看",@@ -913,36 +915,39 @@ fn middle_is_empty(tree: &Tree, screen_h: f64) -> bool {}/// 滑动后等列表停下(最多 [`SCROLL_SETTLE`]):沿滑动方向的位置连续两次差不超过 [`STILL_TOLERANCE`]。-/// 没停下返回提醒;元素很少(游戏、地图)看不出来,不等-async fn wait_scrolled(w: &mut WdaClient<DeviceTransport>, vertical: bool) -> String {- if w.begin_polling().await.is_err() {- return String::new();- }+/// 没停下返回提醒;元素很少(游戏、地图)看不出来,不等。+/// 同时返回停下时读到的树,紧接着的 settle(then=…)从它开始比较,少读一次([`Daemon::settle`])。+/// 调用前已在轮询模式([`WdaClient::swipe_into_polling`])+async fn wait_scrolled(w: &mut WdaClient<DeviceTransport>, vertical: bool) -> (String, Option<Tree>) {let t0 = Instant::now();- let r: Result<bool, WdaError> = async {+ let r: Result<(bool, Tree), WdaError> = async {let mut prev = w.tree().await?;if prev.elements.len() < VISUAL_SETTLE_BELOW {- return Ok(true);+ return Ok((true, prev));}while t0.elapsed() < SCROLL_SETTLE {tokio::time::sleep(Duration::from_millis(30)).await;let cur = w.tree().await?;if cur.still_along(&prev, vertical, STILL_TOLERANCE) {- return Ok(true);+ return Ok((true, cur));}prev = cur;}- Ok(false)+ Ok((false, prev))}.await;w.end_polling().await;match r {- Ok(false) => ictl_l10n::trf!(- "({:.1} 秒后列表还在动,可能还在滚动)",- " (the list was still moving after {:.1} s, it may still be scrolling)",- SCROLL_SETTLE.as_secs_f64()+ Ok((true, tree)) => (String::new(), Some(tree)),+ Ok((false, _)) => (+ ictl_l10n::trf!(+ "({:.1} 秒后列表还在动,可能还在滚动)",+ " (the list was still moving after {:.1} s, it may still be scrolling)",+ SCROLL_SETTLE.as_secs_f64()+ ),+ None,),- _ => String::new(),+ Err(_) => (String::new(), None),}}@@ -953,15 +958,19 @@ async fn poll_stable(w: &mut WdaClient<DeviceTransport>,t0: Instant,max: Duration,-) -> Result<(Tree, Option<(String, Tree)>), String> {- let first = w.tree().await.map_err(|e| e.to_string())?;+ seed: Option<Tree>,+) -> Result<Polled, String> {+ let first = match seed {+ Some(t) => t,+ None => w.tree().await.map_err(|e| e.to_string())?,+ };if first.elements.len() < VISUAL_SETTLE_BELOW {- return Ok((first, None));+ return Ok(Polled::FewElements(first));}- let mut prev = first.clone();- let msg = loop {+ let mut prev = first;+ let (msg, settled) = loop {if t0.elapsed() >= max {- break if prev.loading {+ let msg = if prev.loading {ictl_l10n::trf!("{:.1} 秒内页面一直在加载(有加载圈),按最后的状态返回;要等结果出来用 iphone_wait_for","The page kept loading for {:.1} s (spinner shown), returning the last state; to wait for the result use iphone_wait_for",@@ -974,6 +983,7 @@ async fn poll_stable(max.as_secs_f64())};+ break (msg, false);}// 一次读树本身约 0.2 秒,两次之间不用再多等tokio::time::sleep(Duration::from_millis(30)).await;@@ -981,10 +991,23 @@ async fn poll_stable(let same = cur.close_to(&prev, STILL_TOLERANCE);prev = cur;if same && !prev.loading {- break ictl_l10n::trf!("界面已稳定({:.1} 秒)", "Screen settled ({:.1} s)", t0.elapsed().as_secs_f64());+ let msg = ictl_l10n::trf!("界面已稳定({:.1} 秒)", "Screen settled ({:.1} s)", t0.elapsed().as_secs_f64());+ break (msg, true);}};- Ok((first, Some((msg, prev))))+ Ok(Polled::Done { msg, settled, tree: prev })+}++/// 轮询元素树的结果+enum Polled {+ /// 元素太少(游戏、地图),元素树看不出界面变化,要改看画面+ FewElements(Tree),+ Done {+ msg: String,+ /// 真的稳定了(不是等到上限)+ settled: bool,+ tree: Tree,+ },}/// 判断画面动没动用的缩略图。解码是 CPU 活,放到阻塞线程diff --git a/crates/ictl-daemon/src/watchdog.rs b/crates/ictl-daemon/src/watchdog.rsnew file mode 100644index 0000000..7e6ece2--- /dev/null+++ b/crates/ictl-daemon/src/watchdog.rs@@ -0,0 +1,73 @@+//! The last resort when the daemon wedges: a device call that never returns while holding the device lock would+//! leave every later request queuing until it goes stale, and the process looks healthy from outside. Timeouts around+//! the device calls are the first line of defence; this catches what they miss.+//!+//! Everything that finishes work under the device lock (a request, a full supervision round) goes through+//! [`crate::Daemon`]'s `publish`, which beats the heartbeat. A round that finds the lock busy skips without beating,+//! so a stuck lock holder shows up as silence. The check runs on its own thread, so a blocked runtime is caught too.+//! The service manager (systemd `Restart=on-failure`, Docker `restart: unless-stopped`) starts a fresh daemon.++use std::sync::Arc;+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::{Duration, Instant};++use crate::eventlog::EventLog;++/// Longer than any legitimate hold of the device lock (starting WDA, the slowest thing, is a few minutes)+const STUCK_AFTER: Duration = Duration::from_secs(600);+const CHECK_EVERY: Duration = Duration::from_secs(30);++#[derive(Debug, Clone)]+pub(crate) struct Heartbeat {+ start: Instant,+ /// Seconds after `start` of the last beat+ last: Arc<AtomicU64>,+}++impl Heartbeat {+ pub(crate) fn new() -> Self {+ Self { start: Instant::now(), last: Arc::new(AtomicU64::new(0)) }+ }++ pub(crate) fn beat(&self) {+ self.last.store(self.start.elapsed().as_secs(), Ordering::Relaxed);+ }++ fn silent_for(&self) -> Duration {+ Duration::from_secs(self.start.elapsed().as_secs().saturating_sub(self.last.load(Ordering::Relaxed)))+ }+}++pub(crate) fn spawn(heartbeat: Heartbeat, log: EventLog) {+ let watch = move || {+ loop {+ std::thread::sleep(CHECK_EVERY);+ let silent = heartbeat.silent_for();+ if silent >= STUCK_AFTER {+ log.log(&ictl_l10n::log_trf!(+ "守护进程已 {} 秒没有进展,判定卡死,退出后由服务管理器重启",+ "No progress for {} s, the daemon is stuck; exiting so the service manager restarts it",+ silent.as_secs()+ ));+ std::process::exit(1);+ }+ }+ };+ if let Err(e) = std::thread::Builder::new().name("watchdog".into()).spawn(watch) {+ tracing::warn!("{}", ictl_l10n::log_trf!("启动卡死检测失败:{e}", "Starting the watchdog failed: {e}"));+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_beat_ends_the_silence() {+ let Some(start) = Instant::now().checked_sub(Duration::from_secs(700)) else { return };+ let hb = Heartbeat { start, last: Arc::new(AtomicU64::new(0)) };+ assert!(hb.silent_for() >= STUCK_AFTER);+ hb.clone().beat();+ assert!(hb.silent_for() < Duration::from_secs(2));+ }+}diff --git a/crates/ictl-daemon/src/web.rs b/crates/ictl-daemon/src/web.rsindex f44e880..892a6ef 100644--- a/crates/ictl-daemon/src/web.rs+++ b/crates/ictl-daemon/src/web.rs@@ -13,6 +13,8 @@ use std::time::{Duration, Instant};use ictl_webinspector::{App, Eval, Page, WebInspector};+use ictl_device::Device;+use crate::core::Daemon;/// A kept connection is closed after this long without a request@@ -30,9 +32,9 @@ const LISTING_WAIT: Duration = Duration::from_secs(3);const MAX_RESULT_CHARS: usize = 50_000;impl Daemon {- pub(crate) async fn web_targets(&self) -> Result<String, String> {- let mut slot = self.web.lock().await;- let (apps, pages) = self.web_pages(&mut slot).await?;+ /// `slot` is [`Daemon::web`], already locked by the caller (see `Daemon::handle`)+ pub(crate) async fn web_targets(&self, slot: &mut Option<WebConn>, device: &Device) -> Result<String, String> {+ let (apps, pages) = web_pages(slot, device).await?;if pages.is_empty() {return Ok(ictl_l10n::tr!("没有可检查的页面。需要:设置 → Safari → 高级 → 网页检查器 打开;App 里的 WebView 要是调试构建或设了 isInspectable;页面所在的 App 在前台(刚打开的 App 等几秒再试)",@@ -52,9 +54,15 @@ impl Daemon {Ok(out)}- pub(crate) async fn web_eval(&self, target: &str, expression: &str, timeout: Duration) -> Result<String, String> {- let mut slot = self.web.lock().await;- let (apps, pages) = self.web_pages(&mut slot).await?;+ pub(crate) async fn web_eval(+ &self,+ slot: &mut Option<WebConn>,+ device: &Device,+ target: &str,+ expression: &str,+ timeout: Duration,+ ) -> Result<String, String> {+ let (apps, pages) = web_pages(slot, device).await?;let page = pick(&pages, target).map_err(|e| match e {Pick::None => ictl_l10n::trf!("没有和「{target}」对应的页面,用 iphone_web_targets 查看",@@ -75,7 +83,7 @@ impl Daemon {if breaks_connection(&e) {*slot = None;}- return Err(e.to_string());+ return Err(page_error(&e));}};Ok(match r {@@ -85,36 +93,6 @@ impl Daemon {})}- /// The pages, on the kept connection (opened if there is none, or it belongs to another device). A connection- /// that turns out to be broken is replaced once: listing pages changes nothing on the phone- async fn web_pages(&self, slot: &mut Option<WebConn>) -> Result<(Vec<App>, Vec<Page>), String> {- let device =- self.inner.lock().await.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;- if slot.as_ref().is_some_and(|c| c.udid != device.udid) {- *slot = None;- }- for attempt in 0..2 {- if slot.is_none() {- let w = device.web_inspector().await.map_err(|e| e.to_string())?;- *slot = Some(WebConn { udid: device.udid.clone(), w, used: Instant::now() });- }- let conn = slot.as_mut().ok_or("Web Inspector")?;- conn.used = Instant::now();- match conn.w.pages(LISTING_WAIT).await {- Ok(r) => return Ok(r),- Err(e) if breaks_connection(&e) => {- *slot = None;- if attempt == 1 {- return Err(e.to_string());- }- tracing::debug!("Web Inspector connection broken, opening a new one: {e}");- }- Err(e) => return Err(e.to_string()),- }- }- unreachable!("the second attempt returns")- }-/// Closes the kept connection after [`WEB_IDLE`], or when the daemon no longer controls its device. Called from/// the health check; skipped while a web request is runningpub(crate) fn web_housekeeping(&self, controlled: Option<&str>) {@@ -126,10 +104,49 @@ impl Daemon {}}-/// Errors after which the connection can't be trusted to be in step: everything except a page that didn't answer-/// in time (the session is closed and late answers for it are dropped)+/// The pages, on the kept connection (opened if there is none, or it belongs to another device). A connection that+/// turns out to be broken is replaced once: listing pages changes nothing on the phone+async fn web_pages(slot: &mut Option<WebConn>, device: &Device) -> Result<(Vec<App>, Vec<Page>), String> {+ if slot.as_ref().is_some_and(|c| c.udid != device.udid) {+ *slot = None;+ }+ for attempt in 0..2 {+ if slot.is_none() {+ let w = device.web_inspector().await.map_err(|e| e.to_string())?;+ *slot = Some(WebConn { udid: device.udid.clone(), w, used: Instant::now() });+ }+ let conn = slot.as_mut().ok_or("Web Inspector")?;+ conn.used = Instant::now();+ match conn.w.pages(LISTING_WAIT).await {+ Ok(r) => return Ok(r),+ Err(e) if breaks_connection(&e) => {+ *slot = None;+ if attempt == 1 {+ return Err(page_error(&e));+ }+ tracing::debug!("Web Inspector connection broken, opening a new one: {e}");+ }+ Err(e) => return Err(page_error(&e)),+ }+ }+ unreachable!("the second attempt returns")+}++/// The Web Inspector's own errors are in English; the one an agent or user meets in normal use follows the language+fn page_error(e: &ictl_webinspector::Error) -> String {+ match e {+ ictl_webinspector::Error::Timeout(_) => {+ ictl_l10n::tr!("等待页面回应超时", "timed out waiting for the page to answer").into()+ }+ e => e.to_string(),+ }+}++/// Errors after which the connection can't be trusted: everything except a page that didn't answer in time or+/// refused a command (reads are cancel-safe and late answers for a closed session are dropped). Reopening costs+/// about 8 seconds, and repeated reopening made the phone stop reporting Safari, so only reopen when neededfn breaks_connection(e: &ictl_webinspector::Error) -> bool {- !matches!(e, ictl_webinspector::Error::Timeout(_))+ !matches!(e, ictl_webinspector::Error::Timeout(_) | ictl_webinspector::Error::Command(_))}/// `PID:812/1 WebPage Safari (com.apple.mobilesafari) Title — https://…`@@ -187,6 +204,7 @@ mod tests {fn only_a_page_timeout_keeps_the_connection() {use ictl_webinspector::Error;assert!(!breaks_connection(&Error::Timeout("the page to answer")));+ assert!(!breaks_connection(&Error::Command("Missing injected script for given objectId".into())));assert!(breaks_connection(&Error::Protocol("x".into())));assert!(breaks_connection(&Error::Io(std::io::Error::other("closed"))));}diff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rsindex 4778526..9ca44d7 100644--- a/crates/ictl-device/src/lib.rs+++ b/crates/ictl-device/src/lib.rs@@ -115,6 +115,9 @@ pub enum DeviceError {InvalidInput(String),}+/// 同一时间只装一个包,见 [`Device::install`]+static INSTALLING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());+/// usbmuxd、lockdown 这类一问一答的查询的时限。idevice 读应答没有超时,对方接了连接不应答会一直等const QUERY: Duration = Duration::from_secs(15);@@ -450,6 +453,9 @@ impl Device {/// 上传并安装 .ipa 或 .app 目录pub async fn install(&self, package: &Path) -> Result<()> {+ // idevice 把每个 .ipa 都上传到手机上同一个文件(PublicStaging/idevice.ipa):同时装两个会互相覆盖+ // (重签和 iphone_install_app 撞上、两个会话同时安装)。排队等的时间不算进下面的时限+ let _one_at_a_time = INSTALLING.lock().await;// 含上传几十 MB 的包,USB 2 上也就一两分钟limit(ictl_l10n::tr!("安装", "install"), Duration::from_secs(600), async {idevice::utils::installation::install_package(&*self.provider, package, None).await?;diff --git a/crates/ictl-device/src/media.rs b/crates/ictl-device/src/media.rsindex 41a0b4c..883cd88 100644--- a/crates/ictl-device/src/media.rs+++ b/crates/ictl-device/src/media.rs@@ -26,10 +26,35 @@ const STEP: Duration = Duration::from_secs(10);const CLIENT_SUPPORTED_FEATURES: u64 = 140;/// 活着的媒体流。两个 UDP 套接字必须一直绑定,丢掉就会解绑端口。+///+/// 手机按码率不停地发 RTP 包,jktcp 给每个 UDP 端口的是无界队列:不读的话包一直堆在内存里,HID 会话开多久就+/// 堆多久。`drain` 任务读出来直接丢掉,随媒体流结束pub(crate) struct ScreenMediaStream {client: DisplayServiceClient<Box<dyn ReadWrite>>,- _audio_udp: UdpSocketHandle,- _video_udp: UdpSocketHandle,+ drain: tokio::task::JoinHandle<()>,+}++impl Drop for ScreenMediaStream {+ fn drop(&mut self) {+ // 任务持有两个套接字:中止后它们随之释放、解绑端口+ self.drain.abort();+ }+}++/// 读走并丢弃两个套接字上的数据,直到它们关闭+fn drain(audio: UdpSocketHandle, video: UdpSocketHandle) -> tokio::task::JoinHandle<()> {+ tokio::spawn(async move {+ loop {+ // mpsc 的接收可以安全取消:没收完的包留在队列里,下一轮照样读到+ let r = tokio::select! {+ r = audio.recv() => r,+ r = video.recv() => r,+ };+ if r.is_err() {+ return;+ }+ }+ })}impl ScreenMediaStream {@@ -117,7 +142,7 @@ pub(crate) async fn start(return Err(e);}- Ok(ScreenMediaStream { client, _audio_udp: audio_udp, _video_udp: video_udp })+ Ok(ScreenMediaStream { client, drain: drain(audio_udp, video_udp) })}async fn stop(client: &mut DisplayServiceClient<Box<dyn ReadWrite>>) {diff --git a/crates/ictl-device/src/oslog.rs b/crates/ictl-device/src/oslog.rsindex cd32dea..a8b4683 100644--- a/crates/ictl-device/src/oslog.rs+++ b/crates/ictl-device/src/oslog.rs@@ -24,6 +24,9 @@ pub mod flags {/// Fixed part of an entry before the stringsconst HEADER: usize = 129;+/// Longest entry accepted. The phone's entries are a few hundred bytes; a length beyond this means the stream is out+/// of step, and reading it would allocate up to 4 GB+const MAX_ENTRY: usize = 1024 * 1024;/// One raw entry#[derive(Debug, Clone)]@@ -72,6 +75,9 @@ impl OsLogStream {return Err(DeviceError::Idevice("os_trace_relay: unexpected packet start".into()));}let len = u32::from_le_bytes(be4(&self.0.read_raw(4).await?)?) as usize;+ if len > MAX_ENTRY {+ return Err(DeviceError::Idevice(format!("os_trace_relay: entry of {len} bytes, stream out of step")));+ }let packet = self.0.read_raw(len).await?;match parse(&packet) {Some(e) => return Ok(e),diff --git a/crates/ictl-l10n/src/lib.rs b/crates/ictl-l10n/src/lib.rsindex bc97a4f..e217a23 100644--- a/crates/ictl-l10n/src/lib.rs+++ b/crates/ictl-l10n/src/lib.rs@@ -163,7 +163,10 @@ macro_rules! log_tr {#[macro_export]macro_rules! log_trf {($zh:literal, $en:literal $(, $arg:expr)* $(,)?) => {- if $crate::own_lang() == $crate::Lang::En { format!($en $(, $arg)*) } else { format!($zh $(, $arg)*) }+ // args that render through tr! (errors) follow the log's language too, not the request's+ $crate::in_own_lang(|| {+ if $crate::own_lang() == $crate::Lang::En { format!($en $(, $arg)*) } else { format!($zh $(, $arg)*) }+ })};}diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rsindex 87d11e3..24bf5bf 100644--- a/crates/ictl-mcp/src/lib.rs+++ b/crates/ictl-mcp/src/lib.rs@@ -24,12 +24,12 @@ pub fn instructions() -> &'static str {"控制一台通过 USB 连接的真实 iPhone(或 iPad)。坐标单位是点(pt),与 iphone_screenshot 图像像素一致。\操作前先用 iphone_screenshot 或 iphone_list_elements 看清屏幕;能按名字点就优先用 iphone_tap_element。\游戏、地图等界面没有元素树,只能看截图按坐标操作;小图标、小字看不清时用 iphone_screenshot 的区域放大。\-配置了锁屏密码时,截图、读元素在内的各工具都会先自动解锁。每次操作后再截图确认结果。\+配置了锁屏密码时,截图、读元素和操作类工具会先自动解锁(iphone_status、列 App、列设备、切换设备和开发者工具不会,按 lock 键也不会)。每次操作后再截图确认结果。\涉及付款、删除、发送消息、修改账号或隐私设置的操作,先向用户确认。\省时间:操作类工具可带 then=elements 或 then=screenshot,等界面稳定后顺带返回操作后的界面,不用再单独调一次;\几步确定的连续操作(按键、逐级点菜单、填表)用 iphone_batch 一次发完;等页面加载用 iphone_wait_for,不要反复截图。\接着多台 iPhone/iPad 时同一时间只控制一台:用 iphone_list_devices 查看,iphone_select_device 切换。",- "Controls a real iPhone (or iPad) connected over USB. Coordinates are in points (pt), the same as the pixels of an iphone_screenshot image. Before acting, look at the screen with iphone_screenshot or iphone_list_elements; prefer iphone_tap_element whenever the target has text. Games, maps and similar screens have no element tree: work from screenshots and coordinates, and zoom into small icons or text with an iphone_screenshot region. If a passcode is configured, the tools (including screenshots and reading elements) unlock the phone first. Check the result with a screenshot after each action. Ask the user before anything that pays, deletes, sends a message, or changes account or privacy settings. Save time: action tools accept then=elements or then=screenshot to return the screen once it has settled, without a separate call; send a few predictable steps in a row (keys, menu levels, forms) as one iphone_batch; wait for a page with iphone_wait_for instead of repeated screenshots. With several iPhones/iPads connected only one is controlled at a time: see them with iphone_list_devices, switch with iphone_select_device."+ "Controls a real iPhone (or iPad) connected over USB. Coordinates are in points (pt), the same as the pixels of an iphone_screenshot image. Before acting, look at the screen with iphone_screenshot or iphone_list_elements; prefer iphone_tap_element whenever the target has text. Games, maps and similar screens have no element tree: work from screenshots and coordinates, and zoom into small icons or text with an iphone_screenshot region. If a passcode is configured, screenshots, reading elements and the action tools unlock the phone first (iphone_status, listing apps or devices, switching devices and the developer tools don't, nor does pressing lock). Check the result with a screenshot after each action. Ask the user before anything that pays, deletes, sends a message, or changes account or privacy settings. Save time: action tools accept then=elements or then=screenshot to return the screen once it has settled, without a separate call; send a few predictable steps in a row (keys, menu levels, forms) as one iphone_batch; wait for a page with iphone_wait_for instead of repeated screenshots. With several iPhones/iPads connected only one is controlled at a time: see them with iphone_list_devices, switch with iphone_select_device.")}@@ -788,17 +788,40 @@ pub fn tap_missed(text: &str, outcome: Option<protocol::Outcome>) -> bool {/// 不带 then 的操作做完后要不要查系统弹窗(弹窗挡着时操作都落在弹窗上,WDA 照样报成功)。/// 按键自己处理(Home 先查弹窗;锁屏后不用查),结束 App 后前台是主屏,不会冒出新弹窗+/// Every variant is listed (no `_`), so a new request type has to be decided herepub fn wants_alert_check(req: &Request) -> bool {- // 切换设备后新设备的 WDA 还没起来,查不了弹窗- req.is_device_action()- && !matches!(- req,- Request::PressButton { .. }- | Request::TerminateApp { .. }- | Request::SelectDevice { .. }- | Request::InstallApp { .. }- | Request::UninstallApp { .. }- )+ match req {+ Request::Tap { .. }+ | Request::TapElement { .. }+ | Request::LongPress { .. }+ | Request::Swipe { .. }+ | Request::TypeText { .. }+ | Request::LaunchApp { .. }+ | Request::OpenUrl { .. } => true,+ // 按键见 PressButton 自己的弹窗处理;切换设备后新设备的 WDA 还没起来,查不了弹窗;+ // 安装、卸载、Web Inspector 不碰屏幕(Web Inspector 也不该为它排队等设备锁)+ Request::PressButton { .. }+ | Request::TerminateApp { .. }+ | Request::SelectDevice { .. }+ | Request::InstallApp { .. }+ | Request::UninstallApp { .. }+ | Request::WebEval { .. }+ | Request::Status+ | Request::Screenshot { .. }+ | Request::ListElements { .. }+ | Request::ListApps { .. }+ | Request::Settle { .. }+ | Request::AlertCheck+ | Request::WaitFor { .. }+ | Request::Daemon+ | Request::Doctor+ | Request::Resign { .. }+ | Request::UnlockReset+ | Request::ListDevices+ | Request::AppLogs { .. }+ | Request::CrashReports { .. }+ | Request::WebTargets => false,+ }}/// 守护进程响应 → MCP 结果。错误走工具错误(is_error),文字原样给客户端diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rsindex 33705dc..93fc3eb 100644--- a/crates/ictl-protocol/src/lib.rs+++ b/crates/ictl-protocol/src/lib.rs@@ -207,23 +207,38 @@ impl Response {impl Request {/// 会改变手机状态的操作。守护进程忙时排队太久就放弃,免得点击落到已经变了的屏幕上+ /// Every variant is listed (no `_`), so a new request type has to be classified herepub fn is_device_action(&self) -> bool {- matches!(- self,+ match self {Self::Tap { .. }- | Self::TapElement { .. }- | Self::LongPress { .. }- | Self::Swipe { .. }- | Self::TypeText { .. }- | Self::PressButton { .. }- | Self::LaunchApp { .. }- | Self::TerminateApp { .. }- | Self::OpenUrl { .. }- | Self::SelectDevice { .. }- | Self::InstallApp { .. }- | Self::UninstallApp { .. }- | Self::WebEval { .. }- )+ | Self::TapElement { .. }+ | Self::LongPress { .. }+ | Self::Swipe { .. }+ | Self::TypeText { .. }+ | Self::PressButton { .. }+ | Self::LaunchApp { .. }+ | Self::TerminateApp { .. }+ | Self::OpenUrl { .. }+ | Self::SelectDevice { .. }+ | Self::InstallApp { .. }+ | Self::UninstallApp { .. }+ | Self::WebEval { .. } => true,+ Self::Status+ | Self::Screenshot { .. }+ | Self::ListElements { .. }+ | Self::ListApps { .. }+ | Self::Settle { .. }+ | Self::AlertCheck+ | Self::WaitFor { .. }+ | Self::Daemon+ | Self::Doctor+ | Self::Resign { .. }+ | Self::UnlockReset+ | Self::ListDevices+ | Self::AppLogs { .. }+ | Self::CrashReports { .. }+ | Self::WebTargets => false,+ }}}diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rsindex 34166ad..7084181 100644--- a/crates/ictl-wda/src/client.rs+++ b/crates/ictl-wda/src/client.rs@@ -112,11 +112,22 @@ pub struct WdaClient<T> {lock_state_trusted: bool,/// 点击前后要恢复的等待设置(第一次点击时读一次)idle_baseline: Option<IdleSettings>,+ /// What WDA has now, as far as we know: sending the same again is a wasted round trip+ idle_current: Option<IdleSettings>,+ upright_stream: bool,}impl<T: Transport> WdaClient<T> {pub fn new(transport: T) -> Self {- Self { transport, session: None, screen: None, lock_state_trusted: false, idle_baseline: None }+ Self {+ transport,+ session: None,+ screen: None,+ lock_state_trusted: false,+ idle_baseline: None,+ idle_current: None,+ upright_stream: false,+ }}async fn call(&self, method: &str, path: &str, body: Option<Value>, timeout: Duration) -> Result<Value> {@@ -166,6 +177,14 @@ impl<T: Transport> WdaClient<T> {})?.to_owned();self.session = Some(id.clone());+ self.idle_current = None;+ if self.upright_stream {+ let body = json!({"settings": {"mjpegFixOrientation": true}});+ let path = format!("/session/{id}/appium/settings");+ if let Err(e) = self.call("POST", &path, Some(body), DEFAULT_TIMEOUT).await {+ tracing::debug!("mjpegFixOrientation: {e}");+ }+ }Ok(id)}@@ -401,6 +420,24 @@ impl<T: Transport> WdaClient<T> {self.quick_gesture(&swipe_steps(from, to, ms), IdleSettings::NO_COOL_OFF).await}+ /// Ask WDA to turn the MJPEG frames with the interface, set with each new session. On an iPhone they otherwise stay+ /// portrait with sideways content when the screen is landscape, so the live viewer shows them wrong+ pub fn keep_stream_upright(&mut self) {+ self.upright_stream = true;+ }++ /// Swipes and stays in polling mode for the caller, who ends it with [`Self::end_polling`]: restoring the settings+ /// only to change them again right after would cost two round trips+ pub async fn swipe_into_polling(&mut self, from: (f64, f64), to: (f64, f64), ms: u64) -> Result<()> {+ self.baseline().await?;+ self.set_idle_settings(IdleSettings::NO_COOL_OFF).await?;+ let r = self.actions(&swipe_steps(from, to, ms)).await;+ if r.is_err() {+ self.end_polling().await;+ }+ r+ }+/// 开始轮询界面:读元素树时不等界面空闲、动画冷却(约 0.2 秒一次),由调用方比较前后两次判断稳定。/// 用完调 [`Self::end_polling`] 恢复pub async fn begin_polling(&mut self) -> Result<()> {@@ -616,8 +653,15 @@ impl<T: Transport> WdaClient<T> {}pub async fn set_idle_settings(&mut self, s: IdleSettings) -> Result<()> {+ if self.idle_current == Some(s) {+ return Ok(());+ }+ // not known if this fails+ self.idle_current = None;let body = json!({"settings": {"waitForIdleTimeout": s.wait_for_idle_timeout, "animationCoolOffTimeout": s.animation_cool_off_timeout}});- self.post("/appium/settings", body).await.map(drop)+ self.post("/appium/settings", body).await?;+ self.idle_current = Some(s);+ Ok(())}/// 锁屏密码栏的 (总位数, 已输入位数);找不到密码栏返回 Nonediff --git a/crates/ictl-wda/src/elements.rs b/crates/ictl-wda/src/elements.rsindex aac1e4c..bd4604f 100644--- a/crates/ictl-wda/src/elements.rs+++ b/crates/ictl-wda/src/elements.rs@@ -9,8 +9,16 @@//! - 点击中心取元素在屏幕内的部分;中心被后面(上层)的东西盖住时另找没被盖住的点([`Tree::tap_point`])//! - 锁屏密码键盘的 `Key` 元素不显示时也在树里,**不能**据此判断键盘已出现+use std::sync::LazyLock;+use ictl_device::ScreenSize;use quick_xml::{XmlVersion, events::Event};+use regex::Regex;++/// The patterns are compile-time constants, only checked by the tests that use them+fn regex(pattern: &str) -> Regex {+ Regex::new(pattern).expect("valid pattern")+}/// `/source?format=xml&excluded_attributes=` 要排除的属性pub const SOURCE_EXCLUDED: &str =@@ -138,10 +146,10 @@ impl Rotate {/// 树里第一个 StatusBar 的原始坐标(不管嵌在哪层,状态栏都是整屏坐标)fn status_bar(xml: &str) -> Option<Rect> {- let tag = regex::Regex::new(r"<XCUIElementTypeStatusBar\b[^>]*>").ok()?.find(xml)?.as_str();- let attr = |k: &str| -> Option<f64> {- regex::Regex::new(&format!(r#"\b{k}="([^"]*)""#)).ok()?.captures(tag)?[1].parse().ok()- };+ static TAG: LazyLock<Regex> = LazyLock::new(|| regex(r"<XCUIElementTypeStatusBar\b[^>]*>"));+ static ATTR: LazyLock<Regex> = LazyLock::new(|| regex(r#"\b(x|y|width|height)="([^"]*)""#));+ let tag = TAG.find(xml)?.as_str();+ let attr = |k: &str| -> Option<f64> { ATTR.captures_iter(tag).find(|c| &c[1] == k)?[2].parse().ok() };Some(Rect { x: attr("x")?, y: attr("y")?, w: attr("width")?, h: attr("height")? })}@@ -318,18 +326,21 @@ fn looks_like_identifier(s: &str) -> bool {s.len() >= 3 && s.is_ascii() && !s.contains(char::is_whitespace) && s.contains(['_', '-', '.', ':'])}-/// A scroll bar: an `Other` whose value is the scroll position as a percentage and that is a thin strip-/// (about 30 points across). Its label depends on the system language ("垂直滚动条, 1页",-/// "Vertikaler Rollbalken, 1 Seite", …), so the label is only an extra hint for Chinese and English-fn is_scroll_bar(kind: &str, label: &str, value: &str, size: (f64, f64)) -> bool {+/// A scroll bar: an `Other` whose value is the scroll position as a percentage, about 30 points across and running+/// most of the way along what it scrolls (`within`: the scroll view's visible size, or the screen when there is none,+/// as on the home screen). In the device samples the bars are 25-31 points thick and at least 68% as long as that, but+/// aren't flush with its edge. A custom progress strip reporting a percentage is thinner or shorter, so it stays.+/// The label depends on the system language ("垂直滚动条, 1页", "Vertikaler Rollbalken, 1 Seite", …), so it is only an+/// extra hint for Chinese and English+fn is_scroll_bar(kind: &str, label: &str, value: &str, size: (f64, f64), within: (f64, f64)) -> bool {if kind != "Other" {return false;}if label.contains("滚动条") || label.to_lowercase().contains("scroll bar") {return true;}- let thin = size.0.min(size.1);- is_percentage(value) && thin > 0.0 && thin <= 32.0+ let (thick, long, room) = if size.1 >= size.0 { (size.0, size.1, within.1) } else { (size.1, size.0, within.0) };+ is_percentage(value) && (24.0..=32.0).contains(&thick) && long >= room * 0.6}/// "0%", "73 %" (with a no-break space in German and French), "%40" (Turkish)@@ -498,7 +509,8 @@ pub fn parse_tree(xml: &str, view: impl Into<View>) -> Tree {let (vx1, vy1) = (scr.x.max(0.0), scr.y.max(0.0));let visible = Rect { x: vx1, y: vy1, w: (scr.x + scr.w).min(sw) - vx1, h: (scr.y + scr.h).min(sh) - vy1 };let text = [&label, &name, &value].into_iter().find(|s| !s.is_empty()).cloned();- let scroll_bar = is_scroll_bar(&kind, &label, &value, (raw.w, raw.h));+ let scroll_area = parent.and_then(|p| p.scroller).map_or((sw, sh), |s| (s.w, s.h));+ let scroll_bar = is_scroll_bar(&kind, &label, &value, (scr.w, scr.h), scroll_area);if kind == "ActivityIndicator" && onscreen {tree.loading = true;}@@ -722,8 +734,8 @@ pub fn passcode_field(elements: &[Element]) -> Option<(u32, u32)> {/// 锁屏密码栏的值形如「共6位数,已输入2位」或英文「6-digit passcode, 2 entered」,返回 (总位数, 已输入位数)pub fn parse_passcode_value(value: &str) -> Option<(u32, u32)> {- let nums: Vec<u32> =- regex::Regex::new(r"\d+").ok()?.find_iter(value).filter_map(|m| m.as_str().parse().ok()).collect();+ static DIGITS: LazyLock<Regex> = LazyLock::new(|| regex(r"\d+"));+ let nums: Vec<u32> = DIGITS.find_iter(value).filter_map(|m| m.as_str().parse().ok()).collect();match nums[..] {[total, entered] => Some((total, entered)),_ => None,@@ -749,9 +761,9 @@ pub fn cover_sheet(xml: &str) -> CoverSheet {.iter().any(|m| xml.contains(m));let use_passcode = USE_PASSCODE_LABELS.iter().any(|l| xml.contains(&format!("label=\"{l}\"")));- let passcode_field = regex::Regex::new(r#"<XCUIElementTypeSecureTextField [^>]*value="([^"]*)""#)- .ok()- .is_some_and(|re| re.captures_iter(xml).any(|c| parse_passcode_value(&c[1]).is_some()));+ static PASSCODE: LazyLock<Regex> =+ LazyLock::new(|| regex(r#"<XCUIElementTypeSecureTextField [^>]*value="([^"]*)""#));+ let passcode_field = PASSCODE.captures_iter(xml).any(|c| parse_passcode_value(&c[1]).is_some());if lock_glyph || use_passcode || passcode_field {CoverSheet::Locked} else if xml.contains("\"lockscreen-date-view\"") {@@ -901,9 +913,12 @@ mod tests {for v in ["", "%", "1", "Seite 1 von 2", "50% off", "1,5 %"] {assert!(!is_percentage(v), "{v:?}");}- assert!(!is_scroll_bar("Other", "Akku", "80 %", (60.0, 120.0)), "too wide for a scroll bar");- assert!(!is_scroll_bar("Slider", "Lautstärke", "50 %", (300.0, 30.0)), "only Other");- assert!(is_scroll_bar("Other", "Barre de défilement verticale, 1 page", "0\u{202f}%", (30.0, 700.0)));+ let screen = (393.0, 852.0);+ assert!(!is_scroll_bar("Other", "Akku", "80 %", (60.0, 120.0), screen), "too wide for a scroll bar");+ assert!(!is_scroll_bar("Slider", "Lautstärke", "50 %", (300.0, 30.0), screen), "only Other");+ assert!(is_scroll_bar("Other", "Barre de défilement verticale, 1 page", "0\u{202f}%", (30.0, 700.0), screen));+ assert!(!is_scroll_bar("Other", "Download", "40 %", (350.0, 6.0), screen), "a thin progress strip stays");+ assert!(!is_scroll_bar("Other", "Download", "40 %", (120.0, 30.0), screen), "a short one too");}/// 真机:设置首页往上滑后,「钱包与Apple Pay」那一行(832~886)被底部悬浮搜索栏盖住:diff --git a/crates/ictl-webinspector/src/lib.rs b/crates/ictl-webinspector/src/lib.rsindex 76a1c8e..be54082 100644--- a/crates/ictl-webinspector/src/lib.rs+++ b/crates/ictl-webinspector/src/lib.rs@@ -15,7 +15,7 @@//! (`Target.sendMessageToTarget` / `Target.dispatchMessageFromTarget`); older versions take commands directly.//! 4. `_rpc_forwardDidClose:` detaches.-use std::collections::{BTreeMap, HashMap};+use std::collections::{BTreeMap, HashMap, HashSet};use std::time::Duration;use idevice::{Idevice, IdeviceError, IdeviceService, ReadWrite, provider::IdeviceProvider};@@ -26,6 +26,8 @@ use tokio::time::Instant;/// Messages larger than this are refused (a listing or an evaluation result is far smaller)const MAX_MESSAGE: usize = 64 * 1024 * 1024;+/// Writing one message; a phone that stops reading must not hold the caller forever+const SEND_TIMEOUT: Duration = Duration::from_secs(10);#[derive(Debug, thiserror::Error)]pub enum Error {@@ -37,8 +39,14 @@ pub enum Error {Plist(#[from] plist::Error),#[error("Web Inspector: {0}")]Protocol(String),+ /// The page didn't answer in time. The connection stays usable: reads are cancel-safe and late answers for the+ /// closed session are dropped#[error("timed out waiting for {0}")]Timeout(&'static str),+ /// The page refused a command (for example an object that went away when the page navigated). The connection+ /// stays usable+ #[error("Web Inspector: {0}")]+ Command(String),}pub type Result<T> = std::result::Result<T, Error>;@@ -83,6 +91,10 @@ pub struct WebInspector {listings: HashMap<String, Vec<Page>>,/// Inspector protocol messages that arrived for a session, by sender IDdata: HashMap<String, Vec<serde_json::Value>>,+ /// Senders of the sessions open right now; data for any other sender (a late answer after a timeout) is dropped+ open_sessions: HashSet<String>,+ /// Bytes read but not yet a whole message: reading appends here, so a read cancelled by a timeout loses nothing+ rbuf: Vec<u8>,/// Pieces of a message the phone split up (`WIRPartialMessageKey`)partial: Vec<u8>,reported: bool,@@ -101,6 +113,8 @@ impl IdeviceService for WebInspector {apps: BTreeMap::new(),listings: HashMap::new(),data: HashMap::new(),+ open_sessions: HashSet::new(),+ rbuf: Vec::new(),partial: Vec::new(),reported: false,})@@ -128,7 +142,8 @@ impl WebInspector {self.send("_rpc_getConnectedApplications:", Dictionary::new()).await?;while !self.reported {if !self.recv_until(deadline).await? {- return Err(Error::Timeout("the list of applications"));+ // unlike a slow page, a phone that doesn't report its applications means the connection is stuck+ return Err(Error::Protocol("the phone didn't report its applications in time".into()));}}self.listings.clear();@@ -157,6 +172,7 @@ impl WebInspector {pub async fn evaluate(&mut self, page: &Page, expression: &str, timeout: Duration) -> Result<Eval> {let deadline = Instant::now() + timeout;let sender = uuid::Uuid::new_v4().to_string().to_uppercase();+ self.open_sessions.insert(sender.clone());let mut setup = self.page_args(page);setup.insert("WIRSenderKey".into(), sender.clone().into());setup.insert("WIRMessageDataTypeChunkSupportedKey".into(), 0.into());@@ -183,6 +199,7 @@ impl WebInspector {close.insert("WIRSenderKey".into(), session.sender.clone().into());let _ = self.send("_rpc_forwardDidClose:", close).await;self.data.remove(&session.sender);+ self.open_sessions.remove(&session.sender);result}@@ -263,8 +280,14 @@ impl WebInspector {plist::to_writer_binary(&mut body, &Value::Dictionary(msg))?;let mut framed = (body.len() as u32).to_be_bytes().to_vec();framed.extend_from_slice(&body);- self.socket.write_all(&framed).await?;- self.socket.flush().await?;+ let write = async {+ self.socket.write_all(&framed).await?;+ self.socket.flush().await+ };+ // a write cut off half-way leaves the stream out of step: report it as a broken connection (Io)+ tokio::time::timeout(SEND_TIMEOUT, write).await.map_err(|_| {+ std::io::Error::new(std::io::ErrorKind::TimedOut, "the phone stopped reading Web Inspector messages")+ })??;Ok(())}@@ -280,16 +303,20 @@ impl WebInspector {Ok(true)}+ /// Reads one message. Cancel-safe: bytes go into [`Self::rbuf`] first, and a single `read` call loses nothing when+ /// it is cancelled, so a timeout around this never leaves the stream out of stepasync fn read_message(&mut self) -> Result<Dictionary> {- let mut len = [0u8; 4];- self.socket.read_exact(&mut len).await?;- let len = u32::from_be_bytes(len) as usize;- if len > MAX_MESSAGE {- return Err(Error::Protocol(format!("message of {len} bytes")));+ loop {+ if let Some(body) = take_frame(&mut self.rbuf)? {+ return Ok(plist::from_bytes(&body)?);+ }+ let mut chunk = [0u8; 64 * 1024];+ let n = self.socket.read(&mut chunk).await?;+ if n == 0 {+ return Err(std::io::Error::from(std::io::ErrorKind::UnexpectedEof).into());+ }+ self.rbuf.extend_from_slice(&chunk[..n]);}- let mut body = vec![0u8; len];- self.socket.read_exact(&mut body).await?;- Ok(plist::from_bytes(&body)?)}fn unchunk(&mut self, msg: Dictionary) -> Result<Option<Dictionary>> {@@ -332,6 +359,7 @@ impl WebInspector {let dest = arg.get("WIRDestinationKey").and_then(Value::as_string);let data = arg.get("WIRMessageDataKey").and_then(Value::as_data);if let (Some(dest), Some(data)) = (dest, data)+ && self.open_sessions.contains(dest)&& let Ok(v) = serde_json::from_slice::<serde_json::Value>(data){self.data.entry(dest.to_owned()).or_default().push(v);@@ -342,6 +370,22 @@ impl WebInspector {}}+/// One whole frame (4-byte big-endian length, then the body) from the front of `buf`, if it has arrived+fn take_frame(buf: &mut Vec<u8>) -> Result<Option<Vec<u8>>> {+ let Some(len) = buf.get(..4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize) else {+ return Ok(None);+ };+ if len > MAX_MESSAGE {+ return Err(Error::Protocol(format!("message of {len} bytes")));+ }+ if buf.len() < 4 + len {+ return Ok(None);+ }+ let body = buf[4..4 + len].to_vec();+ buf.drain(..4 + len);+ Ok(Some(body))+}+/// Puts split messages back together: parts come as `WIRPartialMessageKey`, the last as `WIRFinalMessageKey`fn unchunk_into(partial: &mut Vec<u8>, msg: Dictionary) -> Result<Option<Dictionary>> {let arg = msg.get("__argument").and_then(Value::as_dictionary);@@ -420,7 +464,7 @@ fn response_for(m: &serde_json::Value, id: u64) -> Option<Result<serde_json::Valreturn None;}Some(match m.get("error") {- Some(e) => Err(Error::Protocol(e["message"].as_str().unwrap_or("command failed").to_owned())),+ Some(e) => Err(Error::Command(e["message"].as_str().unwrap_or("command failed").to_owned())),None => Ok(m["result"].clone()),})}@@ -448,6 +492,25 @@ mod tests {plist::to_value(&v).unwrap().into_dictionary().unwrap()}+ /// Frames come out whole however the bytes arrive, so a read cut off by a timeout loses nothing+ #[test]+ fn frames_survive_partial_reads() {+ let frame = |body: &[u8]| [(body.len() as u32).to_be_bytes().to_vec(), body.to_vec()].concat();+ let stream = [frame(b"hello"), frame(b""), frame(b"world!")].concat();+ let mut buf = Vec::new();+ let mut out = Vec::new();+ for byte in stream {+ buf.push(byte);+ while let Some(f) = take_frame(&mut buf).unwrap() {+ out.push(f);+ }+ }+ assert_eq!(out, [b"hello".to_vec(), Vec::new(), b"world!".to_vec()]);+ assert!(buf.is_empty());+ let mut huge = (u32::MAX).to_be_bytes().to_vec();+ assert!(take_frame(&mut huge).is_err());+ }+#[test]fn split_messages_are_capped() {let part = |n: usize| dict(json!({"__argument": {}})).tap_part(n);@@ -498,7 +561,7 @@ mod tests {assert_eq!(eval_result(&r), Eval::Value(Some(json!(2))));assert!(response_for(&wrapped, 4).is_none());let direct = json!({"id": 1, "error": {"message": "no such method"}});- assert!(matches!(response_for(&direct, 1), Some(Err(Error::Protocol(m))) if m == "no such method"));+ assert!(matches!(response_for(&direct, 1), Some(Err(Error::Command(m))) if m == "no such method"));}#[test]diff --git a/docs/architecture.md b/docs/architecture.mdindex f79ea5e..006994b 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -44,7 +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 的调用排队、自动解锁。+- `iphone-control viewer` 同样显式开启、只绑 127.0.0.1、检查 Host 头:页面看 WDA 的 MJPEG 流(手机上的 9100 端口,经 usbmuxd,只读);点击、滑动、输入、按键是 POST,还要检查 `Origin` 是页面本身、内容类型是 JSON,然后作为普通请求发给守护进程,和 agent 的调用排队、自动解锁。它绑定启动时正在控制的设备:每个操作带上这台的 UDID,守护进程控制的不是这台就拒绝。### 并发模型@@ -58,8 +58,11 @@- 重签分三段:持锁取参数 → 不持锁签名、安装 → 持锁写结果。- Apple ID 会话检查在后台跑。- `status`(`Daemon` 请求)读 watch 通道发布的快照,不碰锁。-- 改变手机状态的请求排队超过 30 秒就放弃,免得点击落到已经变了的屏幕上。+- 安装(`iphone_install_app`)同样不持设备锁;安装之间互斥(`iphone_install_app`、重签、`sign`,锁在 `Device::install`),因为 idevice 把每个 .ipa 都上传到手机上同一个文件。+- Web 请求(`iphone_web_targets`、`iphone_web_eval`)用独立的锁,不占设备锁,慢页面不挡点击和截图。+- 改变手机状态的请求(含 `iphone_web_eval`、`iphone_install_app`)排队超过 30 秒就放弃,免得点击落到已经变了的屏幕上;调用方取消后还在排队的请求也不执行。- 停止信号优先处理(`biased` select):取消排队和执行中的请求、巡检,再停 HID 媒体流、runner、usbmuxd。+- **卡死兜底**:约 10 分钟没有完成任何巡检或请求(设备锁被占死、运行时卡住)时,守护进程自己退出,交给 systemd 或 Docker 重启,免得一直占着设备又不干活。容器另有 healthcheck 和日志大小限制(`compose.yaml`)。## 3. 守护进程状态机@@ -101,17 +104,18 @@| crate | 职责 | 主要依赖 ||---|---|---|-| `ictl-device` | `Device` 句柄:usbmux 发现与监听、lockdown、配对状态、开发者模式状态、隧道(`Tunnel`,持有 HID 会话和显示媒体流)、开发者镜像(含下载缓存)、截图、App 列表/启动/结束、安装 IPA、卸载、崩溃报告、系统日志流(开发者工具)、打开 Web Inspector;所有设备调用都有时限 | `idevice`(锁上游 git 提交) |+| `ictl-device` | `Device` 句柄:usbmux 发现与监听、lockdown、配对状态、开发者模式状态、隧道(`Tunnel`,持有 HID 会话和显示媒体流)、开发者镜像(含下载缓存)、截图、App 列表/启动/结束、安装 IPA、卸载、崩溃报告、系统日志流(`oslog`,开发者工具用)、打开 Web Inspector;所有设备调用都有时限 | `idevice`(锁上游 git 提交) || `ictl-wda` | `WdaRunner`(XCUITestService 启动/停止)、`WdaClient`(会话、点击、W3C actions、keys、source、screenshot、appium settings、锁屏核对)、经 usbmuxd 直连设备 8100 端口的 HTTP 传输(区分连不上和请求超时)、元素树解析(纯函数,可单测) | `idevice`(`xctest`)、`quick-xml` || `ictl-webinspector` | Web Inspector 服务(`com.apple.webinspector`,经 lockdown)的客户端:列出可检查的网页和 WebView、在页面里执行 JavaScript(`Target` 域和旧版直接收命令两种都支持,Promise 用 `Runtime.awaitPromise` 等待)。纯协议,消息解析可单测 | `idevice`、`plist` |+| `ictl-l10n` | 界面文字的语言:取当前语言,`tr!` / `trf!` / `log_tr!` / `log_trf!` 宏(每条文字在代码里原地写成中英一对,见 D12) | 无 || `ictl-protocol` | 控制接口的 `Request`/`Response` 类型和客户端 `call(socket, req, timeout)` | `serde`、`tokio` || `ictl-sign` | Apple ID 登录(含双重认证交互)、会话持久化、注册设备、App ID、描述文件、签名 `.app`/`.ipa`(**包括 `.xctest`**;bundle 逻辑改写自 plume_utils)、签后自检 | vendored 的 `plume_core`/`plume_store`(MPL-2.0/MIT;经 plume_core 用 vendored 的 `omnisette` 和打过补丁的 `apple-codesign`) || `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`、`viewer`、`notify-test`;隐藏的 `debug <ddi\|hid\|screenshot\|soak\|wda\|e2e>` 真机诊断(原第 0 步 spike,不经守护进程;feature `debug-cmds`,默认不编译) | `clap` |+| `ictl-daemon` | `core`(共享状态、请求分发、快照)、`supervise`(巡检、usbmuxd 看护、后台启动 WDA、重签、会话检查)、`tools`(工具的实现、HID 后备)、`devtools`(日志采集、崩溃报告、安装、卸载)、`web`(Web Inspector 工具,保留一条连接复用)、`devices`(列出、选择设备)、`doctor`;通知(Bark/Telegram)、截图缩放/裁剪、控制接口服务端 | 以上全部、`tokio`、`reqwest`、`image` |+| `ictl-mcp` | MCP stdio 服务,`iphone_*` 工具 17 个,开启开发者工具后 23 个:toolkit 的 13 个 + `iphone_wait_for`、`iphone_batch`、`iphone_list_devices`、`iphone_select_device`,以及 6 个可选的开发者工具(D13);操作类工具可带 `then` 顺带返回操作后的界面;经控制接口调用守护进程 | `ictl-protocol`、`ictl-l10n`、`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`、`viewer`(`viewer.rs`:本机网页看实时画面并操作)、`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-device` 依赖 `ictl-webinspector`。`ictl-mcp` 只依赖 `ictl-protocol`,不依赖守护进程和设备层。`apps` 的 `debug`(feature `debug-cmds`)直接调用 `ictl-device`、`ictl-wda`。+依赖方向:`apps` → `ictl-daemon` / `ictl-mcp`,还直接依赖 `ictl-device`、`ictl-sign`;`ictl-daemon` → `ictl-unlock` → `ictl-wda` → `ictl-device`;`ictl-daemon` 还直接依赖 `ictl-webinspector`、`ictl-sign` 和 `ictl-protocol`。`ictl-device` 也依赖 `ictl-webinspector`(打开连接)。`ictl-mcp` 只依赖 `ictl-protocol` 和 `ictl-l10n`,不依赖守护进程和设备层。`ictl-l10n` 不依赖其他 crate,除 `ictl-webinspector` 外都用它。`apps` 的 `debug`(feature `debug-cmds`)直接调用 `ictl-device`、`ictl-wda`。## 5. 截图与坐标@@ -131,7 +135,7 @@| `ddi/` | 开发者镜像缓存(运行时下载的苹果文件);设了 `ICTL_DDI_DIR` 时用那个目录,不用这里 | 默认 | **否,不得分发** || `wda/` | 当前签好的包 `WDA-signed.ipa`。未签名包在镜像的 `/usr/share/iphone-control/WDA-unsigned.ipa`:构建时下载 Appium 官方的未签名真机包(`WebDriverAgentRunner-Runner.zip` v16.15.3,校验 sha256)重新打包。从源码运行时没有镜像,第一次签名前按同一版本下载、校验,转成 `wda/WDA-unsigned.ipa`(`crates/ictl-daemon/src/wda_pkg.rs`,版本与 Dockerfile 由单测核对);计划改为本项目 macOS CI 编译。描述文件只嵌在签好的包里,到期时间记在 `state.json` | 默认 | 未签名包进镜像(从源码运行时在本机下载) || `secrets/passcodes/<UDID>` | 各设备的锁屏密码(仅启用自动解锁时);旧版本的 `secrets/passcode` 在只接着一台时归到那台名下 | 0600 | 否 |-| `logs/` | 日志,按大小轮转;自动解锁停用标记 `UNLOCK-DISABLED`(与 toolkit 一致,便于人工发现;全局,不分设备) | 默认 | 否 |+| `logs/` | 事件日志 `daemon.log`(超过 5 MB 轮转成 `.1`);`usbmuxd.log`(自管 usbmuxd 时的输出,超过一定大小时在启动 usbmuxd 前轮转);自动解锁停用标记 `UNLOCK-DISABLED`(与 toolkit 一致,便于人工发现;全局,不分设备) | 默认 | 否 || `state.json` | 最近一次签名的 Team ID、WDA Bundle ID、描述文件到期时间;选定的设备;最近一台就绪设备的竖放屏幕尺寸和 UDID;上次重签结果 | 默认 | 否 |没有配置文件,通知渠道也一样:配置全部来自环境变量(容器里由 `.env` 注入,从源码运行时由 shell 或 systemd 的 `EnvironmentFile` 给,见 `.env.example`、`crates/ictl-daemon/src/config.rs`),都有默认值;秘密只放文件。diff --git a/docs/decisions.md b/docs/decisions.mdindex a55e43a..ae0563f 100644--- a/docs/decisions.md+++ b/docs/decisions.md@@ -19,6 +19,7 @@- **决定**:用 idevice 的 provider 直连设备端口访问 WDA;外部工具需要时显式开 bridge,只绑 127.0.0.1。- **理由**:WDA 没有认证;toolkit 早期用 `ios forward` 监听了所有网卡,局域网内任何人都能控制手机。+- **补充**:`iphone-control viewer` 用同样的保护模型(显式开启、只绑 127.0.0.1、检查 `Host`),另加操作的 `Origin` 和 JSON 内容类型检查,并绑定启动时正在控制的设备。## D4:WDA 仍然是 Objective-C,在 macOS CI 上编译@@ -62,6 +63,7 @@- **补充(2026-11-01)**:只做向后兼容的扩展,不改已有工具的名字、参数和默认返回。为减少 agent 往返(每次往返是一轮模型推理,真机观察约 8~13 秒,远大于工具本身的 0.3~1.5 秒),操作类工具加可选参数 `then`(`elements` / `screenshot`:等界面稳定后顺带返回界面),并新增 `iphone_wait_for`(等某段文字出现)和 `iphone_batch`(一次执行最多 20 步,出错即停)。多设备的 `iphone_list_devices`、`iphone_select_device` 见 D11。+- **补充**:另有 6 个可选的开发者工具(`IPHONE_CONTROL_DEV_TOOLS=1`,见 D13),不在这里的兼容承诺内。## D11:接多台设备时,同一时间只控制一台@@ -78,3 +80,14 @@- **理由**:D10 承诺已有工具的默认返回不变,所以英文只能是可选项,不设就和以前完全一样。两种语言并排写在原处,改文字时另一种就在旁边,审查时也能逐条对照。- **代价**:每条新文字都要写两种语言;取语言是一次原子读,开销可以忽略。- **重新评估**:多数用户改用英文时,再讨论默认值。++## D13:开发者工具显式开启,开关不是权限边界++- **决定**:日志、崩溃报告、安装、卸载和 Web Inspector 的 6 个工具由 `IPHONE_CONTROL_DEV_TOOLS` 控制,默认关闭。开关只在 MCP 层决定提不提供,守护进程始终接受这些请求。日志只要默认、Error、Fault 级别,不开 Debug、Info。Web Inspector 保留一条连接复用,只有连接层的错误才重开。卸载只接受 Bundle ID 或完整显示名(不分大小写),不像启动、结束 App 那样模糊匹配,并拒绝卸载 WDA。+- **理由**:+ - 默认关闭:不改变默认的工具列表(D10),用不到的 agent 不必多读工具说明。能连上控制接口(权限 0600)的人本来就能操控手机,在守护进程再加一道开关隔离不了什么。+ - 日志:idevice 默认的 `StreamFlags` 带 Debug,手机上每个进程都开始产生 Debug 消息。真机上约 650 行/秒,不开时约 80 行/秒;开着时手势变慢、失败(`crates/ictl-device/src/oslog.rs`)。+ - Web Inspector:刚关闭后新开一条连接约 8 秒,几轮连接、断开后手机不再向新连接报告 Safari,要重启 Safari;保留的连接上列表和执行只要几毫秒(iPhone 15 Pro Max,iOS 27.0.1,`crates/ictl-daemon/src/web.rs`)。+ - 卸载连同数据一起删掉,猜错名字的代价比启动错 App 大得多。+- **代价**:开关挡不住能连上控制接口的本机进程,真正的边界是 socket 权限;从源码运行时开关要设在 MCP 的环境里,守护进程的 env 文件不生效;看不到 Debug、Info 级别的日志;保留的连接要 5 分钟没有请求才关。+- **重新评估**:出现需要在守护进程上按调用方限权的场景时;iOS 能在手机端按进程过滤日志时。diff --git a/docs/dev/macos-verification.md b/docs/dev/macos-verification.mdindex cd020f2..ca6f710 100644--- a/docs/dev/macos-verification.md+++ b/docs/dev/macos-verification.md@@ -1,6 +1,6 @@# macOS 真机验证-> **下面的验证记录早于 0.1.3**:多设备工具(`iphone_list_devices`、`iphone_select_device`,命令 `devices`、`select`)没有在 macOS 上验证过。+> **下面的验证记录早于 0.1.3**:多设备工具(`iphone_list_devices`、`iphone_select_device`,命令 `devices`、`select`)、实时画面 `viewer`、开发者工具(`IPHONE_CONTROL_DEV_TOOLS`)和英文界面(`IPHONE_CONTROL_LANG=en`)都没有在 macOS 上验证过。CI 已经确认项目在 macOS(Apple Silicon)上能编译、链接,单元测试全部通过(PR #12),但单元测试不连手机。这份文档是在一台插着 iPhone 的 Mac 上要跑的步骤,换了 macOS、iOS 版本或机型时可以照着重跑一遍。diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.mdindex 0896d14..60c39eb 100644--- a/docs/dev/regression-cases.md+++ b/docs/dev/regression-cases.md@@ -1,6 +1,6 @@# 必须覆盖的回归用例-#1~#34 来自 toolkit 和本项目早期实际踩过的坑,#35 起是多设备和 HID 横屏。能单测的写单测,不能单测的进真机回归清单:改了设备、时序、WDA 相关的代码,要在真机上重跑相关的用例,并在 PR 里写明跑了哪些、用什么设备和 iOS 版本。+#1~#34 来自 toolkit 和本项目早期实际踩过的坑,#35~#45 是多设备和 HID 横屏,#46 起是实时画面、开发者工具和英文界面。能单测的写单测,不能单测的进真机回归清单:改了设备、时序、WDA 相关的代码,要在真机上重跑相关的用例,并在 PR 里写明跑了哪些、用什么设备和 iOS 版本。| # | 坑 | 正确行为 | 测试方式 ||---|---|---|---|@@ -49,3 +49,16 @@| 43 | Apple 键盘等配件被当成手机:`doctor` 误报 USB 上有设备,usbmuxd 被反复重启 | 只算 iPhone/iPad/iPod(厂商号 05ac 且产品名匹配) | 单测 + 真机 || 44 | 横屏时 WDA 掉线,HID 触摸按竖屏坐标换算,点错位置 | 每次 HID 触摸前重新截图核对横竖;横屏要有 30 秒内且匹配的 WDA 旋转角才发送,否则拒绝,不猜方向;截图和按键不受影响 | 单测(`hid_rotation_requires_fresh_matching_landscape`)+ 真机(iOS 27 横屏下让 WDA 掉线,点击落点正确;守护进程重启后横屏触摸被拒绝) || 45 | WDA 在横屏时就绪,记下的是横屏尺寸,之后 HID 换算错 | state.json 只存竖放尺寸和对应的 UDID,换算时再按当前方向转 | 真机(iOS 27,横屏下启动 WDA,再让它掉线后点击) |+| 46 | 浏览器里的其他网页向 `viewer` 发请求,借它操作手机 | 操作要求 `Origin` 是页面本身、内容类型是 JSON;`Host` 必须是回环地址 | 单测(`actions_need_own_origin_and_json`) |+| 47 | `viewer` 开着时 `select` 到别的设备,点击落到用户没在看的手机上 | 每个操作带启动时的 UDID,守护进程控制的不是这台就拒绝 | 单测(`request_for_another_device_is_refused`)+ 真机(`viewer` 开着时 `select` 另一台,再点击) |+| 48 | 不需要开发者工具的 agent 多读工具说明,或没开时也能调用 | 开关关闭时工具列表还是 17 个,调用这些工具报错并说明要设 `IPHONE_CONTROL_DEV_TOOLS=1` | 单测(工具列表:`toolkit_tools_plus_wait_for_batch_and_devices`);调用被拒:代码审查(`call_tool` 里的判断,还没有单测) |+| 49 | os_log 开着 Debug 时手机上每个进程都产生 Debug 消息(约 650 行/秒),手势变慢、失败 | 只要默认、Error、Fault 级别(约 80 行/秒) | 真机(`iphone_app_logs` 采集时跑回归脚本默认步骤,和不采集时对比耗时) |+| 50 | 日志采集的缓冲把内存撑大(全部进程,每秒几十行) | 行数和总量都封顶(20,000 行、8 MB),单行截断,结果说明最早一行是多久前 | 单测(`buffer_is_bounded_by_size`) |+| 51 | 每次调用重开 Web Inspector 连接:约 8 秒一次,几轮后手机不再报告 Safari,要重启 Safari | 复用一条连接;只有连接层的错误才重开,页面超时或页面报错不断开 | 单测(`only_a_page_timeout_keeps_the_connection`)+ 真机(连续多次 `iphone_web_targets`、`iphone_web_eval` 都快且找得到页面;重启 Safari 后仍能找到) |+| 52 | `iphone_web_eval` 失败后换新连接重试,脚本执行两遍 | 只有列页面(不改手机状态)时才换连接重试,执行脚本不重试 | 代码审查(`web_eval`) |+| 53 | 卸载 App 按模糊匹配,删错 App 连同数据;卸载 WDA 后无法再控制手机 | 只接受 Bundle ID 或完整显示名(不分大小写),空的、部分匹配、同名多个都拒绝并列出候选;拒绝卸载 WDA | 单测(`uninstall_needs_an_exact_name`、`wda_runner_cannot_be_uninstalled`) |+| 54 | 滚动条的标签随系统语言变化,只认中英文时其他语言的滚动条出现在元素列表里 | 按百分比的值和细长的形状认,不看标签 | 单测(`scroll_bars_are_dropped_in_any_language`) |+| 55 | 升级时新旧版本混用:旧客户端按中文开头认结果,旧守护进程不带 `outcome` | 不带语言的请求照旧回中文;`outcome` 可选,没有时按中文开头认 | 单测(`outcome_is_optional_on_the_wire`) |+| 56 | 安装和重签同时进行:idevice 把每个 .ipa 上传到手机上同一个文件(`PublicStaging/idevice.ipa`),互相覆盖 | 安装(`iphone_install_app`、重签、`sign`)互相排队 | 真机(安装和重签同时进行,两个都成功) |+| 57 | iPhone 横屏时 viewer 画面还是竖的、内容是歪的,点击也错位 | iPhone 上 WDA 每个会话开 `mjpegFixOrientation`,帧随界面转正 | 真机:Safari 转横屏,`/stream` 的帧是 2796×1290 且内容正立 |+| 58 | 持设备锁的调用不返回:之后的请求全部排队到过期,进程却还活着,服务管理器不会重启 | 完成巡检或请求时记心跳,约 10 分钟没有心跳就退出(`watchdog.rs`),巡检因为锁被占而跳过时不算 | 单测 a_beat_ends_the_silence |diff --git a/docs/tools.md b/docs/tools.mdindex 8b2d27e..1b51ae2 100644--- a/docs/tools.md+++ b/docs/tools.md@@ -26,7 +26,7 @@ Coordinates are in **points**, the same unit as the pixels of a full-screen `iph| `iphone_press_button` | `button`: `home`, `volume_up`, `volume_down`, `lock` | `home` refuses to act while a system alert is on screen (it would have no effect). `home` is sent as an IOHID AC Home event and waits until the home screen is in front; `lock` presses the power key over IOHID. Each falls back to the XCTest/WebDriverAgent way if it had no effect || `iphone_launch_app` | `app` (bundle id or display name, e.g. `设置`) | Cold-launches the app, or brings it back to where it was if it is already running. Waits until it is in the foreground; returns early and says so if a system alert is blocking it || `iphone_terminate_app` | `app` | Force-quits, like swiping it away in the app switcher; unsaved input is lost. No error if it wasn't running |-| `iphone_open_url` | `url` | Web pages open in Safari; URL schemes open their app |+| `iphone_open_url` | `url` | Web pages open in the default browser; URL schemes open their app |## Several devices@@ -43,18 +43,27 @@ With `IPHONE_CONTROL_DEV_TOOLS=1` in the MCP server's environment, six more tool| Tool | Parameters | Notes ||---|---|---|-| `iphone_app_logs` | `process`, `grep`, `since` (60 s), `limit` (100), `errors_only` | The phone's unified log (os_log) at the default, Error and Fault levels, one line per entry (Debug and Info are left out: streaming them makes every process on the phone produce them and slows it down): seconds ago, `process[pid]`, level, subsystem, message. `process` is an app (name or bundle ID) or a process name. The first call starts recording, so earlier lines aren't available: call it once, reproduce the problem, call it again. Recording keeps the last 20,000 lines and stops after 15 minutes without a call. Read-only |+| `iphone_app_logs` | `process`, `grep`, `since` (seconds, default 60, at most 3600), `limit` (default 100, 1 to 1000), `errors_only` | The phone's unified log (os_log) at the default, Error and Fault levels, one line per entry: seconds ago, `process[pid]`, level, subsystem, message. `process` is an app (name or bundle ID) or a process name. Read-only. See the recording notes below the table || `iphone_crash_reports` | `filter`, `name` | Lists crash reports, newest first (at most 50); with `name`, returns that report (`.ips`, cut at 40,000 characters). Read-only || `iphone_install_app` | `path` | Installs a signed `.ipa` or `.app` from a path on the machine that runs the daemon (inside the container for a container deployment). Destructive: it replaces an installed copy of the same app |-| `iphone_uninstall_app` | `app` | Removes an app and its data. Refuses to remove the WebDriverAgent runner. Destructive |+| `iphone_uninstall_app` | `app` | Removes an app and its data. `app` must be a bundle ID or the full display name (case-insensitive); an empty, partial or ambiguous name is refused and the candidates are listed. Refuses to remove the WebDriverAgent runner. Destructive || `iphone_web_targets` | — | Inspectable web pages and WebViews over the Web Inspector service: Safari tabs and inspectable WebViews in apps (debug builds of Capacitor, Cordova, React Native…). One line each: id, type, app, title, URL. Only apps in the foreground answer; needs Settings → Safari → Advanced → Web Inspector. Read-only |-| `iphone_web_eval` | `expression`, `target`, `timeout` (10 s, at most 60) | Runs JavaScript in a page and returns the result as JSON; a promise is awaited, a DOM node comes back as its description (`"<body>"`). `target` is an id from `iphone_web_targets`, or text in the URL or title; it can be left out when there is one page. Not read-only: a script can change the page |+| `iphone_web_eval` | `expression`, `target`, `timeout` (10 s, at most 60) | Runs JavaScript in a page and returns the result as JSON; a promise is awaited, a DOM node comes back as its description (`"<body>"`). `target` is an id from `iphone_web_targets`, or text in the URL or title; it can be left out when there is one page. Destructive: a script can change the page, submit forms and send requests |++How `iphone_app_logs` records:++- The first call starts recording, so earlier lines aren't available: call it once, reproduce the problem, call it again.+- Debug and Info messages are left out, because streaming them makes every process on the phone produce them and slows it down.+- The buffer keeps the last 20,000 lines and at most 8 MB of text, and each message is cut to 600 characters. When it doesn't reach back as far as `since`, the result says how old its oldest line is.+- Recording stops after 15 minutes without a call, when the daemon switches to another device, and when the device goes offline.++See [SECURITY.md](../SECURITY.md#developer-tools) before turning these tools on.## Auto-unlock and "read-only" tools-When auto-unlock is configured for the controlled device, a locked phone is unlocked first by the action tools and by `iphone_screenshot`, `iphone_list_elements` and `iphone_wait_for`. `iphone_status`, `iphone_list_apps`, `iphone_list_devices`, `iphone_select_device` and `iphone_press_button` with `lock` never unlock it. While WDA is unavailable nothing is unlocked.+When auto-unlock is configured for the controlled device, a locked phone is unlocked first by the action tools and by `iphone_screenshot`, `iphone_list_elements` and `iphone_wait_for`. `iphone_status`, `iphone_list_apps`, `iphone_list_devices`, `iphone_select_device`, the developer tools and `iphone_press_button` with `lock` never unlock it. While WDA is unavailable nothing is unlocked.-Every tool carries MCP annotations: the six read-only tools (`iphone_status`, `iphone_screenshot`, `iphone_list_elements`, `iphone_list_apps`, `iphone_wait_for`, `iphone_list_devices`) are `readOnlyHint: true`. "Read-only" means they don't change what's on screen; with auto-unlock on, the three above still unlock the phone first. The action tools are not read-only, and taps, long-presses, `iphone_terminate_app` and `iphone_batch` are also marked `destructiveHint: true`, since what they hit on screen can delete or send things.+Every tool carries MCP annotations: the six read-only tools (`iphone_status`, `iphone_screenshot`, `iphone_list_elements`, `iphone_list_apps`, `iphone_wait_for`, `iphone_list_devices`) are `readOnlyHint: true`, and with the developer tools on so are `iphone_app_logs`, `iphone_crash_reports` and `iphone_web_targets`, nine in all. "Read-only" means they don't change what's on screen; with auto-unlock on, `iphone_screenshot`, `iphone_list_elements` and `iphone_wait_for` still unlock the phone first. The action tools are not read-only, and taps, long-presses, `iphone_terminate_app` and `iphone_batch` are also marked `destructiveHint: true`, since what they hit on screen can delete or send things. So are `iphone_web_eval`, `iphone_install_app` and `iphone_uninstall_app`.## Returning the screen after an action: `then`@@ -92,13 +101,7 @@ If the MCP client cancels the call, the remaining steps don't run; a request sti## HID fallback-Screenshots, taps, swipes and buttons fall back to CoreDevice HID only when WDA can't be reached, and only on iOS 27 or later. If a WDA request was already sent and the connection then drops or the response is incomplete, nothing is redone over HID, because the action may already have happened: the tool returns an error, and the agent should take a screenshot before trying again.--Touches over HID need the screen size. If WDA is down and the size of this device isn't known (WDA has never run on it, or the last record is for another device), the tool returns an error unless `SCREEN_W`/`SCREEN_H` are set.--HID taps and swipes convert screen coordinates back to native portrait coordinates. Before each touch, the daemon captures a fresh screenshot and checks its orientation. Landscape touches additionally require a matching WDA rotation sample from the last 30 seconds. Without one — notably after restarting the daemon — the touch is refused rather than guessed. Screenshots and hardware keys remain available.--During a WDA outage, keep the device in the same landscape direction: both sides produce the same screenshot dimensions, so a 180° flip cannot be detected without WDA. Wait for WDA to recover before changing sides and touching again.+When WDA can't be reached, screenshots, taps, swipes and buttons fall back to CoreDevice HID (iOS 27 or later). The limits on landscape, screen size and redoing an action are in the [Tools guide](https://derrors.github.io/iphone-control/en/guide/tools#when-wda-is-down-the-hid-fallback).## Tips for agentsdiff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 84906b0..b848f31 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -7,23 +7,11 @@ iphone-control status # current state, signing info, last log linesiphone-control doctor # checks each layer in order and prints a fix for every failure```-The program's own messages are in Simplified Chinese; the Chinese text is quoted below so you can match it.+Messages are in Simplified Chinese by default, and in English with `IPHONE_CONTROL_LANG=en`. The default Chinese wording is quoted below so you can match it.## States-`status` shows one of these on its first line. The daemon re-checks every 10 seconds and moves on by itself once the cause is fixed.--| State (Chinese text) | Meaning | What to do |-|---|---|---|-| 手机未连接 | usbmuxd sees no phone | Check the cable and unlock the phone. Container: make sure no host `usbmuxd` is running (`sudo systemctl mask usbmuxd`). With several devices, a selected device that isn't connected also shows this: check the `选设备` line of `status`, or run `select auto`. See [Phone not detected](#phone-not-detected) |-| 未配对 | No pairing record | Run `setup` and tap *Trust* on the phone |-| 开发者模式未打开 | Developer Mode is off | *Settings → Privacy & Security → Developer Mode*. The toggle only appears after the phone has been seen by a developer tool; running `setup` takes care of that |-| 手机锁屏,隧道建不起来 | The phone has not been unlocked since it restarted (BFU) | Unlock it once by hand. Auto-unlock cannot do this step. The state stays until then and the daemon keeps retrying |-| WDA 还没签名安装 | WebDriverAgent is not installed | Run `sign` (or `setup`) |-| 正在启动 WDA | Starting WebDriverAgent (up to about 2 minutes) | Wait. On iOS 27 and later, tools that only need coordinates (tap, swipe, screenshot, buttons) already work through the HID fallback. In landscape a touch needs a WDA orientation from the last 30 seconds and is refused otherwise; if the screen size isn't known, a touch returns an error. On older iOS, actions fail until WDA is up |-| WDA 卡在手机上的「Enable UI Automation」密码框 | The phone is showing *Enter iPhone passcode for "XCTest"* | Enter the passcode on the phone. This happens after a reboot, and sometimes after the daemon is restarted several times in a row. The daemon retries every 60 seconds and notifies you once |-| WDA 启动失败,稍后重试:… | WebDriverAgent failed for another reason | Read the error after the colon and run `doctor`. Retries back off up to 5 minutes |-| 就绪 | Everything works | — |+`status` shows the state on its first line. What each state means and what to do about it: [FAQ](https://derrors.github.io/iphone-control/en/troubleshoot/faq#states) (English) · [常见问题](https://derrors.github.io/iphone-control/troubleshoot/faq#状态说明) (中文).## Phone not detecteddiff --git a/website/en/guide/cli.md b/website/en/guide/cli.mdindex ddd0dca..a6031c9 100644--- a/website/en/guide/cli.md+++ b/website/en/guide/cli.md@@ -1,6 +1,6 @@# CLI-Every command is `iphone-control <command>`. With Docker, prefix it with `docker exec -it iphone-control`; for a source install and on macOS, run it directly. `--help` shows help, `--version` the version. Output is in Simplified Chinese.+Every command is `iphone-control <command>`. With Docker, prefix it with `docker exec -it iphone-control`; for a source install and on macOS, run it directly. `--help` shows help, `--version` the version. Output is in Simplified Chinese by default; set `IPHONE_CONTROL_LANG=en` for English.## Global options@@ -61,12 +61,12 @@ 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 |+| `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. It belongs to the device controlled when it starts: after switching to another device its actions are refused and you need to run it again. The picture is WDA's MJPEG stream, so there is none until WDA is ready. 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).## Notes-- **Need the daemon running:** `setup`, `status`, `doctor`, `sign`, `resign`, `devices`, `select`, `unlock-reset`, and MCP tool calls.+- **Need the daemon running:** `setup`, `status`, `doctor`, `sign`, `resign`, `devices`, `select`, `unlock-reset`, `wda-bridge`, `viewer`, and MCP tool calls.- **Need an interactive terminal:** `setup`, `login`, `passcode set`; use `-it` with Docker.-- **Environment variables:** the CLI reads the environment of the current shell. For a source install and on macOS, only the daemon loads `~/.config/iphone-control/env`; before `login`, `setup` (if you set `ICTL_ANISETTE_URL`) or `notify-test`, run `set -a; . ~/.config/iphone-control/env; set +a`.+- **Environment variables:** the CLI reads the environment of the current shell. For a source install and on macOS, only the daemon loads `~/.config/iphone-control/env`; before `login`, `setup` (if you set `ICTL_ANISETTE_URL`), `notify-test` or `mcp-config`, run `set -a; . ~/.config/iphone-control/env; set +a`.diff --git a/website/en/guide/configuration.md b/website/en/guide/configuration.mdindex 6f27301..8a320b7 100644--- a/website/en/guide/configuration.md+++ b/website/en/guide/configuration.md@@ -12,13 +12,22 @@ Everything is configured with environment variables, and all of them are optiona| Variable | Default | Meaning ||---|---|---|| `HTTP_PROXY` / `HTTPS_PROXY` | direct | Proxy for Apple, anisette, Developer Disk Image and notification traffic |-| `IPHONE_CONTROL_LANG` | `zh` | Language: `zh` or `en`. Applies to tool descriptions and results, CLI output, logs and notifications. The MCP server and the CLI each send their own setting and the daemon answers in it; logs and notifications follow the daemon's own setting. So for a source install also set it in the MCP client config (`iphone-control mcp-config` includes it) |-| `IPHONE_CONTROL_DEV_TOOLS` | off | `1` adds the [developer tools](./tools#developer-tools-opt-in) to the MCP server: logs, crash reports, installing and removing apps, and Web Inspector (JavaScript in web pages and WebViews). For a source install set it in the MCP client config (`iphone-control mcp-config` includes it when set) |+| `IPHONE_CONTROL_LANG` | `zh` | Language: `zh` or `en`. Applies to tool descriptions and results, CLI output, logs and notifications. The MCP server and the CLI each send their own setting and the daemon answers in it; logs and notifications follow the daemon's own setting. For a source install, see the note below the table |+| `IPHONE_CONTROL_DEV_TOOLS` | off | `1` adds the [developer tools](./tools#developer-tools-opt-in) to the MCP server: logs, crash reports, installing and removing apps, and Web Inspector (JavaScript in web pages and WebViews). See [Security](./security) for the risks. For a source install, see the note below the table || `IPHONE_UDID` | automatic | Pin the device to control. Unset: the controlled device is kept until it disconnects, and you can switch with the `select` command or the `iphone_select_device` tool. When set, switching is refused || `RESIGN_MIN_DAYS` | `2` | Re-sign when fewer days than this remain || `RESIGN_CHECK_HOURS` | `6` | How often to check; it is also checked within a minute after the phone reconnects or you switch devices || `OFFLINE_ALERT_MIN` | `10` | Notify after the phone has been offline this many minutes; `0` disables |+For a source install and on macOS, only the daemon loads `~/.config/iphone-control/env`. The AI client starts the MCP server, which never reads that file, so `IPHONE_CONTROL_LANG` and `IPHONE_CONTROL_DEV_TOOLS` have to go into the MCP configuration. `iphone-control mcp-config` reads the environment of the current shell, so load the file first and the registration command it prints will include them:++```bash+set -a; . ~/.config/iphone-control/env; set +a+iphone-control mcp-config+```++For clients configured with JSON, see [Connect an AI Client](./mcp-clients#claude-desktop-cursor-and-others).+Notification variables: see [Notifications](./notifications).## Advanceddiff --git a/website/en/guide/mcp-clients.md b/website/en/guide/mcp-clients.mdindex 6550850..9fba7a9 100644--- a/website/en/guide/mcp-clients.md+++ b/website/en/guide/mcp-clients.md@@ -38,6 +38,8 @@ For a source install, use the command that `mcp-config` prints, for example:}```+To turn on the [developer tools](./tools#developer-tools-opt-in) or English: when running the binary directly, add `"env": {"IPHONE_CONTROL_DEV_TOOLS": "1", "IPHONE_CONTROL_LANG": "en"}` to the `iphone` entry; with Docker, add `"-e", "IPHONE_CONTROL_DEV_TOOLS=1"` after `"-i"` in `args` (and `"-e", "IPHONE_CONTROL_LANG=en"` for the language).+macOS has no `XDG_RUNTIME_DIR`, so the socket is `~/.local/share/iphone-control/ctl.sock`; again, use what `mcp-config` prints. Claude Desktop's configuration file is `~/Library/Application Support/Claude/claude_desktop_config.json`.::: warning Client and daemon on the same machinediff --git a/website/en/guide/multi-device.md b/website/en/guide/multi-device.mdindex 23053c8..23915e6 100644--- a/website/en/guide/multi-device.md+++ b/website/en/guide/multi-device.md@@ -16,6 +16,7 @@ Agents use `iphone_list_devices` and `iphone_select_device`, which do the same.- Only devices connected over USB can be selected. It tries the UDID, then the device name, then a part of the name that matches exactly one device. If it matches several, you get an error and need the UDID.- WDA takes 10–60 seconds to start after switching; check with `status` (or `iphone_status`) that it's ready. A device that has never had WDA needs [installing](#install-on-a-new-device) first.+- `iphone-control viewer` belongs to the device controlled when it starts: after switching to another device its actions are refused, so run it again to watch and control the new one.## Which device is controlleddiff --git a/website/en/guide/security.md b/website/en/guide/security.mdindex c3d2cea..909e080 100644--- a/website/en/guide/security.md+++ b/website/en/guide/security.md@@ -2,33 +2,32 @@iphone-control is a remote control for a phone: whoever can reach it can do anything the owner can do while the phone is unlocked. Treat the host like the phone itself.-## What is stored and who can reach it+This page has the essentials. What is stored, who can reach it and the details of each risk are in the full [SECURITY.md](https://github.com/Derrors/iphone-control/blob/main/SECURITY.md).-| What | Where | Who can reach it |-|---|---|---|-| Phone control | Control socket (Unix socket, mode 0600) | Root on the host, anyone who can `docker exec` into the container, the same user for a source install |-| Apple ID session, signing key | `account/` in the data directory | Whoever can read the data directory. The Apple ID password is never stored |-| Pairing records | `lockdown/` in the data directory (Docker) | Whoever can read it; it lets the holder talk to the phone over USB without another *Trust* prompt |-| Passcode (only with auto-unlock) | `secrets/passcodes/<UDID>`, **plain text** | Whoever can read the data directory |-| Notification keys | `.env` or `~/.config/iphone-control/env` | Whoever can read that file |+## What is stored++- **The data directory** holds the Apple ID session, the signing key, pairing records and, with auto-unlock on, the passcode in **plain text**. Keep it and its backups as safe as a password. The Apple ID password is never stored.+- **The control socket** is a Unix socket with mode 0600, and whoever can connect to it controls the phone: root on the host, anyone who can `docker exec` into the container, the same user for a source install.+- **Notification keys** are in `.env` or `~/.config/iphone-control/env`.## 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.+- **No network ports.** WDA is reached through usbmuxd. `wda-bridge` and the live `viewer` are explicit opt-ins that bind 127.0.0.1 only, and other web pages in your browser can't act through them. They have no login, though: every local user can use them, so stop them when done.- **Not privileged**: the container only gets USB character devices.- **Auto-unlock is off by default** and disables itself after one wrong attempt.+- **Developer tools are off by default.**- Exact dependency versions, base images pinned by digest, and the WebDriverAgent download is sha256-checked.## Risks to know about- **The container runs as root.** It needs the USB device nodes and must restart usbmuxd after re-plugging (there is no udev in the container).-- **The anisette server.** Apple ID logins need anisette data, which by default comes from a public third-party server (`mac-ani.jkcoxson.com`). It never gets your password, but your logins depend on the identity it provisions and it can see when you log in. To avoid it, run your own [anisette-v3-server](https://github.com/Dadoum/anisette-v3-server) and set `ICTL_ANISETTE_URL`.-- **Use a dedicated Apple ID.** The session and signing key on disk are enough to manage that account's development certificates and devices; a separate account contains the damage if the host is compromised.+- **The anisette server.** Apple ID logins use a public third-party server by default (`mac-ani.jkcoxson.com`). It never gets your password, but it can see when you log in. To avoid it, run your own [anisette-v3-server](https://github.com/Dadoum/anisette-v3-server) and set `ICTL_ANISETTE_URL`.+- **Use a dedicated Apple ID.** A separate account contains the damage if the host is compromised.- **The agent acts with your hands.** It can send messages, buy things and change settings. The server tells agents to ask first for these, but that is an instruction, not enforcement.+- **The developer tools add risk while they are on.** `iphone_web_eval` runs JavaScript in any inspectable page, Safari tabs included: it can read cookies and `localStorage` and send requests as the logged-in user. `iphone_install_app` accepts any path on the machine that runs the daemon. System logs and crash reports go into the agent's context and can contain private data. The `IPHONE_CONTROL_DEV_TOOLS` switch only decides whether the MCP server offers these tools; it is not a permission boundary. Turn it off when done.## DisclaimerThis project is not affiliated with, endorsed by, or sponsored by Apple Inc. iPhone, iOS and Xcode are trademarks of Apple Inc. Only use it with devices and accounts you own or are authorized to control; automating third-party apps may violate their terms; Apple may limit free developer accounts. The software is provided "as is", without warranty of any kind.-Found a security problem? [Report it privately](https://github.com/Derrors/iphone-control/security/advisories/new). Full details: [SECURITY.md](https://github.com/Derrors/iphone-control/blob/main/SECURITY.md).+Found a security problem? [Report it privately](https://github.com/Derrors/iphone-control/security/advisories/new).diff --git a/website/en/guide/tools.md b/website/en/guide/tools.mdindex 075c0d9..d6e1f4f 100644--- a/website/en/guide/tools.md+++ b/website/en/guide/tools.md@@ -1,6 +1,6 @@# Tools-The MCP server provides 17 tools. Coordinates are in **points**, matching the pixels of a full-screen screenshot (430×932 on an iPhone 15 Pro Max), so the agent can tap what it reads off a screenshot. Coordinates follow the screen orientation: after a rotation the same spot has different coordinates, so take a new screenshot. Screen sizes differ per device; an iPad mini 5 is 768×1024 in portrait.+The MCP server provides 17 tools, 23 with the [developer tools](#developer-tools-opt-in). Coordinates are in **points**, matching the pixels of a full-screen screenshot (430×932 on an iPhone 15 Pro Max), so the agent can tap what it reads off a screenshot. Coordinates follow the screen orientation: after a rotation the same spot has different coordinates, so take a new screenshot. Screen sizes differ per device; an iPad mini 5 is 768×1024 in portrait.## Looking at the screen@@ -45,13 +45,15 @@ Set `IPHONE_CONTROL_DEV_TOOLS=1` for the MCP server to get six more tools. They| Tool | What it does ||---|---|-| `iphone_app_logs` | Read the phone's log (default, Error and Fault levels; Debug and Info would slow the phone down), filtered by app or process, text and time. Recording starts with the first call: call it, reproduce the problem, call it again |+| `iphone_app_logs` | Read the phone's log (default, Error and Fault levels; Debug and Info would slow the phone down), filtered by app or process, text and time. Recording starts with the first call: call it, reproduce the problem, call it again. The buffer is limited, and the result says how far back it reaches || `iphone_crash_reports` | List crash reports, or read one || `iphone_install_app` | Install a signed `.ipa` or `.app` (a path on the machine that runs the daemon) |-| `iphone_uninstall_app` | Remove an app and its data; never the WebDriverAgent runner |+| `iphone_uninstall_app` | Remove an app and its data. Takes only a bundle ID or the full display name (case-insensitive); anything else, or a name several apps share, is refused and the candidates are listed. Never the WebDriverAgent runner || `iphone_web_targets` | List inspectable web pages and WebViews (Safari tabs, debug builds of hybrid apps); the app must be in the foreground || `iphone_web_eval` | Run JavaScript in a page and get the result as JSON: faster, cheaper and more accurate than screenshots for web content |+None of these tools unlock the phone. Read [Security](./security) before turning them on.+## See the screen after an action: `then`The tools under *Acting* accept `then`: it waits for the screen to settle and returns it, saving a round trip.diff --git a/website/en/guide/what-is-iphone-control.md b/website/en/guide/what-is-iphone-control.mdindex 9307a6f..e538932 100644--- a/website/en/guide/what-is-iphone-control.md+++ b/website/en/guide/what-is-iphone-control.md@@ -32,7 +32,7 @@ It works as a set of [MCP](https://modelcontextprotocol.io) (Model Context ProtoOther models and iOS versions should work but are untested — [reports](https://github.com/Derrors/iphone-control/issues) are welcome.::: tip Output language-The CLI, `doctor` output and MCP tool results are currently in Simplified Chinese. Agents handle this fine.+The CLI, `doctor` output and MCP tool results are in Simplified Chinese by default; set `IPHONE_CONTROL_LANG=en` for English, see [Configuration](./configuration).:::## Limitationsdiff --git a/website/en/troubleshoot/faq.md b/website/en/troubleshoot/faq.mdindex 7a018d2..2be974e 100644--- a/website/en/troubleshoot/faq.md+++ b/website/en/troubleshoot/faq.md@@ -9,19 +9,19 @@ iphone-control doctor # checks each layer and prints a fix for every failure## States-The program's messages are in Chinese; here is what they mean.+Messages are in Simplified Chinese by default, and in English with `IPHONE_CONTROL_LANG=en`. The table lists both wordings. The daemon re-checks every 10 seconds and moves on by itself once the cause is fixed.| `status` shows | Meaning | What to do ||---|---|---|-| 手机未连接 | usbmuxd sees no phone | Check the cable and unlock the phone; with a usbmuxd on a Linux host, `sudo systemctl mask usbmuxd`. With several devices, a selected device that isn't connected also shows this: check the `选设备` line of `status`, or run `select auto`; see [Several devices](../guide/multi-device) |-| 未配对 | Not paired | Run `setup` and tap *Trust* on the phone |-| 开发者模式未打开 | Developer Mode is off | Run `setup` and follow the prompts |-| 手机锁屏,隧道建不起来 | Not unlocked since the last reboot | Unlock it once by hand; the state stays until then and the daemon keeps retrying |-| WDA 还没签名安装 | WDA not installed | Run `sign` or `setup` |-| 正在启动 WDA | Starting WDA (up to about 2 minutes) | Wait. On iOS 27 and later, taps, swipes and screenshots already work through the HID fallback, but a landscape touch needs an orientation from WDA in the last 30 seconds or it is refused, and an unknown screen size returns an error; see [Tools](../guide/tools#when-wda-is-down-the-hid-fallback). On older iOS, wait for WDA |-| WDA 卡在手机上的「Enable UI Automation」密码框 | The phone asks for the passcode for "XCTest" | Enter the passcode on the phone |-| WDA 启动失败,稍后重试:… | Other failure | Read the error after the colon and run `doctor` |-| 就绪 | Ready | — |+| 手机未连接<br>Phone not connected | usbmuxd sees no phone | Check the cable and unlock the phone; with a usbmuxd on a Linux host, `sudo systemctl mask usbmuxd`. With several devices, a selected device that isn't connected also shows this: check the `选设备` (`Device`) line of `status`, or run `select auto`; see [Several devices](../guide/multi-device) |+| 未配对<br>Not paired | No pairing record | Run `setup` and tap *Trust* on the phone |+| 开发者模式未打开<br>Developer Mode is off | Developer Mode is off | *Settings → Privacy & Security → Developer Mode*. The toggle only appears after the phone has been seen by a developer tool; running `setup` takes care of that |+| 手机锁屏,隧道建不起来<br>The phone is locked, the tunnel can't be opened | Not unlocked since the last reboot | Unlock it once by hand; the state stays until then and the daemon keeps retrying |+| WDA 还没签名安装<br>WDA not signed and installed yet | WDA not installed | Run `sign` or `setup` |+| 正在启动 WDA<br>Starting WDA | Starting WDA (up to about 2 minutes) | Wait. On iOS 27 and later, taps, swipes and screenshots already work through the HID fallback, but a landscape touch needs an orientation from WDA in the last 30 seconds or it is refused, and an unknown screen size returns an error; see [Tools](../guide/tools#when-wda-is-down-the-hid-fallback). On older iOS, wait for WDA |+| WDA 卡在手机上的「Enable UI Automation」密码框<br>WDA is stuck at the “Enable UI Automation” passcode prompt | The phone asks for the passcode for "XCTest" | Enter the passcode on the phone. This happens after a reboot, and sometimes after the daemon is restarted several times in a row. The daemon retries every 60 seconds and notifies you once |+| WDA 启动失败,稍后重试:…<br>WDA failed to start, retrying later: … | Other failure | Read the error after the colon and run `doctor`. Retries back off up to 5 minutes |+| 就绪<br>Ready | Everything works | — |## The phone isn't detecteddiff --git a/website/guide/cli.md b/website/guide/cli.mdindex e44bef3..1766445 100644--- a/website/guide/cli.md+++ b/website/guide/cli.md@@ -61,12 +61,12 @@|---|---|| `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 的操作排队,并先自动解锁。本机任何用户都能连上这个端口,用完就停 |+| `viewer [--port <端口>]` | 在浏览器里看实时画面,地址 `http://127.0.0.1:8200/`(默认端口):点一下是点击,拖动是滑动,按住是长按,另有输入框和硬件键。点击、输入和 MCP 调用一样经守护进程,和 agent 的操作排队,并先自动解锁。绑定启动时正在控制的设备:切换到别的设备后操作会被拒绝,要重新运行。画面来自 WDA 的 MJPEG 流,WDA 没就绪时没有画面。本机任何用户都能连上这个端口,用完就停 |调试用的 `debug` 子命令默认不编译,见[贡献指南](https://github.com/Derrors/iphone-control/blob/main/CONTRIBUTING.md#testing-on-a-real-phone)。## 使用说明-- **要守护进程在运行的:** `setup`、`status`、`doctor`、`sign`、`resign`、`devices`、`select`、`unlock-reset`,以及 MCP 工具调用。+- **要守护进程在运行的:** `setup`、`status`、`doctor`、`sign`、`resign`、`devices`、`select`、`unlock-reset`、`wda-bridge`、`viewer`,以及 MCP 工具调用。- **要在终端里交互运行的:** `setup`、`login`、`passcode set`,Docker 部署要带 `-it`。-- **环境变量:** 命令行读的是当前 shell 的环境。从源码运行和在 macOS 上,`~/.config/iphone-control/env` 只有守护进程会加载;用 `login`、`setup`(如果配了 `ICTL_ANISETTE_URL`)、`notify-test` 前先运行 `set -a; . ~/.config/iphone-control/env; set +a`。+- **环境变量:** 命令行读的是当前 shell 的环境。从源码运行和在 macOS 上,`~/.config/iphone-control/env` 只有守护进程会加载;用 `login`、`setup`(如果配了 `ICTL_ANISETTE_URL`)、`notify-test`、`mcp-config` 前先运行 `set -a; . ~/.config/iphone-control/env; set +a`。diff --git a/website/guide/configuration.md b/website/guide/configuration.mdindex f6f3b7a..04f6fee 100644--- a/website/guide/configuration.md+++ b/website/guide/configuration.md@@ -12,13 +12,22 @@| 变量 | 默认 | 含义 ||---|---|---|| `HTTP_PROXY` / `HTTPS_PROXY` | 直连 | 访问苹果、anisette、开发者镜像、推送通知用的代理 |-| `IPHONE_CONTROL_LANG` | `zh` | 界面语言:`zh` 或 `en`。工具说明和结果、命令行输出、日志、通知都按它。MCP 和命令行各自按自己的设置请求,守护进程按请求的语言回答;日志和通知按守护进程自己的设置。从源码运行时要在 MCP 配置里也设上(`iphone-control mcp-config` 会带上) |-| `IPHONE_CONTROL_DEV_TOOLS` | 关 | 设为 `1` 时 MCP 服务多出[开发者工具](./tools):日志、崩溃报告、安装和卸载 App、Web Inspector(在网页和 WebView 里执行 JavaScript)。从源码运行时要写进 MCP 客户端的配置(设了时 `iphone-control mcp-config` 会带上) |+| `IPHONE_CONTROL_LANG` | `zh` | 界面语言:`zh` 或 `en`。工具说明和结果、命令行输出、日志、通知都按它。MCP 和命令行各自按自己的设置请求,守护进程按请求的语言回答;日志和通知按守护进程自己的设置。从源码运行时见表下说明 |+| `IPHONE_CONTROL_DEV_TOOLS` | 关 | 设为 `1` 时 MCP 服务多出[开发者工具](./tools#开发者工具-显式开启):日志、崩溃报告、安装和卸载 App、Web Inspector(在网页和 WebView 里执行 JavaScript)。风险见[安全与隐私](./security)。从源码运行时见表下说明 || `IPHONE_UDID` | 自动选 | 固定控制哪台设备。不设时自动选:正在控制的那台一直用到它断开;运行中可以用 `select` 命令或 `iphone_select_device` 工具切换。设了就不能切换 || `RESIGN_MIN_DAYS` | `2` | 描述文件剩余不到几天时重签 || `RESIGN_CHECK_HOURS` | `6` | 每隔几小时检查一次;手机重新连上或切换设备后 1 分钟内也查一次 || `OFFLINE_ALERT_MIN` | `10` | 手机离线超过几分钟推送提醒,`0` 不提醒 |+从源码运行和在 macOS 上,`~/.config/iphone-control/env` 只有守护进程会加载,MCP 服务由 AI 客户端拉起,读不到这个文件,所以 `IPHONE_CONTROL_LANG` 和 `IPHONE_CONTROL_DEV_TOOLS` 要写进 MCP 的配置。`iphone-control mcp-config` 读的是当前 shell 的环境变量,先加载再运行,打印的注册命令才会带上它们:++```bash+set -a; . ~/.config/iphone-control/env; set +a+iphone-control mcp-config+```++用 JSON 配置的客户端见[接入 AI 客户端](./mcp-clients#claude-desktop、cursor-等)。+通知相关的变量见[通知](./notifications)。## 高级diff --git a/website/guide/mcp-clients.md b/website/guide/mcp-clients.mdindex 7e7ab4e..64b5de6 100644--- a/website/guide/mcp-clients.md+++ b/website/guide/mcp-clients.md@@ -38,6 +38,8 @@ claude mcp add iphone -s user -- docker exec -i iphone-control iphone-control mc}```+要开启[开发者工具](./tools#开发者工具-显式开启)或英文界面:直接运行时在 `iphone` 这一项里加 `"env": {"IPHONE_CONTROL_DEV_TOOLS": "1", "IPHONE_CONTROL_LANG": "en"}`;Docker 部署时在 `args` 的 `"-i"` 后面加 `"-e", "IPHONE_CONTROL_DEV_TOOLS=1"`(语言同样是 `"-e", "IPHONE_CONTROL_LANG=en"`)。+macOS 上没有 `XDG_RUNTIME_DIR`,socket 在 `~/.local/share/iphone-control/ctl.sock`,同样以 `mcp-config` 打印的为准。Claude Desktop 的配置文件在 `~/Library/Application Support/Claude/claude_desktop_config.json`。::: warning 客户端和守护进程要在同一台机器上diff --git a/website/guide/multi-device.md b/website/guide/multi-device.mdindex 778960b..0533757 100644--- a/website/guide/multi-device.md+++ b/website/guide/multi-device.md@@ -16,6 +16,7 @@ agent 用 `iphone_list_devices` 和 `iphone_select_device`,效果一样。- 只能选 USB 上接着的设备。先比 UDID,再比设备名;设备名包含这段文字且只有一台时也行,对上多台就报错,要用 UDID 指定。- 切换后 WDA 要 10~60 秒才起来,先用 `status`(或 `iphone_status`)确认就绪。没装过 WDA 的设备要先[安装](#给新设备安装)。+- `iphone-control viewer` 绑定启动时正在控制的设备:切换到别的设备后,它的操作会被拒绝,要重新运行才能看和操作新设备。## 控制哪一台diff --git a/website/guide/security.md b/website/guide/security.mdindex 41b2a5c..3891c21 100644--- a/website/guide/security.md+++ b/website/guide/security.md@@ -2,33 +2,32 @@iphone-control 本质上是一个手机遥控器:能访问它的人,就能在手机解锁时做机主能做的任何事。像对待手机本身一样对待运行它的主机。-## 存了什么、谁能访问+这一页是要点。存了什么、谁能访问、每项风险的细节见完整的 [SECURITY.md](https://github.com/Derrors/iphone-control/blob/main/SECURITY.md)。-| 内容 | 位置 | 谁能访问 |-|---|---|---|-| 操控手机 | 控制接口(Unix socket,权限 0600) | 主机 root、能 `docker exec` 进容器的人、从源码运行时的同一用户 |-| Apple ID 会话、开发签名私钥 | 数据目录 `account/` | 能读数据目录的人。Apple ID 密码本身不保存 |-| 配对记录 | 数据目录 `lockdown/`(容器) | 能读数据目录的人;拿到它不用再点「信任」就能经 USB 访问手机 |-| 锁屏密码(仅开启自动解锁时) | 数据目录 `secrets/passcodes/<UDID>`,**明文** | 能读数据目录的人 |-| 通知密钥 | `.env` 或 `~/.config/iphone-control/env` | 能读这个文件的人 |+## 存了什么++- **数据目录**里有 Apple ID 会话、开发签名私钥、配对记录,开启自动解锁时还有**明文**的锁屏密码,要像密码一样保管和备份。Apple ID 密码本身不保存。+- **控制接口**是权限 0600 的 Unix socket,能连上它就能操控手机:主机 root、能 `docker exec` 进容器的人、从源码运行时的同一用户。+- **通知密钥**在 `.env` 或 `~/.config/iphone-control/env` 里。## 默认的保护-- **不开网络端口。** WDA 经 usbmuxd 直连手机。`wda-bridge` 是显式开启的桥接,只绑 127.0.0.1,但 WDA 没有认证,本机任何用户都能连上,用完就停。-- **实时画面也是显式开启的。** `iphone-control viewer` 只绑 127.0.0.1,和 `wda-bridge` 一样检查 `Host` 头;操作还要求 `Origin` 是这个页面本身、请求体是 JSON,所以浏览器里的其他网页借不了它操作手机。但它没有登录:本机任何用户都能经这个端口看屏幕、操作手机,用完就停。+- **不开网络端口。** WDA 经 usbmuxd 直连手机。`wda-bridge` 和实时画面 `viewer` 都要显式开启,只绑 127.0.0.1,浏览器里的其他网页借不了它们操作手机。但它们没有登录,本机任何用户都能用,用完就停。- **容器不用 privileged**,只开放 USB 字符设备。- **自动解锁默认关闭**,输错一次即停用。+- **开发者工具默认关闭**。- 依赖锁定精确版本,基础镜像锁 digest,下载的 WebDriverAgent 核对 sha256。## 需要知道的风险- **容器以 root 运行。** 要读写 USB 设备节点,拔插后还要能重启 usbmuxd(容器里没有 udev)。-- **anisette 服务。** 登录 Apple ID 需要 anisette 数据,默认来自公共的第三方服务(`mac-ani.jkcoxson.com`)。它拿不到你的密码,但你的登录依赖它生成的设备身份,它也能看到你什么时候登录。介意的话自建 [anisette-v3-server](https://github.com/Dadoum/anisette-v3-server),设 `ICTL_ANISETTE_URL`。-- **用专门的 Apple ID。** 磁盘上的会话和签名私钥足以管理这个账号的开发证书和设备;主机被入侵时,专门的账号能把影响限制住。+- **anisette 服务。** 登录 Apple ID 默认用公共的第三方服务(`mac-ani.jkcoxson.com`)。它拿不到你的密码,但能看到你什么时候登录。介意的话自建 [anisette-v3-server](https://github.com/Dadoum/anisette-v3-server),设 `ICTL_ANISETTE_URL`。+- **用专门的 Apple ID。** 主机被入侵时,专门的账号能把影响限制住。- **agent 用你的手在操作。** 它能发消息、付款、改设置。服务端会要求 agent 在这类操作前先问你,但这只是指示,不是强制。+- **开发者工具开着时风险更大。** `iphone_web_eval` 能在任意可检查的页面(含 Safari 标签页)执行 JavaScript,读 cookie 和 localStorage,以已登录身份发请求;`iphone_install_app` 接受运行守护进程的机器上的任意路径;系统日志和崩溃报告会进入 agent 的上下文,可能含隐私。开关 `IPHONE_CONTROL_DEV_TOOLS` 只决定 MCP 提不提供这些工具,不是权限边界。用完就关。## 免责声明本项目与 Apple Inc. 没有任何关联,也未获其认可或赞助。iPhone、iOS、Xcode 是 Apple Inc. 的商标。只在你自己拥有或获得授权的设备和账号上使用;自动操作第三方 App 可能违反其服务条款;苹果可能限制免费开发者账号。本软件按「原样」提供,不提供任何担保。-发现安全问题请[私下报告](https://github.com/Derrors/iphone-control/security/advisories/new),完整说明见 [SECURITY.md](https://github.com/Derrors/iphone-control/blob/main/SECURITY.md)。+发现安全问题请[私下报告](https://github.com/Derrors/iphone-control/security/advisories/new)。diff --git a/website/guide/tools.md b/website/guide/tools.mdindex 39e3d74..b1b6752 100644--- a/website/guide/tools.md+++ b/website/guide/tools.md@@ -1,6 +1,6 @@# 工具一览-MCP 服务提供 17 个工具。坐标单位是**点**,和整屏截图的像素一一对应(iPhone 15 Pro Max 是 430×932),agent 从截图上读到的位置可以直接点。坐标随屏幕方向变化:转屏后同一个位置的坐标不同,要重新截图。不同设备屏幕尺寸不同,iPad mini 5 竖放是 768×1024。+MCP 服务提供 17 个工具,开启[开发者工具](#开发者工具-显式开启)后 23 个。坐标单位是**点**,和整屏截图的像素一一对应(iPhone 15 Pro Max 是 430×932),agent 从截图上读到的位置可以直接点。坐标随屏幕方向变化:转屏后同一个位置的坐标不同,要重新截图。不同设备屏幕尺寸不同,iPad mini 5 竖放是 768×1024。## 看屏幕@@ -45,13 +45,15 @@ MCP 服务提供 17 个工具。坐标单位是**点**,和整屏截图的像| 工具 | 作用 ||---|---|-| `iphone_app_logs` | 读手机的系统日志(默认、Error、Fault 级别;Debug、Info 会拖慢手机,不记录),可按 App 或进程、文字、时间筛选。第一次调用才开始记录:先调一次,复现问题,再调一次 |+| `iphone_app_logs` | 读手机的系统日志(默认、Error、Fault 级别;Debug、Info 会拖慢手机,不记录),可按 App 或进程、文字、时间筛选。第一次调用才开始记录:先调一次,复现问题,再调一次。缓冲有上限,结果会说明覆盖多久 || `iphone_crash_reports` | 列出崩溃报告,或读取其中一份 || `iphone_install_app` | 安装签好名的 `.ipa` 或 `.app`(路径在运行守护进程的机器上) |-| `iphone_uninstall_app` | 卸载 App 及其数据;不会卸载 WebDriverAgent |+| `iphone_uninstall_app` | 卸载 App 及其数据。只接受 Bundle ID 或完整的显示名(不分大小写),对不上或同名的有多个时不卸载,并列出候选;不会卸载 WebDriverAgent || `iphone_web_targets` | 列出可检查的网页和 WebView(Safari 标签页、混合 App 的调试构建);页面所在的 App 要在前台 || `iphone_web_eval` | 在页面里执行 JavaScript,以 JSON 返回结果:读网页内容比截图快、省 token、也更准 |+这些工具都不会自动解锁手机。开启前先看[安全与隐私](./security)。+## 操作后顺带看界面:`then`上面「操作」一节的工具都可以带 `then`,等界面稳定后顺带返回操作后的样子,省一次往返:diff --git a/website/guide/what-is-iphone-control.md b/website/guide/what-is-iphone-control.mdindex 195d816..1a535e4 100644--- a/website/guide/what-is-iphone-control.md+++ b/website/guide/what-is-iphone-control.md@@ -32,7 +32,7 @@ iphone-control 让 AI agent(例如 Claude)操作一台用数据线接在 Lin其他机型和 iOS 版本应该也能用,但还没测过,欢迎[反馈](https://github.com/Derrors/iphone-control/issues)。::: tip 输出语言-命令行、`doctor` 的输出和 MCP 工具返回的文字目前都是简体中文。+命令行、`doctor` 的输出和 MCP 工具返回的文字默认是简体中文,设 `IPHONE_CONTROL_LANG=en` 切换英文,见[配置](./configuration)。:::## 限制diff --git a/website/troubleshoot/faq.md b/website/troubleshoot/faq.mdindex 1035593..5326df0 100644--- a/website/troubleshoot/faq.md+++ b/website/troubleshoot/faq.md@@ -13,12 +13,12 @@ iphone-control doctor # 逐层检查,每项失败都给出修复办法|---|---|---|| 手机未连接 | usbmuxd 看不到手机 | 检查数据线、解锁手机;Linux 宿主机装了 usbmuxd 时 `sudo systemctl mask usbmuxd`。接着多台时,选定的那台没接也显示这个:看 `status` 的「选设备」行,或运行 `select auto`,见[多台设备](../guide/multi-device) || 未配对 | 没有配对记录 | 运行 `setup`,手机上点「信任」 |-| 开发者模式未打开 | — | 运行 `setup`,按提示在手机上打开 |+| 开发者模式未打开 | — | 在手机的 设置 → 隐私与安全性 → 开发者模式 打开。手机被开发者工具连接过才会出现这个开关,运行 `setup` 会处理 || 手机锁屏,隧道建不起来 | 重启后还没解锁过 | 手动解锁一次;解锁前状态一直是这个,守护进程会定期重试 || WDA 还没签名安装 | — | 运行 `sign` 或 `setup` || 正在启动 WDA | 最长约 2 分钟 | 等一下。iOS 27 起期间点击、滑动、截图走 HID 后备,仍可用,但横屏时要 30 秒内从 WDA 拿到过方向,否则拒绝触摸;屏幕尺寸未知时报错,见[工具一览](../guide/tools#wda-不可用时-hid-后备)。更早的 iOS 要等 WDA 起来 |-| WDA 卡在手机上的「Enable UI Automation」密码框 | 手机在等「为 XCTest 输入 iPhone 密码」 | 在手机上输入锁屏密码 |-| WDA 启动失败,稍后重试:… | 其他原因 | 看冒号后的错误,运行 `doctor` |+| WDA 卡在手机上的「Enable UI Automation」密码框 | 手机在等「为 XCTest 输入 iPhone 密码」 | 在手机上输入锁屏密码。手机重启后会出现,连续重启守护进程几次后有时也会。守护进程每 60 秒重试,只通知一次 |+| WDA 启动失败,稍后重试:… | 其他原因 | 看冒号后的错误,运行 `doctor`。重试会退避,最长间隔 5 分钟 || 就绪 | 一切正常 | — |## 手机连不上