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

fix(daemon): a gesture doesn't wait for the screen size to be measured again (#110)

Qinghe Li1ae4e820948c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 934ded8..dd9447f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ All notable changes to this project are documented here. The format is based on
### Fixed
+- A tap or swipe a minute or more after the last one no longer waits for the screen size to be measured again first: that takes WDA 0.95 s on an iPad mini 5 (iPadOS 26.7.3), where the first tap after a pause took 1.7 s instead of 0.9. The size is now measured again in the background while nobody acts (only Display Zoom changes it), and on rotation as before.
- A control page whose H.264 or the phone's own video didn't show a first frame within 9 s (the viewer or daemon restarting, the encoder starting up) used MJPEG until it was reloaded; it now tries again after 30 s, 1 min and 2 min. A picture the viewer said isn't available still isn't tried again.
- A swipe on the control page through WDA no longer waits for the list to stop before answering (reading the element tree again and again, up to 2.5 s): the person at the page sees it. On an iPad mini 5 a swipe took 3.1 s, now 1.6–2.3 s. Agents (MCP, CLI) still wait, so their next tap doesn't land on a moving list.
- The way Home and locking work on each device is kept in `state.json` instead of only in memory. After the daemon restarted, or another device was controlled meanwhile, the first Home on a device where IOHID's Home doesn't work tried it, waited 2 s for the home screen and pressed again: 4.4 s instead of 0.8 on an iPad mini 5.
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 230ef3f..a55f395 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -8,6 +8,7 @@
### 修复
+- 隔了一分钟以上的点按、滑动不再先等重新读屏幕尺寸:iPad mini 5(iPadOS 26.7.3)上 WDA 读一次要 0.95 秒,停一会儿后的第一次点按要 1.7 秒,平时 0.9 秒。尺寸现在在没人操作时于后台重读(只有「显示缩放」会改变它),转屏时照旧马上重读。
- 控制台页面的 H.264 或手机自己的视频 9 秒内没出第一帧时(控制台服务或守护进程正在重启、编码器正在启动),原来一直用 MJPEG 直到刷新页面;现在 30 秒、1 分钟、2 分钟后各再试一次。控制台服务明确说不可用的画面仍然不再试。
- 控制台上经 WDA 的滑动不再等列表停下才返回(原来要反复读元素树,最多 2.5 秒):页面前的人看得见。iPad mini 5 上一次滑动从 3.1 秒降到 1.6–2.3 秒。Agent(MCP、命令行)仍然等,免得下一次点击落在还在滚的列表上。
- 每台设备按 Home 和锁屏该用哪种方式,现在记在 `state.json` 里,不再只放在内存。原来守护进程重启或中途控制过别的设备后,在 IOHID 的 Home 不起作用的设备上,第一次按 Home 会先用 IOHID 按,等 2 秒没回到主屏幕再补按一次:iPad mini 5 上要 4.4 秒,平时 0.8 秒。
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index 46d6e43..8af3e21 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -435,6 +435,15 @@ pub struct Daemon {
last_action: std::sync::Mutex<Option<Instant>>,
}
+impl Daemon {
+ /// Whether an action was done in the last `within`, or one waits for the device lock: slow background requests
+ /// to WDA wait for a quiet moment ([`ictl_protocol::BACKGROUND`], the screen size in `sample_display`)
+ pub(crate) fn acting_now(&self, within: Duration) -> bool {
+ self.waiting.load(std::sync::atomic::Ordering::SeqCst) > 0
+ || self.last_action.lock().unwrap_or_else(|p| p.into_inner()).is_some_and(|t| t.elapsed() < within)
+ }
+}
+
/// 停掉 HID 会话(屏幕媒体流),隧道保留。媒体流不停的话手机一直以为「配对的电脑」在看屏幕:
/// 灵动岛常驻图标、不会自动锁屏,本进程退出、拔插数据线都清不掉(iOS 27 真机)
pub(crate) async fn close_hid(g: &mut Inner) {
@@ -1422,6 +1431,10 @@ pub(crate) mod tests {
assert!(matches!(r, Response::Text { data: Some(crate::protocol::Data::Status(_)), .. }), "{r:?}");
// right after an action: not yet (the alert check waits longer than the status check)
*d.last_action.lock().unwrap() = Some(Instant::now() - Duration::from_secs(2));
+ assert!(
+ d.acting_now(Duration::from_secs(3)) && !d.acting_now(Duration::from_secs(1)),
+ "slow requests wait too"
+ );
assert!(!busy(&d.handle(Request::Status, Instant::now(), bg()).await), "status: 1 s after");
assert!(busy(&d.handle(Request::AlertCheck, Instant::now(), bg()).await), "the alert check: 4 s after");
assert!(
diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rs
index 1907e04..41665a4 100644
--- a/crates/ictl-daemon/src/supervise.rs
+++ b/crates/ictl-daemon/src/supervise.rs
@@ -13,6 +13,9 @@ use crate::notify::Event;
/// Three 10-second supervisor intervals. A missing background sample within this
/// window can leave a verified gesture running, but can never authorize a new one.
const DISPLAY_SAMPLE_GRACE: Duration = Duration::from_secs(30);
+/// How long after an action an old screen size isn't measured again ([`Daemon::sample_display`]): someone tapping
+/// or swiping may well go on, and the measurement would sit in WDA's queue before their next gesture
+const ACTION_QUIET: Duration = Duration::from_secs(3);
/// 正常 2~10 秒就绪。手机重启后未授权 automation 时,testmanagerd 握手每次卡 30 秒、要重试一两次,
/// 60 秒常常等不到 runner 启动,也就认不出「需要输入密码」
const WDA_START_TIMEOUT: Duration = Duration::from_secs(120);
@@ -177,10 +180,11 @@ impl Daemon {
pub(crate) async fn sample_display(&self, g: &mut Inner, gesture_start: bool) -> (Option<Rotation>, bool) {
let previous = g.dev.display.as_ref().map(|v| v.rotation);
let device = g.device.clone();
+ // an old size is measured again only while nobody acts: on an iPad mini 5 that takes WDA 0.95 s
+ let refresh = !gesture_start && !self.acting_now(ACTION_QUIET);
let Some(wda) = self.wda(g) else { return (None, self.update_display(g, None).await) };
- let (size, rotation) = wda
- .display_sample(previous, gesture_start, async { device?.interface_rotation().await.ok().flatten() })
- .await;
+ let (size, rotation) =
+ wda.display_sample(previous, refresh, async { device?.interface_rotation().await.ok().flatten() }).await;
let changed = self.record_display_sample(g, size, rotation, gesture_start).await;
(rotation, changed)
}
diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rs
index c2bb31d..ee07a11 100644
--- a/crates/ictl-wda/src/client.rs
+++ b/crates/ictl-wda/src/client.rs
@@ -15,8 +15,10 @@ 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;
-/// How long a measured screen size is trusted at the start of a gesture. `/wda/screen` takes about 100 ms (measured on
-/// iOS 27) and only Display Zoom changes the size, so a touch-down doesn't pay for it every time
+/// 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),
+/// which the first tap or swipe after a minute paid on top of its own 0.85 s
const SCREEN_RECHECK: Duration = Duration::from_secs(60);
/// 普通点击按下的时长(毫秒)。太短可能不被识别成点击;解锁按键另有自己的时长
const TAP_PRESS_MS: u64 = 50;
@@ -387,18 +389,18 @@ impl<T: Transport> WdaClient<T> {
}
/// Poll rotation to detect a changed view. The screen size (a slower request) is measured on acquisition and on
- /// rotation; a gesture start measures it again only once the last measurement is older than [`SCREEN_RECHECK`]
- /// (Display Zoom), so a touch-down usually costs only the rotation request.
+ /// rotation, and again once the last measurement is older than [`SCREEN_RECHECK`] (Display Zoom) when
+ /// `refresh_stale`: a poll while nobody acts, never a gesture's start, which costs only the rotation request.
pub async fn display_sample(
&mut self,
previous: Option<u16>,
- gesture_start: bool,
+ refresh_stale: bool,
fallback: impl Future<Output = Option<Rotation>>,
) -> (Option<ScreenSize>, Option<Rotation>) {
let rotation = self.interface_rotation(fallback).await;
let stale = self.screen_at.is_none_or(|t| t.elapsed() >= SCREEN_RECHECK);
let rotated = rotation.is_some_and(|r| Some(r.degrees()) != previous);
- let size = if rotated || (gesture_start && stale) {
+ let size = if rotated || (refresh_stale && stale) {
self.measure_screen().await
} else {
self.base_screen_size().await
@@ -868,22 +870,26 @@ mod tests {
let size = (200, r#"{"value":{"screenSize":{"width":393,"height":852}}}"#);
let portrait = (200, r#"{"value":{"z":0}}"#);
let landscape = (200, r#"{"value":{"z":90}}"#);
- let m = Mock::with(&[session, portrait, size, portrait, landscape, size, landscape, landscape, size]);
+ let m =
+ Mock::with(&[session, portrait, size, portrait, landscape, size, landscape, landscape, landscape, size]);
let mut w = WdaClient::new(&m);
- // (previous rotation, gesture start, size older than SCREEN_RECHECK, expected rotation)
- for (previous, start, stale, expected) in [
- (None, false, false, Rotation::Portrait),
- (Some(0), false, false, Rotation::Portrait),
+ // (previous rotation, a poll that may refresh the size, size older than SCREEN_RECHECK, expected rotation)
+ for (previous, refresh, stale, expected) in [
+ (None, true, false, Rotation::Portrait),
+ (Some(0), true, false, Rotation::Portrait),
+ // rotated: measured whatever the caller
(Some(0), false, false, Rotation::TopToRight),
// a touch-down with a recent size: rotation only
- (Some(90), true, false, Rotation::TopToRight),
- // a touch-down once the size is old: measured again (Display Zoom)
+ (Some(90), false, false, Rotation::TopToRight),
+ // a touch-down with an old size: still rotation only (0.95 s on an iPad mini 5)
+ (Some(90), false, true, Rotation::TopToRight),
+ // a quiet poll with an old size: measured again (Display Zoom)
(Some(90), true, true, Rotation::TopToRight),
] {
if stale {
w.screen_at = Some(Instant::now() - SCREEN_RECHECK);
}
- let (size, rotation) = w.display_sample(previous, start, async { panic!("unexpected fallback") }).await;
+ let (size, rotation) = w.display_sample(previous, refresh, async { panic!("unexpected fallback") }).await;
assert_eq!(rotation, Some(expected));
assert_eq!(size.unwrap().width, 393.);
}
@@ -899,6 +905,7 @@ mod tests {
"/wda/screen",
"/session/A/rotation",
"/session/A/rotation",
+ "/session/A/rotation",
"/wda/screen"
]
);