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

自动解锁:熄屏锁屏时不先查无障碍树;刚锁屏等 3 秒;唤醒失败重来一轮

Derrors53293369b6b7
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index 9f914dc..3fc0f43 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -26,6 +26,8 @@ pub const TICK: Duration = Duration::from_secs(10);
/// 正常 2~10 秒就绪。手机重启后未授权 automation 时,testmanagerd 握手每次卡 30 秒、要重试一两次,
/// 60 秒常常等不到 runner 启动,也就认不出「需要输入密码」
const WDA_START_TIMEOUT: Duration = Duration::from_secs(120);
+/// 锁屏后至少等这么久再自动解锁:锁屏过渡没走完就唤醒,WDA 第一下上滑卡约 16 秒后报 `point.x != INFINITY`
+const LOCK_SETTLE: Duration = Duration::from_secs(3);
const SYSFS_USB: &str = "/sys/bus/usb/devices";
/// 持久化到 `state.json` 的状态(不含秘密)
@@ -86,6 +88,8 @@ struct Inner {
mux: MuxWatch,
usbmuxd: Option<tokio::process::Child>,
offline_since: Option<Instant>,
+ /// 最近一次经本进程锁屏的时间(自动解锁要等锁屏过渡走完,见 [`LOCK_SETTLE`])
+ last_lock: Option<Instant>,
dedup: Dedup,
next_resign: Instant,
next_session_check: Instant,
@@ -121,6 +125,7 @@ impl Daemon {
mux: MuxWatch::default(),
usbmuxd: None,
offline_since: Some(now),
+ last_lock: None,
dedup: Dedup::default(),
// 启动一分钟后再做第一次重签检查和会话验证,先让设备就绪
next_resign: now + Duration::from_secs(60),
@@ -526,6 +531,10 @@ impl Daemon {
/// 配置了密码就在锁屏时自动解锁;没配置而手机锁着则报错(与 toolkit 一致)
async fn ensure_unlocked(&self, g: &mut Inner) -> Result<(), String> {
let cfg = self.unlock_cfg();
+ // 刚锁屏就唤醒,第一下上滑会卡十几秒后报错(真机实测;锁屏后等 3 秒再解锁一次就成)
+ if let Some(left) = g.last_lock.and_then(|t| LOCK_SETTLE.checked_sub(t.elapsed())) {
+ tokio::time::sleep(left).await;
+ }
let Some(wda) = self.wda(g) else { return Ok(()) };
match ictl_unlock::ensure_unlocked(wda, &cfg).await {
Ok(_) => Ok(()),
@@ -742,9 +751,11 @@ impl Daemon {
if let Some(w) = self.wda(g)
&& w.lock().await.is_ok()
{
+ g.last_lock = Some(Instant::now());
return Ok("已锁屏".into());
}
self.hid_do(g, |h| Box::pin(h.press(Button::Lock))).await?;
+ g.last_lock = Some(Instant::now());
return Ok("已锁屏".into());
}
let (wda_name, hid_button) = match button {
diff --git a/crates/ictl-unlock/src/fake.rs b/crates/ictl-unlock/src/fake.rs
index 550b24a..20754da 100644
--- a/crates/ictl-unlock/src/fake.rs
+++ b/crates/ictl-unlock/src/fake.rs
@@ -37,6 +37,7 @@ pub struct State {
pub failed_attempts: u32,
pub digits_typed: u32,
swipes_to_ignore: u32,
+ swipe_errors: u32,
press_count: u32,
drop_press: Option<u32>,
}
@@ -64,6 +65,11 @@ impl FakeLockScreen {
self.st.lock().unwrap().swipes_to_ignore = n;
}
+ /// 接下来 n 次上滑 WDA 报 500(真机:熄屏锁屏刚唤醒时 `point.x != INFINITY`)
+ pub fn swipe_errors(&self, n: u32) {
+ self.st.lock().unwrap().swipe_errors = n;
+ }
+
/// 第 n 次有效按键(从 1 数)被键盘吞掉
pub fn drop_press(&self, n: u32) {
self.st.lock().unwrap().drop_press = Some(n);
@@ -95,6 +101,11 @@ impl FakeLockScreen {
let downs = steps.iter().filter(|a| a["type"] == "pointerDown").count();
let is_swipe =
steps.iter().any(|a| a["type"] == "pointerMove" && a["duration"].as_u64().unwrap_or(0) > 0);
+ if is_swipe && s.swipe_errors > 0 {
+ s.swipe_errors -= 1;
+ let msg = "Invalid parameter not satisfying: point.x != INFINITY && point.y != INFINITY";
+ return (500, json!({"value": {"error": "unknown error", "message": msg}}));
+ }
if is_swipe {
if s.swipes_to_ignore > 0 {
s.swipes_to_ignore -= 1;
diff --git a/crates/ictl-unlock/src/lib.rs b/crates/ictl-unlock/src/lib.rs
index c93f7b6..a445221 100644
--- a/crates/ictl-unlock/src/lib.rs
+++ b/crates/ictl-unlock/src/lib.rs
@@ -94,11 +94,26 @@ impl UnlockConfig {
/// 未锁屏直接返回;否则按规则解锁
pub async fn ensure_unlocked<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig) -> Result<Outcome> {
- match wda.locked().await {
- Ok(false) | Err(WdaError::Unavailable(_)) => return Ok(Outcome::NotLocked),
- Ok(true) => {}
+ // 先只问 WDA:确定没锁就直接返回,日常操作不多发请求
+ let reported = match wda.wda_reports_locked().await {
+ Ok(v) => v,
+ Err(WdaError::Unavailable(_)) => return Ok(Outcome::NotLocked),
Err(e) => return Err(e.into()),
+ };
+ if !reported && wda.lock_state_trusted() {
+ return Ok(Outcome::NotLocked);
}
+ let saved = wda.idle_settings().await?;
+ wda.set_idle_settings(UNLOCK_IDLE).await?;
+ let r = check_and_unlock(wda, cfg, reported).await;
+ if let Err(e) = wda.set_idle_settings(saved).await {
+ tracing::warn!("恢复 WDA 等待设置失败:{e}");
+ }
+ r
+}
+
+/// 可用的密码;不能自动解锁时给出原因(停用、没配、不是纯数字)
+fn passcode(cfg: &UnlockConfig) -> Result<String> {
if cfg.disabled_by_failure() {
return Err(UnlockError::Disabled);
}
@@ -106,13 +121,22 @@ pub async fn ensure_unlocked<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockC
if code.is_empty() || !code.bytes().all(|b| b.is_ascii_digit()) {
return Err(UnlockError::NotDigits);
}
- let saved = wda.idle_settings().await?;
- wda.set_idle_settings(UNLOCK_IDLE).await?;
- let r = unlock(wda, cfg, code.as_bytes()).await;
- if let Err(e) = wda.set_idle_settings(saved).await {
- tracing::warn!("恢复 WDA 等待设置失败:{e}");
+ Ok(code)
+}
+
+/// `reported`:WDA 自己说锁了。熄屏锁屏时第一个无障碍查询(取元素树、前台 App)要等约 8 秒,
+/// 所以能自动解锁时不先核对,直接进解锁流程——第一步按 Home 唤醒屏幕;若其实是通知中心(WDA 误报),
+/// Home 会收起它,随后核对为未锁屏,一位都不输。不能自动解锁时才先核对,免得把通知中心报成「需要人工解锁」
+async fn check_and_unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, reported: bool) -> Result<Outcome> {
+ let code = passcode(cfg);
+ if !(reported && code.is_ok()) {
+ match wda.locked().await {
+ Ok(false) | Err(WdaError::Unavailable(_)) => return Ok(Outcome::NotLocked),
+ Ok(true) => {}
+ Err(e) => return Err(e.into()),
+ }
}
- r
+ unlock(wda, cfg, code?.as_bytes()).await
}
async fn press<T: Transport>(wda: &mut WdaClient<T>, at: (i64, i64), t: &Timing) -> Result<()> {
@@ -141,10 +165,23 @@ async fn unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, code:
let mut keys = None;
for _ in 0..FIRST_DIGIT_ROUNDS {
// Home 唤醒;键盘已打开时会收起并清空半截输入
- wda.press_button("home").await?;
- tokio::time::sleep(t.wake_settle).await;
- let (cx, h) = (screen.width / 2.0, screen.height);
- wda.actions(&swipe_steps((cx, h - 8.0), (cx, h * 0.45), 250)).await?;
+ // 熄屏锁屏刚唤醒时上滑偶尔卡十几秒后报 `point.x != INFINITY`(WDA 还拿不到界面尺寸):一位没输,算这轮落空重来
+ let woke = async {
+ wda.press_button("home").await?;
+ tokio::time::sleep(t.wake_settle).await;
+ let (cx, h) = (screen.width / 2.0, screen.height);
+ wda.actions(&swipe_steps((cx, h - 8.0), (cx, h * 0.45), 250)).await
+ }
+ .await;
+ if let Err(e) = woke {
+ match e {
+ WdaError::Remote { .. } => {
+ tracing::info!("唤醒/上滑失败,重来一轮:{e}");
+ continue;
+ }
+ other => return Err(other.into()),
+ }
+ }
tokio::time::sleep(t.swipe_settle).await;
if !wda.locked().await? {
return Ok(Outcome::Unlocked);
@@ -278,6 +315,16 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
+ #[tokio::test]
+ async fn swipe_error_right_after_wake_retries_round() {
+ let fake = FakeLockScreen::new("123456");
+ fake.swipe_errors(1);
+ let (cfg, dir) = cfg(Some("123456"));
+ assert_eq!(ensure_unlocked(&mut WdaClient::new(&fake), &cfg).await.unwrap(), Outcome::Unlocked);
+ assert_eq!(fake.state().failed_attempts, 0);
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
#[tokio::test]
async fn keypad_never_shows_is_no_keypad_not_wrong() {
let fake = FakeLockScreen::new("123456");
diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rs
index dc6baf7..1779c20 100644
--- a/crates/ictl-wda/src/client.rs
+++ b/crates/ictl-wda/src/client.rs
@@ -189,6 +189,16 @@ impl<T: Transport> WdaClient<T> {
}
}
+ /// WDA 自己报的锁屏状态,不核对。可能误报,见 [`Self::locked`];配合 [`Self::lock_state_trusted`] 做快速判断
+ pub async fn wda_reports_locked(&self) -> Result<bool> {
+ Ok(self.call("GET", "/wda/locked", None, Duration::from_secs(10)).await?["value"] == true)
+ }
+
+ /// 本次 WDA 启动后是否确认过一次没锁屏。确认过且 WDA 说没锁,就确定没锁
+ pub fn lock_state_trusted(&self) -> bool {
+ self.lock_state_trusted
+ }
+
/// 前台是 SpringBoard 时看元素树是锁屏、通知中心还是普通界面;前台是别的 App 就是普通界面
async fn cover_sheet(&self) -> Result<elements::CoverSheet> {
if self.active_app().await? != SPRINGBOARD {
diff --git a/crates/ictl-wda/src/http.rs b/crates/ictl-wda/src/http.rs
index 47baeba..ef7e30d 100644
--- a/crates/ictl-wda/src/http.rs
+++ b/crates/ictl-wda/src/http.rs
@@ -64,9 +64,17 @@ impl Transport for DeviceTransport {
}
parse_response(&buf)
};
- tokio::time::timeout(timeout, fut).await.map_err(|_| {
+ let t0 = std::time::Instant::now();
+ let r = tokio::time::timeout(timeout, fut).await.map_err(|_| {
std::io::Error::new(std::io::ErrorKind::TimedOut, format!("请求超时({} 秒)", timeout.as_secs()))
- })?
+ })?;
+ // 路径截掉查询串(/source 的排除属性很长)
+ let short = path.split('?').next().unwrap_or(path);
+ match &r {
+ Ok((status, _)) => tracing::debug!("wda {method} {short} → {status}({:.2}s)", t0.elapsed().as_secs_f64()),
+ Err(e) => tracing::debug!("wda {method} {short} 失败({:.2}s):{e}", t0.elapsed().as_secs_f64()),
+ }
+ r
}
}