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
发布:0.1.3,支持多设备切换并修复 iPad 与 HID 横屏兼容性 (#20)
Qinghe Li6812bee384bd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ba2fbc0..0ce6277 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,32 @@ All notable changes to this project are documented here. The format is based on## [Unreleased]+## [0.1.3] - 2026-11-07++### Upgrade notes++- Auto-unlock passcodes now belong to individual devices. Before upgrading, ensure the only connected device is the one whose passcode was saved by the old version; that legacy passcode is automatically assigned when exactly one device is connected. If its owner is uncertain, clear it with the old version's `passcode clear` before upgrading, then use `passcode set --device <UDID>` for each device. Back up the data directory first.+- Device selection is shared by all clients. Explicit `select` choices survive daemon restarts; automatic selection keeps the current device only while the daemon runs and it remains connected.+- Landscape HID fallback needs a matching WDA rotation sample no older than 30 seconds. Do not flip the device between landscape sides while WDA is unavailable; wait for WDA to recover before doing so.++### Added++- Choose which device to control when several iPhones/iPads are connected: new MCP tools `iphone_list_devices` and `iphone_select_device`, commands `devices` and `select`. The choice is saved in state.json and survives restarts; `select auto` goes back to automatic choice. `IPHONE_UDID`, when set, wins and switching is refused.+- Auto-unlock passcodes are kept per device (`secrets/passcodes/<UDID>`); `passcode set/clear` accept `--device`. A passcode saved by an older version is assigned to the device when exactly one is connected over USB, and isn't used while several are.++### Fixed++- Screen dimensions now follow rotation, preventing stretched screenshots and filtered-out elements near the bottom. iPad landscape system UI coordinates are converted to screen coordinates, using the status bar position to distinguish the two landscape directions.+- Auto-unlock on Touch ID devices now taps “Use Passcode” first; lock-screen detection and iPad delete-key positioning are handled, with numeric keypad layout validation before typing.+- Read the current device's installed WDA provisioning profiles via misagent for `doctor`, `status` and automatic re-signing, rather than relying on another device's last signing record.+- `setup` waits for the daemon to recognise the target device before signing and installing. Offline and pre-iOS-27 diagnostics are corrected; generic WDA launch errors include a first-install developer-trust troubleshooting hint.+- `open_url` waits for a stable foreground app, reducing cold-start black screenshots and transient system services being reported as the target app.+- HID fallback taps and swipes now map landscape coordinates back to the device's native portrait coordinate system. Saved dimensions and reused HID sessions are normalized to portrait. Every fallback touch checks a fresh screenshot; landscape touches need a matching WDA rotation sample no older than 30 seconds and are refused when it is unavailable, including after a daemon restart. Do not flip the device between landscape sides while WDA is unavailable: screenshot dimensions alone cannot detect a 180° change.+- Without `IPHONE_UDID` and with several devices connected, a change in usbmuxd's list order silently switched control to another device (auto-unlock could type one device's passcode into another). The controlled device is now kept until it disconnects.+- With `IPHONE_UDID` set to a device that isn't connected while another one is, usbmuxd was restarted every 30 seconds.+- In the container, a second device plugged in while one was already connected was never picked up by usbmuxd (no udev, so no hotplug events), and usbmuxd wasn't restarted. The number of iPhones/iPads on USB is now compared with the number usbmuxd sees.+- After switching devices, the previous device's app list cache and screen size were still used.+## [0.1.2] - 2026-11-04### Added@@ -46,7 +72,8 @@ First public release.- Docker image (single binary plus Debian's usbmuxd, not privileged) with a generated third-party license list, published to `ghcr.io/derrors/iphone-control` for linux/amd64 and linux/arm64.- Running without Docker, from source or from the prebuilt Linux binaries (x86_64, aarch64): as a regular user with the system usbmuxd, XDG data and socket paths, the unsigned WebDriverAgent downloaded and checksum-verified before the first signing, `mcp-config` printing a direct command, and a systemd user service.-[Unreleased]: https://github.com/Derrors/iphone-control/compare/v0.1.2...HEAD+[Unreleased]: https://github.com/Derrors/iphone-control/compare/v0.1.3...HEAD+[0.1.3]: https://github.com/Derrors/iphone-control/compare/v0.1.2...v0.1.3[0.1.2]: https://github.com/Derrors/iphone-control/compare/v0.1.1...v0.1.2[0.1.1]: https://github.com/Derrors/iphone-control/compare/v0.1.0...v0.1.1[0.1.0]: https://github.com/Derrors/iphone-control/releases/tag/v0.1.0diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex ad4efe1..329921f 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -6,6 +6,32 @@## [Unreleased]+## [0.1.3] - 2026-11-07++### 升级注意事项++- 自动解锁密码改为按设备保存。升级前只连接旧版保存密码所对应的那台设备:仅连接一台时,旧密码会自动归到它名下。若不确定旧密码属于哪台,请先用旧版 `passcode clear` 清除,再升级并分别运行 `passcode set --device <UDID>` 设置。操作前先备份数据目录。+- 所有客户端共享同一台被控设备。显式 `select` 选择会跨守护进程重启保留;自动模式只在进程运行期间、当前设备不断开的情况下保持选择。+- 横屏 HID 后备触摸需要 30 秒内且匹配的 WDA 旋转角。WDA 不可用期间不要从一个横屏方向翻到另一侧;请等 WDA 恢复后再翻转。++### 新增++- 接着多台 iPhone/iPad 时可以选择控制哪一台:新增 MCP 工具 `iphone_list_devices`、`iphone_select_device`,命令 `devices`、`select`。选定的设备写进 state.json,重启后还记得;`select auto` 改回自动选。设了 `IPHONE_UDID` 时以它为准、不能切换。+- 自动解锁密码按设备分开存(`secrets/passcodes/<UDID>`),`passcode set/clear` 可加 `--device`。旧版本的那份密码在 USB 上只接着一台时自动归到那台名下,接着多台时不会用。++### 修复++- 转屏后实时更新屏幕尺寸,避免截图拉伸和屏幕下部元素被过滤;将 iPad 横屏系统界面的竖屏坐标换算为屏幕坐标,按状态栏位置区分两个横屏方向。+- Touch ID 设备自动解锁会先点“使用密码”;补全锁屏识别及 iPad 删除键定位,并在输入前校验数字键布局。+- 经 misagent 读取当前设备已安装的 WDA 描述文件,供 `doctor`、`status` 和自动重签判断到期时间,避免混用另一台设备的签名记录。+- `setup` 在签名安装前等待守护进程识别目标设备;修正设备离线和 iOS 低于 27 时的提示,并为 WDA 启动的笼统错误补充首次安装时信任开发者的排查提示。+- `open_url` 等待前台 App 稳定后返回,减少冷启动时截到黑屏或把短暂系统服务当成目标 App 的情况。+- HID 后备路线的点击、滑动会把横屏坐标换算回设备原生的竖屏坐标;持久化尺寸和复用的 HID 会话都按竖屏归一化。每次后备触摸前重新截图核对方向;横屏还需 30 秒内且匹配的 WDA 旋转角,缺失时(包括守护进程刚重启)拒绝触摸。WDA 不可用期间不要从一个横屏方向翻到另一个:仅凭截图宽高无法识别 180° 翻转。+- 没设 `IPHONE_UDID`、接着多台时,usbmuxd 列表顺序变了会悄悄换成控制另一台(自动解锁可能把一台的密码输进另一台)。现在正在控制的那台一直用到它断开。+- 设了 `IPHONE_UDID` 而那台没接、另一台接着时,usbmuxd 每 30 秒被重启一次。+- 容器里已经接着一台时再插一台,usbmuxd 认不到新的那台(没有 udev,收不到热插拔),也不会被重启。现在比较 USB 上和 usbmuxd 认到的 iPhone/iPad 台数。+- 换设备后还用上一台的 App 列表缓存和屏幕尺寸。+## [0.1.2] - 2026-11-04### 新增@@ -44,7 +70,8 @@- `setup`、`doctor`、`status`、`mcp-config`、`wda-bridge`、`notify-test` 命令。- Docker 镜像(非 privileged,linux/amd64、linux/arm64);也可不用 Docker,从源码或预编译二进制以普通用户运行,附 systemd 用户服务。-[Unreleased]: https://github.com/Derrors/iphone-control/compare/v0.1.2...HEAD+[Unreleased]: https://github.com/Derrors/iphone-control/compare/v0.1.3...HEAD+[0.1.3]: https://github.com/Derrors/iphone-control/compare/v0.1.2...v0.1.3[0.1.2]: https://github.com/Derrors/iphone-control/compare/v0.1.1...v0.1.2[0.1.1]: https://github.com/Derrors/iphone-control/compare/v0.1.0...v0.1.1[0.1.0]: https://github.com/Derrors/iphone-control/releases/tag/v0.1.0diff --git a/Cargo.lock b/Cargo.lockindex b8f7240..b21adda 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1967,7 +1967,7 @@ dependencies = [[[package]]name = "ictl-daemon"-version = "0.1.2"+version = "0.1.3"dependencies = ["anyhow","base64 0.23.1",@@ -1987,7 +1987,7 @@ dependencies = [[[package]]name = "ictl-device"-version = "0.1.2"+version = "0.1.3"dependencies = ["idevice","plist",@@ -2001,7 +2001,7 @@ dependencies = [[[package]]name = "ictl-mcp"-version = "0.1.2"+version = "0.1.3"dependencies = ["anyhow","ictl-protocol",@@ -2012,7 +2012,7 @@ dependencies = [[[package]]name = "ictl-protocol"-version = "0.1.2"+version = "0.1.3"dependencies = ["libc","serde",@@ -2022,7 +2022,7 @@ dependencies = [[[package]]name = "ictl-sign"-version = "0.1.2"+version = "0.1.3"dependencies = ["plist","plume_core",@@ -2035,7 +2035,7 @@ dependencies = [[[package]]name = "ictl-unlock"-version = "0.1.2"+version = "0.1.3"dependencies = ["ictl-wda","serde_json",@@ -2047,7 +2047,7 @@ dependencies = [[[package]]name = "ictl-wda"-version = "0.1.2"+version = "0.1.3"dependencies = ["base64 0.23.1","ictl-device",@@ -2258,7 +2258,7 @@ dependencies = [[[package]]name = "iphone-control"-version = "0.1.2"+version = "0.1.3"dependencies = ["anyhow","clap",diff --git a/Cargo.toml b/Cargo.tomlindex 082b98f..1628ea7 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -15,7 +15,7 @@ members = [exclude = ["vendor"][workspace.package]-version = "0.1.2"+version = "0.1.3"edition = "2024"# rmcp 3.8 要求 1.88;Impactor/idevice 用 edition 2024rust-version = "1.88"@@ -41,6 +41,7 @@ idevice = { version = "=0.1.68", default-features = false, features = ["cryptexd","tss","installation_proxy",+ "misagent","xctest",] }rmcp = { version = "=3.8.0", features = ["server", "transport-io"] }diff --git a/README.md b/README.mdindex d1af16d..688c9c1 100644--- a/README.md+++ b/README.md@@ -50,7 +50,7 @@ iphone-control does it all in **one Rust binary** on Linux or macOS, built on [i## Features<p align="center">- <img src="docs/images/features.svg" alt="One binary, 15 MCP tools, fewer round trips, runs unattended, HID fallback, doctor and alerts" width="900">+ <img src="docs/images/features.svg" alt="One binary, 17 MCP tools, fewer round trips, runs unattended, HID fallback, doctor and alerts" width="900"></p>- **See and touch the screen**: screenshots with region zoom, tap, swipe, long-press, text input (including Chinese), hardware buttons@@ -79,7 +79,7 @@ claude mcp add iphone -s user -- docker exec -i iphone-control iphone-control mc**macOS** (Docker can't pass USB through on a Mac, so run the binary directly)```bash-V=v0.1.2 # latest release+V=v0.1.3 # latest releasecurl -fsSL https://github.com/Derrors/iphone-control/releases/download/$V/iphone-control-$V-macos-arm64.tar.gz | tar xzmkdir -p ~/.local/bin && install -m 755 iphone-control-$V-macos-arm64/iphone-control ~/.local/bin/echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zprofile && source ~/.zprofile@@ -121,7 +121,8 @@ Run them as `docker exec -it iphone-control iphone-control <command>`, or direct| `setup` | Guided setup; re-run any time || `login` | Sign in to the Apple ID again when the session expires || `resign [--force]` | Re-sign WebDriverAgent if it expires soon (or now) |-| `passcode set\|clear` | Turn auto-unlock on or off |+| `passcode set\|clear` | Turn auto-unlock on or off for a device (passcodes are kept per device) |+| `devices` / `select <UDID\|name\|auto>` | List connected devices / switch which one is controlled || `notify-test [event]` | Send test notifications || `mcp-config` | Print the command that registers the MCP server |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex ff779c2..5b5e9a5 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -50,7 +50,7 @@ iphone-control 在 Linux 或 macOS 上用**一个 Rust 二进制**把这些事## 功能特性<p align="center">- <img src="docs/images/features.zh-CN.svg" alt="一个二进制、15 个 MCP 工具、少走往返、无人值守、HID 后备、诊断与通知" width="900">+ <img src="docs/images/features.zh-CN.svg" alt="一个二进制、17 个 MCP 工具、少走往返、无人值守、HID 后备、诊断与通知" width="900"></p>- **看屏幕、点屏幕**:截图(可放大某块区域)、点击、滑动、长按、输入文字(支持中文)、硬件按键@@ -79,7 +79,7 @@ claude mcp add iphone -s user -- docker exec -i iphone-control iphone-control mc**macOS**(Mac 上的 Docker 不能直通 USB,直接运行二进制)```bash-V=v0.1.2 # 最新版本号+V=v0.1.3 # 最新版本号curl -fsSL https://github.com/Derrors/iphone-control/releases/download/$V/iphone-control-$V-macos-arm64.tar.gz | tar xzmkdir -p ~/.local/bin && install -m 755 iphone-control-$V-macos-arm64/iphone-control ~/.local/bin/echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zprofile && source ~/.zprofile@@ -121,7 +121,8 @@ iphone-control mcp-config # 打印 `claude mcp add` 命令,复制运行| `setup` | 安装向导,随时可以重新运行 || `login` | Apple ID 会话失效时重新登录 || `resign [--force]` | 快过期才重签 WebDriverAgent(或立即重签) |-| `passcode set\|clear` | 开启或关闭自动解锁 |+| `passcode set\|clear` | 开启或关闭一台设备的自动解锁(密码按设备分开存) |+| `devices` / `select <UDID\|设备名\|auto>` | 列出接着的设备 / 切换控制哪一台 || `notify-test [事件]` | 发送测试通知 || `mcp-config` | 打印注册 MCP 的命令 |diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex 2cd6a70..95798fb 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -63,6 +63,13 @@ enum Command {},/// 自动解锁因输错被停用后,核对密码再恢复UnlockReset,+ /// 列出 USB 上接着的设备,标出正在控制哪台+ Devices,+ /// 改为控制另一台设备,重启后还记得;auto 改回自动选(正在控制的那台断开才换)+ Select {+ /// UDID、设备名或 auto+ device: String,+ },/// 显式把 WDA 桥接到 127.0.0.1 供外部工具使用(默认不监听任何端口)WdaBridge {#[arg(long, default_value_t = 8100)]@@ -78,10 +85,22 @@ enum Command {},}+/// 锁屏密码按设备分开存:一台的密码不会输进另一台#[derive(Subcommand)]enum PasscodeAction {- Set,- Clear,+ Set {+ /// 哪台设备(UDID 或设备名);不给就是守护进程正在控制的那台+ #[arg(long)]+ device: Option<String>,+ },+ Clear {+ /// 哪台设备(UDID 或设备名);不给就是守护进程正在控制的那台+ #[arg(long)]+ device: Option<String>,+ /// 删掉所有设备的密码+ #[arg(long, conflicts_with = "device")]+ all: bool,+ },}#[tokio::main]@@ -118,9 +137,11 @@ async fn main() -> anyhow::Result<()> {Command::Login { email } => login(&cli.data_dir, email).await,Command::Sign => print_text(&cli.socket, Request::Resign { force: true }).await,Command::Resign { force } => print_text(&cli.socket, Request::Resign { force }).await,- Command::Passcode { action } => passcode(&cli.data_dir, action),+ Command::Passcode { action } => passcode(&cli.data_dir, &cli.socket, action).await,Command::UnlockReset => print_text(&cli.socket, Request::UnlockReset).await,- Command::WdaBridge { port } => wda_bridge(port).await,+ Command::Devices => print_text(&cli.socket, Request::ListDevices).await,+ Command::Select { device } => print_text(&cli.socket, Request::SelectDevice { device }).await,+ Command::WdaBridge { port } => wda_bridge(&cli.socket, port).await,Command::Debug(args) => debug::run(env_nonempty("IPHONE_UDID").as_deref(), args).await,Command::NotifyTest { event } => notify_test(&cli.data_dir, event.as_deref()).await,}@@ -237,10 +258,34 @@ async fn status(socket: &Path) -> anyhow::Result<()> {if let Some(d) = &s.device {println!("手机 {} {} iOS {}", d.udid, d.product_type, d.product_version);}+ let current = s.device.as_ref().map(|d| d.udid.as_str());+ let others: Vec<String> =+ s.devices.iter().filter(|d| Some(d.udid.as_str()) != current).map(ictl_daemon::core::device_label).collect();+ if !others.is_empty() {+ println!("另外接着 {}(iphone-control select 切换)", others.join("、"));+ }+ match (&s.pinned, s.pinned_by_env) {+ (Some(p), true) => println!("选设备 IPHONE_UDID 固定为 {p}"),+ (Some(p), false) => println!("选设备 选定了 {p}(iphone-control select auto 改回自动选)"),+ (None, _) if !others.is_empty() => println!("选设备 自动(正在控制的那台断开才换)"),+ (None, _) => {}+ }let p = &s.persisted;println!("WDA {}", p.wda_bundle.as_deref().unwrap_or("未签名"));- if let Some(left) = p.profile_left() {- println!("描述文件 还剩 {} 小时", left.as_secs() / 3600);+ match &s.device_profile {+ ictl_daemon::core::DeviceProfile::Missing => {+ println!("描述文件 这台手机上没有装当前 Apple ID 签的 WDA(iphone-control setup)")+ }+ dp => {+ if let Some(left) = dp.left(p) {+ let whose = if matches!(dp, ictl_daemon::core::DeviceProfile::Expires(_)) {+ "手机上的"+ } else {+ "上次签的"+ };+ println!("描述文件 {whose}还剩 {} 小时", left.as_secs() / 3600);+ }+ }}if let Some(r) = &p.last_resign {println!("上次重签 {r}");@@ -328,15 +373,64 @@ async fn login(data_dir: &Path, email: Option<String>) -> anyhow::Result<()> {Ok(())}-fn passcode(data_dir: &Path, action: PasscodeAction) -> anyhow::Result<()> {+/// 命令要针对哪台设备:`IPHONE_UDID` > 守护进程正在控制的(或选定的)> USB 上唯一的一台。+/// 给了 `query`(UDID 或设备名)就在接着的设备里找+async fn target_device(socket: &Path, query: Option<&str>) -> anyhow::Result<ictl_device::DeviceInfo> {+ let snap = snapshot(socket).await.ok();+ let mut infos = snap.as_ref().map(|s| s.devices.clone()).unwrap_or_default();+ if infos.is_empty() {+ for d in ictl_device::list_devices().await.unwrap_or_default() {+ let i = ictl_device::Device::from_usb(&d).info().await.unwrap_or_default();+ infos.push(ictl_device::DeviceInfo { udid: d.udid, ..i });+ }+ }+ let pick = |u: &str| {+ infos+ .iter()+ .find(|d| d.udid.eq_ignore_ascii_case(u))+ .cloned()+ .unwrap_or_else(|| ictl_device::DeviceInfo { udid: u.to_owned(), ..Default::default() })+ };+ if let Some(q) = query {+ let i = ictl_daemon::devices::resolve_device(&infos, q).map_err(anyhow::Error::msg)?;+ return Ok(infos[i].clone());+ }+ if let Some(u) = env_nonempty("IPHONE_UDID") {+ return Ok(pick(&u));+ }+ if let Some(s) = &snap {+ if let Some(d) = &s.device {+ return Ok(d.clone());+ }+ if let Some(p) = &s.pinned {+ return Ok(pick(p));+ }+ }+ match &infos[..] {+ [one] => Ok(one.clone()),+ [] => bail!("没接设备:用数据线接好并解锁"),+ _ => bail!("接着 {} 台设备,不知道是哪台:先用 iphone-control select 选一台,或加 --device 指定", infos.len()),+ }+}++async fn passcode(data_dir: &Path, socket: &Path, action: PasscodeAction) -> anyhow::Result<()> {use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};- let path = ictl_daemon::Config::from_env(data_dir).passcode_file();+ let cfg = ictl_daemon::Config::from_env(data_dir);match action {- PasscodeAction::Clear => {- let _ = std::fs::remove_file(&path);- println!("已删除锁屏密码,自动解锁关闭。");+ PasscodeAction::Clear { all: true, .. } => {+ let _ = std::fs::remove_dir_all(cfg.passcodes_dir());+ let _ = std::fs::remove_file(cfg.legacy_passcode_file());+ println!("已删除所有设备的锁屏密码,自动解锁关闭。");+ }+ PasscodeAction::Clear { device, .. } => {+ let d = target_device(socket, device.as_deref()).await?;+ let _ = std::fs::remove_file(cfg.passcode_file_for(&d.udid));+ println!("已删除 {} 的锁屏密码,这台的自动解锁关闭。", ictl_daemon::core::device_label(&d));}- PasscodeAction::Set => {+ PasscodeAction::Set { device } => {+ let d = target_device(socket, device.as_deref()).await?;+ let path = cfg.passcode_file_for(&d.udid);+ println!("设备:{}", ictl_daemon::core::device_label(&d));println!("自动解锁:锁屏后,MCP 操作前会用这个密码解锁手机。");println!("风险:能登录这台机器、或能调用这个 MCP 的人,都能解锁你的手机。");println!("保护:每按一位都核对;整串输完仍锁着就停用自动解锁并推送通知,不会累计输错。只支持纯数字。");@@ -351,7 +445,7 @@ fn passcode(data_dir: &Path, action: PasscodeAction) -> anyhow::Result<()> {// mode() 只在新建时生效:已有文件也收紧f.set_permissions(std::fs::Permissions::from_mode(0o600))?;f.write_all(p.as_bytes())?;- println!("已保存。别忘了在手机上把「自动锁定」从「永不」改回较短时间。");+ println!("已保存(只用于这台设备)。别忘了在手机上把「自动锁定」从「永不」改回较短时间。");}}Ok(())@@ -388,9 +482,11 @@ async fn setup(cli: &Cli) -> anyhow::Result<()> {if !found {bail!("10 分钟内没检测到手机:用数据线接好并解锁手机");}- let udid = env_nonempty("IPHONE_UDID");+ // 和守护进程控制同一台:第 5 步的签名安装是守护进程对它正在控制的那台做的+ let target = target_device(socket, None).await?;+ let udid = Some(target.udid.clone());let device = Device::find(udid.as_deref()).await?;- println!(" 手机 {}", device.udid);+ println!(" 手机 {}", ictl_daemon::core::device_label(&target));println!("[2/6] 配对");if device.paired().await? {@@ -441,6 +537,18 @@ async fn setup(cli: &Cli) -> anyhow::Result<()> {}println!("[5/6] 注册设备、签名 WDA 并安装到手机(手机要保持解锁)");+ // 前几步直接问 usbmuxd,重签却由守护进程做:它每 10 秒巡检一次才认到手机。手机刚重启完、usbmuxd 刚重启时+ // 这里会先看到手机,马上请求重签就报「手机未连接」,所以先等守护进程认到同一台+ let target = device.udid.clone();+ let seen = wait_until(Duration::from_secs(60), Duration::from_secs(2), || async {+ snapshot(socket).await.is_ok_and(|s| {+ s.state != ictl_daemon::machine::DeviceState::Absent && s.device.as_ref().is_none_or(|d| d.udid == target)+ })+ })+ .await;+ if !seen {+ bail!("守护进程 1 分钟内没认到手机 {},运行 iphone-control doctor 看看卡在哪", device.udid);+ }print_text(socket, Request::Resign { force: true }).await?;println!("[6/6] 等待 WDA 启动");@@ -463,9 +571,10 @@ async fn setup(cli: &Cli) -> anyhow::Result<()> {/// 显式开启:127.0.0.1:port → 手机上的 WDA 8100。只绑本机回环地址。/// 容器用 host 网络,所以这就是宿主机的回环地址:本机的其他用户、浏览器里的网页都能访问到,而 WDA 没有认证。/// 浏览器那条路(DNS rebinding)靠检查 Host 头挡住;本机其他用户挡不住,用完就停。-async fn wda_bridge(port: u16) -> anyhow::Result<()> {- let udid = env_nonempty("IPHONE_UDID");- let device = ictl_device::Device::find(udid.as_deref()).await?;+async fn wda_bridge(socket: &Path, port: u16) -> anyhow::Result<()> {+ // 和守护进程控制同一台(WDA 只在那台上跑着)+ let target = target_device(socket, None).await?;+ let device = ictl_device::Device::find(Some(&target.udid)).await?;let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?;println!("WDA 桥接 127.0.0.1:{port} → 手机 {} 的 8100 端口(Ctrl-C 停止)", device.udid);println!("注意:本机所有用户都能经这个端口控制手机(WDA 没有认证),用完就停掉。");diff --git a/crates/ictl-daemon/src/config.rs b/crates/ictl-daemon/src/config.rsindex 7bdb7ba..8e1c59c 100644--- a/crates/ictl-daemon/src/config.rs+++ b/crates/ictl-daemon/src/config.rs@@ -9,7 +9,8 @@ use ictl_device::ScreenSize;pub struct Config {pub data_dir: PathBuf,pub socket: PathBuf,- /// 指定要控制的手机;None 用第一台+ /// 固定要控制的手机(`IPHONE_UDID`);None 时可以在运行中选(见 [`crate::core::Persisted::selected_udid`]),+ /// 都没选就用第一台pub udid: Option<String>,/// 由守护进程拉起并看护 usbmuxd。默认以 root 运行(容器)时为 true;普通用户拉起的 usbmuxd 碰不到 USB,/// 改用系统的 usbmuxd 服务。宿主机以 root 运行、又已有 usbmuxd 服务时设 ICTL_MANAGE_USBMUXD=0@@ -112,9 +113,19 @@ impl Config {pub fn ddi_cache(&self) -> PathBuf {self.ddi_dir.clone().unwrap_or_else(|| self.data_dir.join("ddi"))}- pub fn passcode_file(&self) -> PathBuf {+ /// 旧版本的锁屏密码:只有一份,不知道是哪台设备的。USB 上只接着一台时归到那台名下(见+ /// [`crate::core::Daemon::adopt_legacy_passcode`]),接着多台时不用,免得把一台的密码输进另一台+ pub fn legacy_passcode_file(&self) -> PathBuf {self.data_dir.join("secrets/passcode")}+ pub fn passcodes_dir(&self) -> PathBuf {+ self.data_dir.join("secrets/passcodes")+ }+ /// 这台设备的锁屏密码。UDID 来自 usbmuxd,只有字母、数字和 `-`;别的字符换掉,不让它变成路径+ pub fn passcode_file_for(&self, udid: &str) -> PathBuf {+ let name: String = udid.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' { c } else { '_' }).collect();+ self.passcodes_dir().join(name)+ }pub fn unlock_disabled_flag(&self) -> PathBuf {self.logs().join("UNLOCK-DISABLED")}diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex 9ff8e32..32a1ccc 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -13,7 +13,7 @@ use std::path::Path;use std::sync::Arc;use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};-use ictl_device::{AppInfo, Device, DeviceError, DeviceInfo, ScreenSize, Tunnel};+use ictl_device::{AppInfo, Device, DeviceError, DeviceInfo, Rotation, ScreenSize, Tunnel, UsbDevice};use ictl_unlock::UnlockConfig;use ictl_wda::{WdaClient, WdaRunner, http::DeviceTransport};use serde::{Deserialize, Serialize};@@ -42,8 +42,14 @@ pub struct Persisted {pub wda_bundle: Option<String>,/// 描述文件到期时间(Unix 秒)pub profile_expires: Option<u64>,+ /// 设备竖放时的屏幕尺寸(WDA 不可用时 HID 换算坐标用;旧版本可能存的是横屏尺寸,用的时候都先转成竖放)pub screen: Option<ScreenSize>,+ /// `screen` 是哪台设备的;换了设备就不能拿来给 HID 换算坐标+ pub screen_udid: Option<String>,pub last_resign: Option<String>,+ /// 运行中选定要控制的设备(`iphone-control select`、`iphone_select_device`);None 是自动选。+ /// 设了 `IPHONE_UDID` 时以它为准,这个不起作用+ pub selected_udid: Option<String>,}impl Persisted {@@ -72,12 +78,68 @@ impl Persisted {}}+/// 这台手机上装着的 WDA 描述文件(经 misagent 读)。[`Persisted`] 只记最近一次签名:给别的手机签过之后,+/// 它的到期时间不是这台手机上那份的(这台装的还是更早签的),按它判断会该重签时不重签+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+pub enum DeviceProfile {+ /// 还没读(手机没接、刚接上还没配对)+ #[default]+ NotChecked,+ /// 读不出来:按签名记录算+ Unknown(String),+ /// 手机上没有当前 Apple ID 给 WDA 签的、包含这台手机的描述文件:没装过 WDA,或装的是别的账号签的+ Missing,+ /// 到期时间(Unix 秒)+ Expires(u64),+}++impl DeviceProfile {+ /// 还剩多久:读到了用手机上的;还没读、读不出来按签名记录;手机上没有返回 None+ pub fn left(&self, persisted: &Persisted) -> Option<Duration> {+ match self {+ Self::Expires(e) => {+ let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();+ Some(Duration::from_secs(e.saturating_sub(now)))+ }+ Self::Missing => None,+ Self::NotChecked | Self::Unknown(_) => persisted.profile_left(),+ }+ }+}++/// 从手机上的描述文件(原始内容)里挑 WDA 的:app-id 是「团队 ID.WDA Bundle ID」(不知道团队 ID 时只看 Bundle ID)、+/// 设备列表里有这台手机,取最晚到期的那份。装过几次会留下几份,旧的过期了也还在+pub fn wda_profile_expiry(profiles: &[Vec<u8>], team: Option<&str>, bundle: &str, udid: &str) -> Option<SystemTime> {+ profiles+ .iter()+ .filter_map(|p| ictl_sign::Profile::parse(p))+ .filter(|p| {+ p.application_identifier+ .split_once('.')+ .is_some_and(|(t, b)| b == bundle && team.is_none_or(|team| t == team))+ && p.devices.iter().any(|d| d.eq_ignore_ascii_case(udid))+ })+ .map(|p| p.expires)+ .max()+}+/// 快照:`iphone-control status` 显示#[derive(Debug, Clone, Serialize, Deserialize)]pub struct Snapshot {pub state: DeviceState,pub device: Option<DeviceInfo>,+ /// USB 上接着的全部设备(读不到名字的只有 UDID)+ #[serde(default)]+ pub devices: Vec<DeviceInfo>,+ /// 选定的设备:`IPHONE_UDID` 或运行中选的;None 是自动选+ #[serde(default)]+ pub pinned: Option<String>,+ #[serde(default)]+ pub pinned_by_env: bool,pub persisted: Persisted,+ /// 当前这台手机上的 WDA 描述文件+ #[serde(default)]+ pub device_profile: DeviceProfile,pub auto_unlock: bool,pub unlock_disabled: bool,pub notify_configured: bool,@@ -86,11 +148,19 @@ pub struct Snapshot {pub(crate) struct Inner {pub persisted: Persisted,+ /// 当前这台手机上的 WDA 描述文件;换连接、离线时清成 NotChecked+ pub device_profile: DeviceProfile,pub state: DeviceState,pub device: Option<Device>,pub info: Option<DeviceInfo>,+ /// 最近一轮巡检时 USB 上接着的全部设备+ pub connected: Vec<UsbDevice>,+ /// 各设备的名字、型号(第一次见到时读一次)+ 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 的任务(含挂开发者镜像),巡检里收结果@@ -143,8 +213,32 @@ pub(crate) async fn drop_tunnel(g: &mut Inner) {}}-pub(crate) fn wda_down(state: &DeviceState) -> String {- format!("WDA 不可用({}),守护进程一般 1~2 分钟内会拉起;截图/点击/滑动/按键可照常用", state.describe())+/// 一台设备的简短说明:`名字(型号 iOS 版本,UDID)`;读不到名字时只有 UDID+pub fn device_label(i: &DeviceInfo) -> String {+ if i.name.is_empty() && i.product_type.is_empty() {+ i.udid.clone()+ } else {+ format!("{}({} iOS {},{})", i.name, i.product_type, i.product_version, i.udid)+ }+}++/// WDA 不可用时的说明。HID 后备路线靠 iOS 27 起才有的 CoreDevice 屏幕服务,低版本不能说「照常用」+pub(crate) fn wda_down(state: &DeviceState, info: Option<&DeviceInfo>) -> String {+ // 没接设备时 WDA 不会自己起来,也没有 HID 后备+ if matches!(state, DeviceState::Absent) {+ return "WDA 不可用(手机未连接);接上设备后守护进程会自动拉起 WDA".into();+ }+ let fallback = if hid_supported(info) {+ "截图/点击/滑动/按键可照常用"+ } else {+ "这台手机 iOS 低于 27,没有 HID 后备路线,WDA 恢复前截图、点击等操作都用不了"+ };+ format!("WDA 不可用({}),守护进程一般 1~2 分钟内会拉起;{fallback}", state.describe())+}++/// HID 后备路线(免 WDA 截图、点击)只有 iOS 27 起能用;不知道版本时照常尝试+pub(crate) fn hid_supported(info: Option<&DeviceInfo>) -> bool {+ info.is_none_or(|i| matches!(i.major_version(), 0 | 27..))}impl Daemon {@@ -154,10 +248,14 @@ impl Daemon {let now = Instant::now();let inner = Inner {persisted,+ device_profile: DeviceProfile::NotChecked,state: DeviceState::Absent,device: None,info: None,+ connected: Vec::new(),+ infos: HashMap::new(),tunnel: None,+ wda_rotation: None,runner: None,wda: None,starting: None,@@ -181,17 +279,16 @@ impl Daemon {next_session_check: now + Duration::from_secs(90),apps: HashMap::new(),};- let unlock = UnlockConfig {- passcode_file: cfg.passcode_file(),- disabled_flag: cfg.unlock_disabled_flag(),- timing: Default::default(),- };let first = Snapshot {state: DeviceState::Absent,device: None,+ devices: Vec::new(),+ pinned: cfg.udid.clone().or_else(|| inner.persisted.selected_udid.clone()),+ pinned_by_env: cfg.udid.is_some(),persisted: inner.persisted.clone(),- auto_unlock: unlock.enabled(),- unlock_disabled: unlock.disabled_by_failure(),+ device_profile: DeviceProfile::NotChecked,+ auto_unlock: false,+ unlock_disabled: cfg.unlock_disabled_flag().exists(),notify_configured: cfg.notify.any(),log_tail: Vec::new(),};@@ -199,14 +296,57 @@ impl Daemon {Arc::new(Self { cfg, log, inner: Mutex::new(inner), snap })}- pub(crate) fn unlock_cfg(&self) -> UnlockConfig {+ /// 自动解锁配置:用设备 `udid` 自己的密码。没接设备时密码文件不存在(自动解锁不可用)+ pub(crate) fn unlock_cfg(&self, udid: Option<&str>) -> UnlockConfig {UnlockConfig {- passcode_file: self.cfg.passcode_file(),+ passcode_file: self.cfg.passcode_file_for(udid.unwrap_or("_none")),disabled_flag: self.cfg.unlock_disabled_flag(),timing: Default::default(),}}+ /// 选定的设备:`IPHONE_UDID` 优先,其次是运行中选的+ pub(crate) fn pinned(&self, g: &Inner) -> Option<String> {+ self.cfg.udid.clone().or_else(|| g.persisted.selected_udid.clone())+ }++ /// 接着的全部设备,读不到名字的只有 UDID+ pub(crate) fn connected_infos(&self, g: &Inner) -> Vec<DeviceInfo> {+ g.connected+ .iter()+ .map(|d| {+ g.infos+ .get(&d.udid)+ .cloned()+ .unwrap_or_else(|| DeviceInfo { udid: d.udid.clone(), ..Default::default() })+ })+ .collect()+ }++ /// 旧版本那份不知道是哪台的密码:USB 上只接着一台、正好是要控制的这台、这台还没有自己的密码时,归到它名下。+ /// 接着多台时不动它(也不用它)+ pub(crate) fn adopt_legacy_passcode(&self, g: &Inner) {+ let legacy = self.cfg.legacy_passcode_file();+ let ([only], Some(d)) = (&g.connected[..], &g.device) else { return };+ if only.udid != d.udid || !legacy.is_file() {+ return;+ }+ let dst = self.cfg.passcode_file_for(&d.udid);+ if dst.exists() {+ return;+ }+ let r = std::fs::create_dir_all(self.cfg.passcodes_dir())+ .and_then(|_| {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(self.cfg.passcodes_dir(), std::fs::Permissions::from_mode(0o700))+ })+ .and_then(|_| std::fs::rename(&legacy, &dst));+ match r {+ Ok(()) => self.log.log(&format!("旧的锁屏密码只有一份,USB 上只接着 {},归到它名下", d.udid)),+ Err(e) => tracing::warn!("把旧的锁屏密码归到 {} 名下失败:{e}", d.udid),+ }+ }+pub(crate) fn notify(&self, g: &mut Inner, e: Event) {if !g.dedup.should_send(&e, Instant::now()) {return;@@ -229,6 +369,28 @@ impl Daemon {}/// 丢掉整个会话:runner、WDA 客户端、正在后台启动的任务、隧道(先停 HID 媒体流)+ /// 重读这台手机上的 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;+ return;+ };+ let Some(bundle) = g.persisted.wda_bundle.clone() else {+ g.device_profile = DeviceProfile::Missing;+ return;+ };+ g.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,+ },+ Err(e) => {+ tracing::warn!("读手机上的描述文件失败,按签名记录算:{e}");+ DeviceProfile::Unknown(e.to_string())+ }+ };+ }+pub(crate) async fn drop_session(&self, g: &mut Inner) {if let Some(h) = g.starting.take() {h.abort();@@ -259,7 +421,7 @@ impl Daemon {}pub(crate) fn require_wda<'a>(&self, g: &'a mut Inner) -> Result<&'a mut WdaClient<DeviceTransport>, String> {- let msg = wda_down(&g.state);+ let msg = wda_down(&g.state, g.info.as_ref());self.wda(g).ok_or(msg)}@@ -269,11 +431,16 @@ impl Daemon {/// 发布快照给不拿锁的读者(`status`)。日志尾巴在读的时候再取pub(crate) fn publish(&self, g: &Inner) {- let unlock = self.unlock_cfg();+ 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 {state: g.state.clone(),device: g.info.clone(),+ devices: self.connected_infos(g),+ pinned,+ pinned_by_env: self.cfg.udid.is_some(),persisted: g.persisted.clone(),+ device_profile: g.device_profile.clone(),auto_unlock: unlock.enabled(),unlock_disabled: unlock.disabled_by_failure(),notify_configured: self.cfg.notify.any(),@@ -289,8 +456,9 @@ impl Daemon {match req {Request::Daemon => {let mut s = self.snap.borrow().clone();- s.unlock_disabled = self.unlock_cfg().disabled_by_failure();- s.auto_unlock = self.unlock_cfg().enabled();+ 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());}@@ -349,6 +517,8 @@ impl Daemon {g.dedup.clear("unlock");Ok("已恢复自动解锁".into())}+ Request::ListDevices => Ok(self.list_devices_text(g)),+ Request::SelectDevice { device } => self.select_device(g, &device).await,Request::Daemon | Request::Resign { .. } => unreachable!("上面已处理"),};if invalidates {@@ -393,6 +563,83 @@ fn check_request(req: &Request) -> Result<(), String> {mod tests {use super::*;+ /// 手机上的描述文件:CMS 外壳里包着 XML plist(同 ictl-sign 的解析方式)+ fn profile(app_id: &str, devices: &[&str], expires: &str) -> Vec<u8> {+ let devs: String = devices.iter().map(|d| format!("<string>{d}</string>")).collect();+ let xml = format!(+ r#"<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>+<key>Name</key><string>iOS Team Provisioning Profile</string>+<key>TeamIdentifier</key><array><string>TEAM1</string></array>+<key>ExpirationDate</key><date>{expires}</date>+<key>ProvisionedDevices</key><array>{devs}</array>+<key>Entitlements</key><dict><key>application-identifier</key><string>{app_id}</string></dict>+</dict></plist>"#+ );+ [&[0x30u8, 0x82][..], xml.as_bytes(), &[0x00, 0xa0]].concat()+ }++ #[test]+ fn wda_down_when_no_device_does_not_promise_recovery() {+ let m = wda_down(&DeviceState::Absent, None);+ assert!(m.contains("手机未连接") && !m.contains("1~2 分钟") && !m.contains("可照常用"), "{m}");+ }++ #[test]+ fn wda_down_mentions_hid_fallback_only_from_ios_27() {+ let info = |v: &str| DeviceInfo { product_version: v.into(), ..Default::default() };+ let st = DeviceState::WdaStarting { last_error: None };+ assert!(wda_down(&st, Some(&info("27.0.1"))).contains("可照常用"));+ assert!(wda_down(&st, None).contains("可照常用"));+ let old = wda_down(&st, Some(&info("26.6.1")));+ assert!(old.contains("没有 HID 后备路线") && !old.contains("可照常用"), "{old}");+ }++ const WDA: &str = "com.facebook.WebDriverAgentRunner.xctrunner.TEAM1";++ /// 和上面 XML 里的日期对应的时刻+ fn at(s: &str) -> SystemTime {+ let secs = match s {+ "2026-11-10T15:35:00Z" => 1794324900,+ "2026-11-12T00:00:00Z" => 1794441600,+ _ => unreachable!(),+ };+ UNIX_EPOCH + Duration::from_secs(secs)+ }++ /// 真机情况:iPhone 上装的是 11-03 签的(11-10 到期),之后给 iPad 签的那份(11-13)只装到了 iPad 上+ #[test]+ fn wda_profile_is_the_one_on_this_phone() {+ let iphone = "00008130-0019295E012B803A";+ let ps = vec![+ profile(&format!("TEAM1.{WDA}"), &[iphone], "2026-11-10T15:35:00Z"),+ profile("TEAM1.com.example.other", &[iphone], "2027-01-01T00:00:00Z"),+ profile(&format!("TEAM2.{WDA}"), &[iphone], "2027-01-01T00:00:00Z"),+ profile(&format!("TEAM1.{WDA}"), &["00008020-000925043499002E"], "2026-11-13T12:26:31Z"),+ b"not a profile".to_vec(),+ ];+ assert_eq!(wda_profile_expiry(&ps, Some("TEAM1"), WDA, iphone), Some(at("2026-11-10T15:35:00Z")));+ // UDID 大小写不敏感;装过两次取晚的+ let mut twice = ps.clone();+ twice.push(profile(&format!("TEAM1.{WDA}"), &[&iphone.to_lowercase()], "2026-11-12T00:00:00Z"));+ assert_eq!(wda_profile_expiry(&twice, Some("TEAM1"), WDA, iphone), Some(at("2026-11-12T00:00:00Z")));+ // 没装过:没有包含这台手机的+ assert_eq!(wda_profile_expiry(&ps, Some("TEAM1"), WDA, "00008101-AAAA"), None);+ // 不知道团队 ID 时只看 Bundle ID+ assert!(wda_profile_expiry(&ps, None, WDA, iphone).is_some());+ }++ #[test]+ fn device_profile_left_falls_back_to_signing_record_only_when_unknown() {+ let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();+ let p = Persisted { profile_expires: Some(now + 6 * 86400), ..Default::default() };+ let days = |d: Option<Duration>| d.map(|d| (d.as_secs() + 3600) / 86400);+ assert_eq!(days(DeviceProfile::Expires(now + 4 * 86400).left(&p)), Some(4));+ assert_eq!(days(DeviceProfile::Unknown("x".into()).left(&p)), Some(6));+ assert_eq!(days(DeviceProfile::NotChecked.left(&p)), Some(6));+ assert_eq!(DeviceProfile::Missing.left(&p), None);+ assert_eq!(DeviceProfile::Expires(now - 10).left(&p), Some(Duration::ZERO));+ }+#[test]fn gesture_seconds_are_bounded() {let swipe = |s| Request::Swipe { from: (0.0, 0.0), to: (1.0, 1.0), seconds: s };diff --git a/crates/ictl-daemon/src/devices.rs b/crates/ictl-daemon/src/devices.rsnew file mode 100644index 0000000..0bf01d8--- /dev/null+++ b/crates/ictl-daemon/src/devices.rs@@ -0,0 +1,168 @@+//! 接着多台设备时:列出来、选一台控制。+//!+//! 同一时间只控制一台(一个 WDA 会话、一把设备锁)。选哪台见 [`crate::machine::pick_device`]:+//! 选定了就只认那一台;没选定时正在控制的那台一直用到它断开。切换时拆掉上一台的会话,在新的一台上拉起 WDA++use ictl_device::{Device, DeviceInfo, UsbDevice};++use crate::core::{Daemon, Inner, device_label};++/// 按 UDID 或设备名找设备,返回下标:先比 UDID(不分大小写),再比设备名,最后是设备名包含这段文字且只有一台+pub fn resolve_device(devices: &[DeviceInfo], query: &str) -> Result<usize, String> {+ let q = query.trim();+ let listed = || devices.iter().map(device_label).collect::<Vec<_>>().join("、");+ if devices.is_empty() {+ return Err("USB 上没有接着设备".into());+ }+ if let Some(i) = devices.iter().position(|d| d.udid.eq_ignore_ascii_case(q)) {+ return Ok(i);+ }+ let by_name: Vec<usize> = (0..devices.len()).filter(|&i| devices[i].name == q).collect();+ let hits = if by_name.is_empty() {+ let lq = q.to_lowercase();+ (0..devices.len()).filter(|&i| !lq.is_empty() && devices[i].name.to_lowercase().contains(&lq)).collect()+ } else {+ by_name+ };+ match hits[..] {+ [i] => Ok(i),+ [] => Err(format!("没有接着「{q}」,接着的有 {}", listed())),+ _ => Err(format!(+ "「{q}」对上了不止一台:{};用 UDID 指定",+ hits.iter().map(|&i| device_label(&devices[i])).collect::<Vec<_>>().join("、")+ )),+ }+}++impl Daemon {+ /// 记下这一轮 USB 上接着的设备;新接上的读一次名字、型号+ pub(crate) async fn note_connected(&self, g: &mut Inner, devices: Vec<UsbDevice>) {+ for d in &devices {+ if !g.infos.contains_key(&d.udid)+ && let Ok(i) = Device::from_usb(d).info().await+ {+ g.infos.insert(d.udid.clone(), i);+ }+ }+ g.connected = devices;+ }++ pub(crate) fn list_devices_text(&self, g: &Inner) -> String {+ let infos = self.connected_infos(g);+ if infos.is_empty() {+ return match self.pinned(g) {+ Some(p) => format!("USB 上没有接着设备(选定的是 {p})"),+ None => "USB 上没有接着设备".into(),+ };+ }+ let current = g.device.as_ref().map(|d| d.udid.as_str());+ let mode = match (&self.cfg.udid, self.pinned(g)) {+ (Some(u), _) => format!("IPHONE_UDID 固定为 {u}"),+ (None, Some(p)) => format!("选定了 {p}"),+ (None, None) => "自动选(正在控制的那台断开才换)".into(),+ };+ let mut lines = vec![format!("接着 {} 台,{mode}:", infos.len())];+ for i in &infos {+ let mark = if Some(i.udid.as_str()) == current { "→ 正在控制 " } else { " " };+ let pin = if self.cfg.passcode_file_for(&i.udid).is_file() { "已设" } else { "没设" };+ lines.push(format!("{mark}{} 自动解锁密码{pin}", device_label(i)));+ }+ if self.cfg.udid.is_none() && infos.len() > 1 {+ lines.push("切换:iphone_select_device(UDID 或设备名),auto 改回自动选".into());+ }+ lines.join("\n")+ }++ /// 改为控制 `query` 指的那台(UDID、设备名或 `auto`),选定的写进 state.json,重启后还记得+ pub(crate) async fn select_device(&self, g: &mut Inner, query: &str) -> Result<String, String> {+ if let Ok(d) = ictl_device::list_devices().await {+ self.note_connected(g, d).await;+ }+ let q = query.trim();+ if q.eq_ignore_ascii_case("auto") || q == "自动" {+ if let Some(u) = &self.cfg.udid {+ return Err(format!(+ "IPHONE_UDID 固定为 {u};要改回自动选,先在 .env 里清掉它再重建容器(或重启守护进程)"+ ));+ }+ g.persisted.selected_udid = None;+ g.persisted.save(&self.cfg.state_file());+ return Ok(match g.info.as_ref().filter(|_| g.device.is_some()) {+ Some(i) => format!("已改回自动选;正在控制 {},它断开时换成别的接着的设备", device_label(i)),+ None if g.connected.is_empty() => "已改回自动选;现在没接设备,接上后自动控制它".into(),+ None => "已改回自动选;10 秒内接管接着的设备,先用 iphone_status 确认就绪".into(),+ });+ }+ let infos = self.connected_infos(g);+ let target = infos[resolve_device(&infos, q)?].clone();+ if let Some(u) = &self.cfg.udid+ && !u.eq_ignore_ascii_case(&target.udid)+ {+ return Err(format!(+ "IPHONE_UDID 固定为 {u};要换设备,先改 .env 里的 IPHONE_UDID 再重建容器(或重启守护进程)"+ ));+ }+ if self.cfg.udid.is_none() {+ g.persisted.selected_udid = Some(target.udid.clone());+ g.persisted.save(&self.cfg.state_file());+ }+ let label = device_label(&target);+ if g.device.as_ref().is_some_and(|d| d.udid == target.udid) {+ return Ok(format!("已经在控制 {label},之后固定控制这台"));+ }+ let usb = g.connected.iter().find(|d| d.udid == target.udid).cloned().ok_or("设备刚刚断开了")?;+ // 上一台的锁屏时间不能拿来等这一台+ g.last_lock = None;+ self.online(g, &usb).await;+ let pin = if self.cfg.passcode_file_for(&target.udid).is_file() {+ ""+ } else {+ ";这台没设自动解锁密码,锁屏时要人工解锁(在这台连着时运行 iphone-control passcode set)"+ };+ Ok(format!(+ "已切换到 {label},之后固定控制这台。状态:{};WDA 起来要 10~60 秒,先用 iphone_status 确认就绪{pin}",+ g.state.describe()+ ))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn dev(udid: &str, name: &str) -> DeviceInfo {+ DeviceInfo {+ udid: udid.into(),+ name: name.into(),+ product_type: "iPhone16,2".into(),+ product_version: "27.0".into(),+ }+ }++ #[test]+ fn passcode_file_is_per_device_and_stays_in_its_dir() {+ let cfg = crate::Config::from_env(std::path::Path::new("/data"));+ assert_eq!(+ cfg.passcode_file_for("00008020-000925043499002E"),+ cfg.passcodes_dir().join("00008020-000925043499002E")+ );+ let odd = cfg.passcode_file_for("../../etc/x");+ assert_eq!(odd.parent(), Some(cfg.passcodes_dir().as_path()));+ assert_ne!(cfg.passcode_file_for("A"), cfg.legacy_passcode_file());+ }++ #[test]+ fn device_is_found_by_udid_then_name() {+ let ds =+ [dev("00008130-AAAA", "Derrors 的 iPhone"), dev("00008020-BBBB", "Derrors 的 iPad"), dev("C", "iPad 2")];+ assert_eq!(resolve_device(&ds, "00008020-bbbb"), Ok(1));+ assert_eq!(resolve_device(&ds, "Derrors 的 iPhone"), Ok(0));+ assert_eq!(resolve_device(&ds, " iphone "), Ok(0));+ // 「iPad」两台都包含:要用 UDID 指定+ assert!(resolve_device(&ds, "ipad").unwrap_err().contains("不止一台"));+ assert!(resolve_device(&ds, "Mac").unwrap_err().contains("没有接着"));+ assert!(resolve_device(&[], "x").is_err());+ // 名字完全相同的优先于包含+ assert_eq!(resolve_device(&ds, "iPad 2"), Ok(2));+ }+}diff --git a/crates/ictl-daemon/src/doctor.rs b/crates/ictl-daemon/src/doctor.rsindex 116798b..1dcbaa4 100644--- a/crates/ictl-daemon/src/doctor.rs+++ b/crates/ictl-daemon/src/doctor.rs@@ -2,7 +2,7 @@use std::time::Duration;-use crate::core::{Daemon, Inner};+use crate::core::{Daemon, DeviceProfile, Inner};impl Daemon {pub(crate) async fn doctor(&self, g: &mut Inner) -> String {@@ -46,6 +46,17 @@ impl Daemon {out.push("⚠️ iOS 低于 27 HID 后备路线(免签名截图/点击)不可用,只能走 WDA".into());}}+ // 选定的那台没接、别的接着:usbmuxd 没问题,不是重启它能解决的+ (None, _) if self.pinned(g).is_some() && !g.connected.is_empty() => {+ let p = self.pinned(g).unwrap_or_default();+ let how = if self.cfg.udid.is_some() {+ "或改 .env 里的 IPHONE_UDID"+ } else {+ "或 iphone-control select 换成接着的另一台(auto 改回自动选)"+ };+ out.push(format!("❌ 选定的设备 {p} 没连接\n → 接上它;{how}"));+ fails += 1;+ }(None, _) => {out.push(if self.cfg.manage_usbmuxd {@@ -61,6 +72,9 @@ impl Daemon {}}out.push(format!(" 状态:{}", g.state.describe()));+ if let Some(l) = self.devices_line(g) {+ out.push(format!(" {l}"));+ }out.push("== Apple ID 与签名".into());match self.account().selected_email().await {@@ -70,19 +84,41 @@ impl Daemon {fails += 1;}}- match (&g.persisted.wda_bundle, g.persisted.profile_left()) {- (Some(b), Some(left)) => {+ match &g.persisted.wda_bundle {+ Some(b) => {out.push(format!("✅ WDA 已签名 {b}"));- if left.is_zero() {- out.push("❌ 描述文件已过期\n → iphone-control resign --force".into());- fails += 1;- } else if left < Duration::from_secs(48 * 3600) {- out.push(format!("⚠️ 描述文件只剩 {} 小时 守护进程会自动重签", left.as_secs() / 3600));- } else {- out.push(format!("✅ 描述文件有效 还剩 {} 天", left.as_secs() / 86400));+ // 接着手机时看手机上装的那份:最近一次签名可能是给别的手机签的+ if g.device.is_some() {+ self.refresh_device_profile(g).await;+ }+ let whose = match &g.device_profile {+ DeviceProfile::Expires(_) => "这台手机上的描述文件",+ DeviceProfile::Unknown(e) => {+ out.push(format!("⚠️ 读不到手机上的描述文件({e}),下面按上次签名的记录"));+ "描述文件"+ }+ _ => "描述文件",+ };+ match g.device_profile.left(&g.persisted) {+ _ if g.device_profile == DeviceProfile::Missing => {+ out.push(+ "❌ 这台手机上没有装当前 Apple ID 签的 WDA\n → iphone-control setup(会把这台手机注册到 Apple ID 并装上 WDA)"+ .into(),+ );+ fails += 1;+ }+ Some(left) if left.is_zero() => {+ out.push(format!("❌ {whose}已过期\n → iphone-control resign --force"));+ fails += 1;+ }+ Some(left) if left < Duration::from_secs(48 * 3600) => {+ out.push(format!("⚠️ {whose}只剩 {} 小时 守护进程会自动重签", left.as_secs() / 3600));+ }+ Some(left) => out.push(format!("✅ {whose}有效 还剩 {} 天", left.as_secs() / 86400)),+ None => out.push("⚠️ 不知道描述文件什么时候到期".into()),}}- _ => {+ None => {out.push("❌ WDA 还没签名安装\n → iphone-control sign".into());fails += 1;}@@ -108,16 +144,25 @@ impl Daemon {} else {out.push("⚠️ 没有配置通知 重签失败、手机离线、需要输密码时不会提醒你".into());}- let unlock = self.unlock_cfg();+ let unlock = self.unlock_cfg(g.device.as_ref().map(|d| d.udid.as_str()));+ if self.cfg.legacy_passcode_file().is_file() {+ out.push(+ "⚠️ 有一份旧版本保存的锁屏密码,没记是哪台设备的;同时接着几台时不会用它\n \+→ 在要用的设备连着时运行 iphone-control passcode set(USB 上只接着一台时会自动归到那台名下)"+ .into(),+ );+ }if unlock.disabled_by_failure() {out.push("❌ 自动解锁已停用(之前输错过或输入中途出错)\n → 核对密码后 iphone-control unlock-reset".into(),);fails += 1;} else if unlock.enabled() {- out.push("✅ 自动解锁已启用".into());+ out.push("✅ 自动解锁已启用(这台设备)".into());+ } else if g.device.is_some() {+ out.push("⚠️ 这台设备没设自动解锁密码 锁屏时需要人工解锁(可选:iphone-control passcode set)".into());} else {- out.push("⚠️ 自动解锁未启用 手机锁屏时需要人工解锁(可选:iphone-control passcode set)".into());+ out.push("⚠️ 没接设备,看不了自动解锁".into());}out.push(String::new());out.push(if fails == 0 { "全部正常".into() } else { format!("{fails} 项需要处理") });diff --git a/crates/ictl-daemon/src/imaging.rs b/crates/ictl-daemon/src/imaging.rsindex 9634485..1e5d213 100644--- a/crates/ictl-daemon/src/imaging.rs+++ b/crates/ictl-daemon/src/imaging.rs@@ -23,10 +23,10 @@ pub fn fmt_3g(v: f64) -> String {if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_owned() } else { s }}-/// 截图是横的而屏幕尺寸是竖的(横屏 App),就把宽高互换+/// 截图和屏幕尺寸横竖不一致(HID 截图、取尺寸和截图之间刚好转了屏)就把宽高互换,按截图的方向来pub fn oriented(img_w: u32, img_h: u32, screen: ScreenSize) -> (u32, u32) {let (w, h) = (screen.width.round() as u32, screen.height.round() as u32);- if img_w > img_h && w < h { (h, w) } else { (w, h) }+ if img_w != img_h && w != h && (img_w > img_h) != (w > h) { (h, w) } else { (w, h) }}/// 解码后马上转成 8 位 RGB:设备截图是 16 位 RGBA(1290×2796 解出来约 29MB),后面缩放、编码都按 RGB8 做,@@ -179,8 +179,7 @@ pub fn region(Ok((jpeg(&crop, 90)?, caption))}-/// 读取 PNG 尺寸(不解码像素)-#[cfg(test)]+/// 读取 PNG 尺寸(只读文件头,不解码像素)pub fn png_size(png: &[u8]) -> Option<(u32, u32)> {image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png).into_dimensions().ok()}@@ -241,6 +240,17 @@ mod tests {assert_eq!(jpeg_size(&j), (932, 430));}+ /// iPad:屏幕尺寸还是横屏的 1024x768,截图已经是竖的,要按竖屏 768x1024 出图,不能压扁+ #[test]+ fn portrait_screenshot_with_landscape_size_is_not_squashed() {+ let land = ScreenSize { width: 1024.0, height: 768.0 };+ let (j, cap) = full_screen(&png(1536, 2048), land, "WDA").unwrap();+ assert_eq!(jpeg_size(&j), (768, 1024));+ assert_eq!(cap, "768x1024 点,图像像素即点坐标(经 WDA)");+ let (j, _) = full_screen(&png(2048, 1536), land, "WDA").unwrap();+ assert_eq!(jpeg_size(&j), (1024, 768));+ }+#[test]fn wide_region_is_capped_at_1200() {let p = plan_zoom(1290, 2796, SCREEN, 0.0, 55.0, 430.0, 40.0).unwrap();diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rsindex 6dc71cc..3b872dd 100644--- a/crates/ictl-daemon/src/lib.rs+++ b/crates/ictl-daemon/src/lib.rs@@ -7,6 +7,7 @@pub mod config;pub mod core;+pub mod devices;mod doctor;pub mod eventlog;pub mod imaging;diff --git a/crates/ictl-daemon/src/machine.rs b/crates/ictl-daemon/src/machine.rsindex 78d5c19..40b61a2 100644--- a/crates/ictl-daemon/src/machine.rs+++ b/crates/ictl-daemon/src/machine.rs@@ -90,10 +90,23 @@ pub struct MuxWatch {pub const USBMUXD_MISS_LIMIT: u32 = 3;+/// 接着几台设备时控制哪一台,返回在 `udids` 里的下标:+/// - 选定了(`IPHONE_UDID` 或运行中选的):只认那一台,没接就是没有(不换成别的,免得操作、自动解锁落到另一台上)+/// - 没选定:正在控制的那台还接着就继续用它,不因 usbmuxd 列表顺序变化换台;没有正在控制的才取第一台+pub fn pick_device(udids: &[&str], pinned: Option<&str>, current: Option<&str>) -> Option<usize> {+ let pos = |u: &str| udids.iter().position(|d| d.eq_ignore_ascii_case(u));+ match pinned {+ Some(p) => pos(p),+ None => current.and_then(pos).or(if udids.is_empty() { None } else { Some(0) }),+ }+}+impl MuxWatch {- /// 返回 true 表示该重启 usbmuxd 了- pub fn observe(&mut self, usb_present: bool, mux_sees_device: bool) -> bool {- if mux_sees_device || !usb_present {+ /// 返回 true 表示该重启 usbmuxd 了。`on_usb`:sysfs 里的 iPhone/iPad 台数;`seen`:usbmuxd 认到的台数。+ /// 比台数而不是「要控制的那台在不在」:那台没接、另一台接着时不该重启;+ /// 也不是「看没看到任何一台」:已经接着一台时再插一台,没有 udev 的 usbmuxd 认不到它+ pub fn observe(&mut self, on_usb: usize, seen: usize) -> bool {+ if seen >= on_usb {self.misses = 0;return false;}@@ -157,16 +170,42 @@ mod tests {assert_eq!(b.current_delay(), BACKOFF_START);}+ #[test]+ fn device_pick_is_pinned_or_sticky() {+ let (a, b) = ("00008130-AAAA", "00008020-BBBB");+ // 没选定:第一台;正在控制 B 时列表顺序变了也还是 B+ assert_eq!(pick_device(&[a, b], None, None), Some(0));+ assert_eq!(pick_device(&[a, b], None, Some(b)), Some(1));+ // 正在控制的拔了:换成还在的+ assert_eq!(pick_device(&[a], None, Some(b)), Some(0));+ // 选定了 B:只认 B(大小写不敏感),B 没接就没有,不换成 A+ assert_eq!(pick_device(&[a, b], Some("00008020-bbbb"), Some(a)), Some(1));+ assert_eq!(pick_device(&[a], Some(b), Some(a)), None);+ assert_eq!(pick_device(&[], None, None), None);+ }+/// 回归用例 #7:sysfs 有设备但 usbmuxd 看不到,连续 3 次才重启#[test]fn usbmuxd_restart_after_three_misses() {let mut w = MuxWatch::default();- assert!(!w.observe(true, false));- assert!(!w.observe(true, false));- assert!(w.observe(true, false));- assert!(!w.observe(true, false), "重启后重新计数");- assert!(!w.observe(false, false), "USB 上没有设备不算漏");- assert!(!w.observe(true, true));+ assert!(!w.observe(1, 0));+ assert!(!w.observe(1, 0));+ assert!(w.observe(1, 0));+ assert!(!w.observe(1, 0), "重启后重新计数");+ assert!(!w.observe(0, 0), "USB 上没有设备不算漏");+ assert!(!w.observe(1, 1));+ }++ /// 接着 iPad 时再插 iPhone:usbmuxd 只认到 1 台,也要重启+ #[test]+ fn usbmuxd_restart_when_a_second_device_is_missed() {+ let mut w = MuxWatch::default();+ assert!(!w.observe(2, 1));+ assert!(!w.observe(2, 1));+ assert!(w.observe(2, 1));+ assert!(!w.observe(2, 2));+ // 拔掉一台、usbmuxd 还没更新列表:不算漏+ assert!(!w.observe(1, 2));}#[test]diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rsindex 7d927fc..c5e3a97 100644--- a/crates/ictl-daemon/src/supervise.rs+++ b/crates/ictl-daemon/src/supervise.rs@@ -7,7 +7,7 @@ use std::time::{Duration, Instant, UNIX_EPOCH};use ictl_device::{Device, DeviceError, SYSFS_USB, Tunnel, UsbDevice};use ictl_wda::{WdaClient, WdaError, WdaRunner, http::DeviceTransport};-use crate::core::{Daemon, Inner, close_hid};+use crate::core::{Daemon, DeviceProfile, Inner, close_hid};use crate::machine::DeviceState;use crate::notify::Event;@@ -123,20 +123,25 @@ impl Daemon {Vec::new()}};- let target = match &self.cfg.udid {- Some(u) => devices.into_iter().find(|d| &d.udid == u),- None => devices.into_iter().next(),- };+ self.note_connected(g, devices).await;+ let pinned = self.pinned(g);+ let udids: Vec<&str> = g.connected.iter().map(|d| d.udid.as_str()).collect();+ let current = g.device.as_ref().map(|d| d.udid.as_str());+ let target = crate::machine::pick_device(&udids, pinned.as_deref(), current).map(|i| g.connected[i].clone());// 只在容器里(自己看护 usbmuxd、没有 udev)需要;用系统的 usbmuxd 服务时插拔由 udev 处理,也重启不了它- let usb_present = ictl_device::apple_usb_present(Path::new(SYSFS_USB));- if self.cfg.manage_usbmuxd && g.mux.observe(usb_present, target.is_some()) {- self.log.log("USB 上有 Apple 设备但 usbmuxd 看不到,重启 usbmuxd");+ let on_usb = ictl_device::ios_usb_count(Path::new(SYSFS_USB));+ if self.cfg.manage_usbmuxd && g.mux.observe(on_usb, g.connected.len()) {+ self.log+ .log(&format!("USB 上有 {on_usb} 台 iPhone/iPad,usbmuxd 只认到 {} 台,重启 usbmuxd", g.connected.len()));self.ensure_usbmuxd(g, true).await;}match target {None => self.offline(g).await,- Some(d) => self.online(g, &d).await,+ Some(d) => {+ self.online(g, &d).await;+ self.adopt_legacy_passcode(g);+ }}let now = Instant::now();@@ -161,8 +166,12 @@ impl Daemon {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("手机离线");+ // 名字、型号、iOS 版本是这台的:留着的话状态、提示文字会把它当成还在控制的设备+ g.info = None;self.drop_session(g).await;g.offline_since = Some(now);g.apps.clear();@@ -175,22 +184,29 @@ impl Daemon {}}- async fn online(&self, g: &mut Inner, seen: &UsbDevice) {+ pub(crate) async fn online(&self, g: &mut Inner, seen: &UsbDevice) {// 只比 UDID 不够:断开几秒又接上(短于离线判定、落在两轮巡检之间)时 UDID 不变,// usbmuxd 却换了编号,旧句柄的每个连接都报 bad device,永远恢复不了if !g.device.as_ref().is_some_and(|d| d.is_connection(seen)) {- if let Some(old) = g.device.take()- && old.udid == seen.udid- {- self.log.log(&format!(+ match g.device.take() {+ Some(old) if old.udid == seen.udid => self.log.log(&format!("手机重新接入(usbmuxd 编号 {} → {}),重建连接",old.device_id(),seen.device_id- ));+ )),+ Some(old) => self.log.log(&format!("改为控制 {}(原来是 {})", seen.udid, old.udid)),+ None => {}}self.drop_session(g).await;+ g.device_profile = DeviceProfile::NotChecked;+ // App 列表是上一台的(同一台重新接入也重读,便宜)+ g.apps.clear();+ g.wda_rotation = None;let d = Device::from_usb(seen);g.info = d.info().await.ok();+ if let Some(i) = &g.info {+ g.infos.insert(seen.udid.clone(), i.clone());+ }let model =g.info.as_ref().map(|i| format!(" {} iOS {}", i.product_type, i.product_version)).unwrap_or_default();self.log.log(&format!("手机在线{model}"));@@ -206,7 +222,11 @@ impl Daemon {let device = g.device.clone().expect("刚设置过");match device.paired().await {- Ok(true) => {}+ Ok(true) => {+ if g.device_profile == DeviceProfile::NotChecked {+ self.refresh_device_profile(g).await;+ }+ }Ok(false) => return self.set_state(g, DeviceState::NeedsTrust),// usbmuxd 出错:这一轮不下结论Err(e) => return tracing::debug!("查配对记录失败:{e}"),@@ -226,6 +246,12 @@ impl Daemon {};if ready {g.wda_misses.reset();+ // 记下界面往哪边转:WDA 挂了以后 HID 点击要靠它换算横屏坐标(约 20 毫秒)+ if let Some(w) = g.wda.as_mut()+ && let Ok(r) = w.rotation().await+ {+ g.wda_rotation = Some((Instant::now(), r));+ }if g.state != DeviceState::Ready {if g.state == DeviceState::NeedsAutomationPin || g.dedup.was_sent("pin") {g.dedup.clear("pin");@@ -236,7 +262,9 @@ impl Daemon {if let Some(w) = g.wda.as_mut()&& let Ok(s) = w.screen_size().await{- g.persisted.screen = Some(s);+ // 存竖放尺寸:WDA 在横屏时就绪的话这里拿到的是横的+ g.persisted.screen = Some(s.portrait());+ g.persisted.screen_udid = g.device.as_ref().map(|d| d.udid.clone());g.persisted.save(&self.cfg.state_file());}}@@ -368,12 +396,21 @@ impl Daemon {pub(crate) async fn resign_now(self: &Arc<Self>, force: bool) -> Result<String, String> {let (device, name) = {let mut g = self.inner.lock().await;- if !force- && g.persisted.wda_bundle.is_some()- && let Some(left) = g.persisted.profile_left()- && left > self.cfg.resign_min- {- return Ok(format!("描述文件还剩 {} 小时,无需重签", left.as_secs() / 3600));+ let g = &mut *g;+ // 看这台手机上装的那份,不看最近一次签名:给别的手机签过之后,这台装的还是更早签的、更早到期+ if !force && g.persisted.wda_bundle.is_some() {+ self.refresh_device_profile(g).await;+ if g.device_profile == DeviceProfile::Missing {+ // 自动重签不替没装过的手机注册设备(占 Apple ID 的设备名额),交给用户决定+ return Ok(+ "这台手机上没有装当前 Apple ID 签的 WDA,不自动重签;要装就运行 iphone-control setup".into()+ );+ }+ if let Some(left) = g.device_profile.left(&g.persisted)+ && left > self.cfg.resign_min+ {+ return Ok(format!("描述文件还剩 {} 小时,无需重签", left.as_secs() / 3600));+ }}if g.resigning {return Ok("正在重签,稍后用 iphone-control status 查看结果".into());@@ -428,6 +465,7 @@ impl Daemon {g.persisted.save(&self.cfg.state_file());// 新包装上后旧的 runner 会失效,下一轮巡检重新拉起self.drop_session(g).await;+ self.refresh_device_profile(g).await;g.backoff.reset();g.dedup.clear("resign");let msg = format!("重签完成,新描述文件到期 {} UTC", crate::eventlog::format_utc(exp));diff --git a/crates/ictl-daemon/src/tools.rs b/crates/ictl-daemon/src/tools.rsindex dfc41e4..8bb9931 100644--- a/crates/ictl-daemon/src/tools.rs+++ b/crates/ictl-daemon/src/tools.rs@@ -3,13 +3,13 @@use std::time::{Duration, Instant};use base64::Engine;-use ictl_device::{AppInfo, Button, DeviceError, HidSession, ScreenSize, apps, hid::ascii_to_usage};+use ictl_device::{AppInfo, Button, DeviceError, HidSession, Rotation, ScreenSize, apps, hid::ascii_to_usage};use ictl_unlock::UnlockError;use ictl_wda::elements::{self, TapPoint, Tree};use ictl_wda::http::DeviceTransport;use ictl_wda::{Launch, WdaClient, WdaError};-use crate::core::{Daemon, Inner, drop_tunnel, wda_down};+use crate::core::{Daemon, Inner, drop_tunnel, hid_supported, wda_down};use crate::imaging::{self, fmt_g};use crate::notify::Event;use crate::protocol::Response;@@ -36,7 +36,7 @@ const SPRINGBOARD: &str = "com.apple.springboard";impl Daemon {/// 配置了密码就在锁屏时自动解锁;没配置而手机锁着则报错(与 toolkit 一致)pub(crate) async fn ensure_unlocked(&self, g: &mut Inner) -> Result<(), String> {- let cfg = self.unlock_cfg();+ 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())) {tokio::time::sleep(left).await;}@@ -47,6 +47,11 @@ impl Daemon {self.notify(g, Event::UnlockDisabled);Err(format!("{e},已推送通知"))}+ Err(UnlockError::NoPasscode) if self.cfg.legacy_passcode_file().is_file() => {+ Err("手机已锁屏,需要人工解锁:旧版本保存的锁屏密码没记是哪台设备的,同时接着几台时不会用它;\+在这台设备连着时运行 iphone-control passcode set 重新设置"+ .into())+ }Err(e) => Err(e.to_string()),}}@@ -57,16 +62,57 @@ impl Daemon {{return Ok(s);}+ // 记下的尺寸是别的设备的就不用(旧版本没记是哪台,照用)+ let same = match (&g.persisted.screen_udid, &g.device) {+ (Some(u), Some(d)) => *u == d.udid,+ (Some(_), None) => false,+ (None, _) => true,+ };g.persisted.screen+ .filter(|_| same).or(self.cfg.screen_fallback).ok_or_else(|| "WDA 不可用,也不知道屏幕尺寸;等 WDA 起来一次,或在 .env 里设 SCREEN_W/SCREEN_H".into())}+ async fn refresh_hid_rotation(&self, g: &mut Inner) {+ if let Some(w) = self.wda(g)+ && let Ok(r) = w.rotation().await+ {+ g.wda_rotation = Some((Instant::now(), r));+ }+ }++ /// 每次 HID 触摸前重新截图核对横竖,不依赖上次截图(转屏、回主屏、解锁都可能改变方向)。+ /// 截图只给宽高,不能分辨横屏左右;短暂掉线时借用近期 WDA 方向,过期或不匹配就不触摸。+ async fn hid_touch_rotation(&self, g: &mut Inner) -> Result<Rotation, String> {+ self.refresh_hid_rotation(g).await;+ let device = g.device.clone().ok_or("手机未连接")?;+ let png = {+ let t = self.ensure_tunnel(g, &device).await.map_err(|e| format!("核对 HID 方向失败:{e}"))?;+ match t.screenshot_png().await {+ Ok(p) => p,+ Err(e) => {+ drop_tunnel(g).await;+ return Err(format!("核对 HID 方向失败,没有发送触摸:{e}"));+ }+ }+ };+ let (w, h) = imaging::png_size(&png).ok_or("无法读取截图尺寸,没有发送触摸")?;+ let known = g.wda_rotation.map(|(at, r)| (at.elapsed(), r));+ hid_rotation(w, h, known)+ }+/// HID 会话(WDA 不可用时的后备路线)。开不起来就丢掉隧道,下次重建async fn hid<'a>(&self, g: &'a mut Inner) -> Result<&'a mut HidSession, String> {+ // 低版本建隧道只会报 service not found:直接说清楚+ if !hid_supported(g.info.as_ref()) {+ return Err(wda_down(&g.state, g.info.as_ref()));+ }let screen = self.screen(g).await?;let device = g.device.clone().ok_or("手机未连接")?;+ // HID 触摸按设备竖放的坐标归一化+ let screen = screen.portrait();let t = self.ensure_tunnel(g, &device).await.map_err(|e| format!("HID 后备路线不可用:{e}"))?;if let Err(e) = t.hid(screen).await {drop_tunnel(g).await;@@ -96,13 +142,45 @@ impl Daemon {}}+ /// 接着多台、或选定的那台没接时,说明在控制哪台、怎么切换;只接着一台时为空(输出和原来一样)+ pub(crate) fn devices_line(&self, g: &Inner) -> Option<String> {+ let pinned = self.pinned(g);+ let current = g.device.as_ref().map(|d| d.udid.as_str());+ let others: Vec<String> = self+ .connected_infos(g)+ .iter()+ .filter(|i| Some(i.udid.as_str()) != current)+ .map(crate::core::device_label)+ .collect();+ let how = if self.cfg.udid.is_some() {+ "(IPHONE_UDID 固定了设备,要换先改 .env)"+ } else {+ ";用 iphone_select_device 切换"+ };+ match (current, &pinned) {+ (None, Some(p)) => Some(format!(+ "设备: 选定的 {p} 没连接{}{how}",+ if others.is_empty() { String::new() } else { format!(",接着的有 {}", others.join("、")) }+ )),+ (Some(_), _) if !others.is_empty() => {+ let me = g.info.as_ref().map(crate::core::device_label).unwrap_or_default();+ let mode = if pinned.is_some() { "选定" } else { "自动选" };+ Some(format!("设备: 正在控制 {me}({mode});另外接着 {}{how}", others.join("、")))+ }+ _ => None,+ }+ }+pub(crate) async fn status_text(&self, g: &mut Inner) -> String {- let daemon_line = format!("守护进程: {}", g.state.describe());- let unlock = self.unlock_cfg();+ let mut daemon_line = format!("守护进程: {}", g.state.describe());+ if let Some(l) = self.devices_line(g) {+ daemon_line = format!("{l}\n{daemon_line}");+ }+ let unlock = self.unlock_cfg(g.device.as_ref().map(|d| d.udid.as_str()));let Some(w) = self.wda(g) else {return format!("{}\n读界面元素、按名字点击、启动 App、输入中文要等 WDA 恢复\n{daemon_line}",- wda_down(&g.state)+ wda_down(&g.state, g.info.as_ref()));};let r: Result<String, WdaError> = async {@@ -146,9 +224,16 @@ impl Daemon {Some(w) => w.screenshot_png().await.ok(),None => None,};+ // 给短暂 WDA 掉线时的 HID 留一份近期方向;不把方向永久缓存到磁盘。+ if wda_png.is_some() {+ self.refresh_hid_rotation(g).await;+ }let (png, via) = match wda_png {Some(p) => (p, "WDA"),None => {+ if !hid_supported(g.info.as_ref()) {+ return Err(wda_down(&g.state, g.info.as_ref()));+ }let device = g.device.clone().ok_or("手机未连接")?;let t = self.ensure_tunnel(g, &device).await.map_err(|e| format!("HID 命令失败: {e}"))?;match t.screenshot_png().await {@@ -341,7 +426,14 @@ impl Daemon {Err(e) => return Err(e.to_string()),}}- self.hid_do(g, |h| Box::pin(h.tap(x, y))).await?;+ let rot = self.hid_touch_rotation(g).await?;+ self.hid_do(g, move |h| {+ Box::pin(async move {+ h.rotation = rot;+ h.tap(x, y).await+ })+ })+ .await?;Ok(format!("已点击 {pos}(经 HID)"))}@@ -412,7 +504,14 @@ impl Daemon {Err(e) => return Err(e.to_string()),}}- self.hid_do(g, |h| Box::pin(h.drag(from, to, seconds))).await?;+ let rot = self.hid_touch_rotation(g).await?;+ self.hid_do(g, move |h| {+ Box::pin(async move {+ h.rotation = rot;+ h.drag(from, to, seconds).await+ })+ })+ .await?;Ok(format!("已滑动 {desc}(经 HID)"))}@@ -576,11 +675,35 @@ impl Daemon {pub(crate) async fn open_url(&self, g: &mut Inner, url: &str) -> Result<String, String> {self.ensure_unlocked(g).await?;- self.require_wda(g)?.open_url(url).await.map_err(|e| e.to_string())?;- Ok(format!("已打开 {url}"))+ let (r, app) = self.require_wda(g)?.open_url(url).await.map_err(|e| e.to_string())?;+ Ok(match r {+ Launch::Foreground => format!("已打开 {url}(前台 {app})"),+ Launch::Blocked(text) => {+ format!("已打开 {url},但屏幕上有系统弹窗「{text}」挡着;先用 iphone_tap_element 点弹窗上的按钮")+ }+ Launch::Slow => format!("已打开 {url},但 8 秒内没有 App 到前台(前台还是 {app}),先截图确认"),+ })}}+/// 只给 WDA 短暂掉线留窗口。缓存不能跨进程重启、跨设备或长期代替方向查询。+const HID_ROTATION_MAX_AGE: Duration = Duration::from_secs(30);++/// 当前截图必须能确定横竖;横屏还需近期 WDA 旋转角。仅凭宽高无法识别 WDA 离线期间的 180° 翻转,+/// 所以后备操作期间不要翻转设备;恢复 WDA 后重新确认方向。+pub(crate) fn hid_rotation(w: u32, h: u32, known: Option<(Duration, Rotation)>) -> Result<Rotation, String> {+ if w == 0 || h == 0 || w == h {+ return Err("截图尺寸无效,无法核对 HID 方向,没有发送触摸".into());+ }+ let recent = known.filter(|(age, _)| *age <= HID_ROTATION_MAX_AGE).map(|(_, r)| r);+ if w > h {+ return recent.filter(|r| r.is_landscape()).ok_or_else(|| {+ "当前为横屏,但没有近期且匹配的 WDA 旋转角,没有发送 HID 触摸;等 WDA 恢复后重试,或转回竖屏".into()+ });+ }+ Ok(if recent == Some(Rotation::UpsideDown) { Rotation::UpsideDown } else { Rotation::Portrait })+}+/// 屏幕中间(上下各去掉一段,留给导航栏、标签栏)几乎没有元素:加载中、空白页/// 按 Home,等主屏真的到前台再说「已按」(紧接着查状态时前台不再是旧 App)。/// 先经 IOHID 按(XCTest 的 home 在 iPhone 12 mini / iOS 26.4.1 上不起作用却报成功),@@ -810,6 +933,22 @@ async fn verify_typed(w: &mut WdaClient<DeviceTransport>, text: &str) -> Typed {mod tests {use super::*;+ #[test]+ fn hid_rotation_requires_fresh_matching_landscape() {+ use Rotation::*;+ let fresh = |r| Some((Duration::ZERO, r));+ assert_eq!(hid_rotation(2796, 1290, fresh(TopToLeft)), Ok(TopToLeft));+ assert_eq!(hid_rotation(2796, 1290, fresh(TopToRight)), Ok(TopToRight));+ assert!(hid_rotation(2796, 1290, None).is_err());+ assert!(hid_rotation(2796, 1290, fresh(Portrait)).is_err());+ assert!(hid_rotation(2796, 1290, Some((Duration::from_secs(31), TopToLeft))).is_err());+ assert_eq!(hid_rotation(1290, 2796, fresh(TopToLeft)), Ok(Portrait));+ assert_eq!(hid_rotation(1290, 2796, fresh(UpsideDown)), Ok(UpsideDown));+ assert_eq!(hid_rotation(1290, 2796, None), Ok(Portrait));+ assert!(hid_rotation(0, 2796, fresh(Portrait)).is_err());+ assert!(hid_rotation(100, 100, fresh(Portrait)).is_err());+ }+fn v(s: &[&str]) -> Vec<String> {s.iter().map(|x| x.to_string()).collect()}diff --git a/crates/ictl-device/src/hid.rs b/crates/ictl-device/src/hid.rsindex 5f56fa8..757ecdd 100644--- a/crates/ictl-device/src/hid.rs+++ b/crates/ictl-device/src/hid.rs@@ -13,7 +13,7 @@ use idevice::{tcp::handle::AdapterHandle,};-use crate::{DeviceError, Result, ScreenSize, limit, media::ScreenMediaStream};+use crate::{DeviceError, Result, Rotation, ScreenSize, limit, media::ScreenMediaStream};pub const HID_MAX: f64 = 65535.0;@@ -103,7 +103,10 @@ pub fn ascii_to_usage(c: char) -> Option<(u64, bool)> {const KEY_LEFT_SHIFT: u64 = 0xE1;pub struct HidSession {+ /// 设备竖放时的尺寸:HID 触摸坐标按竖放归一化pub screen: ScreenSize,+ /// 界面现在转了多少;点击、拖动的坐标是界面上的,发出去前按它换算回竖放(调用方每次操作前设)+ pub rotation: Rotation,stream: Option<ScreenMediaStream>,touch: UniversalHidServiceClient<Box<dyn ReadWrite>>,indigo: IndigoHidClient<Box<dyn ReadWrite>>,@@ -125,7 +128,13 @@ impl HidSession {}.await;match clients {- Ok((touch, indigo)) => Ok(Self { screen, stream: Some(stream), touch, indigo }),+ Ok((touch, indigo)) => Ok(Self {+ screen: screen.portrait(),+ rotation: Rotation::Portrait,+ stream: Some(stream),+ touch,+ indigo,+ }),Err(e) => {// 媒体流已经起来了:不停掉的话手机端会一直挂着它stream.stop().await;@@ -134,15 +143,21 @@ impl HidSession {}}+ /// 界面上的点 → HID 归一化坐标(先按 [`Self::rotation`] 换算回竖放)+ fn hid_point(&self, p: (f64, f64)) -> (u16, u16) {+ let (x, y) = self.rotation.to_portrait(p, self.screen);+ to_hid(x, y, self.screen)+ }+pub async fn tap(&mut self, x: f64, y: f64) -> Result<()> {- let (hx, hy) = to_hid(x, y, self.screen);+ let (hx, hy) = self.hid_point((x, y));limit("HID 点击", Duration::from_secs(10), async { Ok(self.touch.tap(hx, hy).await?) }).await}/// 拖动:按时长换算采样数(每 20ms 一个点,至少 10 个),太快会被识别成点击pub async fn drag(&mut self, from: (f64, f64), to: (f64, f64), seconds: f64) -> Result<()> {- let (x1, y1) = to_hid(from.0, from.1, self.screen);- let (x2, y2) = to_hid(to.0, to.1, self.screen);+ let (x1, y1) = self.hid_point(from);+ let (x2, y2) = self.hid_point(to);let steps = ((seconds * 1000.0 / 20.0).round() as u32).max(10);let d = Duration::from_secs_f64(seconds.max(0.0) + 10.0);limit("HID 拖动", d, async { Ok(self.touch.drag(x1, y1, x2, y2, steps, 20).await?) }).awaitdiff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rsindex 69f3729..61e24fb 100644--- a/crates/ictl-device/src/lib.rs+++ b/crates/ictl-device/src/lib.rs@@ -28,6 +28,7 @@ use idevice::{cryptexd::{Cryptex1Assets, install_ddi, installed_ddi},installation_proxy::InstallationProxyClient,lockdown::LockdownClient,+ misagent::MisagentClient,provider::{IdeviceProvider, UsbmuxdProvider},rsd::RsdHandshake,tcp::handle::AdapterHandle,@@ -97,6 +98,58 @@ pub struct ScreenSize {pub height: f64,}+impl ScreenSize {+ /// 设备竖放时的尺寸(短边是宽)+ pub fn portrait(self) -> Self {+ Self { width: self.width.min(self.height), height: self.width.max(self.height) }+ }+}++/// 界面相对设备竖放转了多少(WDA `GET /rotation` 的 z)。HID 触摸始终按设备竖放的坐标解释,+/// 横屏时要把界面上的点换算回去。真机:iPhone 15 Pro Max 摄像头在左 z=270、在右 z=90;+/// iPad mini 5 Home 键在左 z=90。两个横屏方向 WDA 的 `/orientation` 都报 `LANDSCAPE`,分不出来+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum Rotation {+ #[default]+ Portrait,+ /// z=90:竖放的顶边转到了屏幕右边+ TopToRight,+ /// z=180+ UpsideDown,+ /// z=270:竖放的顶边转到了屏幕左边+ TopToLeft,+}++impl Rotation {+ pub fn from_degrees(z: f64) -> Option<Self> {+ if !z.is_finite() || z.fract() != 0.0 {+ return None;+ }+ Some(match z.rem_euclid(360.0) as u16 {+ 0 => Self::Portrait,+ 90 => Self::TopToRight,+ 180 => Self::UpsideDown,+ 270 => Self::TopToLeft,+ _ => return None,+ })+ }++ pub fn is_landscape(self) -> bool {+ matches!(self, Self::TopToRight | Self::TopToLeft)+ }++ /// 界面上的点 → 设备竖放时的点。`portrait`:竖放时的屏幕尺寸+ pub fn to_portrait(self, (x, y): (f64, f64), portrait: ScreenSize) -> (f64, f64) {+ let (w, h) = (portrait.width, portrait.height);+ match self {+ Self::Portrait => (x, y),+ Self::UpsideDown => (w - x, h - y),+ Self::TopToLeft => (w - y, x),+ Self::TopToRight => (y, h - x),+ }+ }+}+/// usbmuxd 报告的一台 USB 设备#[derive(Debug, Clone, PartialEq, Eq)]pub struct UsbDevice {@@ -134,6 +187,21 @@ pub fn apple_usb_present(root: &Path) -> bool {.any(|e| std::fs::read_to_string(e.path().join("idVendor")).map(|v| v.trim() == "05ac").unwrap_or(false))}+/// sysfs 里 iPhone/iPad/iPod 的台数:厂商号 05ac、产品名以 iPhone/iPad/iPod 开头(Apple 键盘之类的配件不算)。+/// 接着几台时和 usbmuxd 认到的台数比,才看得出「新插的那台没被认出来」+pub fn ios_usb_count(root: &Path) -> usize {+ let Ok(entries) = std::fs::read_dir(root) else { return 0 };+ let read = |p: &Path, f: &str| std::fs::read_to_string(p.join(f)).map(|v| v.trim().to_owned()).unwrap_or_default();+ entries+ .flatten()+ .filter(|e| {+ let p = e.path();+ read(&p, "idVendor") == "05ac"+ && ["iPhone", "iPad", "iPod"].iter().any(|n| read(&p, "product").starts_with(n))+ })+ .count()+}+/// Linux 上 USB 设备在 sysfs 里的目录pub const SYSFS_USB: &str = "/sys/bus/usb/devices";@@ -264,6 +332,12 @@ impl Device {})}+ /// 手机上装着的全部描述文件(.mobileprovision 原始内容,经 misagent 读)。装 App 时随包带的描述文件会留在这里,+ /// 用它判断「这台手机上的 WDA 还能用多久」:同一个 Apple ID 给几台手机先后签过,每台装的是各自那一次签的+ pub async fn installed_profiles(&self) -> Result<Vec<Vec<u8>>> {+ Ok(MisagentClient::connect(&*self.provider).await?.copy_all().await?)+ }+pub async fn developer_mode_enabled(&self) -> Result<bool> {Ok(AmfiClient::connect(&*self.provider).await?.get_developer_mode_status().await?)}@@ -358,7 +432,9 @@ impl Tunnel {.await?;self.hid = Some(h);}- Ok(self.hid.as_mut().expect("刚建好"))+ let h = self.hid.as_mut().expect("刚建好");+ h.screen = screen.portrait();+ Ok(h)}pub fn hid_open(&self) -> bool {@@ -382,6 +458,48 @@ impl Tunnel {mod tests {use super::*;+ /// 真机:摄像头在左(z=270)时,HID 按竖放发 (265,314) 落在了界面的 (314,165),反过来要换算回 (265,314)+ #[test]+ fn rotation_maps_screen_points_back_to_portrait() {+ let p = ScreenSize { width: 932.0, height: 430.0 }.portrait();+ assert_eq!(p, ScreenSize { width: 430.0, height: 932.0 });+ assert_eq!(Rotation::from_degrees(270.0), Some(Rotation::TopToLeft));+ assert_eq!(Rotation::from_degrees(90.0), Some(Rotation::TopToRight));+ assert_eq!(Rotation::from_degrees(-90.0), Some(Rotation::TopToLeft));+ assert_eq!(Rotation::from_degrees(0.0), Some(Rotation::Portrait));+ assert_eq!(Rotation::from_degrees(45.0), None);+ for z in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.4, 90.1] {+ assert_eq!(Rotation::from_degrees(z), None);+ }+ assert_eq!(Rotation::TopToLeft.to_portrait((314.0, 165.0), p), (265.0, 314.0));+ // 顶边在右:界面左上角是竖放时的左下角+ assert_eq!(Rotation::TopToRight.to_portrait((0.0, 0.0), p), (0.0, 932.0));+ assert_eq!(Rotation::TopToRight.to_portrait((226.0, 97.0), p), (97.0, 706.0));+ assert_eq!(Rotation::UpsideDown.to_portrait((0.0, 0.0), p), (430.0, 932.0));+ assert_eq!(Rotation::Portrait.to_portrait((12.0, 34.0), p), (12.0, 34.0));+ }++ #[test]+ fn ios_usb_count_counts_iphones_and_ipads_only() {+ let root = std::env::temp_dir().join(format!("ictl-sysfs-{}", std::process::id()));+ let dev = |name: &str, vendor: &str, product: &str| {+ let d = root.join(name);+ std::fs::create_dir_all(&d).unwrap();+ std::fs::write(d.join("idVendor"), format!("{vendor}\n")).unwrap();+ std::fs::write(d.join("product"), format!("{product}\n")).unwrap();+ };+ dev("5-1", "05ac", "iPhone");+ dev("7-1", "05ac", "iPad");+ dev("3-1", "05ac", "Magic Keyboard");+ dev("1-1", "2109", "USB2.0 Hub");+ // 接口目录没有 idVendor+ std::fs::create_dir_all(root.join("5-1:1.0")).unwrap();+ assert_eq!(ios_usb_count(&root), 2);+ assert!(apple_usb_present(&root));+ std::fs::remove_dir_all(&root).unwrap();+ assert_eq!(ios_usb_count(&root), 0);+ }+#[test]fn same_udid_new_mux_id_is_new_connection() {let first = UsbDevice { udid: "00008130-0019295E012B803A".into(), device_id: 2 };diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rsindex f3daab4..5667c83 100644--- a/crates/ictl-mcp/src/lib.rs+++ b/crates/ictl-mcp/src/lib.rs@@ -25,7 +25,8 @@ pub const INSTRUCTIONS: &str = "控制一台通过 USB 连接的真实 iPhone。配置了锁屏密码时,各操作工具会先自动解锁。每次操作后再截图确认结果。\涉及付款、删除、发送消息、修改账号或隐私设置的操作,先向用户确认。\省时间:操作类工具可带 then=elements 或 then=screenshot,等界面稳定后顺带返回操作后的界面,不用再单独调一次;\-几步确定的连续操作(按键、逐级点菜单、填表)用 iphone_batch 一次发完;等页面加载用 iphone_wait_for,不要反复截图。";+几步确定的连续操作(按键、逐级点菜单、填表)用 iphone_batch 一次发完;等页面加载用 iphone_wait_for,不要反复截图。\+接着多台 iPhone/iPad 时同一时间只控制一台:用 iphone_list_devices 查看,iphone_select_device 切换。";fn num(desc: &str) -> Value {json!({"type": "number", "description": desc})@@ -103,7 +104,7 @@ fn acting(title: &str, destructive: bool, idempotent: bool) -> ToolAnnotations {ToolAnnotations::with_title(title).read_only(false).destructive(destructive).idempotent(idempotent).open_world(true)}-/// 15 个工具的定义(toolkit 的 13 个 + iphone_wait_for、iphone_batch)。+/// 17 个工具的定义(toolkit 的 13 个 + iphone_wait_for、iphone_batch、iphone_list_devices、iphone_select_device)。/// 描述可以改写,但工具名、参数、默认返回不改(docs/decisions.md D10)pub fn tools() -> Vec<Tool> {let t = |name: &'static str, desc: String, s: Map<String, Value>, a: ToolAnnotations| {@@ -338,6 +339,29 @@ WDA 不可用时改用 HID,只能输入美式键盘上的英文和符号。",),looking("等文字出现"),),+ t(+ "iphone_list_devices",+ "列出 USB 上接着的全部 iPhone/iPad,每行一台:设备名、型号、iOS 版本、UDID,标出正在控制哪台、有没有设自动解锁密码。\n\n\+何时用:接着多台设备、要确认操作落在哪台,或切换前查设备名和 UDID。同一时间只控制一台,其他工具都作用在正在控制的那台上。只读。"+ .into(),+ schema(json!({}), &[]),+ looking("列出设备"),+ ),+ t(+ "iphone_select_device",+ "改为控制另一台设备,之后所有工具都作用在它上面,守护进程重启后还记得。device 是 UDID 或设备名(设备名包含这段文字且只有一台也行),\+auto 表示取消选定、改回自动选(正在控制的那台断开才换)。\n\n\+何时用:接着多台设备、要操作的不是正在控制的那台。先用 iphone_list_devices 看有哪几台。\n\n\+行为:切换后要在新设备上拉起 WDA(10~60 秒),期间读界面、按名字点击等用不了,先用 iphone_status 确认就绪。\+自动解锁按设备分开存密码,新设备没设就不会自动解锁。设了 IPHONE_UDID 时不能切换。\n\n\+返回:一行结果文字,例如「已切换到 Derrors 的 iPad(iPad11,1 iOS 26.6.1,00008020-…)」。"+ .into(),+ schema(+ json!({"device": {"type": "string", "description": "UDID、设备名,或 auto(改回自动选)"}}),+ &["device"],+ ),+ ToolAnnotations::with_title("切换设备").read_only(false).destructive(false).idempotent(true).open_world(false),+ ),t("iphone_batch",action_desc(@@ -446,6 +470,8 @@ pub fn to_request(name: &str, args: &Map<String, Value>) -> Result<Request, Stri"iphone_launch_app" => Request::LaunchApp { app: a.s("app")? },"iphone_terminate_app" => Request::TerminateApp { app: a.s("app")? },"iphone_open_url" => Request::OpenUrl { url: a.s("url")? },+ "iphone_list_devices" => Request::ListDevices,+ "iphone_select_device" => Request::SelectDevice { device: a.s("device")? },"iphone_wait_for" => {let secs = a.f_or("timeout", 5.0)?;if !(0.0..=30.0).contains(&secs) {@@ -549,7 +575,9 @@ pub fn tap_missed(text: &str) -> bool {/// 不带 then 的操作做完后要不要查系统弹窗(弹窗挡着时操作都落在弹窗上,WDA 照样报成功)。/// 按键自己处理(Home 先查弹窗;锁屏后不用查),结束 App 后前台是主屏,不会冒出新弹窗pub fn wants_alert_check(req: &Request) -> bool {- req.is_device_action() && !matches!(req, Request::PressButton { .. } | Request::TerminateApp { .. })+ // 切换设备后新设备的 WDA 还没起来,查不了弹窗+ req.is_device_action()+ && !matches!(req, Request::PressButton { .. } | Request::TerminateApp { .. } | Request::SelectDevice { .. })}/// 守护进程响应 → MCP 结果。错误走工具错误(is_error),文字原样给客户端@@ -737,10 +765,17 @@ mod tests {}#[test]- fn toolkit_tools_plus_wait_for_and_batch() {+ fn toolkit_tools_plus_wait_for_batch_and_devices() {let names: Vec<_> = tools().iter().map(|t| t.name.to_string()).collect();- assert_eq!(names.len(), 15);- for n in ["iphone_status", "iphone_screenshot", "iphone_tap_element", "iphone_open_url"] {+ assert_eq!(names.len(), 17);+ for n in [+ "iphone_status",+ "iphone_screenshot",+ "iphone_tap_element",+ "iphone_open_url",+ "iphone_list_devices",+ "iphone_select_device",+ ] {assert!(names.contains(&n.to_owned()), "{n}");}for t in tools().into_iter().filter(|t| t.name != "iphone_batch") {diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rsindex c52d4bb..e6cbf45 100644--- a/crates/ictl-protocol/src/lib.rs+++ b/crates/ictl-protocol/src/lib.rs@@ -117,6 +117,12 @@ pub enum Request {force: bool,},UnlockReset,+ /// 列出 USB 上接着的全部设备,标出正在控制哪台+ ListDevices,+ /// 改为控制另一台设备:`device` 是 UDID、设备名或 `auto`(取消选定,改回自动选)+ SelectDevice {+ device: String,+ },}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]@@ -158,6 +164,7 @@ impl Request {| Self::LaunchApp { .. }| Self::TerminateApp { .. }| Self::OpenUrl { .. }+ | Self::SelectDevice { .. })}}diff --git a/crates/ictl-unlock/src/fake.rs b/crates/ictl-unlock/src/fake.rsindex ba60a22..88a9e2d 100644--- a/crates/ictl-unlock/src/fake.rs+++ b/crates/ictl-unlock/src/fake.rs@@ -6,6 +6,8 @@//! - 按 Home 不清空半截输入(iOS 27 真机);右下角删除键每按一下删一位//! - 可选熄屏:熄屏时上滑无效,要先按 Home 点亮;可设成 XCTest 的 home 点不亮(iPhone 12 mini / iOS 26.4.1 真机),//! 只有 IOHID 的 AC Home 能点亮+//! - 可选 iPad 模式(iPad mini 5 / iPadOS 26.6.1 真机):横屏、Touch ID。上滑后是「触控 ID」提示,点「使用密码」才出键盘;+//! SpringBoard 的树是竖屏坐标,点击是屏幕坐标。点到别处什么都不发生(记在 `stray_taps`)use std::sync::Mutex;use std::time::Duration;@@ -31,6 +33,27 @@ const KEYS: [(i64, i64); 10] = [/// lockscreen.xml 里右下角按钮(有输入时是「删除」)的中心const DELETE: (i64, i64) = (327, 857);+const IPAD_TOUCHID_XML: &str = include_str!("../../ictl-wda/tests/fixtures/ipad-touchid-landscape.xml");+const IPAD_PIN_XML: &str = include_str!("../../ictl-wda/tests/fixtures/ipad-passcode-landscape.xml");+/// Home 键在左的横屏:树里的坐标和上面中心对称,换算到屏幕上键位不变+const IPAD_TOUCHID_LEFT_XML: &str = include_str!("../../ictl-wda/tests/fixtures/ipad-touchid-landscape-home-left.xml");+const IPAD_PIN_LEFT_XML: &str = include_str!("../../ictl-wda/tests/fixtures/ipad-passcode-landscape-home-left.xml");+/// ipad-passcode-landscape.xml 里各键按 Home 键在右的横屏换算到屏幕上的中心点(真机截图对得上)+const IPAD_KEYS: [(i64, i64); 10] = [+ (512, 586),+ (406, 282),+ (512, 282),+ (618, 282),+ (406, 384),+ (512, 384),+ (618, 384),+ (406, 484),+ (512, 484),+ (618, 484),+];+const IPAD_DELETE: (i64, i64) = (618, 586);+const IPAD_USE_PASSCODE: (i64, i64) = (512, 430);+#[derive(Debug, Clone, Default)]pub struct State {pub locked: bool,@@ -56,17 +79,35 @@ pub struct State {/// XCTest 的 home 点不亮屏幕xctest_home_dead: bool,pub hid_events: u32,+ /// iPad 模式:点过「使用密码」,键盘出来了+ pub passcode_requested: bool,+ /// iPad 模式:点在键和按钮以外的次数+ pub stray_taps: u32,}pub struct FakeLockScreen {code: Vec<u8>,st: Mutex<State>,+ /// iPad 模式时 WDA 报的方向(`/orientation`);None 是 iPhone 模式,`/orientation` 报 404+ ipad: Option<&'static str>,+ /// iPad 横屏时 Home 键在左(默认在右)+ ipad_home_left: bool,}impl FakeLockScreen {pub fn new(code: &str) -> Self {let st = State { locked: true, idle: (10.0, 2.0), ..Default::default() };- Self { code: code.bytes().map(|b| b - b'0').collect(), st: Mutex::new(st) }+ Self { code: code.bytes().map(|b| b - b'0').collect(), st: Mutex::new(st), ipad: None, ipad_home_left: false }+ }++ /// iPad 横屏(Home 键在右)、Touch ID;WDA 报的方向是 `orientation`+ pub fn ipad_touch_id(code: &str, orientation: &'static str) -> Self {+ Self { ipad: Some(orientation), ..Self::new(code) }+ }++ /// 同上,但 Home 键在左。真机上 WDA 照样报 `LANDSCAPE`+ pub fn ipad_touch_id_home_left(code: &str, orientation: &'static str) -> Self {+ Self { ipad_home_left: true, ..Self::ipad_touch_id(code, orientation) }}pub fn state(&self) -> State {@@ -129,7 +170,11 @@ impl FakeLockScreen {let v = match (method, path) {("GET", "/wda/locked") => json!(s.locked && !s.stale_wda_lock),("GET", "/wda/activeAppInfo") => json!({"bundleId": "com.apple.springboard"}),+ ("GET", "/wda/screen") if self.ipad.is_some() => {+ json!({"screenSize": {"width": 1024, "height": 768}, "scale": 2})+ }("GET", "/wda/screen") => json!({"screenSize": {"width": 430, "height": 932}, "scale": 3}),+ ("GET", "/orientation") if self.ipad.is_some() => json!(self.ipad),("POST", "/session") => return (200, json!({"sessionId": "S", "value": {}})),("GET", "/appium/settings") => json!({"waitForIdleTimeout": s.idle.0, "animationCoolOffTimeout": s.idle.1}),("POST", "/appium/settings") => {@@ -176,14 +221,28 @@ impl FakeLockScreen {} else {s.presses_per_action_max = s.presses_per_action_max.max(downs);let (x, y) = (steps[0]["x"].as_f64().unwrap() as i64, steps[0]["y"].as_f64().unwrap() as i64);- if (x, y) == DELETE {+ let (keys, delete) = if self.ipad.is_some() { (IPAD_KEYS, IPAD_DELETE) } else { (KEYS, DELETE) };+ // iPad:键盘要点「使用密码」才出来+ let pad_shown = s.shown && (self.ipad.is_none() || s.passcode_requested);+ if self.ipad.is_some() && (x, y) == IPAD_USE_PASSCODE {if s.shown {+ s.passcode_requested = true;+ }+ return (200, json!({"value": null, "sessionId": "S"}));+ }+ if (x, y) == delete {+ if pad_shown {s.entered.pop();}return (200, json!({"value": null, "sessionId": "S"}));}- let digit = KEYS.iter().position(|k| *k == (x, y)).expect("按在键盘以外") as u8;- if s.shown {+ let Some(digit) = keys.iter().position(|k| *k == (x, y)) else {+ assert!(self.ipad.is_some(), "按在键盘以外:{x},{y}");+ s.stray_taps += 1;+ return (200, json!({"value": null, "sessionId": "S"}));+ };+ let digit = digit as u8;+ if pad_shown {s.press_count += 1;let times = match s.press_count {n if s.drop_press == Some(n) => 0,@@ -197,6 +256,7 @@ impl FakeLockScreen {if s.entered == self.code {s.locked = false;s.shown = false;+ s.passcode_requested = false;} else {s.failed_attempts += 1;}@@ -210,11 +270,21 @@ impl FakeLockScreen {("GET", p) if p.starts_with("/source") => {if s.locked {let field = format!("共{}位数,已输入{}位", self.code.len(), s.entered.len());- json!(LOCK_XML.replace("共6位数,已输入0位", &field))+ let pin = s.shown && s.passcode_requested;+ let xml = match (self.ipad, self.ipad_home_left, pin) {+ (None, ..) => LOCK_XML,+ (Some(_), false, true) => IPAD_PIN_XML,+ (Some(_), false, false) => IPAD_TOUCHID_XML,+ (Some(_), true, true) => IPAD_PIN_LEFT_XML,+ (Some(_), true, false) => IPAD_TOUCHID_LEFT_XML,+ };+ json!(xml.replace("共6位数,已输入0位", &field))} else {json!(HOME_XML)}}+ // iPad 的「触控 ID」提示页上没有密码栏+ ("POST", "/elements") if self.ipad.is_some() && !(s.shown && s.passcode_requested) => json!([]),("POST", "/elements") => json!([{"ELEMENT": "E1"}]),("GET", "/element/E1/attribute/value") => {json!(format!("共{}位数,已输入{}位", self.code.len(), s.entered.len()))diff --git a/crates/ictl-unlock/src/lib.rs b/crates/ictl-unlock/src/lib.rsindex e1df5e4..cd10c79 100644--- a/crates/ictl-unlock/src/lib.rs+++ b/crates/ictl-unlock/src/lib.rs@@ -2,7 +2,9 @@//!//! 规则全部来自 toolkit 实测(docs/dev/capability-matrix.md §5)://! 1. 先读 `/wda/locked`,没锁直接返回;WDA 不可用也直接返回(交给后面的调用去报错)-//! 2. 每轮固定:按 Home → 等 1.0s → 底部上滑 → 等 1.5s。不以「树里有键盘」判断:键盘收起时按键元素也常驻树中+//! 2. 每轮固定:按 Home → 等 1.0s → 底部上滑 → 等 1.5s。不以「树里有键盘」判断:键盘收起时按键元素也常驻树中。+//! 有 Touch ID 的机型上滑后是「触控 ID」提示,先点「使用密码」再等 1.5s 调出键盘。+//! 数字键的位置排不成电话键盘(坐标换算错了)就当没有键盘,一位都不按//! 3. 读密码栏「共N位数,已输入M位」:总位数和配置不符一位都不输;有残留输入先用右下角删除键逐位删到 0//! (iOS 27 上 Home 不会清空残留),删不掉就下一轮//! 4. 每位一个独立 W3C 手势(按下 80ms),按完核对已输入位数正好 +1,不符立即停——确定没凑满整串的不算输错;@@ -26,7 +28,7 @@ pub enum UnlockError {#[error("手机已锁屏;自动解锁之前失败过已停用,请人工解锁、核对密码后运行 iphone-control unlock-reset")]Disabled,#[error(- "调不出锁屏密码键盘(一位都没输进去),请截图看看锁屏界面;手机横放充电时会进入待机显示,那个界面调不出键盘,可在「设置 → 待机显示」里关掉"+ "调不出锁屏密码键盘(一位都没输进去),需要人工解锁;iPhone 横放充电时会进入待机显示,那个界面调不出键盘,可在「设置 → 待机显示」里关掉")]NoKeypad,/// 输入不完整,不算输错@@ -199,7 +201,6 @@ fn write_flag(cfg: &UnlockConfig, why: &str) -> std::io::Result<()> {async fn unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, code: &[u8]) -> Result<Outcome> {let t = &cfg.timing;- let screen = wda.screen_size().await?;let digit = |i: usize| (code[i] - b'0') as usize;let len = code.len() as u32;@@ -208,7 +209,8 @@ async fn unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, code:// Home 唤醒(键盘已打开时 iOS 27 只是把键收起,半截输入还在,下面用删除键处理)// 熄屏锁屏刚唤醒时上滑偶尔卡十几秒后报 `point.x != INFINITY`(WDA 还拿不到界面尺寸):一位没输,算这轮落空重来。// XCTest 的 home 和 IOHID 的 Home 轮流用:iPhone 12 mini(iOS 26.4.1)上 XCTest 的 home 点不亮熄灭的屏幕,- // IOHID 的能;iOS 27 上一直用的是 XCTest 的,第一轮还是它+ // IOHID 的能;iOS 27 上一直用的是 XCTest 的,第一轮还是它。+ // 唤醒后才问方向(iPad 横竖屏的上滑位置、键位换算都靠它):熄屏时的第一个无障碍查询要等约 8 秒let woke = async {if round % 2 == 0 {wda.press_button("home").await?;@@ -216,19 +218,20 @@ async fn unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, code:wda.press_home_hid().await?;}tokio::time::sleep(t.wake_settle).await;- let (cx, h) = (screen.width / 2.0, screen.height);- wda.actions(&swipe_steps((cx, h - 8.0), (cx, h * 0.45), 250)).await+ let view = wda.view().await?;+ let (cx, h) = (view.screen.width / 2.0, view.screen.height);+ wda.actions(&swipe_steps((cx, h - 8.0), (cx, h * 0.45), 250)).await?;+ Ok::<_, WdaError>(view)}.await;- if let Err(e) = woke {- match e {- WdaError::Remote { .. } => {- tracing::info!("唤醒/上滑失败,重来一轮:{e}");- continue;- }- other => return Err(other.into()),+ let view = match woke {+ Ok(v) => v,+ Err(e @ WdaError::Remote { .. }) => {+ tracing::info!("唤醒/上滑失败,重来一轮:{e}");+ continue;}- }+ Err(other) => return Err(other.into()),+ };tokio::time::sleep(t.swipe_settle).await;let check = wda.check_lock(None, false).await?;if !check.locked {@@ -237,12 +240,20 @@ async fn unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, code:// 核对时已取到元素树就直接用,密码栏也从树里读。那棵树是上滑后马上取的,键盘有时还没进树:// 缺键盘或密码栏时再取一次(真机上这样省掉一整轮,约 4.5 秒)let mut els = match &check.tree {- Some(xml) => elements::parse(xml, screen),+ Some(xml) => elements::parse(xml, view),None => wda.elements().await?,};if check.tree.is_some() && (elements::keypad(&els).is_none() || elements::passcode_field(&els).is_none()) {els = wda.elements().await?;}+ // Touch ID 机型:点「使用密码」调出键盘。不是数字键,点了不会算输错+ if elements::keypad(&els).is_none()+ && let Some(at) = elements::use_passcode_button(&els)+ {+ press(wda, at, t).await?;+ tokio::time::sleep(t.swipe_settle).await;+ els = wda.elements().await?;+ }let field = match elements::passcode_field(&els) {Some(f) => Some(f),None => wda.passcode_field().await?,@@ -477,6 +488,41 @@ mod tests {std::fs::remove_dir_all(dir).unwrap();}+ /// iPad mini 5(iPadOS 26.6.1)横屏:上滑后是「触控 ID」提示,点「使用密码」调出键盘;树是竖屏坐标,换算后按对键+ #[tokio::test]+ async fn ipad_touch_id_landscape_taps_use_passcode_then_unlocks() {+ let fake = FakeLockScreen::ipad_touch_id("123456", "LANDSCAPE");+ let (cfg, dir) = cfg(Some("123456"));+ assert_eq!(ensure_unlocked(&mut WdaClient::new(&fake), &cfg).await.unwrap(), Outcome::Unlocked);+ let s = fake.state();+ assert_eq!((s.failed_attempts, s.digits_typed, s.stray_taps), (0, 6, 0));+ assert!(!cfg.disabled_flag.exists());+ std::fs::remove_dir_all(dir).unwrap();+ }++ /// 另一个横屏方向(Home 键在左):WDA 照样报 `LANDSCAPE`,按状态栏的位置换算,按对键+ #[tokio::test]+ async fn ipad_touch_id_landscape_home_left_unlocks() {+ let fake = FakeLockScreen::ipad_touch_id_home_left("123456", "LANDSCAPE");+ let (cfg, dir) = cfg(Some("123456"));+ assert_eq!(ensure_unlocked(&mut WdaClient::new(&fake), &cfg).await.unwrap(), Outcome::Unlocked);+ let s = fake.state();+ assert_eq!((s.failed_attempts, s.digits_typed, s.stray_taps), (0, 6, 0));+ std::fs::remove_dir_all(dir).unwrap();+ }++ /// 方向报错(树是竖屏坐标却当成不用转):键位排不成电话键盘,一位数字都不按+ #[tokio::test]+ async fn ipad_landscape_with_wrong_orientation_types_nothing() {+ let fake = FakeLockScreen::ipad_touch_id("123456", "PORTRAIT");+ let (cfg, dir) = cfg(Some("123456"));+ assert!(matches!(ensure_unlocked(&mut WdaClient::new(&fake), &cfg).await, Err(UnlockError::NoKeypad)));+ let s = fake.state();+ assert_eq!((s.failed_attempts, s.digits_typed), (0, 0));+ assert!(!cfg.disabled_flag.exists());+ std::fs::remove_dir_all(dir).unwrap();+ }+#[tokio::test]async fn keypad_never_shows_is_no_keypad_not_wrong() {let fake = FakeLockScreen::new("123456");diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rsindex 86587c2..a81e3c2 100644--- a/crates/ictl-wda/src/client.rs+++ b/crates/ictl-wda/src/client.rs@@ -102,6 +102,7 @@ pub struct LockCheck {pub struct WdaClient<T> {transport: T,session: Option<String>,+ /// `/wda/screen` 第一次给的尺寸(当时的方向)。当前方向下的宽高见 [`Self::view`]screen: Option<ScreenSize>,/// 本客户端(对应一次 WDA 启动)是否确认过一次「确实没锁屏」,确认后 `/wda/locked` 就可信了lock_state_trusted: bool,@@ -183,19 +184,52 @@ impl<T: Transport> WdaClient<T> {Ok(self.call("GET", "/status", None, Duration::from_secs(5)).await?["value"]["ready"] == true)}- /// 屏幕点尺寸,拿到后缓存+ /// 当前方向下的屏幕点尺寸(转屏后宽高跟着变)pub async fn screen_size(&mut self) -> Result<ScreenSize> {- if let Some(s) = self.screen {- return Ok(s);- }- let v = self.get("/wda/screen").await?;- let s = &v["screenSize"];- let size = match (s["width"].as_f64(), s["height"].as_f64()) {- (Some(width), Some(height)) => ScreenSize { width, height },- _ => return Err(WdaError::Unavailable("/wda/screen 没有 screenSize".into())),+ Ok(self.view().await?.screen)+ }++ /// 当前方向下的屏幕尺寸和方向。尺寸只问一次 `/wda/screen`(约 0.3 秒),方向每次问(约 20 毫秒):+ /// 尺寸缓存的是问的那一刻的方向,转屏后不换算的话截图会被压扁、屏幕下半截的元素被当成屏幕外。+ /// 问不到方向(旧版 WDA 等)就按缓存的尺寸、方向未知(不换算元素坐标)+ pub async fn view(&mut self) -> Result<elements::View> {+ let base = match self.screen {+ Some(s) => s,+ None => {+ let v = self.get("/wda/screen").await?;+ let s = &v["screenSize"];+ let size = match (s["width"].as_f64(), s["height"].as_f64()) {+ (Some(width), Some(height)) => ScreenSize { width, height },+ _ => return Err(WdaError::Unavailable("/wda/screen 没有 screenSize".into())),+ };+ self.screen = Some(size);+ size+ }};- self.screen = Some(size);- Ok(size)+ Ok(match self.orientation().await {+ Ok(o) => elements::View { screen: o.orient(base), orientation: Some(o) },+ Err(e) => {+ tracing::debug!("读屏幕方向失败,按缓存的屏幕尺寸算:{e}");+ elements::View { screen: base, orientation: None }+ }+ })+ }++ /// 界面相对设备竖放转了多少(`GET /rotation` 的 z)。能分出两个横屏方向,`/orientation` 分不出+ pub async fn rotation(&mut self) -> Result<ictl_device::Rotation> {+ let v = self.in_session("GET", "/rotation", None, Duration::from_secs(10)).await?;+ v["z"]+ .as_f64()+ .and_then(ictl_device::Rotation::from_degrees)+ .ok_or_else(|| WdaError::Unavailable(format!("看不懂 WDA 给的旋转角:{v}")))+ }++ /// 前台界面的方向+ pub async fn orientation(&mut self) -> Result<elements::Orientation> {+ let v = self.in_session("GET", "/orientation", None, Duration::from_secs(10)).await?;+ v.as_str()+ .and_then(elements::Orientation::from_wda)+ .ok_or_else(|| WdaError::Unavailable(format!("看不懂 WDA 给的方向:{v}")))}/// 是否锁屏。WDA 的 `/wda/locked` 只靠 `com.apple.springboard.lockstate` 的变化通知维护@@ -290,8 +324,8 @@ impl<T: Transport> WdaClient<T> {/// 元素树,带上「谁盖住谁」「有没有加载圈」等信息pub async fn tree(&mut self) -> Result<elements::Tree> {- let screen = self.screen_size().await?;- Ok(elements::parse_tree(&self.source_xml().await?, screen))+ let view = self.view().await?;+ Ok(elements::parse_tree(&self.source_xml().await?, view))}/// 点击:一个 W3C actions 单指手势(按下 50ms),期间把等待设置临时调小。真机计时(iOS 27):@@ -441,6 +475,12 @@ impl<T: Transport> WdaClient<T> {_ => Launch::Slow,});}+ self.settle_launched(started).await;+ Ok(Launch::Foreground)+ }++ /// App 到了前台之后再等它画出来。`started`:发出启动请求的时刻+ async fn settle_launched(&mut self, started: tokio::time::Instant) {// 冷启动后立即点击会被吞(回归用例 #13)。原来固定再等 1 秒;改为等界面稳定:连续两次元素树一样// (读元素树时 WDA 本身也等界面空闲),最多仍是 1 秒let deadline = tokio::time::Instant::now() + Duration::from_secs(1);@@ -456,15 +496,52 @@ impl<T: Transport> WdaClient<T> {if let Some(left) = LAUNCH_MIN.checked_sub(started.elapsed()) {tokio::time::sleep(left).await;}- Ok(Launch::Foreground)}pub async fn terminate_app(&mut self, bundle_id: &str) -> Result<()> {self.post("/wda/apps/terminate", json!({"bundleId": bundle_id})).await.map(drop)}- pub async fn open_url(&mut self, url: &str) -> Result<()> {- self.in_session("POST", "/url", Some(json!({"url": url})), Duration::from_secs(60)).await.map(drop)+ /// 打开网址或 URL Scheme,等打开它的 App 到前台、画出来再返回(最多约 8 秒),同 [`Self::launch_app`]。+ /// 不等的话 App 冷启动时还是黑屏,紧接着截图会把两帧黑屏当成「画面已静止」(iPad Safari 真机)。+ /// 返回结果和前台 App;在原来的前台 App 里打开(Safari 里开网址)时等 1 秒没换就算打开了+ pub async fn open_url(&mut self, url: &str) -> Result<(Launch, String)> {+ let started = tokio::time::Instant::now();+ let before = self.active_app().await.unwrap_or_default();+ self.in_session("POST", "/url", Some(json!({"url": url})), Duration::from_secs(60)).await?;+ let deadline = started + Duration::from_secs(8);+ // 前台要连续两次是同一个才算:Safari 冷启动的一瞬间前台是 `com.apple.DocumentManager.DockFolderViewService`(iPad 真机)+ let mut last = String::new();+ loop {+ tokio::time::sleep(Duration::from_millis(300)).await;+ let waited = started.elapsed() >= Duration::from_secs(1);+ let now = self.active_app().await;+ let steady = now.as_ref().is_ok_and(|a| *a == last);+ if let Ok(a) = &now {+ last.clone_from(a);+ }+ match now {+ Ok(a) if a != before && a != SPRINGBOARD && steady => {+ self.settle_launched(started).await;+ return Ok((Launch::Foreground, a));+ }+ Ok(a) if a == before && a != SPRINGBOARD && waited => {+ self.settle_launched(started).await;+ return Ok((Launch::Foreground, a));+ }+ // 「要在某 App 中打开吗」之类的系统弹窗挡着时前台一直是 SpringBoard+ Ok(a) if a == SPRINGBOARD && waited => {+ if let Ok(Some(text)) = self.alert_text().await {+ return Ok((Launch::Blocked(text), a));+ }+ }+ _ => {}+ }+ if tokio::time::Instant::now() >= deadline {+ let now = self.active_app().await.unwrap_or_default();+ return Ok((Launch::Slow, now));+ }+ }}pub async fn idle_settings(&mut self) -> Result<IdleSettings> {@@ -618,14 +695,76 @@ mod tests {#[tokio::test]async fn screen_size_is_cached_and_status_ready() {+ let unknown = r#"{"value":{"error":"unknown command","message":"no"}}"#;let m = Mock::with(&[(200, r#"{"value":{"screenSize":{"width":430,"height":932},"scale":3}}"#),+ (200, r#"{"sessionId":"S"}"#),+ (404, unknown),+ (404, unknown),(200, r#"{"value":{"ready":true}}"#),]);let mut c = WdaClient::new(&m);+ // 问不到方向:按缓存的尺寸assert_eq!(c.screen_size().await.unwrap(), ScreenSize { width: 430.0, height: 932.0 });assert_eq!(c.screen_size().await.unwrap().width, 430.0);assert!(c.ready().await.unwrap());+ let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect();+ assert_eq!(paths.iter().filter(|p| *p == "/wda/screen").count(), 1);+ }++ #[tokio::test]+ async fn rotation_reads_z_angle() {+ let m = Mock::with(&[+ (200, r#"{"sessionId":"S"}"#),+ (200, r#"{"value":{"x":0,"y":0,"z":270}}"#),+ (200, r#"{"value":{"x":0,"y":0,"z":12}}"#),+ ]);+ let mut c = WdaClient::new(&m);+ assert_eq!(c.rotation().await.unwrap(), ictl_device::Rotation::TopToLeft);+ assert!(c.rotation().await.is_err());+ assert_eq!(m.seen.lock().unwrap()[1].1, "/session/S/rotation");+ }++ /// WDA 在横屏时启动,缓存的是 1024x768;转成竖屏后要给 768x1024+ #[tokio::test]+ async fn screen_size_follows_orientation_after_rotation() {+ let m = Mock::with(&[+ (200, r#"{"value":{"screenSize":{"width":1024,"height":768},"scale":2}}"#),+ (200, r#"{"sessionId":"S"}"#),+ (200, r#"{"value":"LANDSCAPE"}"#),+ (200, r#"{"value":"PORTRAIT"}"#),+ ]);+ let mut c = WdaClient::new(&m);+ let v = c.view().await.unwrap();+ assert_eq!(+ (v.screen, v.orientation),+ (ScreenSize { width: 1024.0, height: 768.0 }, Some(elements::Orientation::LandscapeLeft))+ );+ assert_eq!(c.screen_size().await.unwrap(), ScreenSize { width: 768.0, height: 1024.0 });+ assert_eq!(m.seen.lock().unwrap()[2].1, "/session/S/orientation");+ }++ /// 从主屏打开网址:等 Safari 到前台、元素树稳定才返回,不是发完请求就走;一闪而过的系统服务不算+ #[tokio::test]+ async fn open_url_waits_for_the_opening_app() {+ let m = Mock::with(&[+ (200, r#"{"value":{"bundleId":"com.apple.springboard"}}"#),+ (200, r#"{"sessionId":"S"}"#),+ (200, r#"{"value":null}"#),+ (200, r#"{"value":{"bundleId":"com.apple.DocumentManager.DockFolderViewService"}}"#),+ (200, r#"{"value":{"bundleId":"com.apple.mobilesafari"}}"#),+ (200, r#"{"value":{"bundleId":"com.apple.mobilesafari"}}"#),+ (200, r#"{"value":"<a/>"}"#),+ (200, r#"{"value":"<a/>"}"#),+ ]);+ let mut c = WdaClient::new(&m);+ let t0 = std::time::Instant::now();+ let (r, app) = c.open_url("https://example.com").await.unwrap();+ assert_eq!((r, app.as_str()), (Launch::Foreground, "com.apple.mobilesafari"));+ assert!(t0.elapsed() >= LAUNCH_MIN);+ let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect();+ assert_eq!(paths[2], "/session/S/url");+ assert!(paths[6].starts_with("/source"), "{paths:?}");}#[tokio::test]diff --git a/crates/ictl-wda/src/elements.rs b/crates/ictl-wda/src/elements.rsindex 32e501e..dbc9992 100644--- a/crates/ictl-wda/src/elements.rs+++ b/crates/ictl-wda/src/elements.rs@@ -31,6 +31,115 @@ impl Rect {}}+/// 界面方向,来自 WDA 的 `GET /session/:id/orientation`+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Orientation {+ Portrait,+ PortraitUpsideDown,+ /// WDA 报 `LANDSCAPE`+ LandscapeLeft,+ /// WDA 报 `UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT`+ LandscapeRight,+}++impl Orientation {+ pub fn from_wda(s: &str) -> Option<Self> {+ Some(match s {+ "PORTRAIT" => Self::Portrait,+ "UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN" => Self::PortraitUpsideDown,+ "LANDSCAPE" => Self::LandscapeLeft,+ "UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT" => Self::LandscapeRight,+ _ => return None,+ })+ }++ pub fn is_landscape(self) -> bool {+ matches!(self, Self::LandscapeLeft | Self::LandscapeRight)+ }++ /// 把任一方向下量到的屏幕尺寸换成这个方向下的(横屏宽大于高,竖屏反过来)+ pub fn orient(self, s: ScreenSize) -> ScreenSize {+ let (short, long) = (s.width.min(s.height), s.width.max(s.height));+ if self.is_landscape() {+ ScreenSize { width: long, height: short }+ } else {+ ScreenSize { width: short, height: long }+ }+ }+}++/// 解析元素树要知道的:当前方向下的屏幕尺寸,和方向(不知道时为 None,不做坐标换算)+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct View {+ pub screen: ScreenSize,+ pub orientation: Option<Orientation>,+}++impl From<ScreenSize> for View {+ fn from(screen: ScreenSize) -> Self {+ Self { screen, orientation: None }+ }+}++/// 元素树坐标到屏幕坐标的换算。iPad 横屏时 SpringBoard(主屏、长按菜单、锁屏)给的是竖屏坐标:+/// 窗口 768x1024,屏幕 1024x768;App 里给的是屏幕坐标(iPadOS 26.6.1 真机)。点击用的是屏幕坐标。+/// 往哪边转看状态栏:它在竖屏坐标里是一条贴边的竖条,贴哪边,哪边就是屏幕顶边。+/// WDA 报的方向靠不住:iPad mini 5 两个横屏方向在主屏上都报 `LANDSCAPE`(rotation z=90)+#[derive(Debug, Clone, Copy, PartialEq)]+enum Rotate {+ None,+ /// 竖屏的顶边转到了屏幕左边(Home 键在右):(x, y) → (y, 屏幕高 - x)+ TopToLeft,+ /// 竖屏的顶边转到了屏幕右边(Home 键在左):(x, y) → (屏幕宽 - y, x)+ TopToRight,+}++impl Rotate {+ /// 第一个窗口的宽高和横屏的屏幕正好相反:树是竖屏坐标,按状态栏(`status_bar`,树里第一个 StatusBar)贴的边转。+ /// 树里没有贴边的状态栏时退回看 WDA 报的方向;方向也不知道就不转+ fn detect(window: Rect, view: View, status_bar: Option<Rect>) -> Self {+ let s = view.screen;+ let swapped = s.width > s.height && (window.w - s.height).abs() < 1.0 && (window.h - s.width).abs() < 1.0;+ if !swapped {+ return Self::None;+ }+ // 竖屏坐标里贴边的竖条:贴左边(x=0)是 Home 键在左,贴右边(x+w=屏幕高)是 Home 键在右+ if let Some(b) = status_bar.filter(|b| (b.h - s.width).abs() < 1.0 && b.w > 0.0 && b.w < s.height / 4.0) {+ if b.x.abs() < 1.0 {+ return Self::TopToRight;+ }+ if (b.x + b.w - s.height).abs() < 1.0 {+ return Self::TopToLeft;+ }+ }+ match view.orientation {+ Some(Orientation::LandscapeLeft) => Self::TopToLeft,+ Some(Orientation::LandscapeRight) => Self::TopToRight,+ o => {+ tracing::warn!("元素树是竖屏坐标而屏幕是横的,但没有状态栏、方向是 {o:?},坐标不换算");+ Self::None+ }+ }+ }++ /// 树里第一个 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()+ };+ Some(Rect { x: attr("x")?, y: attr("y")?, w: attr("width")?, h: attr("height")? })+ }++ fn apply(self, r: Rect, s: ScreenSize) -> Rect {+ match self {+ Self::None => r,+ Self::TopToLeft => Rect { x: r.y, y: s.height - r.x - r.w, w: r.h, h: r.w },+ Self::TopToRight => Rect { x: s.width - r.y - r.h, y: r.x, w: r.h, h: r.w },+ }+ }+}+#[derive(Debug, Clone, Default)]pub struct Element {pub kind: String,@@ -244,12 +353,13 @@ fn py_round(v: f64) -> i64 {if (v - v.trunc()).abs() == 0.5 && (r as i64) % 2 != 0 { (r - v.signum()) as i64 } else { r as i64 }}-pub fn parse(xml: &str, screen: ScreenSize) -> Vec<Element> {- parse_tree(xml, screen).elements+pub fn parse(xml: &str, view: impl Into<View>) -> Vec<Element> {+ parse_tree(xml, view).elements}/// 解析时每个还没闭合的节点struct Open {+ /// 元素树坐标(小组件偏移已加上,还没换算到屏幕)abs: Rect,/// 在工具栏/标签栏里in_bar: bool,@@ -268,8 +378,12 @@ struct Open {blocker: Option<usize>,}-pub fn parse_tree(xml: &str, screen: ScreenSize) -> Tree {+pub fn parse_tree(xml: &str, view: impl Into<View>) -> Tree {+ let view = view.into();+ let screen = view.screen;let (sw, sh) = (screen.width, screen.height);+ // 看到 Application 下第一个窗口时定下来+ let mut rotate: Option<Rotate> = None;let mut reader = quick_xml::Reader::from_str(xml);let mut seen = std::collections::HashSet::new();let mut tree = Tree::default();@@ -330,6 +444,11 @@ pub fn parse_tree(xml: &str, screen: ScreenSize) -> Tree {offset = (p.abs.x, p.abs.y);}let abs = Rect { x: raw.x + offset.0, y: raw.y + offset.1, ..raw };+ if rotate.is_none() && kind == "Window" && stack.len() == 1 && abs.w > 0.0 && abs.h > 0.0 {+ rotate = Some(Rotate::detect(abs, view, Rotate::status_bar(xml)));+ }+ // 下面判断在不在屏幕内、挡没挡住、点哪里,都用屏幕坐标+ let scr = rotate.unwrap_or(Rotate::None).apply(abs, screen);let in_status_bar = kind == "StatusBar" || parent.is_some_and(|p| p.in_status_bar);let in_bar = matches!(kind.as_str(), "Toolbar" | "TabBar") || parent.is_some_and(|p| p.in_bar);let on_bar = in_bar || kind == "NavigationBar" || parent.is_some_and(|p| p.on_bar);@@ -338,9 +457,9 @@ pub fn parse_tree(xml: &str, screen: ScreenSize) -> Tree {let modal = MODALS.contains(&kind.as_str()) || parent.is_some_and(|p| p.modal);let group = if GROUPS.contains(&kind.as_str()) { n } else { parent.map_or(0, |p| p.group) };let onscreen =- abs.w > 0.0 && abs.h > 0.0 && abs.x < sw && abs.y < sh && abs.x + abs.w > 0.0 && abs.y + abs.h > 0.0;- let (vx1, vy1) = (abs.x.max(0.0), abs.y.max(0.0));- let visible = Rect { x: vx1, y: vy1, w: (abs.x + abs.w).min(sw) - vx1, h: (abs.y + abs.h).min(sh) - vy1 };+ scr.w > 0.0 && scr.h > 0.0 && scr.x < sw && scr.y < sh && scr.x + scr.w > 0.0 && scr.y + scr.h > 0.0;+ 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);if kind == "ActivityIndicator" && onscreen {@@ -383,7 +502,7 @@ pub fn parse_tree(xml: &str, screen: ScreenSize) -> Tree {let kind_for_children = kind.clone();let kept = text.filter(|text| {let noise = !onscreen- || (abs.w >= sw && abs.h >= sh)+ || (scr.w >= sw && scr.h >= sh)|| scroll_bar|| (in_status_bar && kind != "Button")|| (matches!(kind.as_str(), "Other" | "Image")@@ -397,7 +516,7 @@ pub fn parse_tree(xml: &str, screen: ScreenSize) -> Tree {&& !a.label.is_empty()&& (kind == "Image" || a.label.contains(text.as_str()))}));- !noise && seen.insert((text.clone(), py_round(abs.x), py_round(abs.y), py_round(abs.w), py_round(abs.h)))+ !noise && seen.insert((text.clone(), py_round(scr.x), py_round(scr.y), py_round(scr.w), py_round(scr.h)))});let kept = kept.map(|_| {tree.elements.push(Element {@@ -406,7 +525,7 @@ pub fn parse_tree(xml: &str, screen: ScreenSize) -> Tree {name,value,center: (py_round(visible.x + visible.w / 2.0), py_round(visible.y + visible.h / 2.0)),- size: (py_round(abs.w), py_round(abs.h)),+ size: (py_round(scr.w), py_round(scr.h)),visible,span: (n, n),layer: if on_bar {@@ -484,6 +603,7 @@ pub fn field_values(elements: &[Element]) -> Option<Vec<String>> {/// 锁屏密码键盘上 0~9 各键的中心点;没找齐 10 个返回 None。/// 找到了也不代表键盘在屏幕上——按键后要核对密码栏的已输入位数。+/// 键位不像电话键盘时也返回 None(见 [`keypad_layout_ok`])。pub fn keypad(elements: &[Element]) -> Option<[(i64, i64); 10]> {let mut keys: [Option<(i64, i64)>; 10] = [None; 10];for e in elements.iter().filter(|e| e.kind == "Button" || e.kind == "Key") {@@ -503,20 +623,52 @@ pub fn keypad(elements: &[Element]) -> Option<[(i64, i64); 10]> {for (i, k) in keys.into_iter().enumerate() {out[i] = k?;}+ if !keypad_layout_ok(&out) {+ tracing::warn!("锁屏数字键的位置不像电话键盘(坐标可能没换算对),不按:{out:?}");+ return None;+ }Some(out)}+/// 键位像电话键盘:1 2 3、4 5 6、7 8 9 三行各自同高、从左到右、自上而下,三列上下对齐,0 在 8 正下方。+/// 坐标换算错了(例如横屏时没把竖屏坐标转过来,1 2 3 会竖着排)就过不了:宁可调不出键盘,也不能按错键+fn keypad_layout_ok(k: &[(i64, i64); 10]) -> bool {+ const TOL: i64 = 10;+ let near = |a: i64, b: i64| (a - b).abs() <= TOL;+ let rows = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];+ let rows_ok = rows.iter().all(|r| {+ near(k[r[0]].1, k[r[1]].1) && near(k[r[0]].1, k[r[2]].1) && k[r[0]].0 < k[r[1]].0 && k[r[1]].0 < k[r[2]].0+ });+ let cols_ok = (1..=3).all(|c| near(k[c].0, k[c + 3].0) && near(k[c].0, k[c + 6].0));+ rows_ok && cols_ok && k[1].1 < k[4].1 && k[4].1 < k[7].1 && near(k[0].0, k[8].0) && k[0].1 > k[8].1+}+/// 密码键盘右下角的按钮:有输入时是「删除」(每按一下删一位),没输入时是「取消」。-/// 标签随语言变,按位置认:和 9 同一列、在 0 下面的 Button+/// 标签随语言变,按位置认:和 9 同一列、在 9 下面的 Button(iPhone 上在 0 的右下,iPad 上和 0 同一行)pub fn delete_key(elements: &[Element], pad: &[(i64, i64); 10]) -> Option<(i64, i64)> {- let (col, row0) = (pad[9].0, pad[0].1);+ let (col, row9) = (pad[9].0, pad[9].1);elements.iter()- .filter(|e| e.kind == "Button" && (e.center.0 - col).abs() <= 10 && e.center.1 > row0 + 50)+ .filter(|e| e.kind == "Button" && (e.center.0 - col).abs() <= 10 && e.center.1 > row9 + 50).map(|e| e.center).next()}+/// 有 Touch ID 的机型(iPad mini 5,iPadOS 26.6.1 真机)上滑后先是「触控 ID」提示,只有「使用密码」和「取消」两个按钮,+/// 树里没有数字键和密码栏,点「使用密码」才出键盘。返回它的中心。英文标签没在真机上核对过+pub fn use_passcode_button(elements: &[Element]) -> Option<(i64, i64)> {+ elements+ .iter()+ .find(|e| {+ e.kind == "Button"+ && (USE_PASSCODE_LABELS.contains(&e.label.as_str()) || USE_PASSCODE_LABELS.contains(&e.name.as_str()))+ })+ .map(|e| e.center)+}++/// 「触控 ID」提示上「使用密码」按钮的标签(英文的没在真机上核对过)+const USE_PASSCODE_LABELS: [&str; 3] = ["使用密码", "Use Passcode", "Enter Passcode"];+/// 元素树里锁屏密码栏的 (总位数, 已输入位数)pub fn passcode_field(elements: &[Element]) -> Option<(u32, u32)> {elements.iter().filter(|e| e.kind == "SecureTextField").find_map(|e| parse_passcode_value(&e.value))@@ -533,9 +685,11 @@ pub fn parse_passcode_value(value: &str) -> Option<(u32, u32)> {}/// SpringBoard 元素树看到的是哪种「封面」界面。用来纠正 `/wda/locked`(见 [`crate::WdaClient::locked`])。-/// 标识都与语言无关(iOS 27 真机样本):-/// - 锁屏有锁图标 `proud-lock`(灵动岛里还有 `systemApertureElementIdentifierLock`),上滑后的密码键盘有 `passcode-view`-/// - 通知中心和锁屏是同一个界面(都有 `lockscreen-date-view`),但没有锁图标+/// 锁屏的标识(iOS 27 iPhone 和 iPadOS 26.6.1 iPad mini 5 真机样本):+/// - Face ID 机型锁屏有锁图标 `proud-lock`(灵动岛里还有 `systemApertureElementIdentifierLock`),上滑后的密码键盘有 `passcode-view`+/// - Touch ID 机型没有锁图标,锁屏有 `call-to-action-label`(「按下主屏幕按钮以解锁」);上滑后的「触控 ID」提示和数字键盘+/// 都没有与语言无关的标识,只能认「使用密码」按钮和锁屏密码栏(值是「共6位数,已输入0位」这样的)+/// - 通知中心和锁屏是同一个界面(都有 `lockscreen-date-view`),但没有上面这些#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum CoverSheet {Locked,@@ -545,8 +699,14 @@ pub enum CoverSheet {pub fn cover_sheet(xml: &str) -> CoverSheet {let lock_glyph =- ["\"proud-lock\"", "systemApertureElementIdentifierLock", "\"passcode-view\""].iter().any(|m| xml.contains(m));- if lock_glyph {+ ["\"proud-lock\"", "systemApertureElementIdentifierLock", "\"passcode-view\"", "\"call-to-action-label\""]+ .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()));+ if lock_glyph || use_passcode || passcode_field {CoverSheet::Locked} else if xml.contains("\"lockscreen-date-view\"") {CoverSheet::NotificationCenter@@ -569,6 +729,40 @@ mod tests {const SETTINGS_IOS27: &str = include_str!("../tests/fixtures/settings-floating-search-ios27.xml");const HOME_WIDGETS_IOS27: &str = include_str!("../tests/fixtures/home-widgets-ios27.xml");const WALLET_IOS27: &str = include_str!("../tests/fixtures/settings-wallet-ios27.xml");+ const IPAD_TOUCHID: &str = include_str!("../tests/fixtures/ipad-touchid-landscape.xml");+ const IPAD_PIN: &str = include_str!("../tests/fixtures/ipad-passcode-landscape.xml");+ const IPAD_LOCK_P: &str = include_str!("../tests/fixtures/ipad-lockscreen-portrait.xml");+ const IPAD_TOUCHID_P: &str = include_str!("../tests/fixtures/ipad-touchid-portrait.xml");+ const IPAD_PIN_P: &str = include_str!("../tests/fixtures/ipad-passcode-portrait.xml");+ const IPAD_TOUCHID_LEFT: &str = include_str!("../tests/fixtures/ipad-touchid-landscape-home-left.xml");+ const IPAD_PIN_LEFT: &str = include_str!("../tests/fixtures/ipad-passcode-landscape-home-left.xml");+ const IPAD_LAND: ScreenSize = ScreenSize { width: 1024.0, height: 768.0 };++ fn land(o: Option<Orientation>) -> View {+ View { screen: IPAD_LAND, orientation: o }+ }++ /// iPad 横屏主屏:Application 是屏幕坐标,窗口是竖屏坐标+ fn ipad_home(window: (u32, u32)) -> String {+ ipad_home_at(window, (386, 546), None)+ }++ /// `icon` 是「计算器」图标的原始坐标;`status_bar_x` 是竖屏坐标里状态栏竖条(32x1024)的 x+ fn ipad_home_at(window: (u32, u32), icon: (u32, u32), status_bar_x: Option<u32>) -> String {+ let bar = status_bar_x.map_or(String::new(), |x| {+ format!(+ r#"<XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+<XCUIElementTypeStatusBar type="XCUIElementTypeStatusBar" x="{x}" y="0" width="32" height="1024"/></XCUIElementTypeWindow>"#+ )+ });+ format!(+ r#"<XCUIElementTypeApplication type="XCUIElementTypeApplication" x="0" y="0" width="1024" height="768">+<XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="{}" height="{}">+<XCUIElementTypeIcon type="XCUIElementTypeIcon" label="计算器" x="{}" y="{}" width="96" height="72"/>+</XCUIElementTypeWindow>{bar}</XCUIElementTypeApplication>"#,+ window.0, window.1, icon.0, icon.1+ )+ }#[test]fn delete_key_found_by_position_on_real_keypad() {@@ -853,45 +1047,64 @@ mod tests {assert_eq!(filter(&h, "新项目").iter().map(|e| e.label.as_str()).collect::<Vec<_>>(), ["设置"]);}- fn key(label: &str, x: i64, kind: &str) -> Element {+ fn key(label: &str, at: (i64, i64), kind: &str) -> Element {Element {kind: kind.into(),label: label.into(),name: label.into(),- center: (x, 100),+ center: at,size: (80, 80),..Default::default()}}+ /// 电话键盘上数字 d 的位置:1 2 3 / 4 5 6 / 7 8 9 / 0 在 8 下面,间距 100+ fn phone(d: i64) -> (i64, i64) {+ if d == 0 { (200, 400) } else { ((d - 1) % 3 * 100 + 100, (d - 1) / 3 * 100 + 100) }+ }+#[test]fn keypad_needs_all_ten_digits() {- let keys: Vec<_> = (0..10).map(|d| key(&d.to_string(), d * 10, "Key")).collect();+ let keys: Vec<_> = (0..10).map(|d| key(&d.to_string(), phone(d), "Key")).collect();let pad = keypad(&keys).unwrap();- assert_eq!(pad[0], (0, 100));- assert_eq!(pad[9], (90, 100));+ assert_eq!(pad[0], (200, 400));+ assert_eq!(pad[9], (300, 300));assert!(keypad(&keys[..9]).is_none());}#[test]fn keypad_accepts_letters_after_digit_but_not_multi_digit_labels() {- let keys: Vec<_> = (0..10).map(|d| key(&format!("{d} ABC"), d, "Button")).collect();+ let keys: Vec<_> = (0..10).map(|d| key(&format!("{d} ABC"), phone(d), "Button")).collect();assert!(keypad(&keys).is_some());- let mut keys: Vec<_> = (0..9).map(|d| key(&d.to_string(), d, "Key")).collect();- keys.push(key("10", 0, "Key"));+ let mut keys: Vec<_> = (0..9).map(|d| key(&d.to_string(), phone(d), "Key")).collect();+ keys.push(key("10", phone(0), "Key"));assert!(keypad(&keys).is_none());// 锁屏通知上的「3条通知」不能占掉 3 的位置- let mut keys = vec![key("3条通知", 99, "Button")];- keys.extend((0..10).map(|d| key(&d.to_string(), d, "Key")));- assert_eq!(keypad(&keys).unwrap()[3], (3, 100));+ let mut keys = vec![key("3条通知", (999, 50), "Button")];+ keys.extend((0..10).map(|d| key(&d.to_string(), phone(d), "Key")));+ assert_eq!(keypad(&keys).unwrap()[3], (300, 100));}#[test]fn keypad_ignores_non_key_types() {- let keys: Vec<_> = (0..10).map(|d| key(&d.to_string(), d, "StaticText")).collect();+ let keys: Vec<_> = (0..10).map(|d| key(&d.to_string(), phone(d), "StaticText")).collect();assert!(keypad(&keys).is_none());}+ /// 横屏时竖屏坐标没换算:1 2 3 竖着排。不能当成键盘去按(会按错数字)+ #[test]+ fn keypad_with_wrong_layout_is_rejected() {+ let rotated: Vec<_> = (0..10).map(|d| key(&d.to_string(), (phone(d).1, phone(d).0), "Key")).collect();+ assert!(keypad(&rotated).is_none());+ let mut swapped: Vec<_> = (0..10).map(|d| key(&d.to_string(), phone(d), "Key")).collect();+ swapped[1].center = phone(3);+ swapped[3].center = phone(1);+ assert!(keypad(&swapped).is_none());+ let mut zero_on_top: Vec<_> = (0..10).map(|d| key(&d.to_string(), phone(d), "Key")).collect();+ zero_on_top[0].center = (200, 0);+ assert!(keypad(&zero_on_top).is_none());+ }+/// 回归用例 #1:键盘收起时 Key 元素仍在树里。只能证明"树里有",解锁逻辑不能拿它判断键盘已显示#[test]fn hidden_keypad_still_present_in_tree() {@@ -911,4 +1124,144 @@ mod tests {assert_eq!(parse_passcode_value("共4位数"), None);assert_eq!(parse_passcode_value(""), None);}++ #[test]+ fn orientation_from_wda_and_screen_size() {+ assert_eq!(Orientation::from_wda("LANDSCAPE"), Some(Orientation::LandscapeLeft));+ assert_eq!(Orientation::from_wda("UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT"), Some(Orientation::LandscapeRight));+ assert_eq!(+ Orientation::from_wda("UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN"),+ Some(Orientation::PortraitUpsideDown)+ );+ assert_eq!(Orientation::from_wda("PORTRAIT"), Some(Orientation::Portrait));+ assert_eq!(Orientation::from_wda("UNKNOWN"), None);+ let portrait = ScreenSize { width: 768.0, height: 1024.0 };+ assert_eq!(Orientation::LandscapeRight.orient(portrait), IPAD_LAND);+ assert_eq!(Orientation::Portrait.orient(IPAD_LAND), portrait);+ assert_eq!(Orientation::PortraitUpsideDown.orient(portrait), portrait);+ }++ /// 真机:横屏主屏上「计算器」树里在 (434,582),截图里在 (582,334) 附近+ #[test]+ fn ipad_landscape_springboard_is_rotated_to_screen_coordinates_by_orientation_without_status_bar() {+ let left = parse(&ipad_home((768, 1024)), land(Some(Orientation::LandscapeLeft)));+ assert_eq!((left[0].center, left[0].size), ((582, 334), (72, 96)));+ let right = parse(&ipad_home((768, 1024)), land(Some(Orientation::LandscapeRight)));+ assert_eq!((right[0].center, right[0].size), ((442, 434), (72, 96)));+ }++ /// App 里(窗口和屏幕一样是横的)坐标本来就是屏幕坐标,不转+ #[test]+ fn ipad_landscape_app_tree_is_not_rotated() {+ let els = parse(&ipad_home((1024, 768)), land(Some(Orientation::LandscapeLeft)));+ assert_eq!((els[0].center, els[0].size), ((434, 582), (96, 72)));+ }++ /// 竖屏时屏幕下半截(y > 768)的元素也要在:转屏前缓存的横屏尺寸会把它们当成屏幕外+ #[test]+ fn ipad_portrait_keeps_elements_below_768() {+ let xml = r#"<XCUIElementTypeApplication type="XCUIElementTypeApplication" x="0" y="0" width="768" height="1024">+<XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+<XCUIElementTypeIcon type="XCUIElementTypeIcon" label="Safari浏览器" x="40" y="940" width="69" height="69"/>+</XCUIElementTypeWindow>+<XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="1024" height="768"/>+</XCUIElementTypeApplication>"#;+ let portrait =+ View { screen: ScreenSize { width: 768.0, height: 1024.0 }, orientation: Some(Orientation::Portrait) };+ assert_eq!(parse(xml, portrait)[0].center, (74, 974));+ }++ /// 横屏锁屏:转好之后键盘是电话键盘的样子,「取消/删除」和 0 同一行,「使用密码」在提示页中间(真机截图对得上)+ #[test]+ fn ipad_landscape_lock_screen_keypad_and_use_passcode() {+ let els = parse(IPAD_PIN, land(Some(Orientation::LandscapeLeft)));+ let pad = keypad(&els).expect("转好坐标后应能认出键盘");+ let want = [+ (512, 586),+ (406, 282),+ (512, 282),+ (618, 282),+ (406, 384),+ (512, 384),+ (618, 384),+ (406, 484),+ (512, 484),+ (618, 484),+ ];+ assert_eq!(pad, want);+ assert_eq!(delete_key(&els, &pad), Some((618, 586)));+ assert_eq!(passcode_field(&els), Some((6, 0)));+ assert_eq!(use_passcode_button(&els), None);++ let bouncer = parse(IPAD_TOUCHID, land(Some(Orientation::LandscapeLeft)));+ assert_eq!(use_passcode_button(&bouncer), Some((512, 430)));+ assert!(keypad(&bouncer).is_none());+ assert_eq!(passcode_field(&bouncer), None);+ }++ /// 没有状态栏、也不知道方向就不转;没转的竖屏坐标排不成电话键盘,认不出键盘,一位都不会按+ #[test]+ fn ipad_landscape_keypad_without_status_bar_or_orientation_is_not_used() {+ let no_bar = regex::Regex::new(r"<XCUIElementTypeStatusBar [^>]*/>").unwrap().replace(IPAD_PIN, "");+ assert!(!no_bar.contains("StatusBar"));+ assert!(keypad(&parse(&no_bar, land(None))).is_none());+ assert!(keypad(&parse(&no_bar, land(Some(Orientation::Portrait)))).is_none());+ // 有状态栏就按它转,不用方向+ assert!(keypad(&parse(IPAD_PIN, land(None))).is_some());+ }++ /// Touch ID 的 iPad 锁屏、上滑后的提示、数字键盘都要认成锁屏:WDA 在锁屏时启动时 `/wda/locked` 报 false,+ /// 认不出就会当成没锁(真机上发生过:工具照常执行,停在锁屏上)+ #[test]+ fn ipad_touch_id_lock_screens_are_locked() {+ for xml in [IPAD_LOCK_P, IPAD_TOUCHID_P, IPAD_PIN_P, IPAD_TOUCHID, IPAD_PIN] {+ assert_eq!(cover_sheet(xml), CoverSheet::Locked);+ }+ assert_eq!(cover_sheet(NC_IOS27), CoverSheet::NotificationCenter);+ assert_eq!(cover_sheet(HOME), CoverSheet::None);+ }++ /// 真机竖屏:提示页点「使用密码」,键盘页按键是电话键盘、「取消/删除」和 0 同一行+ #[test]+ fn ipad_portrait_touch_id_and_keypad_from_real_trees() {+ let portrait =+ View { screen: ScreenSize { width: 768.0, height: 1024.0 }, orientation: Some(Orientation::Portrait) };+ let bouncer = parse(IPAD_TOUCHID_P, portrait);+ assert_eq!(use_passcode_button(&bouncer), Some((384, 533)));+ assert!(keypad(&bouncer).is_none());+ let els = parse(IPAD_PIN_P, portrait);+ let pad = keypad(&els).unwrap();+ assert_eq!((pad[1], pad[0]), ((278, 410), (384, 714)));+ assert_eq!(delete_key(&els, &pad), Some((490, 714)));+ assert_eq!(passcode_field(&els), Some((6, 0)));+ }++ /// 真机两个横屏方向 WDA 都报 `LANDSCAPE`,「计算器」都在截图的 (582,334):+ /// Home 键在右时原始框 (386,546)、状态栏贴树的右边;Home 键在左时原始框 (286,406)、状态栏贴树的左边(x=0)+ #[test]+ fn ipad_landscape_direction_comes_from_status_bar_not_orientation() {+ let o = land(Some(Orientation::LandscapeLeft));+ let home_right = parse(&ipad_home_at((768, 1024), (386, 546), Some(736)), o);+ assert_eq!((home_right[0].center, home_right[0].size), ((582, 334), (72, 96)));+ let home_left = parse(&ipad_home_at((768, 1024), (286, 406), Some(0)), o);+ assert_eq!((home_left[0].center, home_left[0].size), ((582, 334), (72, 96)));+ // 状态栏说了算,方向报反了也一样+ let reported_right = land(Some(Orientation::LandscapeRight));+ assert_eq!(parse(&ipad_home_at((768, 1024), (386, 546), Some(736)), reported_right)[0].center, (582, 334));+ // 状态栏不是贴边的竖条:按方向+ assert_eq!(parse(&ipad_home_at((768, 1024), (386, 546), Some(300)), o)[0].center, (582, 334));+ }++ /// Home 键在左的横屏锁屏:WDA 照样报 LandscapeLeft,按状态栏换算后键位、「使用密码」和 Home 键在右时一样+ #[test]+ fn ipad_landscape_home_left_lock_screen_matches_home_right() {+ let o = land(Some(Orientation::LandscapeLeft));+ let right = parse(IPAD_PIN, o);+ let left = parse(IPAD_PIN_LEFT, o);+ let pad = keypad(&left).expect("Home 键在左也应认出键盘");+ assert_eq!(Some(pad), keypad(&right));+ assert_eq!(delete_key(&left, &pad), Some((618, 586)));+ assert_eq!(use_passcode_button(&parse(IPAD_TOUCHID_LEFT, o)), Some((512, 430)));+ assert_eq!(cover_sheet(IPAD_PIN_LEFT), CoverSheet::Locked);+ }}diff --git a/crates/ictl-wda/src/lib.rs b/crates/ictl-wda/src/lib.rsindex f0ae6bc..f4abb07 100644--- a/crates/ictl-wda/src/lib.rs+++ b/crates/ictl-wda/src/lib.rs@@ -10,7 +10,7 @@ pub mod http;pub mod runner;pub use client::{IdleSettings, Launch, LockCheck, PointerStep, WdaClient, actions_body, swipe_steps, tap_steps};-pub use elements::Element;+pub use elements::{Element, Orientation, View};pub use runner::WdaRunner;#[derive(Debug, thiserror::Error)]diff --git a/crates/ictl-wda/src/runner.rs b/crates/ictl-wda/src/runner.rsindex 2281562..2ad4829 100644--- a/crates/ictl-wda/src/runner.rs+++ b/crates/ictl-wda/src/runner.rs@@ -48,6 +48,19 @@ fn automation_signal(msg: &str) -> Option<AutomationSignal> {}}+/// 手机拒绝启动 runner 时回的是 NSError,但 idevice 收到的是没解开的归档(字段都是 `Uid(n)` 引用),读不出文字,+/// 只报 `unexpected response`。首次安装后最常见的原因是还没信任开发者(iPad mini 5 / iPadOS 26.6.1 真机:+/// 点「信任」之前这样报,之后下一次就能启动),在报错里提示一句+fn launch_hint(msg: String) -> String {+ if msg.contains("unexpected response") {+ format!(+ "{msg}(如果是第一次在这台手机上装 WDA:到 设置 → 通用 → VPN 与设备管理 里信任你的 Apple ID 开发者,需要联网)"+ )+ } else {+ msg+ }+}+/// XCTest 过程中收集的信息:报错文字(识别密码框超时用),以及 runner 是否正在等 automation mode#[derive(Default)]struct Progress {@@ -154,7 +167,7 @@ impl WdaRunner {if is_automation_pin_error(&joined) || p.automation_wait.is_some() {WdaError::NeedsAutomationPin} else {- WdaError::StartFailed(joined)+ WdaError::StartFailed(launch_hint(joined))}};@@ -209,6 +222,13 @@ impl Drop for WdaRunner {mod tests {use super::*;+ #[test]+ fn untrusted_developer_hint_only_for_unexpected_response() {+ let m = launch_hint("unexpected response from device: unexpected response".into());+ assert!(m.contains("VPN 与设备管理"), "{m}");+ assert_eq!(launch_hint("WDA 在限定时间内没有就绪".into()), "WDA 在限定时间内没有就绪");+ }+#[test]fn automation_signals_from_runner_debug_log() {// iOS 27.0.1 手机重启后真机日志(去掉时间和进程号前缀)diff --git a/crates/ictl-wda/tests/fixtures/ipad-lockscreen-portrait.xml b/crates/ictl-wda/tests/fixtures/ipad-lockscreen-portrait.xmlnew file mode 100644index 0000000..738a585--- /dev/null+++ b/crates/ictl-wda/tests/fixtures/ipad-lockscreen-portrait.xml@@ -0,0 +1,190 @@+<?xml version="1.0" encoding="UTF-8"?>+<!-- iPad mini 5(iPadOS 26.6.1,Touch ID)竖屏锁屏,真机:没有锁图标 proud-lock,有 call-to-action-label「按下主屏幕按钮以解锁」 -->+<XCUIElementTypeApplication type="XCUIElementTypeApplication" name=" " label=" " x="0" y="0" width="768" height="1024" processId="173" bundleId="com.apple.springboard">+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="1166" y="-150" width="8" height="8"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="1024" height="768">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1024" height="768">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1024" height="768"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" name="SBCoverSheetWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="1024" width="768" height="1024"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeImage type="XCUIElementTypeImage" name="StatusBarLegibilityShadow" x="0" y="0" width="450" height="75"/>+ <XCUIElementTypeImage type="XCUIElementTypeImage" x="318" y="0" width="450" height="75"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ <XCUIElementTypeScrollView type="XCUIElementTypeScrollView" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="161" y="0" width="446" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ <XCUIElementTypeScrollView type="XCUIElementTypeScrollView" x="161" y="0" width="446" height="1024">+ <XCUIElementTypeScrollView type="XCUIElementTypeScrollView" x="171" y="0" width="426" height="249">+ <XCUIElementTypeScrollView type="XCUIElementTypeScrollView" x="171" y="0" width="426" height="249">+ <XCUIElementTypeButton type="XCUIElementTypeButton" name="ListCell" x="171" y="0" width="426" height="249">+ <XCUIElementTypeOther type="XCUIElementTypeOther" name="ListCell.ContentView" x="171" y="0" width="426" height="249">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="171" y="0" width="426" height="249">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="171" y="0" width="426" height="249">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="171" y="0" width="426" height="249"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="171" y="0" width="426" height="249"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="171" y="0" width="426" height="249">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="171" y="0" width="426" height="249"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeButton>+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="0%" name="垂直滚动条, 1页" label="垂直滚动条, 1页" x="563" y="32" width="31" height="217">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="590" y="35" width="4" height="211"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="0%" name="垂直滚动条, 1页" label="垂直滚动条, 1页" x="563" y="32" width="31" height="217">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="590" y="35" width="4" height="211"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeScrollView>+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="0%" name="垂直滚动条, 1页" label="垂直滚动条, 1页" x="563" y="32" width="31" height="217">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="590" y="35" width="4" height="211"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="0%" name="垂直滚动条, 1页" label="垂直滚动条, 1页" x="563" y="32" width="31" height="217">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="590" y="35" width="4" height="211"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeScrollView>+ <XCUIElementTypeScrollView type="XCUIElementTypeScrollView" x="171" y="1024" width="426" height="441">+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="0%" name="垂直滚动条, 1页" label="垂直滚动条, 1页" x="563" y="1024" width="31" height="441">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="590" y="985" width="4" height="36"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="0%" name="垂直滚动条, 1页" label="垂直滚动条, 1页" x="563" y="1024" width="31" height="441">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="590" y="985" width="4" height="36"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeScrollView>+ </XCUIElementTypeScrollView>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="0%" name="垂直滚动条, 2页" label="垂直滚动条, 2页" x="735" y="32" width="30" height="992">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="762" y="35" width="3" height="986"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="0%" name="垂直滚动条, 2页" label="垂直滚动条, 2页" x="735" y="32" width="30" height="992">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="762" y="35" width="3" height="986"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeScrollView>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="314" y="966" width="140" height="18">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="314" y="966" width="140" height="18">+ <XCUIElementTypeButton type="XCUIElementTypeButton" name="call-to-action-label" label="按下主屏幕按钮以解锁" x="314" y="966" width="140" height="18"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypePageIndicator type="XCUIElementTypePageIndicator" value="第1页(共2页)" x="369" y="998" width="30" height="15"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" name="lockscreen-date-view" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="11月6日 星期五, 丙午年九月廿八" name="11月6日 星期五, 丙午年九月廿八" label="11月6日 星期五, 丙午年九月廿八" x="198" y="85" width="372" height="36"/>+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="21:05" name="21:05" label="21:05" x="202" y="99" width="362" height="156"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="198" y="258" width="372" height="69">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="198" y="258" width="372" height="69"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="692" y="31" width="62" height="3">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="692" y="31" width="62" height="3"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="692" y="59" width="62" height="3"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStatusBar type="XCUIElementTypeStatusBar" x="0" y="0" width="768" height="32">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="32">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="32">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="6" y="11" width="370" height="10"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="392" y="11" width="371" height="10">+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="SSID, 3(共3格无线局域网信号)" name="3(共3格无线局域网信号)" x="681" y="11" width="15" height="10"/>+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="86%" name="86%" label="86%" x="700" y="7" width="34" height="18"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="正在充电" name="电池电量86%" label="电池电量86%" x="735" y="9" width="28" height="14"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeStatusBar>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+</XCUIElementTypeApplication>diff --git a/crates/ictl-wda/tests/fixtures/ipad-passcode-landscape-home-left.xml b/crates/ictl-wda/tests/fixtures/ipad-passcode-landscape-home-left.xmlnew file mode 100644index 0000000..84c44bc--- /dev/null+++ b/crates/ictl-wda/tests/fixtures/ipad-passcode-landscape-home-left.xml@@ -0,0 +1,26 @@+<?xml version="1.0" encoding="UTF-8"?>+<!-- iPad mini 5(iPadOS 26.6.1)横屏锁屏点「使用密码」后的数字键盘(按真机 dump 精简,由 Home 键在右的样本在竖屏坐标里中心对称得到,Home 键在左;状态栏贴树的左边):+ 窗口和里面的元素是竖屏坐标 768x1024;「取消」(有输入时是「删除」)和 0 在同一行 -->+<XCUIElementTypeApplication type="XCUIElementTypeApplication" name=" " label=" " x="0" y="0" width="1024" height="768">+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStatusBar type="XCUIElementTypeStatusBar" x="0" y="0" width="32" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" name="SBCoverSheetWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="触控 ID 或输入密码" name="触控 ID 或输入密码" label="触控 ID 或输入密码" x="110" y="440" width="24" height="144"/>+ <XCUIElementTypeSecureTextField type="XCUIElementTypeSecureTextField" label="密码栏" value="共6位数,已输入0位" x="152" y="0" width="16" height="1024"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="1" x="232" y="565" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="2" x="232" y="459" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="3" x="232" y="353" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="4" x="333" y="565" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="5" x="333" y="459" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="6" x="333" y="353" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="7" x="434" y="565" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="8" x="434" y="459" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="9" x="434" y="353" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="0" x="535" y="459" width="101" height="106"/>+ <XCUIElementTypeButton type="XCUIElementTypeButton" name="取消" label="取消" x="535" y="353" width="101" height="106"/>+ </XCUIElementTypeWindow>+</XCUIElementTypeApplication>diff --git a/crates/ictl-wda/tests/fixtures/ipad-passcode-landscape.xml b/crates/ictl-wda/tests/fixtures/ipad-passcode-landscape.xmlnew file mode 100644index 0000000..7e14aa8--- /dev/null+++ b/crates/ictl-wda/tests/fixtures/ipad-passcode-landscape.xml@@ -0,0 +1,26 @@+<?xml version="1.0" encoding="UTF-8"?>+<!-- iPad mini 5(iPadOS 26.6.1)横屏锁屏点「使用密码」后的数字键盘(按真机 dump 精简,Home 键在右;状态栏是贴树右边的竖条):+ 窗口和里面的元素是竖屏坐标 768x1024;「取消」(有输入时是「删除」)和 0 在同一行 -->+<XCUIElementTypeApplication type="XCUIElementTypeApplication" name=" " label=" " x="0" y="0" width="1024" height="768">+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStatusBar type="XCUIElementTypeStatusBar" x="736" y="0" width="32" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" name="SBCoverSheetWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="触控 ID 或输入密码" name="触控 ID 或输入密码" label="触控 ID 或输入密码" x="634" y="440" width="24" height="144"/>+ <XCUIElementTypeSecureTextField type="XCUIElementTypeSecureTextField" label="密码栏" value="共6位数,已输入0位" x="600" y="0" width="16" height="1024"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="1" x="435" y="353" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="2" x="435" y="459" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="3" x="435" y="565" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="4" x="334" y="353" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="5" x="334" y="459" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="6" x="334" y="565" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="7" x="233" y="353" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="8" x="233" y="459" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="9" x="233" y="565" width="101" height="106"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="0" x="132" y="459" width="101" height="106"/>+ <XCUIElementTypeButton type="XCUIElementTypeButton" name="取消" label="取消" x="132" y="565" width="101" height="106"/>+ </XCUIElementTypeWindow>+</XCUIElementTypeApplication>diff --git a/crates/ictl-wda/tests/fixtures/ipad-passcode-portrait.xml b/crates/ictl-wda/tests/fixtures/ipad-passcode-portrait.xmlnew file mode 100644index 0000000..a57598f--- /dev/null+++ b/crates/ictl-wda/tests/fixtures/ipad-passcode-portrait.xml@@ -0,0 +1,152 @@+<?xml version="1.0" encoding="UTF-8"?>+<!-- iPad mini 5(iPadOS 26.6.1)竖屏点「使用密码」后的数字键盘,真机:没有 passcode-view;「取消」和 0 同一行 -->+<XCUIElementTypeApplication type="XCUIElementTypeApplication" name=" " label=" " x="0" y="0" width="768" height="1024" processId="173" bundleId="com.apple.springboard">+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="1166" y="-150" width="8" height="8"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="1024" height="768">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1024" height="768">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1024" height="768"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" name="SBCoverSheetWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeImage type="XCUIElementTypeImage" name="StatusBarLegibilityShadow" x="0" y="-1024" width="450" height="75"/>+ <XCUIElementTypeImage type="XCUIElementTypeImage" x="318" y="-1024" width="450" height="75"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="692" y="-993" width="62" height="3"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="692" y="-965" width="62" height="3"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="触控ID或输入密码" name="触控ID或输入密码" label="触控ID或输入密码" x="311" y="252" width="147" height="22"/>+ <XCUIElementTypeSecureTextField type="XCUIElementTypeSecureTextField" value="共6位数,已输入0位" name="密码栏" label="密码栏" x="0" y="293" width="768" height="16"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="204" y="340" width="360" height="504">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="204" y="340" width="360" height="504">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="204" y="340" width="360" height="504">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="204" y="340" width="360" height="504">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="204" y="340" width="360" height="504">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="204" y="340" width="360" height="504">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="204" y="340" width="360" height="504"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="204" y="340" width="360" height="504">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="204" y="340" width="360" height="504"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="224" y="360" width="320" height="464">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="225" y="360" width="318" height="404">+ <XCUIElementTypeKey type="XCUIElementTypeKey" name="1" label="1" x="225" y="360" width="106" height="101"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" name="2" label="2" x="331" y="360" width="106" height="101"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" name="3" label="3" x="437" y="360" width="106" height="101"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" name="4" label="4" x="225" y="461" width="106" height="101"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" name="5" label="5" x="331" y="461" width="106" height="101"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" name="6" label="6" x="437" y="461" width="106" height="101"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" name="7" label="7" x="225" y="562" width="106" height="101"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" name="8" label="8" x="331" y="562" width="106" height="101"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" name="9" label="9" x="437" y="562" width="106" height="101"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="225" y="663" width="106" height="101"/>+ <XCUIElementTypeKey type="XCUIElementTypeKey" name="0" label="0" x="331" y="663" width="106" height="101"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="437" y="663" width="106" height="101"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeButton type="XCUIElementTypeButton" name="取消" label="取消" x="437" y="663" width="106" height="101">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="取消" name="取消" label="取消" x="476" y="705" width="28" height="17"/>+ </XCUIElementTypeButton>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStatusBar type="XCUIElementTypeStatusBar" x="0" y="0" width="768" height="32">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="32">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="32">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="6" y="11" width="370" height="10">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="21:06" name="21:06" label="21:06" x="6" y="7" width="38" height="18"/>+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="11月6日周五" name="11月6日周五" label="11月6日周五" x="53" y="7" width="80" height="18"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="392" y="11" width="371" height="10">+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="SSID, 3(共3格无线局域网信号)" name="3(共3格无线局域网信号)" x="681" y="11" width="15" height="10"/>+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="86%" name="86%" label="86%" x="700" y="7" width="34" height="18"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="正在充电" name="电池电量86%" label="电池电量86%" x="735" y="9" width="28" height="14"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeStatusBar>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+</XCUIElementTypeApplication>diff --git a/crates/ictl-wda/tests/fixtures/ipad-touchid-landscape-home-left.xml b/crates/ictl-wda/tests/fixtures/ipad-touchid-landscape-home-left.xmlnew file mode 100644index 0000000..79d4fd7--- /dev/null+++ b/crates/ictl-wda/tests/fixtures/ipad-touchid-landscape-home-left.xml@@ -0,0 +1,21 @@+<?xml version="1.0" encoding="UTF-8"?>+<!-- iPad mini 5(iPadOS 26.6.1)横屏锁屏上滑后的「触控 ID」提示(按真机 dump 精简,由 Home 键在右的样本在竖屏坐标里中心对称得到,Home 键在左;状态栏贴树的左边):+ Application 是屏幕坐标 1024x768,窗口和里面的元素是竖屏坐标 768x1024;没有数字键和密码栏 -->+<XCUIElementTypeApplication type="XCUIElementTypeApplication" name=" " label=" " x="0" y="0" width="1024" height="768">+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStatusBar type="XCUIElementTypeStatusBar" x="0" y="0" width="32" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" name="SBCoverSheetWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="触控 ID" name="触控 ID" label="触控 ID" x="362" y="476" width="20" height="72"/>+ <XCUIElementTypeButton type="XCUIElementTypeButton" name="使用密码" label="使用密码" x="416" y="484" width="29" height="56">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="使用密码" name="使用密码" label="使用密码" x="421" y="484" width="20" height="56"/>+ </XCUIElementTypeButton>+ <XCUIElementTypeButton type="XCUIElementTypeButton" name="取消" label="取消" x="461" y="497" width="29" height="30">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="取消" name="取消" label="取消" x="465" y="497" width="20" height="30"/>+ </XCUIElementTypeButton>+ </XCUIElementTypeWindow>+</XCUIElementTypeApplication>diff --git a/crates/ictl-wda/tests/fixtures/ipad-touchid-landscape.xml b/crates/ictl-wda/tests/fixtures/ipad-touchid-landscape.xmlnew file mode 100644index 0000000..472eef1--- /dev/null+++ b/crates/ictl-wda/tests/fixtures/ipad-touchid-landscape.xml@@ -0,0 +1,21 @@+<?xml version="1.0" encoding="UTF-8"?>+<!-- iPad mini 5(iPadOS 26.6.1)横屏锁屏上滑后的「触控 ID」提示(按真机 dump 精简,Home 键在右;状态栏是贴树右边的竖条):+ Application 是屏幕坐标 1024x768,窗口和里面的元素是竖屏坐标 768x1024;没有数字键和密码栏 -->+<XCUIElementTypeApplication type="XCUIElementTypeApplication" name=" " label=" " x="0" y="0" width="1024" height="768">+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStatusBar type="XCUIElementTypeStatusBar" x="736" y="0" width="32" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" name="SBCoverSheetWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="触控 ID" name="触控 ID" label="触控 ID" x="386" y="476" width="20" height="72"/>+ <XCUIElementTypeButton type="XCUIElementTypeButton" name="使用密码" label="使用密码" x="323" y="484" width="29" height="56">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="使用密码" name="使用密码" label="使用密码" x="327" y="484" width="20" height="56"/>+ </XCUIElementTypeButton>+ <XCUIElementTypeButton type="XCUIElementTypeButton" name="取消" label="取消" x="278" y="497" width="29" height="30">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="取消" name="取消" label="取消" x="283" y="497" width="20" height="30"/>+ </XCUIElementTypeButton>+ </XCUIElementTypeWindow>+</XCUIElementTypeApplication>diff --git a/crates/ictl-wda/tests/fixtures/ipad-touchid-portrait.xml b/crates/ictl-wda/tests/fixtures/ipad-touchid-portrait.xmlnew file mode 100644index 0000000..3035218--- /dev/null+++ b/crates/ictl-wda/tests/fixtures/ipad-touchid-portrait.xml@@ -0,0 +1,127 @@+<?xml version="1.0" encoding="UTF-8"?>+<!-- iPad mini 5(iPadOS 26.6.1)竖屏锁屏上滑后的「触控 ID」提示,真机:只有「使用密码」「取消」,没有 passcode-view、数字键和密码栏 -->+<XCUIElementTypeApplication type="XCUIElementTypeApplication" name=" " label=" " x="0" y="0" width="768" height="1024" processId="173" bundleId="com.apple.springboard">+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="1166" y="-150" width="8" height="8"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="1536" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1536" height="2048"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="1024" height="768">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1024" height="768">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="1024" height="768"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" name="SBCoverSheetWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="2048">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeImage type="XCUIElementTypeImage" name="StatusBarLegibilityShadow" x="0" y="-1024" width="450" height="75"/>+ <XCUIElementTypeImage type="XCUIElementTypeImage" x="318" y="-1024" width="450" height="75"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="692" y="-993" width="62" height="3"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="692" y="-965" width="62" height="3"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="-1024" width="768" height="1024"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="351" y="376" width="66" height="67">+ <XCUIElementTypeOther type="XCUIElementTypeOther" name="glyph" x="351" y="376" width="66" height="67">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="351" y="376" width="66" height="67"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="触控ID" name="触控ID" label="触控ID" x="360" y="463" width="48" height="19"/>+ <XCUIElementTypeButton type="XCUIElementTypeButton" name="使用密码" label="使用密码" x="356" y="518" width="56" height="30">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="使用密码" name="使用密码" label="使用密码" x="356" y="524" width="56" height="18"/>+ </XCUIElementTypeButton>+ <XCUIElementTypeButton type="XCUIElementTypeButton" name="取消" label="取消" x="369" y="614" width="30" height="30">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="取消" name="取消" label="取消" x="370" y="620" width="28" height="18"/>+ </XCUIElementTypeButton>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeStatusBar type="XCUIElementTypeStatusBar" x="0" y="0" width="768" height="32">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="32">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="32">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="6" y="11" width="370" height="10">+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="21:06" name="21:06" label="21:06" x="6" y="7" width="38" height="18"/>+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="11月6日周五" name="11月6日周五" label="11月6日周五" x="53" y="7" width="80" height="18"/>+ </XCUIElementTypeOther>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="392" y="11" width="371" height="10">+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="SSID, 3(共3格无线局域网信号)" name="3(共3格无线局域网信号)" x="681" y="11" width="15" height="10"/>+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="86%" name="86%" label="86%" x="700" y="7" width="34" height="18"/>+ <XCUIElementTypeOther type="XCUIElementTypeOther" value="正在充电" name="电池电量86%" label="电池电量86%" x="735" y="9" width="28" height="14"/>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeOther>+ </XCUIElementTypeStatusBar>+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="768" height="1024">+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="0" y="0" width="768" height="1024"/>+ </XCUIElementTypeWindow>+</XCUIElementTypeApplication>diff --git a/docs/architecture.md b/docs/architecture.mdindex a3079a0..94a373d 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -62,7 +62,7 @@## 3. 守护进程状态机-状态定义在 `crates/ictl-daemon/src/machine.rs`(`DeviceState`),推进在 `supervise.rs`。先支持单设备(`IPHONE_UDID` 指定,否则用第一台)。+状态定义在 `crates/ictl-daemon/src/machine.rs`(`DeviceState`),推进在 `supervise.rs`。同一时间只控制一台设备:`IPHONE_UDID` 固定 > 运行中选定的(`select`,存在 state.json)> 自动选(正在控制的那台一直用到它断开,没有才取第一台)。选定的那台没接时就是 Absent,不换成别的(`machine::pick_device`、`devices.rs`)。每 10 秒巡检一次,从上往下判断,第一个不满足的就是当前状态:@@ -129,7 +129,7 @@| `profiles/` | 当前描述文件 | 0700 | 否 || `ddi/` | 开发者镜像缓存(运行时下载的苹果文件) | 0755 | **否,不得分发** || `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 编译 | 0755 | 未签名包进镜像(从源码运行时在本机下载) |-| `secrets/passcode` | 锁屏密码(仅启用自动解锁时) | 0600 | 否 |+| `secrets/passcodes/<UDID>` | 各设备的锁屏密码(仅启用自动解锁时);旧版本的 `secrets/passcode` 在只接着一台时归到那台名下 | 0600 | 否 || `notify.toml` | 通知渠道配置 | 0600 | 否 || `logs/` | 日志,按大小轮转 | 0755 | 否 || `state.json` | 状态机快照、自动解锁停用标记、上次重签结果 | 0600 | 否 |diff --git a/docs/images/features.svg b/docs/images/features.svgindex 23a88c2..3d22e95 100644--- a/docs/images/features.svg+++ b/docs/images/features.svg@@ -1,4 +1,4 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 388" width="1200" height="388" role="img" aria-label="One binary: Linux or macOS. No Xcode, no paid developer account, no jailbreak.; 15 MCP tools: Screenshots, taps, swipes, text input, buttons, apps, URLs, element tree.; Fewer round trips: Actions return the settled screen; iphone_batch runs 20 steps per call.; Runs unattended: Recovers from replugs and reboots; re-signs WDA before it expires.; HID fallback: Screenshots, taps and keys keep working via CoreDevice (iOS 27+).; doctor and alerts: Checks every layer from USB to WDA; Telegram or Bark when it needs you.">+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 388" width="1200" height="388" role="img" aria-label="One binary: Linux or macOS. No Xcode, no paid developer account, no jailbreak.; 17 MCP tools: Screenshots, taps, swipes, text input, buttons, apps, URLs, element tree.; Fewer round trips: Actions return the settled screen; iphone_batch runs 20 steps per call.; Runs unattended: Recovers from replugs and reboots; re-signs WDA before it expires.; HID fallback: Screenshots, taps and keys keep working via CoreDevice (iOS 27+).; doctor and alerts: Checks every layer from USB to WDA; Telegram or Bark when it needs you."><defs><linearGradient id="cd-bg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#0f1b2d"/>@@ -22,7 +22,7 @@<rect x="0.5" y="0.5" width="375" height="175" rx="18" fill="url(#cd-bg)" stroke="#155e75" stroke-opacity="0.7"/><rect x="24" y="24" width="48" height="48" rx="12" fill="url(#cd-icon)"/><g transform="translate(24 24)"><g fill="#fff"><rect x="13" y="13" width="10" height="10" rx="2.5"/><rect x="25" y="13" width="10" height="10" rx="2.5"/><rect x="13" y="25" width="10" height="10" rx="2.5"/><rect x="25" y="25" width="10" height="10" rx="2.5" fill-opacity="0.6"/></g></g>- <text x="24" y="104" font-size="22" font-weight="700" fill="#f0f9ff">15 MCP tools</text>+ <text x="24" y="104" font-size="22" font-weight="700" fill="#f0f9ff">17 MCP tools</text><text x="24" y="132" font-size="15" fill="#94a3b8">Screenshots, taps, swipes, text input,</text><text x="24" y="155" font-size="15" fill="#94a3b8">buttons, apps, URLs, element tree.</text></g>diff --git a/docs/images/features.zh-CN.svg b/docs/images/features.zh-CN.svgindex 593e080..20a5ef8 100644--- a/docs/images/features.zh-CN.svg+++ b/docs/images/features.zh-CN.svg@@ -1,4 +1,4 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 388" width="1200" height="388" role="img" aria-label="一个二进制: Linux 或 macOS 上直接运行 不需要 Xcode、付费账号,不越狱; 15 个 MCP 工具: 截图、点击、滑动、输入中文 按键、管理 App、读元素树; 少走往返: 操作后顺带返回稳定后的界面 iphone_batch 一次最多 20 步; 无人值守: 拔插、重启、WDA 崩溃后自动恢复 描述文件到期前自动重签; HID 后备: WDA 不可用时截图、点击、按键 改走 CoreDevice(iOS 27+); 诊断与通知: doctor 从 USB 到 WDA 逐层检查 需要你时发 Telegram 或 Bark">+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 388" width="1200" height="388" role="img" aria-label="一个二进制: Linux 或 macOS 上直接运行 不需要 Xcode、付费账号,不越狱; 17 个 MCP 工具: 截图、点击、滑动、输入中文 按键、管理 App、读元素树; 少走往返: 操作后顺带返回稳定后的界面 iphone_batch 一次最多 20 步; 无人值守: 拔插、重启、WDA 崩溃后自动恢复 描述文件到期前自动重签; HID 后备: WDA 不可用时截图、点击、按键 改走 CoreDevice(iOS 27+); 诊断与通知: doctor 从 USB 到 WDA 逐层检查 需要你时发 Telegram 或 Bark"><defs><linearGradient id="cd-bg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#0f1b2d"/>@@ -22,7 +22,7 @@<rect x="0.5" y="0.5" width="375" height="175" rx="18" fill="url(#cd-bg)" stroke="#155e75" stroke-opacity="0.7"/><rect x="24" y="24" width="48" height="48" rx="12" fill="url(#cd-icon)"/><g transform="translate(24 24)"><g fill="#fff"><rect x="13" y="13" width="10" height="10" rx="2.5"/><rect x="25" y="13" width="10" height="10" rx="2.5"/><rect x="13" y="25" width="10" height="10" rx="2.5"/><rect x="25" y="25" width="10" height="10" rx="2.5" fill-opacity="0.6"/></g></g>- <text x="24" y="104" font-size="22" font-weight="700" fill="#f0f9ff">15 个 MCP 工具</text>+ <text x="24" y="104" font-size="22" font-weight="700" fill="#f0f9ff">17 个 MCP 工具</text><text x="24" y="132" font-size="15" fill="#94a3b8">截图、点击、滑动、输入中文</text><text x="24" y="155" font-size="15" fill="#94a3b8">按键、管理 App、读元素树</text></g>diff --git a/docs/tools.md b/docs/tools.mdindex 82308f7..94ddea6 100644--- a/docs/tools.md+++ b/docs/tools.md@@ -1,6 +1,6 @@# MCP tools-The MCP server (`iphone-control mcp`) exposes 15 tools. The tool descriptions the agent sees, and every result text, are in Simplified Chinese; this page is the English reference. The definitions live in [`crates/ictl-mcp/src/lib.rs`](../crates/ictl-mcp/src/lib.rs).+The MCP server (`iphone-control mcp`) exposes 17 tools. The tool descriptions the agent sees, and every result text, are in Simplified Chinese; this page is the English reference. The definitions live in [`crates/ictl-mcp/src/lib.rs`](../crates/ictl-mcp/src/lib.rs).Coordinates are in **points**, the same unit as the pixels of a full-screen `iphone_screenshot` (for example 430×932 on an iPhone 15 Pro Max), so an agent can read a position off a screenshot and tap it directly.@@ -28,13 +28,22 @@ Coordinates are in **points**, the same unit as the pixels of a full-screen `iph| `iphone_open_url` | `url` | Web pages open in Safari; URL schemes open their app || `iphone_list_apps` | `include_system` (default false) | Name and bundle id of installed apps |+## Several devices++Only one device is controlled at a time; every other tool acts on it. With one device connected nothing changes.++| Tool | Parameters | Notes |+|---|---|---|+| `iphone_list_devices` | — | Every iPhone/iPad on USB: name, model, iOS version, UDID; marks the one being controlled and whether it has an auto-unlock passcode |+| `iphone_select_device` | `device`: UDID, device name, or `auto` | Switches to that device and keeps controlling it, also after a restart. A unique substring of the name works too. `auto` goes back to automatic choice: the controlled device is kept until it disconnects. WDA has to start on the new device (10–60 s). Refused when `IPHONE_UDID` is set |+When auto-unlock is configured, action tools unlock the phone first.-Every tool carries MCP annotations: the five that only look at the screen (`iphone_status`, `iphone_screenshot`, `iphone_list_elements`, `iphone_list_apps`, `iphone_wait_for`) are `readOnlyHint: true`; the action tools are not, 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`; the action tools are not, 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.### Returning the screen after an action: `then`-Every action tool accepts:+Screen-action tools accept the following options. `iphone_select_device` does not: use `iphone_status` after switching to check that WDA is ready.| Parameter | Meaning ||---|---|@@ -64,6 +73,12 @@ Steps run in order. The batch stops at the first error or the first `iphone_tap_}```+## HID fallback in landscape++On iOS 27+, 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.+## Tips for agents- Prefer `iphone_tap_element` over coordinates when the element has text.diff --git a/website/deploy/backup.md b/website/deploy/backup.mdindex 489ae12..97ba08e 100644--- a/website/deploy/backup.md+++ b/website/deploy/backup.md@@ -8,7 +8,7 @@| `lockdown/` | 配对记录(Docker 部署) | 要在手机上重新点「信任」 || `wda/` | 签好的 WebDriverAgent | 自动重签 || `ddi/` | 开发者镜像缓存 | 自动重新下载 |-| `secrets/passcode` | 锁屏密码(仅开启自动解锁时) | 要重新 `passcode set` |+| `secrets/passcodes/` | 各设备的锁屏密码(仅开启自动解锁时) | 要重新 `passcode set` || `state.json` | 状态快照、上次重签结果 | 自动重建 || `logs/` | 日志 | — |diff --git a/website/deploy/macos.md b/website/deploy/macos.mdindex 88a3e2b..6c607e1 100644--- a/website/deploy/macos.md+++ b/website/deploy/macos.md@@ -24,7 +24,7 @@ Docker Desktop 在 Mac 上把容器跑在 Linux 虚拟机里,不支持 USB 直从 0.1.2 起,[Releases](https://github.com/Derrors/iphone-control/releases) 里有 macOS(Apple Silicon,macOS 11 以上)的压缩包 `iphone-control-<版本>-macos-arm64.tar.gz`。在终端里下载安装(把 `V` 换成最新版本号):```bash-V=v0.1.2+V=v0.1.3curl -fsSLO https://github.com/Derrors/iphone-control/releases/download/$V/iphone-control-$V-macos-arm64.tar.gzcurl -fsSLO https://github.com/Derrors/iphone-control/releases/download/$V/iphone-control-$V-macos-arm64.tar.gz.sha256shasum -a 256 -c iphone-control-$V-macos-arm64.tar.gz.sha256 # 应显示 OKdiff --git a/website/en/deploy/backup.md b/website/en/deploy/backup.mdindex 9f62603..04197c3 100644--- a/website/en/deploy/backup.md+++ b/website/en/deploy/backup.md@@ -8,7 +8,7 @@| `lockdown/` | Pairing records (Docker) | Tap *Trust* on the phone again || `wda/` | Signed WebDriverAgent | Re-signed automatically || `ddi/` | Developer Disk Image cache | Downloaded again |-| `secrets/passcode` | Passcode (only with auto-unlock) | Run `passcode set` again |+| `secrets/passcodes/` | Per-device passcodes (only with auto-unlock) | Run `passcode set` again || `state.json` | State snapshot, last signing result | Rebuilt automatically || `logs/` | Logs | — |diff --git a/website/en/deploy/macos.md b/website/en/deploy/macos.mdindex 83dd5f4..91e7f4b 100644--- a/website/en/deploy/macos.md+++ b/website/en/deploy/macos.md@@ -24,7 +24,7 @@ Docker Desktop on a Mac runs containers in a Linux VM without USB passthrough, sSince 0.1.2, [Releases](https://github.com/Derrors/iphone-control/releases) has a macOS archive (Apple Silicon, macOS 11+): `iphone-control-<version>-macos-arm64.tar.gz`. Download and install it from a terminal (set `V` to the latest version):```bash-V=v0.1.2+V=v0.1.3curl -fsSLO https://github.com/Derrors/iphone-control/releases/download/$V/iphone-control-$V-macos-arm64.tar.gzcurl -fsSLO https://github.com/Derrors/iphone-control/releases/download/$V/iphone-control-$V-macos-arm64.tar.gz.sha256shasum -a 256 -c iphone-control-$V-macos-arm64.tar.gz.sha256 # should print OKdiff --git a/website/en/guide/auto-unlock.md b/website/en/guide/auto-unlock.mdindex 27a5a5e..2a05b70 100644--- a/website/en/guide/auto-unlock.md+++ b/website/en/guide/auto-unlock.md@@ -12,12 +12,18 @@ The passcode is stored **in plain text** in the data directory. Anyone who can ldocker exec -it iphone-control iphone-control passcode set```-Numeric passcodes of 4 or more digits only. To disable:+The passcode is saved for the device the daemon is controlling; for another one add `--device <UDID or name>`. Numeric passcodes of 4 or more digits only. To disable:```bashdocker exec -it iphone-control iphone-control passcode clear```+## Several devices++Passcodes are **kept per device** (`secrets/passcodes/<UDID>` in the data directory), so one device's passcode is never typed into another; a device without one needs a person to unlock it. The `devices` command (or the `iphone_list_devices` tool) shows which devices have one.++Older versions kept a single passcode (`secrets/passcode`) without knowing which device it belonged to. After upgrading, it is assigned to the device if exactly one is connected over USB; while several are connected it isn't used — run `passcode set` again with the right device connected.+## Safeguards- After every digit it checks how many digits the passcode field shows and stops at once if they don't match (an incomplete entry is not a wrong attempt); only a first digit that didn't register is retried, up to 3 rounds.diff --git a/website/en/guide/configuration.md b/website/en/guide/configuration.mdindex 189d95c..27f3649 100644--- a/website/en/guide/configuration.md+++ b/website/en/guide/configuration.md@@ -12,7 +12,7 @@ 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_UDID` | first phone | Which phone to use when several are connected |+| `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 || `OFFLINE_ALERT_MIN` | `10` | Notify after the phone has been offline this many minutes; `0` disables |diff --git a/website/en/guide/security.md b/website/en/guide/security.mdindex e788d0c..e773b1a 100644--- a/website/en/guide/security.md+++ b/website/en/guide/security.md@@ -9,7 +9,7 @@ iphone-control is a remote control for a phone: whoever can reach it can do anyt| 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/passcode`, **plain text** | Whoever can read the data directory |+| 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 |## Built-in protectionsdiff --git a/website/en/guide/tools.md b/website/en/guide/tools.mdindex 05dc155..2d5da9e 100644--- a/website/en/guide/tools.md+++ b/website/en/guide/tools.md@@ -1,6 +1,6 @@# Tools-The MCP server provides 15 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.+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.## Looking at the screen@@ -26,6 +26,15 @@ The MCP server provides 15 tools. Coordinates are in **points**, matching the pi| `iphone_list_apps` | Installed apps || `iphone_batch` | Run up to 20 steps in one call, stopping at the first error |+## Several devices++Only one device is controlled at a time; every other tool acts on it. With one device connected you can ignore these.++| Tool | What it does |+|---|---|+| `iphone_list_devices` | Every iPhone/iPad on USB: name, model, iOS version, UDID; marks the one being controlled and whether it has an auto-unlock passcode |+| `iphone_select_device` | Switch to another device (UDID or name), remembered across restarts; `auto` goes back to automatic choice. WDA takes 10–60 s to start on the new device. Not possible when `IPHONE_UDID` is set |+## See the screen after an action: `then`Every action tool accepts `then`: it waits for the screen to settle and returns it, saving a round trip.diff --git a/website/en/index.md b/website/en/index.mdindex 06b3668..e1931fa 100644--- a/website/en/index.md+++ b/website/en/index.md@@ -22,7 +22,7 @@ hero:features:- icon: 🤖title: Tools for agents- details: Screenshots, on-screen elements, tap by text, swipe, typing (Chinese too), apps, waiting for pages, multi-step batches — 15 MCP tools+ details: Screenshots, on-screen elements, tap by text, swipe, typing (Chinese too), apps, waiting for pages, multi-step batches — 17 MCP tools- icon: 💻title: Linux or Macdetails: No Mac needed on Linux, no Xcode needed on a Mac. WebDriverAgent is signed with a free Apple ID and re-signed before the 7-day profile expiresdiff --git a/website/guide/auto-unlock.md b/website/guide/auto-unlock.mdindex 82ccfd5..9473b46 100644--- a/website/guide/auto-unlock.md+++ b/website/guide/auto-unlock.md@@ -12,12 +12,18 @@docker exec -it iphone-control iphone-control passcode set```-只支持 4 位以上的纯数字密码。关闭:+密码存给守护进程正在控制的那台设备;要给别的设备设,加 `--device <UDID 或设备名>`。只支持 4 位以上的纯数字密码。关闭:```bashdocker exec -it iphone-control iphone-control passcode clear```+## 多台设备++密码**按设备分开存**(数据目录 `secrets/passcodes/<UDID>`),一台的密码不会输进另一台;没设密码的设备锁屏时要人工解锁。`devices` 命令(或 `iphone_list_devices` 工具)会标出每台有没有设。++旧版本只存一份密码(`secrets/passcode`),不知道是哪台的:升级后 USB 上只接着一台时,它自动归到那台名下;同时接着几台时不会用它,在要用的设备连着时重新 `passcode set` 即可。+## 保护规则- 每按一位都核对密码栏的位数,对不上立即停止(没输完不算输错);只有第一位没生效时会重来,最多 3 轮。diff --git a/website/guide/configuration.md b/website/guide/configuration.mdindex 6285983..48b7f54 100644--- a/website/guide/configuration.md+++ b/website/guide/configuration.md@@ -12,7 +12,7 @@| 变量 | 默认 | 含义 ||---|---|---|| `HTTP_PROXY` / `HTTPS_PROXY` | 直连 | 访问苹果、anisette、开发者镜像、推送通知用的代理 |-| `IPHONE_UDID` | 第一台 | 接了多台手机时指定用哪台 |+| `IPHONE_UDID` | 自动选 | 固定控制哪台设备。不设时自动选:正在控制的那台一直用到它断开;运行中可以用 `select` 命令或 `iphone_select_device` 工具切换。设了就不能切换 || `RESIGN_MIN_DAYS` | `2` | 描述文件剩余不到几天时重签 || `RESIGN_CHECK_HOURS` | `6` | 每隔几小时检查一次 || `OFFLINE_ALERT_MIN` | `10` | 手机离线超过几分钟推送提醒,`0` 不提醒 |diff --git a/website/guide/security.md b/website/guide/security.mdindex 1dc99d9..ab80348 100644--- a/website/guide/security.md+++ b/website/guide/security.md@@ -9,7 +9,7 @@ iphone-control 本质上是一个手机遥控器:能访问它的人,就能| 操控手机 | 控制接口(Unix socket,权限 0600) | 主机 root、能 `docker exec` 进容器的人、从源码运行时的同一用户 || Apple ID 会话、开发签名私钥 | 数据目录 `account/` | 能读数据目录的人。Apple ID 密码本身不保存 || 配对记录 | 数据目录 `lockdown/`(容器) | 能读数据目录的人;拿到它不用再点「信任」就能经 USB 访问手机 |-| 锁屏密码(仅开启自动解锁时) | 数据目录 `secrets/passcode`,**明文** | 能读数据目录的人 |+| 锁屏密码(仅开启自动解锁时) | 数据目录 `secrets/passcodes/<UDID>`,**明文** | 能读数据目录的人 || 通知密钥 | `.env` 或 `~/.config/iphone-control/env` | 能读这个文件的人 |## 默认的保护diff --git a/website/guide/tools.md b/website/guide/tools.mdindex 364188d..597dbf3 100644--- a/website/guide/tools.md+++ b/website/guide/tools.md@@ -1,6 +1,6 @@# 工具一览-MCP 服务提供 15 个工具。坐标单位是**点**,和整屏截图的像素一一对应(iPhone 15 Pro Max 是 430×932),agent 从截图上读到的位置可以直接点。+MCP 服务提供 17 个工具。坐标单位是**点**,和整屏截图的像素一一对应(iPhone 15 Pro Max 是 430×932),agent 从截图上读到的位置可以直接点。## 看屏幕@@ -26,6 +26,15 @@ MCP 服务提供 15 个工具。坐标单位是**点**,和整屏截图的像| `iphone_list_apps` | 已安装的 App || `iphone_batch` | 一次执行最多 20 步,出错就停 |+## 接着多台设备++同一时间只控制一台,其他工具都作用在它上面。只接着一台时不用管这两个工具。++| 工具 | 作用 |+|---|---|+| `iphone_list_devices` | 列出 USB 上接着的 iPhone/iPad:名字、型号、iOS 版本、UDID,标出正在控制哪台、有没有设自动解锁密码 |+| `iphone_select_device` | 改为控制另一台(UDID 或设备名),重启后还记得;`auto` 改回自动选。新设备上的 WDA 起来要 10~60 秒。设了 `IPHONE_UDID` 时不能切换 |+## 操作后顺带看界面:`then`每个操作工具都可以带 `then`,等界面稳定后顺带返回操作后的样子,省一次往返:diff --git a/website/index.md b/website/index.mdindex 6ddf5be..c810f5d 100644--- a/website/index.md+++ b/website/index.md@@ -22,7 +22,7 @@ hero:features:- icon: 🤖title: 给 AI 用的工具- details: 截图、读屏幕元素、按文字点击、滑动、输入中文、启动 App、等页面加载、一次执行多步,共 15 个 MCP 工具+ details: 截图、读屏幕元素、按文字点击、滑动、输入中文、启动 App、等页面加载、一次执行多步,共 17 个 MCP 工具- icon: 💻title: Linux 或 Mac 都行details: Linux 上不需要 Mac,Mac 上不需要 Xcode。用免费 Apple ID 给 WebDriverAgent 签名,7 天到期前自动重签