Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools
Rust ai-agentautomationclaudeclaude-codedockeriosiphonelinuxmcpmcp-servermodel-context-protocolrustwebdriveragent
WDA 启动:手机重启后能识别「Enable UI Automation」密码框
Derrors1eaec39e3303
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex 44f977f..9f914dc 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -23,7 +23,9 @@ use crate::notify::{self, Dedup, Event};use crate::protocol::{Request, Response};pub const TICK: Duration = Duration::from_secs(10);-const WDA_START_TIMEOUT: Duration = Duration::from_secs(60);+/// 正常 2~10 秒就绪。手机重启后未授权 automation 时,testmanagerd 握手每次卡 30 秒、要重试一两次,+/// 60 秒常常等不到 runner 启动,也就认不出「需要输入密码」+const WDA_START_TIMEOUT: Duration = Duration::from_secs(120);const SYSFS_USB: &str = "/sys/bus/usb/devices";/// 持久化到 `state.json` 的状态(不含秘密)diff --git a/crates/ictl-wda/src/lib.rs b/crates/ictl-wda/src/lib.rsindex 0b87cba..8314b5b 100644--- a/crates/ictl-wda/src/lib.rs+++ b/crates/ictl-wda/src/lib.rs@@ -30,9 +30,10 @@ pub enum WdaError {pub type Result<T> = std::result::Result<T, WdaError>;-/// 识别 XCTest 启动失败是否是「等待自动化密码」(toolkit 实测的报错文字)+/// 识别 XCTest 启动失败是否是「等待自动化密码」:密码框 60 秒没输(toolkit 和 iOS 27 真机同一文字),+/// 或手机锁屏时密码框弹不出来、被系统直接取消(LocalAuthentication 错误,如 Code=-4「认证已取消」)pub fn is_automation_pin_error(message: &str) -> bool {- message.contains("enabling automation mode")+ message.contains("enabling automation mode") || message.contains("com.apple.LocalAuthentication")}#[cfg(test)]@@ -42,6 +43,10 @@ mod tests {assert!(super::is_automation_pin_error("Timed out while enabling automation mode. (Error code: 1000, Domain: com.apple.dt.XCTest.XCTFuture)"));+ // iOS 27.0.1 锁屏时的真机报错+ assert!(super::is_automation_pin_error(+ "Failed to initialize for UI testing: Error Domain=com.apple.LocalAuthentication Code=-4 \"认证已取消。\""+ ));assert!(!super::is_automation_pin_error("Failed to load the test bundle (Error code: 103)"));}}diff --git a/crates/ictl-wda/src/runner.rs b/crates/ictl-wda/src/runner.rsindex bb2bca5..50233ae 100644--- a/crates/ictl-wda/src/runner.rs+++ b/crates/ictl-wda/src/runner.rs@@ -19,16 +19,89 @@ use crate::{Result, WdaClient, WdaError, is_automation_pin_error};pub const WDA_PORT: u16 = 8100;-/// 记下 XCTest 过程中报告的错误文字,用来识别「Enable UI Automation」密码框超时-struct ErrorListener(Arc<Mutex<Vec<String>>>);+/// runner 等「Enable UI Automation」密码的时长是 60 秒(runner 自己的超时),多留 5 秒收它的报错+const AUTOMATION_WAIT: Duration = Duration::from_secs(65);++/// runner 调试日志里和「Enable UI Automation」相关的信号。+/// 手机重启后 runner 一启动就进入 `enabling automation mode` 等待(手机上弹密码框),60 秒没输密码报+/// `Timed out while enabling automation mode.`。这个报错经 `_XCT_initializationForUITestingDidFailWithError:`+/// 发回,idevice 解码失败(只给出 unexpected response,不调回调),所以从调试日志里认+#[derive(Debug, PartialEq)]+enum AutomationSignal {+ /// 开始等 automation mode(已授权时会马上结束)+ Waiting,+ /// 等待结束(成功或超时都有这一行)+ Done,+ /// UI 测试初始化失败,消息里带原因+ Failed,+}++fn automation_signal(msg: &str) -> Option<AutomationSignal> {+ if msg.contains("Failed to initialize for UI testing") {+ Some(AutomationSignal::Failed)+ } else if msg.contains("entering wait loop") && msg.contains("enabling automation mode") {+ Some(AutomationSignal::Waiting)+ } else if msg.contains("cleaning up enabling automation mode") {+ Some(AutomationSignal::Done)+ } else {+ None+ }+}++/// XCTest 过程中收集的信息:报错文字(识别密码框超时用),以及 runner 是否正在等 automation mode+#[derive(Default)]+struct Progress {+ errors: Vec<String>,+ automation_wait: Option<tokio::time::Instant>,+}++struct ErrorListener(Arc<Mutex<Progress>>);impl ErrorListener {fn push(&self, s: &str) {- self.0.lock().unwrap().push(s.to_owned());+ self.0.lock().unwrap().errors.push(s.to_owned());}}+// 其余回调只记 debug 日志,用于排查启动卡住impl XCUITestListener for ErrorListener {+ async fn log_message(&mut self, message: &str) -> std::result::Result<(), IdeviceError> {+ tracing::debug!("xctest log: {message}");+ Ok(())+ }++ async fn log_debug_message(&mut self, message: &str) -> std::result::Result<(), IdeviceError> {+ tracing::debug!("xctest debug: {message}");+ let mut p = self.0.lock().unwrap();+ match automation_signal(message) {+ Some(AutomationSignal::Waiting) => p.automation_wait = Some(tokio::time::Instant::now()),+ Some(AutomationSignal::Done) => p.automation_wait = None,+ Some(AutomationSignal::Failed) => p.errors.push(message.to_owned()),+ None => {}+ }+ Ok(())+ }++ async fn did_begin_initializing_for_ui_testing(&mut self) -> std::result::Result<(), IdeviceError> {+ tracing::debug!("xctest: 开始初始化 UI 测试");+ Ok(())+ }++ async fn test_bundle_ready(&mut self) -> std::result::Result<(), IdeviceError> {+ tracing::debug!("xctest: test bundle ready");+ Ok(())+ }++ async fn test_runner_ready_with_capabilities(&mut self) -> std::result::Result<(), IdeviceError> {+ tracing::debug!("xctest: runner ready");+ Ok(())+ }++ async fn did_begin_executing_test_plan(&mut self) -> std::result::Result<(), IdeviceError> {+ tracing::debug!("xctest: 开始执行测试计划");+ Ok(())+ }+async fn initialization_for_ui_testing_did_fail(&mut self,description: &str,@@ -62,23 +135,40 @@ impl WdaRunner {other => WdaError::StartFailed(other.to_string()),})?;- let errors = Arc::new(Mutex::new(Vec::new()));+ let progress = Arc::new(Mutex::new(Progress::default()));let task = {- let (provider, errors) = (provider.clone(), errors.clone());- tokio::spawn(async move { XCUITestService::new(provider).run(cfg, &mut ErrorListener(errors), None).await })+ let (provider, progress) = (provider.clone(), progress.clone());+ tokio::spawn(+ async move { XCUITestService::new(provider).run(cfg, &mut ErrorListener(progress), None).await },+ )};let runner = Self { bundle_id: bundle_id.to_owned(), task };let client = WdaClient::new(DeviceTransport::new(provider, WDA_PORT));let failure = |extra: Option<String>| {- let mut text: Vec<String> = errors.lock().unwrap().clone();+ let p = progress.lock().unwrap();+ let mut text = p.errors.clone();text.extend(extra);let joined = text.join("; ");- if is_automation_pin_error(&joined) { WdaError::NeedsAutomationPin } else { WdaError::StartFailed(joined) }+ // 报错文字没收到、但 runner 停在等 automation mode 也算+ if is_automation_pin_error(&joined) || p.automation_wait.is_some() {+ WdaError::NeedsAutomationPin+ } else {+ WdaError::StartFailed(joined)+ }};- let deadline = tokio::time::Instant::now() + timeout;+ let mut deadline = tokio::time::Instant::now() + timeout;+ let mut announced = false;loop {+ // runner 在等手机上输密码:等满它自己的 60 秒,期间输了密码就能直接就绪+ if let Some(since) = progress.lock().unwrap().automation_wait {+ deadline = deadline.max(since + AUTOMATION_WAIT);+ if !announced {+ announced = true;+ tracing::info!("runner 在等手机上的「Enable UI Automation」密码");+ }+ }if runner.task.is_finished() {let r = runner.task.await;let msg = match r {@@ -93,7 +183,7 @@ impl WdaRunner {}if tokio::time::Instant::now() >= deadline {runner.task.abort();- return Err(failure(Some(format!("{} 秒内 WDA 没有就绪", timeout.as_secs()))));+ return Err(failure(Some("WDA 在限定时间内没有就绪".to_owned())));}tokio::time::sleep(Duration::from_millis(500)).await;}@@ -108,3 +198,25 @@ impl WdaRunner {self.task.abort();}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn automation_signals_from_runner_debug_log() {+ // iOS 27.0.1 手机重启后真机日志(去掉时间和进程号前缀)+ let wait =+ "<XCTWaiter: 0x1089cebb0> entering wait loop for 60.00s with expectations: `enabling automation mode`";+ let done = "cleaning up enabling automation mode";+ let fail = "Failed to initialize for UI testing: Error Domain=com.apple.dt.XCTest.XCTFuture Code=1000 \+ \"Timed out while enabling automation mode.\" UserInfo={NSLocalizedDescription=Timed out while enabling automation mode.}";+ assert_eq!(automation_signal(wait), Some(AutomationSignal::Waiting));+ assert_eq!(automation_signal(done), Some(AutomationSignal::Done));+ assert_eq!(automation_signal(fail), Some(AutomationSignal::Failed));+ assert!(is_automation_pin_error(fail));+ // 创建 future 那一行不算开始等待(已授权时也有)+ assert_eq!(automation_signal("Creating future for 'enabling automation mode' with timeout 60.00"), None);+ assert_eq!(automation_signal("Loading test bundle at: file:///..."), None);+ }+}diff --git a/spike/src/main.rs b/spike/src/main.rsindex 786e6f5..14ffc46 100644--- a/spike/src/main.rs+++ b/spike/src/main.rs@@ -42,7 +42,12 @@ enum Check {minutes: u64,},/// 5. 启动 WDA:读 /status、/source、/screenshot,最后停掉 runner- Wda { bundle_id: String },+ Wda {+ bundle_id: String,+ /// 等 WDA 就绪的秒数(排查「Enable UI Automation」时调大)+ #[arg(long, default_value_t = 60)]+ timeout: u64,+ },/// 阶段 1 完成标准:隧道 → 镜像 → WDA → 截图 → 读元素 → 点「设置」→ Home,每步以 WDA 报告的前台 App 为准。/// 再用 HID 重做「点设置 → Home」一遍,确认 HID 点击真的生效E2e {@@ -239,10 +244,10 @@ async fn main() -> anyhow::Result<()> {}println!("{n} 次成功、{fails} 次失败,共 {:.1} MB,最慢 {worst:.2}s", bytes as f64 / 1e6);}- Check::Wda { bundle_id } => {+ Check::Wda { bundle_id, timeout } => {let t0 = Instant::now();let (runner, mut wda) =- ictl_wda::WdaRunner::start(device.provider(), &bundle_id, Duration::from_secs(60)).await?;+ ictl_wda::WdaRunner::start(device.provider(), &bundle_id, Duration::from_secs(timeout)).await?;println!("WDA 就绪,耗时 {:.1}s", t0.elapsed().as_secs_f64());println!("屏幕 {:?}", wda.screen_size().await?);let t1 = Instant::now();