Skip to content

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

test: strengthen device regressions and fix WDA stall detection (#140)

Qinghe Li28ff361d55de
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index c8da119..22c3511 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -17,7 +17,8 @@
- Device, iOS version, host (Linux / macOS): <!-- e.g. iPhone 15 Pro Max, iOS 27.0.1, Debian 12 -->
- [ ] `tests/device/run.py` default steps pass on this branch (exit code 0)
-- [ ] The same steps on `main` or the latest release, same device, for comparison; no step clearly slower, or why:
+- [ ] `tests/device/scenarios.py` passes on this branch: <!-- which scenarios; `lock` / `url` if the change concerns them -->
+- [ ] The same steps on `main` or the latest release, same device, for comparison (`run.py --repeat 5 --json`, `compare.py`); no step clearly slower, or why:
- [ ] Steps exercising this change: <!-- what you ran -->
- [ ] Longer run (WDA start-up/recovery, reconnecting, unlocking, live picture, timers): <!-- duration and result, or "not affected" -->
- [ ] Not needed: the change doesn't touch code that talks to a phone — why:
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8c23c87..2394b8c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -41,6 +41,12 @@ jobs:
- uses: actions/checkout@v7
- name: Viewer interaction tests
run: node --test tests/viewer/*.test.mjs
+ # 回归清单里点名的测试都还在(改名、删掉后清单会指向不存在的测试)
+ - name: Regression cases name existing tests
+ run: python3 tests/check_regression_cases.py
+ # 真机脚本的解析和断言也需离线验证,无需连接设备或安装 MCP SDK。
+ - name: Device test helper unit tests
+ run: python3 -m unittest discover -s tests/device -p 'test_*.py'
# 锁定工具链(与发布一致):新版 clippy 的 lint 不会在代码没变时把 CI 弄挂
- uses: dtolnay/[email protected]
with:
@@ -48,7 +54,7 @@ jobs:
- uses: Swatinem/rust-cache@v2
# vendor/ 是上游代码,不格式化;只检查本仓库的包
- name: fmt
- run: for p in ictl-l10n ictl-webinspector ictl-device ictl-wda ictl-sign ictl-unlock ictl-daemon ictl-mcp ictl-protocol iphone-control; do cargo fmt -p $p -- --check; done
+ run: for p in ictl-ax ictl-l10n ictl-webinspector ictl-device ictl-wda ictl-sign ictl-unlock ictl-daemon ictl-mcp ictl-protocol iphone-control; do cargo fmt -p $p -- --check; done
# --all-features:默认不编的 debug-cmds(调试子命令)也要能编译
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
# check_fish_candidates 的候选词断言需要真正的 fish;缺了它该段会被静默跳过
diff --git a/.gitignore b/.gitignore
index c24eb17..a00fe86 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,3 +19,4 @@ THIRD_PARTY_LICENSES.html
# Python release tooling
/packaging/__pycache__/
+/tests/device/__pycache__/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 43af506..d433e42 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,10 @@ What changed in each release, one line per change. Versions follow [Semantic Ver
- An action that had to unlock the phone first says so, and how long it took (#135).
+### Fixes
+
+- A WDA probe that answers, even with an error, resets the timeout count instead of accumulating unrelated slow requests into a stall. Recovery logs state the reason, and timeout logs include the endpoint and elapsed time.
+
## [0.2.7] - 2026-11-15
### Upgrade notes
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index a6c34f4..fa578f6 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -10,6 +10,10 @@
- 操作前先自动解锁了的话,结果里会说明,并写明用了多久(#135)。
+### 修复
+
+- WDA 的短探测正常应答或返回远端错误时清零超时计数,不再把多个独立慢请求累计成卡死;恢复日志写明判定依据,请求超时日志包含端点和耗时。
+
## [0.2.7] - 2026-11-15
### 升级注意事项
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0c7533f..3156a62 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -47,7 +47,26 @@ export MCP_CMD="$PWD/target/release/iphone-control mcp" # your build; the daem
.venv/bin/python tests/device/run.py '[["iphone_launch_app", {"app": "设置"}], ["iphone_screenshot", {}]]'
```
-`run.py` prints every result with its wall time, ends with a line counting calls and failures, saves screenshots to `./shots` and exits with 1 if any call failed. `MCP_CMD` defaults to `iphone-control mcp` on your `PATH`. To test your branch, run its daemon too (stop the installed service with `iphone-control service stop`, then start `target/release/iphone-control daemon` in another terminal; `service start` afterwards). What a pull request has to run on the device is in [Required tests](#required-tests).
+`run.py` prints every result with its wall time, ends with a line counting calls and failures, saves screenshots to `./shots` and exits with 1 if any step failed. It starts with a `###` line naming the device it controls (model, iOS version, screen, native or WDA) and fails if another device is controlled by the end. The default steps check their answers (the tab tapped becomes the selected one, a screenshot has the screen's size, the typed text shows up) and work on any screen size and in any language; a step of your own may carry a third element saying what to expect: `["iphone_type_text", {"text": "x"}, {"error": true, "has": ["keyboard"]}]` (`has`, `lacks`, `error`, `max_s`, `image`; see `judge` in `tests/device/device.py`). `MCP_CMD` defaults to `iphone-control mcp` on your `PATH`. To test your branch, run its daemon too (stop the installed service with `iphone-control service stop`, then start `target/release/iphone-control daemon` in another terminal; `service start` afterwards). What a pull request has to run on the device is in [Required tests](#required-tests).
+
+The tools themselves have scenarios in `tests/device/scenarios.py`: the device cases of [docs/dev/regression-cases.md](docs/dev/regression-cases.md) that a script can repeat, each check a PASS / FAIL line with the case's number:
+
+```bash
+.venv/bin/python tests/device/scenarios.py # tools, typing, fresh, batch, menu
+.venv/bin/python tests/device/scenarios.py typing batch # only these
+.venv/bin/python tests/device/scenarios.py --url url # opens https://example.com in Safari
+.venv/bin/python tests/device/scenarios.py --lock lock # locks the phone and lets it unlock itself
+```
+
+`lock` types the saved passcode into the phone: make sure the passcode saved for this device is this device's (`iphone-control passcode set`) before passing `--lock`, or the phone counts a wrong attempt and automatic unlocking is switched off.
+
+To compare times with `main`, let `run.py` write them down and `compare.py` judge them (the median of several runs, without the time an automatic unlock took):
+
+```bash
+.venv/bin/python tests/device/run.py --repeat 5 --json main.json # with main's daemon running
+.venv/bin/python tests/device/run.py --repeat 5 --json branch.json # with your branch's
+python3 tests/device/compare.py main.json branch.json # marks steps that became SLOWER
+```
AI tasks (anything in `crates/ictl-daemon/src/tasks.rs`, `task`, the viewer's task API, the MCP server's task handling) have their own scenarios in `tests/device/tasks.py`, each check a PASS / FAIL line:
@@ -103,8 +122,8 @@ Every pull request must pass the tests below, and its description must show it:
Needed when the change touches code that talks to a phone or changes what it does or how long it takes: anything under `crates/` and `apps/` except pure text changes (comments, translations that don't change meaning). Not needed for changes limited to documentation, the website, CI, packaging or other tests; say so in the template. A bug fix or a feature always needs [part 4](#4-real-device-proof--every-bug-fix-and-every-feature), wherever the change is.
-- **Default steps:** build your branch, run its daemon and `tests/device/run.py` with the default steps on a real iPhone or iPad ([Testing on a real phone](#testing-on-a-real-phone)). Every call succeeds and the exit code is 0.
-- **No slower, no less stable:** on the same device, run the default steps once more on `main` (or the latest release), and paste both outputs. A step that became clearly slower (more than about 20 %, or by more than 0.5 s) needs a reason. A change that could affect long-running behaviour (WDA start-up and recovery, reconnecting, unlocking, the live picture, timers) also needs a longer run: repeat the default steps for at least an hour, e.g. `for i in $(seq 12); do .venv/bin/python tests/device/run.py || break; sleep 300; done`, and report failures and how the times developed.
+- **Default steps:** build your branch, run its daemon and `tests/device/run.py` with the default steps on a real iPhone or iPad ([Testing on a real phone](#testing-on-a-real-phone)). Every step passes and the exit code is 0. Run `tests/device/scenarios.py` too (its default scenarios; `lock` when the change concerns locking or unlocking, `url` when it concerns links, Safari or web content): every check passes.
+- **No slower, no less stable:** on the same device, run the default steps once more on `main` (or the latest release), and paste both outputs; `run.py --repeat 5 --json` on each and `tests/device/compare.py` do the comparison for you. A step that became clearly slower (more than about 20 %, or by more than 0.5 s) needs a reason. A change that could affect long-running behaviour (WDA start-up and recovery, reconnecting, unlocking, the live picture, timers) also needs a longer run: repeat the default steps for at least an hour, e.g. `for i in $(seq 12); do .venv/bin/python tests/device/run.py || break; sleep 300; done`, and report failures and how the times developed.
- **What you changed:** also run steps that exercise the change itself (pass them as a JSON list) and paste the output.
- **The right hardware:** when the change concerns iPad, landscape, an iOS version or a platform, test on that. Changes to macOS-only code go through [docs/dev/macos-verification.md](docs/dev/macos-verification.md).
- **In the pull request:** device model, iOS version, Linux or macOS, and the outputs (the `===` lines and the last line are enough; remove private data).
@@ -114,8 +133,8 @@ Needed when the change touches code that talks to a phone or changes what it doe
[docs/dev/regression-cases.md](docs/dev/regression-cases.md) lists the problems this project has run into, with the right behaviour and how each is tested. Every pull request must keep all of them passing.
- Cases tested by unit tests are covered by part 1.
-- Cases tested on a device (真机, headless Chrome, measured by hand) in the area you changed: run them again and list their numbers in the pull request. To find them, search the file for the module, tool or behaviour you changed; if none apply, say so.
-- A pull request that fixes a problem not in the list adds a row: the problem, the right behaviour, and how it is tested (the unit test's name, or the device steps).
+- Cases tested on a device (真机, headless Chrome, measured by hand) in the area you changed: run them again and list their numbers in the pull request. To find them, search the file for the module, tool or behaviour you changed; if none apply, say so. Cases whose test names `scenarios.py` or `tasks.py` are run by that script.
+- A pull request that fixes a problem not in the list adds a row: the problem, the right behaviour, and how it is tested (the unit test's name, or the device steps; a device case a script can repeat becomes a check in `tests/device/scenarios.py`). CI checks that every test the list names exists (`tests/check_regression_cases.py`): when you rename a test, rename it in the list.
### 4. Real-device proof — every bug fix and every feature
diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rs
index a0c4e14..6398a32 100644
--- a/crates/ictl-daemon/src/supervise.rs
+++ b/crates/ictl-daemon/src/supervise.rs
@@ -523,8 +523,8 @@ impl Daemon {
}
}
- /// WDA 卡死了没有:经 XCTest 的请求连续 [`ictl_wda::client::STALL_LIMIT`] 次没有应答([`WdaClient::stalled`])。
- /// 还没到就再探测一次([`WdaClient::xctest_responsive`]),算进同一个计数。WDA 回了错误、或者应答了,都算活着
+ /// 按客户端记录的连续无应答或长请求后的失败短探测判断是否需恢复。
+ /// 尚未判定时再探测一次;正常回答或远端错误都表明仍有响应,会清零计数。
async fn xctest_stalled(&self, g: &mut Inner) -> bool {
let Some(w) = g.wda.as_ref() else { return false };
if !w.stalled()
@@ -545,10 +545,12 @@ impl Daemon {
/// WDA 卡死([`WdaClient::stalled`]):丢掉会话,重新启动。巡检和每个工具请求开头都会检查:
/// 工具调用接连不断时巡检抢不到设备,不能只靠它
pub(crate) async fn restart_stalled_wda(&self, g: &mut Inner) {
+ let Some(reason) = g.wda.as_ref().and_then(|w| w.stall_reason()) else { return };
+ let why = reason.describe();
+ // 请求入口也会走这里,未必刚检查过 /status,不宣称它此刻正常。
self.log.log(&ictl_l10n::log_trf!(
- "WDA 卡死:/status 正常,但经 XCTest 的请求连续 {} 次没有应答,重新启动 WDA",
- "WDA is stuck: /status answers, but {} requests in a row through XCTest went unanswered; restarting WDA",
- ictl_wda::client::STALL_LIMIT
+ "WDA 卡死判定:{why},重新启动 WDA",
+ "WDA is considered stuck: {why}; restarting WDA"
));
// 后台启动的那个不能再接上:忘掉它,重新后台启动时会先结束它
self.forget_detached_here(g);
diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rs
index 25df659..1d4f02a 100644
--- a/crates/ictl-daemon/src/tasks.rs
+++ b/crates/ictl-daemon/src/tasks.rs
@@ -1526,6 +1526,30 @@ mod tests {
assert_eq!(steps[4]["gesture"]["x2"], 3.0);
}
+ /// A result that lists elements is full of `@(x,y)`: only a tap by text is marked from what its result says
+ #[tokio::test]
+ async fn only_a_tap_by_text_gets_a_mark_from_its_result() {
+ let listed = "Button \"通用\" @(200,300) 100x40\nButton \"蓝牙\" @(200,350) 100x40";
+ assert_eq!(gesture("iphone_list_elements", &json!({}), listed), None);
+ assert_eq!(
+ gesture("iphone_wait_for", &json!({"text": "通用"}), "已出现 Button \"通用\" @(200,300) 100x40"),
+ None
+ );
+ assert_eq!(gesture("iphone_tap_element", &json!({"text": "x"}), "没找到包含 \"x\" 的元素"), None);
+ let ts = tasks();
+ let t = open(&ts);
+ let req = |tool: &str, args: Value| Request::TaskStep { tool: tool.into(), args };
+ ts.handle(&req("iphone_list_elements", json!({})), Some(&t.token), None, &mut None).await;
+ t.step_done(1, true, 80, listed, None);
+ ts.handle(&req("iphone_tap_element", json!({"text": "蓝牙"})), Some(&t.token), None, &mut None).await;
+ t.step_done(2, true, 90, "已点击 Button \"蓝牙\" @(200,350) 100x40", None);
+ let (log, _, _) = t.subscribe();
+ let done: Vec<&Value> =
+ log.iter().filter(|e| e.event == "step" && e.data.get("ms").is_some()).map(|e| &e.data).collect();
+ assert!(done[0].get("gesture").is_none(), "{}", done[0]);
+ assert_eq!(done[1]["gesture"], json!({"kind": "tap", "x": 200.0, "y": 350.0}));
+ }
+
#[tokio::test]
async fn another_device_interrupts_the_task() {
let ts = tasks();
diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rs
index 39ad963..f9d8c44 100644
--- a/crates/ictl-wda/src/client.rs
+++ b/crates/ictl-wda/src/client.rs
@@ -15,6 +15,30 @@ const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
pub const XCTEST_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
/// 经 XCTest 的请求连续这么多次送到了却没有应答(超时,或应答到一半断了),就当 WDA 卡死(见 [`WdaClient::stalled`])
pub const STALL_LIMIT: u32 = 3;
+/// 高位单独记录「长请求及其短探测都未应答」,低位仍是实际的连续无应答数。
+const UNANSWERED_PROBE: u32 = 1 << 31;
+
+/// 无响应的判定依据,不等同于已证明设备端永久死锁。
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum StallReason {
+ ConsecutiveRequests(u32),
+ LongRequestAndProbe,
+}
+
+impl StallReason {
+ pub fn describe(self) -> String {
+ match self {
+ Self::ConsecutiveRequests(n) => {
+ ictl_l10n::trf!("连续 {n} 次请求没有完整应答", "{n} requests in a row had no complete reply")
+ }
+ Self::LongRequestAndProbe => ictl_l10n::trf!(
+ "较长的请求和随后 {} 秒的 /wda/activeAppInfo 探测都没有完整应答",
+ "a long request and the following {} s /wda/activeAppInfo probe both had no complete reply",
+ XCTEST_PROBE_TIMEOUT.as_secs()
+ ),
+ }
+ }
+}
/// How long a measured screen size is used before it is measured again, and then in the background
/// ([`WdaClient::display_sample`] with `refresh_stale`), not at the start of a gesture: only Display Zoom changes the
/// size, and `/wda/screen` takes about 100 ms on an iPhone with iOS 27 but 0.95 s on an iPad mini 5 (iPadOS 26.7.3),
@@ -135,6 +159,11 @@ fn acts(method: &str, path: &str) -> bool {
method != "GET" && !path.starts_with("/element")
}
+/// 正常响应和远端错误都证明请求获得了回答;连接失败则不算。
+fn answered(reply: &Result<Value>) -> bool {
+ matches!(reply, Ok(_) | Err(WdaError::Remote { .. }))
+}
+
/// Frames a second and size (percent) of WDA's MJPEG stream with [`WdaClient::fast_stream`].
///
/// Full size, so WDA passes on the JPEG that testmanagerd encodes in hardware. Any other size makes WDA decode,
@@ -202,7 +231,8 @@ pub struct WdaClient<T> {
idle_current: Option<IdleSettings>,
/// See [`Self::fast_stream`]
fast_stream: bool,
- /// 经 XCTest 的请求(除 `/status` 外都是)连续几次没有应答,有应答就清零。工具调用和守护进程的探测都算
+ /// 低位为连续无应答数;高位记录长请求后的短探测也未应答,详见 [`Self::stall_reason`]。
+ /// 工具调用和守护进程的探测都算;获得正常回答或远端错误才清零。
unanswered: AtomicU32,
/// 下次读元素树用的上限,[`SNAPSHOT_LEVELS`] 的下标
snapshot_level: usize,
@@ -255,10 +285,11 @@ impl<T: Transport> WdaClient<T> {
}
// 已判定卡死:不再发、不再一次次等超时(一个工具调用里接连几个请求,每个都等满时限的话,
// 设备会被占好几分钟,守护进程没机会重启 WDA)
- if self.stalled() {
+ if let Some(reason) = self.stall_reason() {
+ let why = reason.describe();
return Err(WdaError::Unavailable(ictl_l10n::trf!(
- "WDA 卡死:经 XCTest 的请求连续 {STALL_LIMIT} 次没有应答,等守护进程重启它",
- "WDA is stuck: {STALL_LIMIT} requests in a row through XCTest went unanswered; waiting for the daemon to restart it"
+ "WDA 卡死判定:{why},等守护进程重启它",
+ "WDA is considered stuck: {why}; waiting for the daemon to restart it"
)));
}
let r = self.send(method, path, body, timeout).await;
@@ -268,30 +299,43 @@ impl<T: Transport> WdaClient<T> {
self.delete_session(sid).await;
}
let n = self.unanswered.fetch_add(1, Ordering::Relaxed) + 1;
- // a long request went unanswered: one quick question tells a stuck WDA from a slow request, instead of
- // waiting the full time twice more (a tool call took 90 s before the daemon could restart it)
+ // 长请求未应答,补一次短探测;保留实际计数,不把两个请求写成三次无应答。
if n < STALL_LIMIT && timeout > XCTEST_PROBE_TIMEOUT {
match self.send("GET", "/wda/activeAppInfo", None, XCTEST_PROBE_TIMEOUT).await {
- Err(p) if p.no_answer() => self.unanswered.store(STALL_LIMIT, Ordering::Relaxed),
- // it answers: slow, not stuck (still counted, until something is answered)
+ Err(p) if p.no_answer() => {
+ self.unanswered.store((n + 1) | UNANSWERED_PROBE, Ordering::Relaxed);
+ }
+ reply if answered(&reply) => self.unanswered.store(0, Ordering::Relaxed),
_ => {}
}
}
}
- _ => self.unanswered.store(0, Ordering::Relaxed),
+ _ if answered(&r) => self.unanswered.store(0, Ordering::Relaxed),
+ _ => {}
}
r
}
- /// 经 XCTest 的请求连续 [`STALL_LIMIT`] 次没有应答:WDA 卡死了(`/status` 可能照样正常)。之后经 XCTest 的请求不再发,
- /// 直接报不可用,由守护进程重启 WDA(换一个新的客户端)
+ /// 连续三次无应答,或长请求和其短探测均无应答时,后续请求不再发送,等待守护进程恢复。
pub fn stalled(&self) -> bool {
- self.unanswered() >= STALL_LIMIT
+ self.stall_reason().is_some()
+ }
+
+ /// 读取一致的计数与判定原因;`/status` 的响应不参与此状态。
+ pub fn stall_reason(&self) -> Option<StallReason> {
+ let state = self.unanswered.load(Ordering::Relaxed);
+ if state & UNANSWERED_PROBE != 0 {
+ Some(StallReason::LongRequestAndProbe)
+ } else if state >= STALL_LIMIT {
+ Some(StallReason::ConsecutiveRequests(state))
+ } else {
+ None
+ }
}
- /// 经 XCTest 的请求眼下连续几次没有应答
+ /// 实际连续无应答次数,不含判定标记。
pub fn unanswered(&self) -> u32 {
- self.unanswered.load(Ordering::Relaxed)
+ self.unanswered.load(Ordering::Relaxed) & !UNANSWERED_PROBE
}
async fn send(&self, method: &str, path: &str, body: Option<Value>, timeout: Duration) -> Result<Value> {
@@ -1272,7 +1316,7 @@ mod tests {
let c = WdaClient::new(&t);
assert!(c.wda_reports_locked().await.unwrap_err().no_answer());
assert!(c.active_app().await.unwrap_err().no_answer());
- assert_eq!(c.unanswered(), 2);
+ assert_eq!(c.unanswered(), 0, "两次短探测均获得回答,应清零");
// 回了错误:还活着,从头数
assert!(matches!(c.active_app().await, Err(WdaError::Remote { .. })));
assert_eq!(c.unanswered(), 0);
@@ -1293,6 +1337,89 @@ mod tests {
assert!(c.stalled());
}
+ /// 较长请求超时后,短探测的正常回答或远端错误都证明 WDA 仍有响应,应重新计数。
+ #[tokio::test]
+ async fn answered_probe_resets_stall_count_after_each_slow_request() {
+ for (status, body) in [
+ (200, r#"{"value":{}}"#),
+ (500, r#"{"value":{"error":"unknown error","message":"busy"}}"#),
+ (404, r#"{"message":"unknown route"}"#),
+ (502, "temporarily unavailable"),
+ ] {
+ let replies = (0..4).flat_map(|_| [timed_out(), Ok((status, body.as_bytes().to_vec()))]).collect();
+ let t = Script::new(replies);
+ let c = WdaClient::new(&t);
+ for _ in 0..4 {
+ assert!(c.wda_reports_locked().await.unwrap_err().no_answer());
+ assert_eq!(c.unanswered(), 0, "探测返回 {status} {body}");
+ assert!(!c.stalled());
+ }
+ assert_eq!(t.sent().len(), 8, "每个慢请求后都应继续做短探测");
+ }
+ }
+
+ /// 连不上不是收到回答,不能抹掉之前已经发生的无应答。
+ #[tokio::test]
+ async fn connection_error_does_not_reset_unanswered_count() {
+ let t = Script::new(vec![
+ timed_out(),
+ Err(std::io::Error::new(std::io::ErrorKind::NotConnected, "offline")),
+ Ok((500, br#"{"value":{"error":"unknown error","message":"busy"}}"#.to_vec())),
+ ]);
+ let c = WdaClient::new(&t);
+ assert!(c.xctest_responsive().await.unwrap_err().no_answer());
+ assert_eq!(c.unanswered(), 1);
+ assert!(matches!(c.xctest_responsive().await, Err(WdaError::Unavailable(_))));
+ assert_eq!(c.unanswered(), 1);
+ assert!(matches!(c.xctest_responsive().await, Err(WdaError::Remote { .. })));
+ assert_eq!(c.unanswered(), 0);
+ assert!(!c.stalled());
+ }
+
+ /// 两个请求未应答即可触发快速恢复,但实际计数和原因不能伪装成三次无应答。
+ #[tokio::test]
+ async fn long_request_and_failed_probe_keep_the_actual_count_and_reason() {
+ let t = Script::new(vec![timed_out(), timed_out(), ok(r#"{"value":{"ready":true}}"#)]);
+ let c = WdaClient::new(&t);
+ assert!(c.wda_reports_locked().await.unwrap_err().no_answer());
+ assert_eq!(c.unanswered(), 2);
+ assert_eq!(c.stall_reason(), Some(StallReason::LongRequestAndProbe));
+ assert!(c.stalled());
+ let why = c.stall_reason().unwrap().describe();
+ assert!(why.contains("/wda/activeAppInfo"));
+ assert!(!why.contains("3 次"));
+ // 本地 /status 的回答不应把已记录的判定抹掉。
+ assert!(c.ready().await.unwrap());
+ assert_eq!(c.stall_reason(), Some(StallReason::LongRequestAndProbe));
+ assert_eq!(t.sent(), ["GET /wda/locked", "GET /wda/activeAppInfo", "GET /status"]);
+ }
+
+ #[tokio::test]
+ async fn three_short_unanswered_requests_report_a_consecutive_stall() {
+ let t = Script::new(vec![timed_out(), timed_out(), timed_out()]);
+ let c = WdaClient::new(&t);
+ for n in 1..=STALL_LIMIT {
+ assert!(c.xctest_responsive().await.unwrap_err().no_answer());
+ assert_eq!(c.unanswered(), n);
+ assert_eq!(c.stalled(), n == STALL_LIMIT);
+ }
+ assert_eq!(c.stall_reason(), Some(StallReason::ConsecutiveRequests(STALL_LIMIT)));
+ // 后续调用仍立即拒绝,不再发送请求。
+ assert!(matches!(c.xctest_responsive().await, Err(WdaError::Unavailable(_))));
+ assert_eq!(t.sent().len(), STALL_LIMIT as usize);
+ }
+
+ /// 结束会话的回答只用于清理,不应代替真正的前台响应探测。
+ #[tokio::test]
+ async fn answered_session_delete_does_not_mask_a_failed_probe() {
+ let t = Script::new(vec![ok(r#"{"sessionId":"A"}"#), timed_out(), ok(r#"{"value":null}"#), timed_out()]);
+ let mut c = WdaClient::new(&t);
+ assert!(matches!(c.press_button("home").await, Err(WdaError::Timeout(_))));
+ assert_eq!(c.unanswered(), 2);
+ assert_eq!(c.stall_reason(), Some(StallReason::LongRequestAndProbe));
+ assert_eq!(t.sent()[2], "DELETE /session/A");
+ }
+
/// 经 XCTest 的探测:只有「送到了却没有应答」算卡死的迹象;WDA 回了错误说明它还在办事,连不上归 `/status` 管
#[tokio::test]
async fn xctest_probe_counts_only_missing_answers() {
diff --git a/crates/ictl-wda/src/http.rs b/crates/ictl-wda/src/http.rs
index d293c78..1671f69 100644
--- a/crates/ictl-wda/src/http.rs
+++ b/crates/ictl-wda/src/http.rs
@@ -59,7 +59,43 @@ impl Transport for DeviceTransport {
timeout: Duration,
) -> std::io::Result<(u16, Vec<u8>)> {
let t0 = std::time::Instant::now();
- let req = build_request(method, path, body.as_deref());
+ let r = self.send_request(method, path, body.as_deref(), timeout).await;
+ match &r {
+ Err(e) if matches!(e.kind(), std::io::ErrorKind::TimedOut | AFTER_SENT) => {
+ tracing::warn!("{}", request_log(method, path, t0.elapsed(), &r));
+ }
+ _ => tracing::debug!("{}", request_log(method, path, t0.elapsed(), &r)),
+ }
+ r
+ }
+}
+
+/// 诊断只记录方法、短路径、耗时与状态,不记录请求正文或查询参数。
+fn request_log(method: &str, path: &str, took: Duration, result: &std::io::Result<(u16, Vec<u8>)>) -> String {
+ let short = path.split('?').next().unwrap_or(path);
+ let secs = took.as_secs_f64();
+ match result {
+ Ok((status, _)) => ictl_l10n::log_trf!(
+ "wda {method} {short} → {status}({secs:.2}s)",
+ "wda {method} {short} → {status} ({secs:.2}s)"
+ ),
+ Err(e) => ictl_l10n::log_trf!(
+ "wda {method} {short} 失败({secs:.2}s):{e}",
+ "wda {method} {short} failed ({secs:.2}s): {e}"
+ ),
+ }
+}
+
+impl DeviceTransport {
+ /// 将所有提前返回的连接错误和请求超时交回外层,保证这些失败也能留下诊断日志。
+ async fn send_request(
+ &self,
+ method: &str,
+ path: &str,
+ body: Option<&[u8]>,
+ timeout: Duration,
+ ) -> std::io::Result<(u16, Vec<u8>)> {
+ let req = build_request(method, path, body);
let idevice = tokio::time::timeout(CONNECT_TIMEOUT, self.provider.connect(self.port))
.await
.map_err(|_| {
@@ -105,33 +141,12 @@ impl Transport for DeviceTransport {
}
parse_response(buf).map_err(after_sent)
};
- let r = tokio::time::timeout(timeout, fut).await.map_err(|_| {
+ tokio::time::timeout(timeout, fut).await.map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::TimedOut,
- ictl_l10n::trf!("请求超时({} 秒)", "request timed out ({} s)", timeout.as_secs()),
+ ictl_l10n::trf!("请求超时({} 秒)", "request timed out ({} s)", timeout.as_secs_f64()),
)
- })?;
- // 路径截掉查询串(/source 的排除属性很长)
- let short = path.split('?').next().unwrap_or(path);
- match &r {
- Ok((status, _)) => tracing::debug!(
- "{}",
- ictl_l10n::log_trf!(
- "wda {method} {short} → {status}({:.2}s)",
- "wda {method} {short} → {status} ({:.2}s)",
- t0.elapsed().as_secs_f64()
- )
- ),
- Err(e) => tracing::debug!(
- "{}",
- ictl_l10n::log_trf!(
- "wda {method} {short} 失败({:.2}s):{e}",
- "wda {method} {short} failed ({:.2}s): {e}",
- t0.elapsed().as_secs_f64()
- )
- ),
- }
- r
+ })?
}
}
@@ -251,6 +266,29 @@ fn dechunk(mut body: &[u8]) -> Option<Vec<u8>> {
mod tests {
use super::*;
+ #[test]
+ fn failed_request_log_keeps_endpoint_and_time_without_query() {
+ for kind in [std::io::ErrorKind::TimedOut, AFTER_SENT, std::io::ErrorKind::NotConnected] {
+ let result = Err(std::io::Error::new(kind, "test failure"));
+ let line = request_log("POST", "/session/A/elements?text=private", Duration::from_millis(1250), &result);
+ assert!(line.contains("POST /session/A/elements"));
+ assert!(line.contains("1.25s"));
+ assert!(line.contains("test failure"));
+ assert!(!line.contains("private"));
+ assert!(!line.contains('?'));
+ }
+ }
+
+ #[test]
+ fn successful_request_log_does_not_include_response_body() {
+ let result = Ok((200, b"private response".to_vec()));
+ let line = request_log("GET", "/status", Duration::from_millis(10), &result);
+ assert!(line.contains("GET /status"));
+ assert!(line.contains("200"));
+ assert!(line.contains("0.01s"));
+ assert!(!line.contains("private response"));
+ }
+
#[test]
fn request_has_length_only_with_body() {
let get = String::from_utf8(build_request("GET", "/status", None)).unwrap();
diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md
index e01c290..5f0a9f3 100644
--- a/docs/dev/regression-cases.md
+++ b/docs/dev/regression-cases.md
@@ -1,6 +1,6 @@
# 必须覆盖的回归用例
-#1~#34 来自 toolkit 和本项目早期实际踩过的坑,#35~#45 是多设备和 HID 横屏,#46~#58 是实时画面、开发者工具和英文界面,#59~#63 是 iPhone 18 Pro Max(iOS 27.2.1)真机全量测试发现的问题,#64 起是 viewer 的 AI 任务和新页面,#116~#122 是任务的控制权、控制台的局域网访问与登录、跨主机,#123 起是 0.2.4 发版前回归中发现的。能单测的写单测,不能单测的进真机回归清单。**每个 PR 都必须保持这里的全部用例通过**:单测的由 `cargo test` 覆盖;改到的范围里测试方式是真机、无头 Chrome 或手动测量的,要重跑并在 PR 里列出编号,写明设备和 iOS 版本;修了清单里没有的问题,要加一行。完整要求见 [CONTRIBUTING.md 的 Required tests](../../CONTRIBUTING.md#required-tests)。
+#1~#34 来自 toolkit 和本项目早期实际踩过的坑,#35~#45 是多设备和 HID 横屏,#46~#58 是实时画面、开发者工具和英文界面,#59~#63 是 iPhone 18 Pro Max(iOS 27.2.1)真机全量测试发现的问题,#64 起是 viewer 的 AI 任务和新页面,#116~#122 是任务的控制权、控制台的局域网访问与登录、跨主机,#123 起是 0.2.4 发版前回归中发现的。能单测的写单测,不能单测的进真机回归清单。真机上能用脚本重复的写成 `tests/device/scenarios.py`(工具)或 `tests/device/tasks.py`(AI 任务)里的一项检查,测试方式里写明场景名。**每个 PR 都必须保持这里的全部用例通过**:单测的由 `cargo test` 覆盖;改到的范围里测试方式是真机、无头 Chrome 或手动测量的,要重跑并在 PR 里列出编号,写明设备和 iOS 版本;修了清单里没有的问题,要加一行。完整要求见 [CONTRIBUTING.md 的 Required tests](../../CONTRIBUTING.md#required-tests)。
| # | 坑 | 正确行为 | 测试方式 |
|---|---|---|---|
@@ -16,10 +16,10 @@
| 10 | `ios forward` 监听所有网卡,WDA 无认证,局域网可直接控制手机 | 默认不监听任何端口;bridge 只绑 127.0.0.1 | 集成测试(检查监听地址) |
| 11 | 依赖大版本漂移(mcp 2.x 把 FastMCP 改名、idevice 0.1.x 每版破坏性变更) | 所有依赖锁定精确版本 + `Cargo.lock` 入库;升级单独提交 | CI |
| 12 | host 侧 runner 退出后手机上残留 WDA 仍响应几十秒 | 就绪 = 本进程 XCTest 会话存活 且 `/status` ready | 真机 |
-| 13 | App 冷启动后立即点击会被吞 | `launch_app` 等到前台再停 1 秒 | 真机 |
+| 13 | App 冷启动后立即点击会被吞 | `launch_app` 等到前台再停 1 秒 | 真机;真机脚本 `scenarios.py fresh` |
| 14 | 完整元素树 7~8 秒 | `excluded_attributes` 排除可见性等属性(约 0.3 秒),可见性按坐标判断 | 单测 + 计时 |
| 15 | 铺满全屏的 Application/Window/Toolbar 等元素没有定位价值 | 列表中过滤 | 单测 |
-| 16 | 区域放大倍数只保留 2 位有效数字导致边缘约 1.4 点误差 | 保留 3 位 | 单测 |
+| 16 | 区域放大倍数只保留 2 位有效数字导致边缘约 1.4 点误差 | 保留 3 位 | 单测;真机脚本 `scenarios.py tools` |
| 17 | 只有 ToolError 的消息能透传给 MCP 客户端(Python SDK) | 所有预期错误都转成工具错误文本 | 单测 |
| 18 | 锁屏(未首次解锁)时隧道报 `PasswordProtected` | 进入 NeedsUnlock,提示人工 | 真机 |
| 19 | Apple ID 会话过期只在重签时才发现 | 每日独立验证会话 | 单测(模拟过期) |
@@ -35,9 +35,9 @@
| 29 | WDA 请求超时或中途断开后退到 HID,同一个动作做了两遍 | 传输层区分连不上(`WdaError::Unavailable`,可以退到 HID)和请求已发出之后的超时、断开、响应不完整(不退,报错让 agent 先截图确认) | 单测 + 代码审查 |
| 30 | 设置文件里留空的 `ICTL_LOG=` 生成一个什么都不放行的过滤器,日志全没了 | 空值当作没设 | 真机(看守护进程的输出) |
| 31 | `/wda/tap` 每次先等界面空闲:主屏点图标约 1.7 秒(调小等待设置也没用);W3C actions 手势做完又要等动画冷却(默认 2 秒),App 里切标签约 1.9 秒 | 点击用单个 actions 手势,期间临时把 waitForIdleTimeout/animationCoolOffTimeout 调成 1/0.2,做完恢复(原值只读一次)。真机:主屏点图标 1.70→0.91 秒(到前台 1.80→1.01 秒),App 里 0.62→0.72 秒 | 单测(请求顺序、恢复原值)+ 真机计时 |
-| 32 | `/wda/keys` 没有输入框获得焦点时也返回成功,什么都没输(真机:Safari 地址栏没点中、主屏上直接输入) | 输入前查屏幕上有没有软键盘(`XCUIElementTypeKeyboard`,约 0.2 秒),没有就报错让先点输入框 | 真机 |
+| 32 | `/wda/keys` 没有输入框获得焦点时也返回成功,什么都没输(真机:Safari 地址栏没点中、主屏上直接输入) | 输入前查屏幕上有没有软键盘(`XCUIElementTypeKeyboard`,约 0.2 秒),没有就报错让先点输入框 | 真机;真机脚本 `scenarios.py typing` |
| 33 | 系统弹窗(定位、通知权限)挡着时 Home 不生效、App 到不了前台,WDA 照样报成功;弹窗属于 SpringBoard,看前台 App 发现不了 | 按 Home 前查 `/alert/text`(App 静止时约 0.4 秒;按下后动画中查要好几秒);有弹窗就说明并不按。launch_app 没到前台时同样带上弹窗文字。按 Home 后等主屏到前台再返回 | 真机计时;弹窗路径待弹窗再出现时复测 |
-| 34 | `/wda/touchAndHold` 前后都等界面空闲:主屏长按图标 1.2 秒要约 12 秒 | 长按和点击一样用单个 actions 手势、临时调小等待:约 2 秒 | 真机计时 |
+| 34 | `/wda/touchAndHold` 前后都等界面空闲:主屏长按图标 1.2 秒要约 12 秒 | 长按和点击一样用单个 actions 手势、临时调小等待:约 2 秒 | 真机计时;真机脚本 `scenarios.py menu` |
| 35 | 接着多台时,`devices` / `iphone_list_devices` 漏设备或标错正在控制的那台 | 列出 USB 上每一台的名字、型号、iOS 版本、UDID,标出正在控制哪台、有没有设自动解锁密码 | 真机(两台) |
| 36 | 按 usbmuxd 的列表顺序选设备,列表顺序一变就换了台 | 选定了只认那一台,没接就是离线、不换;没选定时正在控制的那台一直用到它断开 | 单测(`device_pick_is_pinned_or_sticky`)+ 真机(拔掉选定的那台) |
| 37 | `select` 按名字选到了别的设备 | 先比 UDID,再比设备名,最后是名字包含这段文字且只有一台;对上多台就报错,让用 UDID 指定 | 单测(`device_is_found_by_udid_then_name`) |
@@ -71,7 +71,7 @@
| 65 | viewer 已经停了、任务已经停了,agent 的 MCP 服务还在继续操作手机 | 连不上守护进程或任务已结束一律拒绝,并告诉 agent 停下;开任务的程序断开,任务就结束(abandoned) | 单测(`without_the_daemon_a_task_call_is_refused`、`an_ended_or_unknown_token_is_refused_for_everything`、`an_opened_task_holds_the_phone_until_its_lease_goes`)+ 真机(任务中途停止,之后没有新步骤,agent 进程组已结束) |
| 66 | 暂停只挡住了界面上的按钮,agent 照样继续点 | 暂停、接管、等确认时,任务的请求在守护进程里挂住(包括一个工具调用中间的请求,如 `iphone_batch` 的下一步),恢复后才放行 | 单测(`a_paused_task_holds_its_requests_until_resumed`、`a_held_request_whose_caller_left_is_dropped`)+ 真机(暂停 8 秒没有新步骤) |
| 67 | 用户接管时动过手机,交还后 agent 按旧的界面接着点 | 交还后、或别人动过手机后,任务的操作一直被拒,直到它截图或读过元素 | 单测(`after_someone_else_acted_the_agent_looks_before_acting`)+ 真机(交还后先截图) |
-| 68 | 用户拒绝确认后 agent 正常结束,页面显示「已完成」 | 有被拒绝的一步就按「已停止」结束 | 单测(`a_rejected_confirmation_tells_the_agent_not_to_do_it`)+ 真机(拒绝删除世界时钟城市,没有删) |
+| 68 | 用户拒绝确认后 agent 正常结束,页面显示「已完成」 | 有被拒绝的一步就按「已停止」结束 | 单测(`a_rejected_confirmation_ends_the_task_as_rejected`)+ 真机(拒绝删除世界时钟城市,没有删) |
| 69 | 按结果文字里的 `@(x,y)` 给所有步骤画点击标记,读元素的一步也被标成点击 | 只给 `iphone_tap_element` 的结果解析点击位置 | 单测(`only_a_tap_by_text_gets_a_mark_from_its_result`) |
| 70 | 其他网站用 `<img src="http://127.0.0.1:8200/api/elements">` 触发读元素,顺带自动解锁手机 | 浏览器标明 `Sec-Fetch-Site` 不是 same-origin / none 的读请求一律 403 | 单测(`reads_from_other_sites_are_refused`)+ curl |
| 71 | AI 任务执行中,用户在页面上点击和 agent 同时操作 | 没有接管时 viewer 拒绝手动操作(409 并说明),页面也锁住 | 真机(任务中 `/api/tap` 被拒,接管后按 Home 生效) |
@@ -105,10 +105,10 @@
| 99 | `iphone-control status \| head -1`:读者先退出,后面的 `println!` 遇到 EPIPE 就 panic(退出码 101,打出崩溃信息)。Rust 启动时把 SIGPIPE 设成了忽略 | 只打印结果就结束的命令恢复 SIGPIPE 默认行为,安静退出;守护进程、MCP、viewer、wda-bridge 和跨守护进程重启的 update、service、setup 保持忽略 | 单测 sigpipe_default_only_for_commands_that_print_and_end、集成测试 a_closed_stdout_ends_printing_commands_quietly |
| 100 | 0.2.2 起控制台每次按下都先请求 `/wda/screen`(约 0.1~0.2 秒),HID 会话空闲 30 秒关掉后,鼠标一直停在画面里时第一下还要等约 0.5 秒重开 | 按下只问方向,尺寸在转屏时和距上次测量满 60 秒后才重量;鼠标在画面上移动时每 20 秒最多预热一次 HID 会话 | 单测 display_poll_remeasures_size_only_when_needed;页面测试 hovering keeps the HID session warm at most every 20 seconds;真机:控制台连按,按下往返在几十毫秒内 |
| 101 | 控制台开着、页面走 WDA 截图的画面(浏览器解不了 HEVC,或低于 iOS 27)时,WDA 每 1.5~2.5 分钟被 iOS 杀掉(`cpu_resource_fatal`:60 秒内平均 86%~93% CPU,上限 80%)。MJPEG 缩到 75% 让 WDA 逐帧解码、缩放(CoreGraphics)、重新编码;横屏时 `mjpegFixOrientation` 让它逐帧旋转、重新编码,同样超限 | MJPEG 原尺寸、不转正(`MJPEG_SCALE` = 100,`mjpegFixOrientation` = false):WDA 直接转发 testmanagerd 硬件编好的 JPEG,帧率不变(约 34 fps)。横屏的竖帧由页面转正(H.264 按 `display.rotation`,MJPEG 的 img 由浏览器按 EXIF) | 真机(iPhone 15 Pro Max,iOS 27.0.1):拉本机编码的 `/video`,竖屏 25 分钟、横屏 5 分钟不再被杀(开着转正时横屏 2 分钟被杀);无头 Chrome:横屏下 H.264 和 MJPEG 画面方向正确、坐标换算正确 |
-| 102 | iPhone 15 Pro Max(iOS 27.0.1)每次锁屏约 10 秒:经 IOHID 短按电源键(0.05~0.1 秒)调用卡约 5.3 秒且不锁,再等 3 秒才退回 `/wda/lock`(约 1.9 秒)。iPhone 18 Pro Max(iOS 27.2.1)正相反 | 按设备记住哪种锁屏有效(`PerDevice::lock_via_wda`),之后先用它;先用的不灵仍会试另一种 | 单测 lock_order_follows_what_worked_on_this_device;真机:同一台连续锁屏,第一次约 10 秒、之后约 2 秒 |
-| 103 | WDA 半死:`/status` 照常 200,前台 App、截图、读元素、`/wda/locked` 全部超时(iPad mini 5,iPadOS 26.7.3,后台启动的 WDA 跑 20~40 分钟后;2026-11-16 对照:XCTest 会话启动的 WDA 一样会卡,跑几分钟也会,卡时手机上 testmanagerd 不再输出,见 D18 补充)。守护进程只看 `/status`,一直显示「就绪」,不重启;后台模式下守护进程重启还会把它接回来。只靠巡检探测也不够:卡死时工具调用一个接一个等满超时(每个 10~30 秒),设备被占好几分钟,巡检抢不到锁 | WDA 客户端数经 XCTest 的请求(`/status` 之外都是,工具调用和巡检探测 `/wda/activeAppInfo` 一样算)连续几次送到了却没有应答,有应答(哪怕是错误)就清零;连续 3 次就算卡死:之后经 XCTest 的请求直接报不可用,巡检和每个设备请求开头都会忘掉记下的后台 WDA、丢掉会话重新启动 | 单测 three_unanswered_requests_mean_stalled、xctest_probe_counts_only_missing_answers;真机:绕过守护进程让 WDA 长按(期间 `/status` 5 毫秒 200,`/wda/activeAppInfo` 超时)。空闲时 0.2.3 一直「就绪」,修复后约 28 秒判定卡死、34 秒恢复;同时经守护进程背靠背发工具调用时,main(#60)180 秒里 8 次调用各等 10~30 秒、不重启,修复后第 3 次超时(约 50 秒)就重启,13 秒后就绪,其间的调用立即返回;经守护进程连续长按 6×10 秒不误判 |
+| 102 | iPhone 15 Pro Max(iOS 27.0.1)每次锁屏约 10 秒:经 IOHID 短按电源键(0.05~0.1 秒)调用卡约 5.3 秒且不锁,再等 3 秒才退回 `/wda/lock`(约 1.9 秒)。iPhone 18 Pro Max(iOS 27.2.1)正相反 | 按设备记住哪种锁屏有效(`PerDevice::lock_via_wda`),之后先用它;先用的不灵仍会试另一种 | 单测 lock_order_follows_what_worked_on_this_device;真机:同一台连续锁屏,第一次约 10 秒、之后约 2 秒;真机脚本 `scenarios.py lock` |
+| 103 | WDA 半死:`/status` 照常 200,前台 App、截图、读元素、`/wda/locked` 全部超时(iPad mini 5,iPadOS 26.7.3,后台启动的 WDA 跑 20~40 分钟后;2026-11-16 对照:XCTest 会话启动的 WDA 一样会卡,跑几分钟也会,卡时手机上 testmanagerd 不再输出,见 D18 补充)。守护进程只看 `/status`,一直显示「就绪」,不重启;后台模式下守护进程重启还会把它接回来。只靠巡检探测也不够:卡死时工具调用一个接一个等满超时(每个 10~30 秒),设备被占好几分钟,巡检抢不到锁 | WDA 客户端数经 XCTest 的请求(`/status` 之外都是,工具调用和巡检探测 `/wda/activeAppInfo` 一样算)连续几次送到了却没有应答,有应答(哪怕是错误)就清零;连续 3 次,或较长请求及其后的短探测均未应答,就判为无响应(日志区分实际依据):之后经 XCTest 的请求直接报不可用,巡检和每个设备请求开头都会忘掉记下的后台 WDA、丢掉会话重新启动 | 单测 three_unanswered_requests_mean_stalled、xctest_probe_counts_only_missing_answers;真机:绕过守护进程让 WDA 长按(期间 `/status` 5 毫秒 200,`/wda/activeAppInfo` 超时)。空闲时 0.2.3 一直「就绪」,修复后约 28 秒判定卡死、34 秒恢复;同时经守护进程背靠背发工具调用时,main(#60)180 秒里 8 次调用各等 10~30 秒、不重启,修复后第 3 次超时(约 50 秒)就重启,13 秒后就绪,其间的调用立即返回;经守护进程连续长按 6×10 秒不误判 |
| 104 | iOS 27 以下(iPad mini 5,iPadOS 26.7.3)锁屏没锁上:经 IOHID 按电源键 3 秒后未锁、`/wda/lock` 报「Timed out while waiting until the screen gets locked」,之后退到 HID 后备路线,而低版本没有 HID,报的是「WDA 不可用(刚掉线)」,WDA 其实正常 | WDA 在、两种办法都没锁上、又没有 HID 后备时,报「没锁上屏」和两种办法各自的原因;有 HID 后备时照旧退到 HID | 单测 a_failed_lock_says_why_not_that_wda_is_down;真机:见 PR |
-| 105 | iPad mini 5(iPadOS 26.7.3)一直锁不上屏:经 IOHID 按电源键 0.1 秒调用卡约 5.4 秒、不锁;`/wda/lock`(iOS 27 以下是 XCTest 的 `pressLockButton`)10 秒后报「Timed out while waiting until the screen gets locked」。iPhone 15 Pro Max(iOS 27.0.1)上 0.1 秒同样不认,每台第一次锁屏要退到 `/wda/lock`,约 10 秒 | 电源键按 0.15 秒(`POWER_PRESS_SECS`):iPad mini 5、iPhone 15 Pro Max 上 0.15~0.3 秒都能锁,iPhone 18 Pro Max(iOS 27.2.1)上 0.05~0.15 秒能锁、0.5 秒不行 | 单测 hid_buttons_send_consumer_page_events;真机:经 `wda-bridge` 每次先解锁再按不同时长,看 `/wda/locked`;经守护进程连续锁屏 3 次 |
+| 105 | iPad mini 5(iPadOS 26.7.3)一直锁不上屏:经 IOHID 按电源键 0.1 秒调用卡约 5.4 秒、不锁;`/wda/lock`(iOS 27 以下是 XCTest 的 `pressLockButton`)10 秒后报「Timed out while waiting until the screen gets locked」。iPhone 15 Pro Max(iOS 27.0.1)上 0.1 秒同样不认,每台第一次锁屏要退到 `/wda/lock`,约 10 秒 | 电源键按 0.15 秒(`POWER_PRESS_SECS`):iPad mini 5、iPhone 15 Pro Max 上 0.15~0.3 秒都能锁,iPhone 18 Pro Max(iOS 27.2.1)上 0.05~0.15 秒能锁、0.5 秒不行 | 单测 hid_buttons_send_consumer_page_events;真机:经 `wda-bridge` 每次先解锁再按不同时长,看 `/wda/locked`;经守护进程连续锁屏 3 次;真机脚本 `scenarios.py lock` |
| 106 | AI 任务进行中,另一个 MCP 客户端或命令行照样能点手机,和 agent 抢着操作(监管只在 viewer 里) | 任务由守护进程管:不带任务口令的请求可以看,操作一律拒绝并说明是哪个任务,用户接管后才放行;切换设备一律拒绝 | 单测(`others_may_look_but_not_act_until_the_user_takes_over`、`an_opened_task_holds_the_phone_until_its_lease_goes`)+ 真机(任务进行中用 `iphone-control` 另开的 MCP 点击被拒,截图照常) |
| 107 | 任务进行中在别处 `select` 或自动选设备换了一台,任务接着操作另一台手机 | 任务的请求固定发往开任务时的设备;控制的设备变成另一台时任务中断(interrupted) | 单测(`the_task_goes_to_its_own_device`、`another_device_interrupts_the_task`) |
| 108 | 守护进程重启后任务和步骤记录都没了,也说不清任务怎么结束的 | 任务事件逐条落盘(`tasks/<id>.jsonl`,最多 50 个),重启后没结束的记成 interrupted,旧口令失效 | 单测(`logs_survive_a_restart_and_unfinished_tasks_are_interrupted`、`tasks_keep_their_order_across_a_restart_even_within_a_millisecond`、`only_the_newest_logs_are_kept`) |
@@ -128,15 +128,15 @@
| 122 | 升级时运行新程序的 `--version` 偶尔失败:`Text file busy`(同一进程的其他线程 fork 时,新程序还以写方式打开) | 遇到 `ETXTBSY` 等 50 毫秒重试,最多 20 次 | 单测 `the_candidate_runs_once_it_is_no_longer_open_for_writing`(修复前稳定复现) |
| 123 | iPad(iPadOS 26)重启后要输入密码启用 UI 自动化时,通知写的是「iPhone 需要输入锁屏密码」;所有通知标题都写死「iPhone」,多台设备时看不出是哪一台 | 标题用设备名(没有名字时用型号类别),密码提示按设备类别写系统弹窗的说法;离线通知用离线前记下的名字 | 单测 `a_notification_names_its_device`;真机 `notify-test pin`(控制 iPad,经本地假 Bark 截到标题) |
| 124 | 切到另一台设备再切回 iPhone(iOS 27)后,WDA 卡在「Enable UI Automation」密码框期间,HID 后备路线的截图、按键都报「WDA 不可用,也不知道屏幕尺寸」:state.json 只记最后一台的尺寸 | 每台设备的尺寸按 UDID 记下(`screens`),`screen`/`screen_udid` 照旧写给旧版本 | 单测 `every_device_keeps_its_screen_size`;真机:iPhone 和 iPad 来回切换后,iPhone 的 WDA 还没起来时截图、按 Home |
-| 125 | 原生控制(iOS 27 不用 WDA):手机只在切换 App 时推送元素树,App 内换页(设置 → 通用)读到的还是点击前的页面 | 每次读界面都自己走树(类型 4 + 每层一次发出类型 5) | 真机(`then=elements` 里有新页面的元素,「界面有变化」) |
+| 125 | 原生控制(iOS 27 不用 WDA):手机只在切换 App 时推送元素树,App 内换页(设置 → 通用)读到的还是点击前的页面 | 每次读界面都自己走树(类型 4 + 每层一次发出类型 5) | 真机(`then=elements` 里有新页面的元素,「界面有变化」);真机脚本 `scenarios.py fresh` |
| 126 | 原生:HID 的屏幕媒体流开着时,锁屏键盘和系统密码框对无障碍是空的(任何会话都只读到应用元素),自动解锁报「调不出键盘」 | 读锁屏前先关 HID 会话,元素 0.1~0.7 秒后回来 | 真机(锁屏后任一操作) |
-| 127 | 原生:解锁后马上点击,被锁屏滑开的动画吞掉,界面不变 | 解锁后等 0.7 秒再操作 | 真机(锁屏后 `tap_element`,3/3) |
+| 127 | 原生:解锁后马上点击,被锁屏滑开的动画吞掉,界面不变 | 解锁后等 0.7 秒再操作 | 真机(锁屏后 `tap_element`,3/3);真机脚本 `scenarios.py lock` |
| 128 | 原生:走树一个元素一次请求、一来一回约 40 毫秒,57 个元素 2.5 秒;滑动后等列表停下时还连带读 SpringBoard,读太慢,每次都报「还在滚动」 | 一层的请求一次发出、按答复里的元素对象配对;等列表停下只读 App | 真机计时(列元素约 0.2 秒;向上滑不再报还在动) |
| 129 | 原生:SpringBoard 的提问(「…想从“dtpasteboardd”粘贴」、权限请求)没有 Alert 元素:按 Home 不拦、「允许粘贴」不点、输入中文失败 | 前台是 SpringBoard、元素不多、两个以上按钮、没有图标/键盘/密码栏/单元格时包一层 Alert | 单测 `a_question_springboard_asks_reads_as_an_alert` + 真机 |
-| 130 | 原生:按 Home 关掉主屏的长按菜单后马上启动 App,菜单动画结束时 App 又被送回主屏(3/3) | Home 按下后至少 0.6 秒才返回 | 真机(3/3 留在前台) |
-| 131 | 原生:结束 App 后马上打开链接,手机报「无法确定启动的应用的进程标识符」,报错是一串归档的字节 | 结束 App 等进程真的退出(最多 2 秒);CoreDevice 的报错取出里面的说明文字 | 单测 `a_coredevice_error_says_what_it_says` + 真机 |
+| 130 | 原生:按 Home 关掉主屏的长按菜单后马上启动 App,菜单动画结束时 App 又被送回主屏(3/3) | Home 按下后至少 0.6 秒才返回 | 真机(3/3 留在前台);真机脚本 `scenarios.py menu` |
+| 131 | 原生:结束 App 后马上打开链接,手机报「无法确定启动的应用的进程标识符」,报错是一串归档的字节 | 结束 App 等进程真的退出(最多 2 秒);CoreDevice 的报错取出里面的说明文字 | 单测 `a_coredevice_error_says_what_it_says` + 真机;真机脚本 `scenarios.py url` |
| 132 | 原生:解锁沿用 WDA 的固定等待(唤醒 1 秒、上滑 1.5 秒),一次解锁约 8 秒 | 原生读锁屏只要约 0.1 秒:上滑后每 0.2 秒找键盘,唤醒等 0.5 秒;每位照旧读回核对(#4) | 单测 `a_screen_read_cheaply_finds_the_keypad_without_waiting_it_out` + 真机计时 |
-| 133 | 原生:网页(Safari)的文字读不到:网页元素在 WebKit WebContent 进程里,没有宿主视图 | 按进程列表认出 WebContent,元素原样放置 | 单测 + 真机(`wait_for` 网页文字 0.2~0.8 秒) |
+| 133 | 原生:网页(Safari)的文字读不到:网页元素在 WebKit WebContent 进程里,没有宿主视图 | 按进程列表认出 WebContent,元素原样放置 | 单测 + 真机(`wait_for` 网页文字 0.2~0.8 秒);真机脚本 `scenarios.py url` |
| 134 | 原生:每次截图都重新连截屏服务,新连接上第一个请求要多做一次握手(0.82 秒,同一连接上之后 0.30 秒)。截屏服务只认 `png`(idevice 的 `jpeg` 和其他十几个格式名都被拒),在隧道的 SYN 里通告 MSS 也没让 8 MB 的 PNG 变快 | 截屏服务的连接留在隧道上复用,失效就重连一次 | 真机计时(截图中位数 0.91 → 0.43 秒);`debug shot-formats` |
| 135 | 原生:按键盘「下一个键盘」按钮的值判断是英文键盘就直接按键:那个值是点了要切到的键盘,不是当前的;HID 按键走硬件键盘的输入法,屏幕上是英文键盘也照样组成拼音(「wifi」成了带下划线的「w i f i」),去掉空格的读回核对没拦住 | 一律粘贴 | 真机 |
| 136 | 原生:SpringBoard 在前台时(锁屏、面容 ID 框)状态栏的按钮被算进「SpringBoard 的提问」,报出一个标题是时间的弹窗 | 判断提问、取标题都不算状态栏元素 | 单测 `a_question_springboard_asks_reads_as_an_alert` |
@@ -146,5 +146,6 @@
| 140 | 开着后台启动(`ICTL_WDA_DETACHED=1`)用过 WDA、再切回原生控制:之前后台启动的 WDA 一直在手机上运行,state.json 里也一直记着它。原来结束它用的 DVT `kill_app` 对 WDA 无效(WDA 模式下关掉开关时,随后用 XCTest 会话启动的 WDA 会顶替它,所以那条路看不出问题) | 原生准备手机时(开发者镜像好了之后)结束记下的那个 WDA;结束一律走 AppService 的 SIGKILL,等它从进程列表消失(最多 2 秒)再忘掉;结束不了就留着记录,下次准备时再试 | 真机(切 WDA 让后台 WDA 起来,再切回原生,看日志和 state.json) |
| 141 | 开着后台启动(`ICTL_WDA_DETACHED=1`)时 `iphone-control service stop`、`service uninstall` 之后,后台启动的 WDA 还在手机上运行(它本来就不随守护进程退出,好让重启、升级不打断它),一直占着 8100 端口 | `service stop`/`uninstall` 停掉服务后(还有守护进程应答时不动),对接着的手机逐个结束记下的后台 WDA(AppService SIGKILL,等它从进程列表消失),忘掉结束了的;没接着、结束不了的留着记录,守护进程下次准备这台手机时处理。`service restart`、升级照旧不结束 | 单测 `only_the_wda_runner_with_that_pid_is_wda` + 真机(`service stop` 后进程列表里没有 WDA、记录清空;`restart` 后接上原进程) |
| 142 | 开着后台启动时切换设备:`state.json` 只记一条后台 WDA,切到另一台就被覆盖,原来那台手机上的 WDA 没人记着、继续运行,切回去时只能重新后台启动 | 每台设备各记一条(`detached_wdas`,按 UDID),切回去直接接上;最近一条照旧写进 `detached_wda` 给旧版本;旧版本留下的那一条在记下别的设备之前先迁进新表 | 单测 `each_device_keeps_its_background_wda`、`an_older_versions_background_wda_is_still_known` + 真机(iPhone ↔ iPad 来回切,日志是「接上…没有重新启动」) |
-| 143 | 原生:Spotlight 打开时选中上次的搜索词,再粘贴同样的词会把它替换成自己,输入框的值不变,`iphone_type_text` 报「粘贴了…但输入框里没有这段文字」(带 `submit` 时还不按回车),其实已经输进去了 | 「允许粘贴」点过之后,输入框原来就有这段文字、1.5 秒不变,算输入成功并提示截图确认;没点过「允许粘贴」时仍报错 | 单测 `a_paste_that_replaced_the_same_text_is_told_apart_from_one_that_missed` + 真机(Spotlight 留着「设置」时再输入「设置」,`run.py` 连跑两遍)|
-| 144 | 设备闲置时自动锁屏,下一个操作先自动解锁(iPad 经 WDA 约 15 秒,iPhone 原生约 9 秒),结果和事件日志都没说,看着像「切换设备后第一个操作慢」 | 结果第一行(截图在说明里、出错时在报错里)写「手机锁着,先自动解锁了,用时 X 秒」,事件日志记「已自动解锁」 | 单测 `an_unlock_first_is_said_on_the_answers_first_line` + 真机(锁屏后按名字点击、截图,两台设备)|
+| 143 | 原生:Spotlight 打开时选中上次的搜索词,再粘贴同样的词会把它替换成自己,输入框的值不变,`iphone_type_text` 报「粘贴了…但输入框里没有这段文字」(带 `submit` 时还不按回车),其实已经输进去了 | 「允许粘贴」点过之后,输入框原来就有这段文字、1.5 秒不变,算输入成功并提示截图确认;没点过「允许粘贴」时仍报错 | 单测 `a_paste_that_replaced_the_same_text_is_told_apart_from_one_that_missed` + 真机(Spotlight 留着「设置」时再输入「设置」,`run.py` 连跑两遍);真机脚本 `scenarios.py typing` |
+| 144 | 设备闲置时自动锁屏,下一个操作先自动解锁(iPad 经 WDA 约 15 秒,iPhone 原生约 9 秒),结果和事件日志都没说,看着像「切换设备后第一个操作慢」 | 结果第一行(截图在说明里、出错时在报错里)写「手机锁着,先自动解锁了,用时 X 秒」,事件日志记「已自动解锁」 | 单测 `an_unlock_first_is_said_on_the_answers_first_line` + 真机(锁屏后按名字点击、截图,两台设备);真机脚本 `scenarios.py lock` |
+| 145 | WDA 的短探测已正常应答或返回远端错误,却不清零超时计数,三个独立慢请求仍会触发重启;连接失败反而清零。日志还把长请求和短探测均未应答写成「连续 3 次」、宣称尚未检查的 `/status` 正常,请求超时本身缺端点日志 | 只有正常响应或远端错误清零,连接失败不清零;连续无应答和长请求后的失败探测分别记录原因及实际次数;超时诊断记录方法、短路径和耗时,不记录查询参数或正文 | 单测 `answered_probe_resets_stall_count_after_each_slow_request`、`connection_error_does_not_reset_unanswered_count`、`long_request_and_failed_probe_keep_the_actual_count_and_reason`、`three_short_unanswered_requests_report_a_consecutive_stall`、`answered_session_delete_does_not_mask_a_failed_probe`、`failed_request_log_keeps_endpoint_and_time_without_query`、`successful_request_log_does_not_include_response_body`;真机:同一 iPad、同一 WDA,把只读业务请求的客户端时限缩短到 20ms,短探测保留 5s,对照修复前后各 3 轮 |
diff --git a/tests/check_regression_cases.py b/tests/check_regression_cases.py
new file mode 100644
index 0000000..612e320
--- /dev/null
+++ b/tests/check_regression_cases.py
@@ -0,0 +1,58 @@
+"""Checks that the tests docs/dev/regression-cases.md names still exist.
+
+ python3 tests/check_regression_cases.py
+
+The list says for each problem how it is tested, often by a unit test's name. A test that is renamed or removed
+leaves the list pointing at nothing, and the case looks covered when it no longer is. Every snake_case name with
+at least three underscores in the list has to appear somewhere in the sources (crates/, apps/, tests/, packaging/):
+that covers Rust tests, the Python ones and identifiers the list quotes from the code. Exit code 1 names the rows
+whose test is gone. No dependencies beyond the standard library.
+"""
+
+import os
+import re
+import sys
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+LIST = os.path.join(ROOT, "docs", "dev", "regression-cases.md")
+SOURCES = ("crates", "apps", "tests", "packaging")
+KINDS = (".rs", ".py", ".mjs", ".js", ".html", ".sh", ".toml")
+NAME = re.compile(r"(?<![A-Za-z0-9_])[a-z][a-z0-9]*(?:_[a-z0-9]+){3,}(?![A-Za-z0-9_])")
+ROW = re.compile(r"^\| (\d+) \|")
+
+
+def sources() -> str:
+ out = []
+ for top in SOURCES:
+ for folder, dirs, files in os.walk(os.path.join(ROOT, top)):
+ dirs[:] = [d for d in dirs if d not in ("target", "node_modules", "__pycache__", "fixtures")]
+ for name in files:
+ path = os.path.join(folder, name)
+ if name.endswith(KINDS) and os.path.abspath(path) != os.path.abspath(__file__):
+ with open(path, encoding="utf-8", errors="replace") as f:
+ out.append(f.read())
+ return "\n".join(out)
+
+
+def main() -> int:
+ code = sources()
+ rows = names = 0
+ missing = []
+ with open(LIST, encoding="utf-8") as f:
+ for line in f:
+ m = ROW.match(line)
+ if not m:
+ continue
+ rows += 1
+ for name in sorted(set(NAME.findall(line))):
+ names += 1
+ if name not in code:
+ missing.append((m[1], name))
+ for row, name in missing:
+ print(f"#{row}: `{name}` is not in the sources (renamed or removed? fix the row, or restore the test)")
+ print(f"{rows} cases, {names} names, {len(missing)} missing")
+ return 1 if missing or not rows else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/device/compare.py b/tests/device/compare.py
new file mode 100644
index 0000000..392eda6
--- /dev/null
+++ b/tests/device/compare.py
@@ -0,0 +1,60 @@
+"""Compares the step times of two `run.py --json` runs on the same device: is the branch slower than main?
+
+ MCP_CMD='iphone-control mcp' python tests/device/run.py --repeat 5 --json main.json # main's daemon running
+ MCP_CMD="$PWD/target/release/iphone-control mcp" python tests/device/run.py --repeat 5 --json branch.json
+ python tests/device/compare.py main.json branch.json
+
+Per step it takes the median over the runs, without the time an automatic unlock took (the answer says how long:
+a phone that locked itself while idle would otherwise make one step 8 to 15 seconds slower). A step counts as
+slower when it takes over 20 % and over 0.1 s longer, or over 0.5 s longer (CONTRIBUTING.md, "Required tests",
+part 2): those are marked SLOWER and need a reason in the pull request. Exit code 1 if any step is slower or the
+two runs didn't do the same steps. No dependencies beyond the standard library.
+"""
+
+import json
+import statistics
+import sys
+
+
+def medians(path: str):
+ with open(path, encoding="utf-8") as f:
+ data = json.load(f)
+ runs = [r for r in data["runs"] if r]
+ steps = [(s["tool"], json.dumps(s["args"], ensure_ascii=False, sort_keys=True)) for s in runs[0]]
+ same = [r for r in runs if [(s["tool"], json.dumps(s["args"], ensure_ascii=False, sort_keys=True)) for s in r] == steps]
+ times = [statistics.median(max(r[i]["seconds"] - r[i].get("unlock_seconds", 0), 0) for r in same) for i in range(len(steps))]
+ failed = sum(not s["ok"] for r in runs for s in r)
+ return data.get("device", "?"), steps, times, len(same), len(runs), failed
+
+
+def slower(base: float, new: float) -> bool:
+ d = new - base
+ return d > 0.5 or (d > 0.1 and new > base * 1.2)
+
+
+def main() -> int:
+ if len(sys.argv) != 3:
+ print(__doc__)
+ return 2
+ (dev_a, steps_a, t_a, n_a, all_a, bad_a), (dev_b, steps_b, t_b, n_b, all_b, bad_b) = map(medians, sys.argv[1:])
+ print(f"base: {sys.argv[1]} {dev_a} ({n_a} of {all_a} runs, {bad_a} failed steps)")
+ print(f"new: {sys.argv[2]} {dev_b} ({n_b} of {all_b} runs, {bad_b} failed steps)")
+ wrong = 0
+ if dev_a != dev_b:
+ print("NOT THE SAME DEVICE or control mode: the times don't compare")
+ wrong += 1
+ if steps_a != steps_b:
+ print("NOT THE SAME STEPS: run both with the same steps")
+ return 1
+ print(f"{'step':<44} {'base':>7} {'new':>7} {'diff':>7}")
+ for (tool, args), a, b in zip(steps_a, t_a, t_b):
+ mark = " SLOWER" if slower(a, b) else ""
+ wrong += bool(mark)
+ name = f"{tool} {args}"
+ print(f"{name[:43]:<44} {a:7.2f} {b:7.2f} {b - a:+7.2f}{mark}")
+ print(f"{'total':<44} {sum(t_a):7.2f} {sum(t_b):7.2f} {sum(t_b) - sum(t_a):+7.2f}")
+ return 1 if wrong else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/device/device.py b/tests/device/device.py
new file mode 100644
index 0000000..7da0f2a
--- /dev/null
+++ b/tests/device/device.py
@@ -0,0 +1,201 @@
+"""What run.py and scenarios.py share: reading the device out of the tools' answers, checking an answer against
+what is expected of it, and a few texts in both languages.
+
+The tools answer in Chinese or English (IPHONE_CONTROL_LANG of the daemon and the MCP server), and the phone has
+its own language, so nothing here depends on either: an expected text is given in both languages (`T`), and app
+names are read from the phone (`iphone_list_apps`)."""
+
+import re
+import struct
+from dataclasses import dataclass, field
+
+CLOCK = "com.apple.mobiletimer"
+SETTINGS = "com.apple.Preferences"
+SAFARI = "com.apple.mobilesafari"
+SPRINGBOARD = "com.apple.springboard"
+
+
+def T(zh: str, en: str) -> list[str]:
+ """A text the tools say, in both languages: either one counts"""
+ return [zh, en]
+
+
+NOT_FOUND = T("没找到", "Not found")
+CHANGED = T("界面有变化", "the screen changed")
+UNCHANGED = T("界面和操作前一样", "the screen is the same")
+APPEARED = T("已出现", "Appeared")
+NO_KEYBOARD = T("屏幕上没有键盘", "No keyboard on screen")
+AFTER = T("操作后的界面", "after the action")
+UNAVAILABLE = T("WDA 不可用", "WDA unavailable") # the phone can't be controlled right now: not an answer to the call
+
+
+def ready(status_text: str) -> bool:
+ """Does iphone_status say the phone can be controlled (it then knows the screen's size)?"""
+ return bool(_SCREEN.search(status_text)) and not any(u in status_text for u in UNAVAILABLE)
+
+_UNLOCKED = re.compile(r"先自动解锁了,用时 ([\d.]+) 秒|unlocked first, which took ([\d.]+) s")
+_DEVICE = re.compile(r"\((iP[A-Za-z]+\d+,\d+) (?:iOS|iPadOS) ([\d.]+), ?([0-9A-Fa-f-]{24,40})\)")
+_SCREEN = re.compile(r"(?:屏幕|Screen): (\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)")
+_ELEMENT = re.compile(r'^(\w+) "((?:[^"\\]|\\.)*)"(.*?) @\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\) (\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)')
+
+
+def unlock_seconds(text: str) -> float:
+ """How long the answer says the phone took to unlock first (0: it didn't have to)"""
+ m = _UNLOCKED.search(text)
+ return float(m.group(1) or m.group(2)) if m else 0.0
+
+
+@dataclass
+class Element:
+ kind: str
+ label: str
+ rest: str
+ x: float
+ y: float
+ w: float
+ h: float
+
+ @property
+ def value(self) -> str | None:
+ m = re.search(r'value="([^"]*)"', self.rest)
+ return m.group(1) if m else None
+
+
+def elements(text: str) -> list[Element]:
+ """The elements in an answer of iphone_list_elements (or after `--- the screen after the action ---`)"""
+ out = []
+ for line in text.splitlines():
+ if m := _ELEMENT.match(line.strip()):
+ out.append(Element(m[1], m[2], m[3], *(float(m[i]) for i in range(4, 8))))
+ return out
+
+
+def tabs(text: str) -> list[Element]:
+ """A tab bar's buttons: a row of three or more buttons of which exactly one says it is selected (value 1; the
+ others say 0 natively, nothing through WDA). Found by what they say about themselves, not by their names, which
+ follow the phone's language, nor by where the bar is (the bottom on an iPhone, the top on an iPad)"""
+ rows: dict[tuple[float, float], list[Element]] = {}
+ for e in elements(text):
+ if e.kind == "Button":
+ rows.setdefault((e.y, e.h), []).append(e)
+ for row in rows.values():
+ if len(row) >= 3 and sum(e.value == "1" for e in row) == 1 and all(e.value in ("0", "1", None) for e in row):
+ return sorted(row, key=lambda e: e.x)
+ return []
+
+
+@dataclass
+class Device:
+ model: str = "?"
+ ios: str = "?"
+ udid: str = ""
+ w: float = 0
+ h: float = 0
+ native: bool = False
+ locked: bool = False
+ apps: dict[str, str] = field(default_factory=dict) # bundle ID → the name the phone shows
+
+ def line(self) -> str:
+ how = "native" if self.native else "WDA"
+ return f"{self.model}, iOS {self.ios}, {self.w:g}x{self.h:g} pt, {how}, {self.udid}"
+
+ def name(self, bundle: str) -> str:
+ """The app's name on this phone (to launch it the way an agent would), or its bundle ID"""
+ return self.apps.get(bundle, bundle)
+
+
+def controlled(devices_text: str, status_text: str = "") -> tuple[str, str, str]:
+ """(model, iOS version, UDID) of the device being controlled, from iphone_list_devices: the line with the arrow
+ when several are connected, else the only one"""
+ lines = [ln for ln in devices_text.splitlines() if "→" in ln] or devices_text.splitlines() + status_text.splitlines()
+ for ln in lines:
+ if m := _DEVICE.search(ln):
+ return m[1], m[2], m[3]
+ return "?", "?", ""
+
+
+def read_status(d: Device, text: str) -> Device:
+ if m := _SCREEN.search(text):
+ d.w, d.h = float(m[1]), float(m[2])
+ first = text.splitlines()[0] if text else ""
+ d.native = "原生" in first or "native" in first.lower()
+ d.locked = is_locked(text)
+ return d
+
+
+def is_locked(status_text: str) -> bool:
+ """Does iphone_status say the phone is locked? Its line reads `锁屏: 已锁屏(…)` / `Locked: locked (…)`"""
+ line = next((ln for ln in status_text.splitlines() if ln.startswith(("锁屏:", "Locked:"))), "")
+ return line.partition(":")[2].strip().startswith(("已锁屏", "locked"))
+
+
+def read_apps(d: Device, text: str) -> Device:
+ for ln in text.splitlines():
+ name, tab, bundle = ln.partition("\t")
+ if tab and bundle.strip():
+ d.apps.setdefault(bundle.strip(), name.strip())
+ return d
+
+
+def jpeg_size(data: bytes) -> tuple[int, int] | None:
+ """(width, height) of a JPEG, from its frame header; PNG too. None when it is neither"""
+ if data[:8] == b"\x89PNG\r\n\x1a\n":
+ return struct.unpack(">II", data[16:24])
+ if data[:2] != b"\xff\xd8":
+ return None
+ i = 2
+ while i + 9 < len(data):
+ if data[i] != 0xFF:
+ i += 1
+ continue
+ marker = data[i + 1]
+ if marker in (0xC0, 0xC1, 0xC2):
+ h, w = struct.unpack(">HH", data[i + 5 : i + 9])
+ return w, h
+ if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD7:
+ i += 2
+ continue
+ i += 2 + struct.unpack(">H", data[i + 2 : i + 4])[0]
+ return None
+
+
+def enlarged_region(size: tuple[int, int] | None, width: float, height: float) -> bool:
+ """区域图片应比点数尺寸大,且保持长宽比;原始截图恰好为 2 倍也合法。"""
+ if size is None or width <= 0 or height <= 0 or size[1] <= 0:
+ return False
+ ratio = width / height
+ return size[0] > width and abs(size[0] / size[1] - ratio) < 0.02 * ratio
+
+
+def _says(text: str, want) -> bool:
+ """`want`: a text, or the same text in several languages (any one of them)"""
+ return any(w in text for w in ([want] if isinstance(want, str) else want))
+
+
+def judge(expect: dict, text: str, is_error: bool, seconds: float, images: list[tuple[int, int] | None]) -> list[str]:
+ """What is wrong with an answer, given what the step expects of it (nothing expected: only that it isn't an
+ error). `expect`:
+
+ error true: the tool must refuse (an error result); default false
+ has texts the answer must contain; each a text, or a list of alternatives (the two languages)
+ lacks texts it must not contain, likewise
+ max_s seconds it may take, not counting an automatic unlock the answer reports
+ image [width, height] the returned picture must have, in pixels (±1)
+ """
+ wrong = []
+ if bool(expect.get("error", False)) != is_error:
+ wrong.append("was refused" if is_error else "should have been refused")
+ for w in expect.get("has", []):
+ if not _says(text, w):
+ wrong.append(f"doesn't say {w!r}")
+ for w in expect.get("lacks", []):
+ if _says(text, w):
+ wrong.append(f"says {w!r}")
+ if "max_s" in expect and seconds - unlock_seconds(text) > expect["max_s"]:
+ wrong.append(f"took {seconds - unlock_seconds(text):.2f}s, over {expect['max_s']:g}s")
+ if "image" in expect:
+ want = tuple(expect["image"])
+ got = images[0] if images else None
+ if not got or any(abs(g - w) > 1 for g, w in zip(got, want)):
+ wrong.append(f"picture is {got}, not {want}")
+ return wrong
diff --git a/tests/device/run.py b/tests/device/run.py
index 436b7f6..a839d97 100644
--- a/tests/device/run.py
+++ b/tests/device/run.py
@@ -1,18 +1,32 @@
-"""Real-device regression runner: start the MCP server over stdio, call tools in order, print each
-result with its wall time, and save screenshots.
+"""Real-device regression runner: start the MCP server over stdio, call tools in order, check each answer, print
+it with its wall time, and save screenshots.
pip install -r tests/device/requirements.txt
python tests/device/run.py # default steps (harmless: Home, Clock tabs, Spotlight search)
python tests/device/run.py '[["iphone_status", {}], ["sleep", 1], ["iphone_screenshot", {}]]'
+ python tests/device/run.py --repeat 5 --json new.json # timings to compare: see compare.py
The MCP server command comes from MCP_CMD (default: `iphone-control mcp`; for a build of your branch use its
full path, e.g. `target/release/iphone-control mcp`). With MCP_URL set it connects there over HTTP instead (the
viewer's `/mcp`; MCP_CA trusts its self-signed certificate), see mcp_http.py. Screenshots go to SHOTS_DIR (default: ./shots).
-A step `["sleep", seconds]` waits without calling a tool. Exit code is 1 if any tool returned an error.
-The last line sums it up (calls, failures, total time): paste the output into the pull request, see
-CONTRIBUTING.md, "Required tests".
+
+It first asks which device it controls (model, iOS version, screen, native or WDA: the `###` line, which a pull
+request needs) and at the end checks that it is still the same one: another session switching devices in between
+makes the run worthless.
+
+The default steps check what they get, not only that no tool failed: the tab they tap becomes the selected one, the
+screen is reported as changed, a screenshot has the screen's size, the text typed into Spotlight shows up. They
+work on any screen size and in any language of the phone or of the tools' answers (device.py).
+
+Your own steps are a JSON list. A step is `[tool, arguments]`, or `[tool, arguments, expect]` to check its answer
+(`has`, `lacks`, `error`, `max_s`, `image`: see `judge` in device.py); without `expect` a step only has to succeed.
+`["sleep", seconds]` waits without calling a tool.
+
+Exit code is 1 if any step failed. The last line sums it up (calls, failures, total time): paste the output into
+the pull request, see CONTRIBUTING.md, "Required tests".
"""
+import argparse
import asyncio
import base64
import json
@@ -25,26 +39,9 @@ from contextlib import AsyncExitStack, asynccontextmanager
from mcp import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client
+import device as dev
import mcp_http
-# Harmless by design: no messages, purchases, deletions or settings changes.
-DEFAULT_STEPS = [
- ["iphone_status", {}],
- ["iphone_tap_element", {"text": "不存在的按钮xyz"}], # must report "not found", not tap anything
- ["iphone_press_button", {"button": "home"}],
- ["iphone_launch_app", {"app": "时钟"}],
- ["iphone_list_elements", {"limit": 12}],
- ["iphone_tap_element", {"text": "秒表", "then": "elements", "then_filter": "Button"}],
- ["iphone_screenshot", {}],
- ["iphone_screenshot", {"x": 0, "y": 0, "width": 430, "height": 60}],
- ["iphone_press_button", {"button": "home"}],
- ["iphone_swipe", {"from_x": 215, "from_y": 400, "to_x": 215, "to_y": 700}],
- ["iphone_type_text", {"text": "设置"}],
- ["iphone_wait_for", {"text": "设置", "timeout": 5}],
- ["iphone_screenshot", {}],
- ["iphone_press_button", {"button": "home"}],
-]
-
@asynccontextmanager
async def connect(params: StdioServerParameters):
@@ -57,43 +54,165 @@ async def connect(params: StdioServerParameters):
yield await stack.enter_async_context(ClientSession(r, w))
+class Runner:
+ """Calls tools, prints each answer and keeps what a comparison needs"""
+
+ def __init__(self, session: ClientSession, shots: str):
+ self.session = session
+ self.shots = shots
+ self.calls = self.failed = self.images = 0
+ self.records: list[dict] = []
+ self.quiet = False
+ self.sizes: list[tuple[int, int] | None] = [] # the pictures in the last answer
+
+ def fail(self, name: str, why: str):
+ """A check the step's own expectations don't cover"""
+ self.failed += 1
+ if self.records:
+ self.records[-1]["ok"] = False
+ print(f" FAILED: {name}: {why}", flush=True)
+
+ async def step(self, name: str, args: dict | None = None, **expect) -> str:
+ """Calls the tool and checks its answer against `expect` (device.judge); returns the answer's text"""
+ args = args or {}
+ t = time.time()
+ res = await self.session.call_tool(name, args)
+ dt = time.time() - t
+ out, sizes = [], []
+ for c in res.content:
+ if c.type == "image":
+ data = base64.b64decode(c.data)
+ sizes.append(dev.jpeg_size(data))
+ if self.quiet:
+ continue
+ self.images += 1
+ path = os.path.join(self.shots, f"shot{self.images}.jpg")
+ with open(path, "wb") as f:
+ f.write(data)
+ out.append(f"<image {path} {sizes[-1]}>")
+ else:
+ out.append(c.text)
+ text = "\n".join(o for o in out if not o.startswith("<image "))
+ self.sizes = sizes
+ wrong = dev.judge(expect, text, bool(res.is_error), dt, sizes)
+ if self.quiet:
+ if wrong:
+ raise RuntimeError(f"{name}: {'; '.join(wrong)}: {text}")
+ return text
+ self.calls += 1
+ self.failed += bool(wrong)
+ self.records.append({"tool": name, "args": args, "seconds": round(dt, 3),
+ "unlock_seconds": dev.unlock_seconds(text), "ok": not wrong})
+ flag = "".join(f"\n FAILED: {w}" for w in wrong) if wrong else ""
+ head = f"=== {name} {json.dumps(args, ensure_ascii=False)} {dt:.2f}s{' ERROR' if res.is_error else ''}"
+ print(head + "\n" + "\n".join(out) + flag, flush=True)
+ return text
+
+ async def look(self, with_apps: bool = True) -> dev.Device:
+ """Which device, without printing or counting it as steps. None of these unlock or touch the phone"""
+ self.quiet = True
+ try:
+ d = dev.Device()
+ status = await self.step("iphone_status")
+ d.model, d.ios, d.udid = dev.controlled(await self.step("iphone_list_devices"), status)
+ dev.read_status(d, status)
+ if with_apps:
+ dev.read_apps(d, await self.step("iphone_list_apps", {"include_system": True}))
+ return d
+ finally:
+ self.quiet = False
+
+
+async def default_steps(r: Runner, d: dev.Device):
+ """Harmless by design: no messages, purchases, deletions or settings changes. Every step says what it expects"""
+ cx = round(d.w / 2)
+ await r.step("iphone_status")
+ # must say "not found" and tap nothing
+ await r.step("iphone_tap_element", {"text": "不存在的按钮xyz"}, has=[dev.NOT_FOUND])
+ await r.step("iphone_press_button", {"button": "home"})
+ await r.step("iphone_launch_app", {"app": d.name(dev.CLOCK)}, has=[dev.CLOCK])
+ # enough to reach the tab bar on whichever tab Clock was left (the timer's page has the most before it)
+ listed = await r.step("iphone_list_elements", {"limit": 40})
+ tabs = dev.tabs(listed)
+ if len(tabs) < 2:
+ r.fail("iphone_list_elements", "Clock's tab bar isn't among the first 40 elements")
+ else:
+ # a tab that isn't the selected one: tapping it must make it the selected one. The answer may not say
+ # whether the screen changed (a page judged by its picture has no tree to compare with the one before),
+ # but it must not say it stayed the same
+ was = next(t for t in tabs if t.value == "1")
+ other = next(t for t in tabs if t.value != "1")
+ for tab in (other, was): # and back, so that the next run starts from the same screen
+ await r.step(
+ "iphone_tap_element", {"text": tab.label, "then": "elements", "then_filter": "Button"},
+ has=[f'Button "{tab.label}" value="1"'], lacks=[dev.NOT_FOUND, dev.UNCHANGED],
+ )
+ await r.step("iphone_screenshot", image=[d.w, d.h])
+ # the top strip, enlarged: the picture keeps the strip's shape
+ await r.step("iphone_screenshot", {"x": 0, "y": 0, "width": d.w, "height": 60})
+ got = r.sizes[0] if r.sizes else None
+ if not got or abs(got[0] / got[1] - d.w / 60) > 0.03 * d.w / 60 or got[0] < d.w:
+ r.fail("iphone_screenshot", f"the strip's picture is {got}: not an enlarged {d.w:g}x60")
+ await r.step("iphone_press_button", {"button": "home"})
+ # down from the middle of the home screen: Spotlight, with its keyboard up
+ await r.step("iphone_swipe", {"from_x": cx, "from_y": round(d.h * 0.43), "to_x": cx, "to_y": round(d.h * 0.75)})
+ word = d.name(dev.SETTINGS) if dev.SETTINGS in d.apps else "设置"
+ await r.step("iphone_type_text", {"text": word}, lacks=[dev.NO_KEYBOARD])
+ await r.step("iphone_wait_for", {"text": word, "timeout": 5}, has=[dev.APPEARED])
+ await r.step("iphone_screenshot", image=[d.w, d.h])
+ await r.step("iphone_press_button", {"button": "home"})
+ await r.step("iphone_status", has=[dev.SPRINGBOARD])
+
+
async def main() -> int:
- steps = json.loads(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_STEPS
+ ap = argparse.ArgumentParser(description="Real-device regression runner (see the top of this file)")
+ ap.add_argument("steps", nargs="?", help="steps as a JSON list; the default steps if left out")
+ ap.add_argument("--repeat", type=int, default=1, metavar="N", help="run the steps N times (timings: the median counts)")
+ ap.add_argument("--json", metavar="FILE", help="write the device and every step's time to FILE, for compare.py")
+ a = ap.parse_args()
+ steps = json.loads(a.steps) if a.steps else None
cmd = shlex.split(os.environ.get("MCP_CMD", "iphone-control mcp"))
shots = os.environ.get("SHOTS_DIR", "shots")
os.makedirs(shots, exist_ok=True)
- failed = 0
# the whole environment: the MCP SDK passes only a few variables by default, and without XDG_RUNTIME_DIR the
# server looks for the daemon's socket in the wrong place (every call fails at once)
params = StdioServerParameters(command=cmd[0], args=cmd[1:], env=dict(os.environ))
- calls = 0
t0 = time.time()
+ runs = []
async with connect(params) as session:
await session.initialize()
- n = 0
- for name, args in steps:
- if name == "sleep":
- await asyncio.sleep(float(args))
- continue
- t = time.time()
- res = await session.call_tool(name, args)
- dt = time.time() - t
- out = []
- for c in res.content:
- if c.type == "image":
- n += 1
- path = os.path.join(shots, f"shot{n}.jpg")
- with open(path, "wb") as f:
- f.write(base64.b64decode(c.data))
- out.append(f"<image {path}>")
- else:
- out.append(c.text)
- calls += 1
- failed += bool(res.is_error)
- flag = " ERROR" if res.is_error else ""
- print(f"=== {name} {json.dumps(args, ensure_ascii=False)} {dt:.2f}s{flag}\n" + "\n".join(out), flush=True)
- print(f"--- {calls} calls, {failed} failed, {time.time() - t0:.1f}s in all", flush=True)
- return 1 if failed else 0
+ r = Runner(session, shots)
+ try:
+ d = await r.look()
+ except Exception as e: # noqa: BLE001 - whatever went wrong, there is no device to test
+ print(f"--- no device to test: {e}", flush=True)
+ return 1
+ print(f"### {d.line()}", flush=True)
+ if not steps and not (d.w and d.h):
+ print("--- the screen's size is unknown (is the daemon ready? `iphone-control status`)", flush=True)
+ return 1
+ for i in range(a.repeat):
+ if a.repeat > 1:
+ print(f"### run {i + 1} of {a.repeat}", flush=True)
+ r.records = []
+ if steps:
+ for name, args, *expect in steps:
+ if name == "sleep":
+ await asyncio.sleep(float(args))
+ else:
+ await r.step(name, args, **(expect[0] if expect else {}))
+ else:
+ await default_steps(r, d)
+ runs.append(r.records)
+ now = await r.look(with_apps=False)
+ if now.udid != d.udid:
+ r.failed += 1
+ print(f"FAILED: the device changed during the run: it was {d.udid}, now {now.udid or 'none'}", flush=True)
+ if a.json:
+ with open(a.json, "w", encoding="utf-8") as f:
+ json.dump({"device": d.line(), "command": shlex.join(cmd), "runs": runs}, f, ensure_ascii=False, indent=1)
+ print(f"--- {r.calls} calls, {r.failed} failed, {time.time() - t0:.1f}s in all", flush=True)
+ return 1 if r.failed else 0
if __name__ == "__main__":
diff --git a/tests/device/scenarios.py b/tests/device/scenarios.py
new file mode 100644
index 0000000..8e2eaff
--- /dev/null
+++ b/tests/device/scenarios.py
@@ -0,0 +1,401 @@
+"""Real-device scenarios for the tools themselves: the device cases of docs/dev/regression-cases.md that can be
+repeated by a script, each check a PASS / FAIL line (tasks.py does the same for AI tasks).
+
+ pip install -r tests/device/requirements.txt
+ python tests/device/scenarios.py # every scenario except `lock` and `url`
+ python tests/device/scenarios.py typing batch # only these
+ python tests/device/scenarios.py --lock lock # locks the phone and lets it unlock itself: read below first
+ python tests/device/scenarios.py --url url # opens https://example.com in Safari (leaves a tab there)
+ python tests/device/scenarios.py --lock --url # everything
+
+Scenarios (the numbers are regression cases):
+
+ tools the tools run.py's default steps don't use: tap by coordinates, terminate, list apps and devices,
+ selecting the device already selected, an enlarged region (#16), then=screenshot
+ typing typing with no keyboard up is refused and types nothing (#32); the same text typed twice into
+ Spotlight counts as typed the second time too (#143)
+ fresh a tap right after a cold start isn't swallowed (#13); then=elements shows the page after the tap,
+ not the one before (#125)
+ batch iphone_batch runs its steps in order and answers for each; a tap that found nothing stops it and
+ the rest is not done
+ menu a long press on a home-screen icon takes about as long as it was asked to (#34); Home closes the menu
+ and an app started right afterwards stays in front (#130)
+ url a link opened right after its app was terminated opens (#131); text on the web page can be waited for (#133)
+ lock the lock button locks within seconds, again and again (#59, #102, #105); the next action unlocks first
+ and says so (#144); a tap right after unlocking isn't swallowed (#127)
+
+`lock` types the saved passcode into the phone. If the passcode saved for this device is not this device's
+(`iphone-control devices` says whether one is saved; `iphone-control passcode set` saves it), the phone counts a
+wrong attempt and automatic unlocking is switched off. Make sure of it, then pass --lock.
+
+Everything else is harmless by design: Home, Clock, Spotlight, screenshots. Nothing is sent, bought, deleted or
+changed. Environment: MCP_CMD, MCP_URL, SHOTS_DIR as for run.py. Exit code 1 if any check failed. Paste the output
+into the pull request (CONTRIBUTING.md, "Required tests").
+"""
+
+import argparse
+import asyncio
+import base64
+import json
+import os
+import shlex
+import sys
+import time
+import traceback
+
+from mcp.client.stdio import StdioServerParameters
+
+import device as dev
+from run import Runner, connect
+
+results: list[bool] = []
+MISSING = "不存在的按钮xyz"
+AUTO_UNLOCK = dev.T("操作时会自动解锁", "actions unlock automatically")
+PINNED = dev.T("(选定)", "(selected)")
+
+
+def short(text: str, n: int = 170) -> str:
+ one = " ".join(text.split())
+ return one if len(one) <= n else one[: n - 1] + "…"
+
+
+def check(case: str, what: str, ok: bool, got: str = "") -> bool:
+ # "the phone can't be controlled right now" answers every call with an error: never what a check wanted,
+ # also not one that expects a refusal
+ ok = bool(ok) and not says(got, dev.UNAVAILABLE)
+ results.append(bool(ok))
+ print(f"{'PASS' if ok else 'FAIL'} [{case}] {what}" + (f" ← {short(got)}" if got else ""), flush=True)
+ return bool(ok)
+
+
+def says(text: str, want) -> bool:
+ return any(w in text for w in ([want] if isinstance(want, str) else want))
+
+
+class Phone:
+ """The MCP session, with answers as (is_error, text, seconds, picture sizes)"""
+
+ def __init__(self, session, d: dev.Device):
+ self.s = session
+ self.d = d
+
+ async def call(self, name: str, args: dict | None = None, timeout: float = 90):
+ t = time.time()
+ res = await asyncio.wait_for(self.s.call_tool(name, args or {}), timeout)
+ dt = time.time() - t
+ text = "\n".join(c.text for c in res.content if c.type == "text")
+ sizes = [dev.jpeg_size(base64.b64decode(c.data)) for c in res.content if c.type == "image"]
+ return bool(res.is_error), text, dt, sizes
+
+ async def ok(self, case: str, name: str, args: dict | None = None) -> str:
+ """A step the scenario only needs to have worked (getting somewhere); a failure is a failed check"""
+ err, text, dt, _ = await self.call(name, args)
+ if err:
+ check(case, f"{name} {json.dumps(args or {}, ensure_ascii=False)} works", False, text)
+ elif took := dev.unlock_seconds(text):
+ # worth knowing when reading the times and whatever fails next
+ print(f"NOTE [{case}] {name} unlocked the phone first ({took:.1f}s of {dt:.1f}s)", flush=True)
+ return text
+
+ async def home(self, case: str):
+ await self.ok(case, "iphone_press_button", {"button": "home"})
+
+ async def front(self) -> str:
+ return (await self.call("iphone_status"))[1]
+
+ async def clock_tabs(self, case: str) -> list[dev.Element]:
+ """Clock's tab bar, as it is now (Clock in front)"""
+ _, text, _, _ = await self.call("iphone_list_elements")
+ tabs = dev.tabs(text)
+ if not tabs:
+ front = next((ln for ln in (await self.front()).splitlines() if dev.SPRINGBOARD in ln or "com." in ln), "")
+ check(case, "Clock shows its tab bar", False, f"[{front}] {text}")
+ return tabs
+
+ async def spotlight(self, case: str):
+ d = self.d
+ await self.home(case)
+ cx = round(d.w / 2)
+ await self.ok(case, "iphone_swipe", {"from_x": cx, "from_y": round(d.h * 0.43), "to_x": cx, "to_y": round(d.h * 0.75)})
+
+
+def selected(text: str, label: str) -> bool:
+ return f'Button "{label}" value="1"' in text
+
+
+# ---------------------------------------------------------------- scenarios
+
+
+async def tools(p: Phone):
+ c, d = "tools", p.d
+ await p.home(c)
+ await p.ok(c, "iphone_launch_app", {"app": dev.CLOCK})
+ tabs = await p.clock_tabs(c)
+ if tabs:
+ other = next(t for t in tabs if t.value != "1")
+ err, text, dt, _ = await p.call("iphone_tap", {"x": other.x, "y": other.y, "then": "elements", "then_filter": "Button"})
+ check(c, f"iphone_tap at a tab's coordinates selects that tab ({dt:.2f}s)", not err and selected(text, other.label), text)
+ was = next(t for t in tabs if t.value == "1")
+ err, text, dt, sizes = await p.call("iphone_tap", {"x": was.x, "y": was.y, "then": "screenshot"})
+ check(c, f"then=screenshot returns the screen's picture ({dt:.2f}s)", not err and sizes[:1] == [(round(d.w), round(d.h))], f"{sizes} {text}")
+ # 区域输出保留原始像素,只有长边不足下限才额外放大;iPad 的 2 倍原图无需再次放大。
+ # 检查是否确实大于点数尺寸且保持长宽比,而不是要求所有设备都超过 2 倍。
+ rw, rh = round(d.w / 3), 40
+ err, text, dt, sizes = await p.call("iphone_screenshot", {"x": 7, "y": 55, "width": rw, "height": rh})
+ got = sizes[0] if sizes else None
+ check(c, f"a region of {rw}x{rh} comes back enlarged and in shape ({dt:.2f}s)",
+ not err and dev.enlarged_region(got, rw, rh), f"{got} {text}")
+ err, text, _, _ = await p.call("iphone_screenshot", {"x": 10, "y": 10})
+ check(c, "a region without width and height is refused", err, text)
+ err, text, dt, _ = await p.call("iphone_terminate_app", {"app": dev.CLOCK})
+ front = await p.front()
+ check(c, f"iphone_terminate_app ends Clock: the home screen is in front ({dt:.2f}s)", not err and dev.CLOCK in text and dev.SPRINGBOARD in front, f"{text} / {front}")
+ err, text, dt, _ = await p.call("iphone_list_apps", {"include_system": True})
+ check(c, f"iphone_list_apps with system apps lists Settings and Clock ({dt:.2f}s)", not err and dev.SETTINGS in text and dev.CLOCK in text, text)
+ err, text, _, _ = await p.call("iphone_list_apps")
+ check(c, "without them it doesn't list Settings", not err and dev.SETTINGS not in text, text)
+ err, text, _, _ = await p.call("iphone_launch_app", {"app": "没有这个App-xyz"})
+ check(c, "launching an app that doesn't exist is refused", err, text)
+ err, text, _, _ = await p.call("iphone_list_devices")
+ check(c, "iphone_list_devices names the device being controlled", not err and d.udid in text, text)
+ if says(await p.front(), PINNED) or text.count("iOS") == 1:
+ # the device already selected (or the only one): nothing changes hands
+ err, text, dt, _ = await p.call("iphone_select_device", {"device": d.udid})
+ now = dev.controlled((await p.call("iphone_list_devices"))[1])
+ check(c, f"selecting the device already controlled keeps it ({dt:.2f}s)", not err and now[2] == d.udid, text)
+ else:
+ print(f"SKIP [{c}] iphone_select_device: several devices and none selected (selecting would pin one)", flush=True)
+ err, text, _, _ = await p.call("iphone_select_device", {"device": "没有这台设备-xyz"})
+ check(c, "selecting a device that isn't there is refused", err, text)
+
+
+async def typing(p: Phone):
+ c, d = "typing", p.d
+ await p.home(c)
+ err, text, dt, _ = await p.call("iphone_type_text", {"text": "x"})
+ check(c, f"#32 typing on the home screen (no keyboard) is refused ({dt:.2f}s)", err and says(text, dev.NO_KEYBOARD), text)
+ word = d.name(dev.CLOCK)
+ for nth in ("first", "second"):
+ await p.spotlight(c)
+ err, text, dt, _ = await p.call("iphone_type_text", {"text": word})
+ why = "" if nth == "first" else " (#143: Spotlight still holds it, selected)"
+ check(c, f"typing {word!r} into Spotlight the {nth} time counts as typed{why} ({dt:.2f}s)", not err, text)
+ err, text, dt, _ = await p.call("iphone_wait_for", {"text": word, "timeout": 5})
+ check(c, f"…and it is on screen ({dt:.2f}s)", not err and says(text, dev.APPEARED), text)
+ err, text, dt, _ = await p.call("iphone_wait_for", {"text": MISSING, "timeout": 2})
+ check(c, f"waiting for text that never comes gives up after its timeout ({dt:.2f}s)", 1.5 < dt < 6 and not says(text, dev.APPEARED), text)
+ await p.home(c)
+
+
+async def fresh(p: Phone):
+ c = "fresh"
+ await p.home(c)
+ await p.ok(c, "iphone_launch_app", {"app": dev.CLOCK})
+ tabs = await p.clock_tabs(c)
+ if not tabs:
+ return
+ for n in range(3):
+ await p.ok(c, "iphone_terminate_app", {"app": dev.CLOCK})
+ await p.ok(c, "iphone_launch_app", {"app": dev.CLOCK})
+ err, before, _, _ = await p.call("iphone_list_elements")
+ # 冷启动后各系统恢复的标签不同,每次从实际页面选一个尚未选中的标签,不能靠固定轮换。
+ current = dev.tabs(before)
+ if not check(c, "冷启动后读到时钟标签栏", not err and bool(current), before):
+ return
+ target = next(t for t in reversed(current) if t.value != "1")
+ err, text, dt, _ = await p.call("iphone_tap_element", {"text": target.label, "then": "elements"})
+ after = text.split("---")[-1]
+ check(c, f"#13 a tap right after a cold start takes effect, {n + 1} of 3 ({dt:.2f}s)",
+ not err and selected(after, target.label) and not says(text, dev.UNCHANGED), text)
+ old = {e.label for e in dev.elements(before)} - {t.label for t in current}
+ new = {e.label for e in dev.elements(after)} - {t.label for t in current}
+ check(c, "#125 then=elements shows the new page, not the one before the tap", bool(new) and new != old and not says(text, dev.UNCHANGED),
+ f"before {sorted(old)[:4]}, after {sorted(new)[:4]}")
+ await p.home(c)
+
+
+async def batch(p: Phone):
+ c = "batch"
+ await p.home(c)
+ steps = [
+ {"tool": "iphone_launch_app", "app": dev.CLOCK},
+ {"tool": "wait", "seconds": 0.5},
+ {"tool": "iphone_wait_for", "text": "", "timeout": 3},
+ {"tool": "iphone_press_button", "button": "home"},
+ ]
+ await p.ok(c, "iphone_launch_app", {"app": dev.CLOCK})
+ tabs = await p.clock_tabs(c)
+ await p.home(c)
+ if not tabs:
+ return
+ steps[2]["text"] = tabs[0].label
+ err, text, dt, _ = await p.call("iphone_batch", {"steps": steps, "then": "elements"})
+ lines = [ln for ln in text.splitlines() if ln[:2] in ("1.", "2.", "3.", "4.")]
+ check(c, f"a batch of 4 steps answers for each of them, in order ({dt:.2f}s)", not err and len(lines) == 4 and dev.CLOCK in lines[0], text)
+ check(c, "its then=elements shows the screen after the last step (the home screen)", "Icon " in text.split("---")[-1], text.split("---")[-1])
+ check(c, "the home screen is in front", dev.SPRINGBOARD in await p.front())
+ # a tap that found nothing stops the batch: Clock is started, but Home (the step after) is not pressed
+ steps = [
+ {"tool": "iphone_launch_app", "app": dev.CLOCK},
+ {"tool": "iphone_tap_element", "text": MISSING},
+ {"tool": "iphone_press_button", "button": "home"},
+ ]
+ err, text, dt, _ = await p.call("iphone_batch", {"steps": steps})
+ front = await p.front()
+ check(c, f"a tap that found nothing stops the batch with an error ({dt:.2f}s)", err and says(text, dev.NOT_FOUND) and "3." not in text, text)
+ check(c, "…and the step after it was not done (Clock is still in front)", dev.CLOCK in front, front)
+ for bad, why in (([{"tool": "iphone_screenshot"}], "a tool that isn't an action"), ([{"tool": "iphone_tap", "x": 1}], "a step missing an argument")):
+ err, text, _, _ = await p.call("iphone_batch", {"steps": [{"tool": "iphone_press_button", "button": "home"}, *bad]})
+ front = await p.front()
+ check(c, f"a batch with {why} is refused before anything runs (Clock still in front)", err and dev.CLOCK in front, text)
+ await p.home(c)
+
+
+async def menu(p: Phone):
+ c = "menu"
+ await p.home(c)
+ _, text, _, _ = await p.call("iphone_list_elements")
+ icons = [e for e in dev.elements(text) if e.kind == "Icon" and e.h < 130 and e.w < 130]
+ if not check(c, "the home screen lists app icons", bool(icons), text):
+ return
+ icon = icons[0]
+ for n in range(3):
+ err, text, dt, _ = await p.call("iphone_long_press", {"x": icon.x, "y": icon.y, "seconds": 1.2, "then": "elements"})
+ check(c, f"#34 a 1.2 s long press on an icon takes seconds, not ten ({dt:.2f}s incl. settling)", not err and dt < 6, text.splitlines()[0])
+ if n == 0:
+ check(c, "…and its menu is up (the screen changed)", not says(text, dev.UNCHANGED), short(text, 300))
+ await p.home(c)
+ err, text, dt, _ = await p.call("iphone_launch_app", {"app": dev.CLOCK})
+ await asyncio.sleep(1.5) # the menu's closing animation used to send the app back about now
+ front = await p.front()
+ check(c, f"#130 Clock started right after Home closed the menu stays in front, {n + 1} of 3", not err and dev.CLOCK in front, f"{text} / {front}")
+ await p.home(c)
+
+
+async def url(p: Phone):
+ c = "url"
+ await p.home(c)
+ await p.ok(c, "iphone_launch_app", {"app": dev.SAFARI})
+ await p.ok(c, "iphone_terminate_app", {"app": dev.SAFARI})
+ err, text, dt, _ = await p.call("iphone_open_url", {"url": "https://example.com"})
+ # iPad 的过渡动画中回答可能暂时写 DockFolderViewService;用实际前台状态核对启动结果。
+ front = await p.front()
+ check(c, f"#131 a link opened right after Safari was terminated opens in Safari ({dt:.2f}s)",
+ not err and "https://example.com" in text and dev.SAFARI in front, f"{text} / {front}")
+ if not err and dev.SAFARI in front and dev.SAFARI not in text:
+ print(f"NOTE [{c}] 打开链接的回答和随后查询的前台 App 不一致:{short(text)}", flush=True)
+ # a word of the page's English paragraph (the page has no heading in the tree, and its first paragraph follows
+ # the phone's language)
+ err, text, dt, _ = await p.call("iphone_wait_for", {"text": "documentation", "timeout": 15})
+ check(c, f"#133 text on the web page can be waited for ({dt:.2f}s)", not err and says(text, dev.APPEARED), text)
+ names = {t.name for t in (await p.s.list_tools()).tools}
+ if "iphone_web_targets" in names:
+ times = []
+ for _ in range(4):
+ err, text, dt, _ = await p.call("iphone_web_targets")
+ times.append(dt)
+ check(c, f"#51 iphone_web_targets finds the page, and fast after the first time ({', '.join(f'{t:.2f}' for t in times)} s)",
+ not err and "example" in text.lower() and max(times[1:]) < 3, text)
+ else:
+ print(f"SKIP [{c}] #51 iphone_web_targets: the developer tools are off (IPHONE_CONTROL_DEV_TOOLS=1)", flush=True)
+ err, text, _, _ = await p.call("iphone_open_url", {"url": "not a url"})
+ check(c, "something that isn't a link is refused", err, text)
+ await p.home(c)
+
+
+async def lock(p: Phone):
+ c = "lock"
+ await p.home(c)
+ await p.ok(c, "iphone_launch_app", {"app": dev.CLOCK})
+ tabs = await p.clock_tabs(c)
+ if not tabs:
+ return
+ times = []
+ for n in range(3):
+ err, text, dt, _ = await p.call("iphone_press_button", {"button": "lock"})
+ # the status may still say unlocked for a moment after the button's answer (seen: about 0.3 s)
+ t0, locked, status = time.time(), False, ""
+ while not locked and time.time() - t0 < 3:
+ status = await p.front()
+ locked = dev.is_locked(status)
+ if not locked:
+ await asyncio.sleep(0.2)
+ seen = time.time() - t0
+ times.append(dt + seen)
+ if not check(c, f"the lock button locks the phone, {n + 1} of 3 ({dt:.2f}s, the status says so {seen:.2f}s later)",
+ not err and locked, f"{text} / {status}"):
+ return
+ if not check(c, "the status says the next action unlocks it", says(status, AUTO_UNLOCK), status):
+ print(f"STOP [{c}] automatic unlocking is not available: unlock the phone by hand", flush=True)
+ return
+ # right after it locked, the daemon doesn't unlock (3 s): not what is measured here
+ await asyncio.sleep(4)
+ target = next(t for t in tabs if t.value != "1") if n % 2 == 0 else next(t for t in tabs if t.value == "1")
+ err, text, dt, _ = await p.call("iphone_tap_element", {"text": target.label, "then": "elements", "then_filter": "Button"}, timeout=120)
+ took = dev.unlock_seconds(text)
+ check(c, f"#144 the next action unlocks first and says how long it took ({took:.1f}s of {dt:.1f}s)", not err and 0 < took < 30, text.splitlines()[0])
+ check(c, "#127 the tap right after unlocking takes effect", selected(text, target.label), text)
+ if err or not took:
+ print(f"STOP [{c}] it did not unlock: not locking again", flush=True)
+ return
+ check(c, f"#102 #105 locking takes seconds each time ({', '.join(f'{t:.1f}' for t in times)} s)", max(times[1:]) < 5, "")
+ await p.home(c)
+
+
+SCENARIOS = {"tools": tools, "typing": typing, "fresh": fresh, "batch": batch, "menu": menu, "url": url, "lock": lock}
+OPT_IN = {"lock": "--lock", "url": "--url"}
+
+
+async def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ ap.add_argument("only", nargs="*", help=f"scenarios ({', '.join(SCENARIOS)}); all but lock and url if none")
+ ap.add_argument("--lock", action="store_true", help="allow `lock`: the saved passcode is this device's")
+ ap.add_argument("--url", action="store_true", help="allow `url`: opens https://example.com in Safari")
+ a = ap.parse_args()
+ names = a.only or [n for n in SCENARIOS if n not in OPT_IN or getattr(a, OPT_IN[n][2:])]
+ if unknown := [n for n in names if n not in SCENARIOS]:
+ ap.error(f"unknown {unknown}")
+ for n, flag in OPT_IN.items():
+ if n in names and not getattr(a, flag[2:]):
+ ap.error(f"`{n}` needs {flag}: see --help")
+ cmd = shlex.split(os.environ.get("MCP_CMD", "iphone-control mcp"))
+ params = StdioServerParameters(command=cmd[0], args=cmd[1:], env=dict(os.environ))
+ t0 = time.time()
+ async with connect(params) as session:
+ await session.initialize()
+ d = await Runner(session, os.environ.get("SHOTS_DIR", "shots")).look()
+ print(f"### {d.line()}", flush=True)
+ if not (d.udid and d.w and d.h):
+ print("--- no device ready to test (`iphone-control status`)", flush=True)
+ return 1
+ p = Phone(session, d)
+ for name in names:
+ print(f"--- {name}", flush=True)
+ # WDA restarting (below iOS 27 there is nothing else to fall back on) fails every call for a minute
+ # or two: wait for it instead of failing a whole scenario over it
+ t = time.time()
+ while not dev.ready(await p.front()) and time.time() - t < 180:
+ await asyncio.sleep(3)
+ if time.time() - t > 3:
+ print(f"NOTE [{name}] waited {time.time() - t:.0f}s for the phone to be ready", flush=True)
+ if not dev.ready(await p.front()):
+ check(name, "the phone is ready", False, await p.front())
+ break
+ t = time.time()
+ try:
+ await SCENARIOS[name](p)
+ except Exception as e: # noqa: BLE001 - a scenario that blew up is a failure, the next one still runs
+ traceback.print_exc()
+ check(name, f"scenario raised {type(e).__name__}", False, str(e))
+ now = dev.controlled((await p.call("iphone_list_devices"))[1])[2]
+ if now != d.udid:
+ check(name, "the same device is still controlled", False, f"it was {d.udid}, now {now or 'none'}")
+ break
+ print(f" ({time.time() - t:.1f}s)", flush=True)
+ failed = results.count(False)
+ print(f"--- {len(results)} checks, {failed} failed, {time.time() - t0:.1f}s in all", flush=True)
+ return 1 if failed else 0
+
+
+if __name__ == "__main__":
+ sys.exit(asyncio.run(main()))
diff --git a/tests/device/test_device.py b/tests/device/test_device.py
new file mode 100644
index 0000000..c0b506a
--- /dev/null
+++ b/tests/device/test_device.py
@@ -0,0 +1,91 @@
+"""真机测试辅助逻辑的离线单测,无需 MCP 包或手机。
+
+ python3 -m unittest discover -s tests/device -p 'test_*.py'
+"""
+
+import struct
+import unittest
+
+import device as dev
+
+
+class DeviceTests(unittest.TestCase):
+ def test_selected_device_is_found_in_both_languages(self):
+ udid = "00008020-1111111111111111"
+ for separator in (",", ", "):
+ text = (
+ " Phone (iPhone16,2 iOS 27.2.1, 00008130-2222222222222222)\n"
+ f"→ iPad (iPad11,1 iOS 26.7.3{separator}{udid})"
+ )
+ with self.subTest(separator=separator):
+ self.assertEqual(dev.controlled(text), ("iPad11,1", "26.7.3", udid))
+
+ def test_locked_does_not_match_unlocked(self):
+ for text in ("锁屏: 已锁屏(操作时会自动解锁)", "Locked: locked (actions unlock automatically)"):
+ self.assertTrue(dev.is_locked(text), text)
+ for text in ("锁屏: 未锁屏", "Locked: unlocked", "Locked: unknown", ""):
+ self.assertFalse(dev.is_locked(text), text)
+
+ def test_tab_bar_can_be_at_top_or_bottom(self):
+ for y, off in ((54, ""), (880, ' value="0"')):
+ text = (
+ f'Button "世界时钟"{off} @(404,{y}) 101x36\n'
+ f'Button "闹钟"{off} @(488,{y}) 67x36\n'
+ f'Button "秒表" value="1" @(554,{y}) 67x36\n'
+ f'Button "计时器"{off} @(628,{y}) 84x36'
+ )
+ with self.subTest(y=y):
+ self.assertEqual([e.label for e in dev.tabs(text)], ["世界时钟", "闹钟", "秒表", "计时器"])
+
+ def test_tab_bar_requires_one_selected_button(self):
+ text = 'Button "甲" value="1" @(10,54) 20x36\nButton "乙" value="1" @(40,54) 20x36\nButton "丙" @(70,54) 20x36'
+ self.assertEqual(dev.tabs(text), [])
+
+ def test_ipad_twofold_region_is_valid(self):
+ self.assertTrue(dev.enlarged_region((682, 80), 341, 40))
+ self.assertTrue(dev.enlarged_region((600, 168), 143, 40))
+
+ def test_region_requires_enlargement_and_correct_shape(self):
+ for size in (None, (341, 40), (682, 40), (682, 0)):
+ with self.subTest(size=size):
+ self.assertFalse(dev.enlarged_region(size, 341, 40))
+ self.assertFalse(dev.enlarged_region((682, 80), 0, 40))
+
+ def test_jpeg_and_png_picture_sizes(self):
+ # 只需格式头,辅助函数不应解码整张图片。
+ png = b"\x89PNG\r\n\x1a\n" + b"\x00\x00\x00\x0dIHDR" + struct.pack(">II", 1024, 768)
+ jpeg = b"\xff\xd8\xff\xc0\x00\x11\x08" + struct.pack(">HH", 80, 682) + b"\x03\x00"
+ self.assertEqual(dev.jpeg_size(png), (1024, 768))
+ self.assertEqual(dev.jpeg_size(jpeg), (682, 80))
+ self.assertIsNone(dev.jpeg_size(b"not an image"))
+
+ def test_expected_error_and_bilingual_text_are_checked(self):
+ expect = {"error": True, "has": [dev.NO_KEYBOARD]}
+ for text in dev.NO_KEYBOARD:
+ self.assertEqual(dev.judge(expect, text, True, 0.2, []), [])
+ self.assertTrue(dev.judge(expect, "WDA unavailable", True, 0.2, []))
+ self.assertTrue(dev.judge(expect, dev.NO_KEYBOARD[0], False, 0.2, []))
+
+ def test_screenshot_expectation_rejects_missing_or_wrong_picture(self):
+ expect = {"image": [1024, 768]}
+ self.assertEqual(dev.judge(expect, "", False, 0.2, [(1024, 768)]), [])
+ self.assertTrue(dev.judge(expect, "", False, 0.2, []))
+ self.assertTrue(dev.judge(expect, "", False, 0.2, [(768, 1024)]))
+
+ def test_unlock_time_is_deducted_in_both_languages(self):
+ for text in (
+ "已按 home(手机锁着,先自动解锁了,用时 8.5 秒)",
+ "Pressed home (the phone was locked and was unlocked first, which took 8.5 s)",
+ ):
+ self.assertEqual(dev.unlock_seconds(text), 8.5)
+ self.assertEqual(dev.judge({"max_s": 1}, text, False, 9.2, []), [])
+ self.assertTrue(dev.judge({"max_s": 1}, text, False, 10, []))
+
+ def test_unavailable_status_is_not_ready_even_with_screen_size(self):
+ self.assertTrue(dev.ready("Screen: 1024x768 points"))
+ self.assertFalse(dev.ready("WDA unavailable\nScreen: 1024x768 points"))
+ self.assertFalse(dev.ready("WDA 不可用\n屏幕: 1024x768 点"))
+
+
+if __name__ == "__main__":
+ unittest.main()