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
fix(daemon): restart a stuck axauditd instead of failing until the phone is replugged (#152)
Qinghe Lie2afc62ce025
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 86cd448..8f69fbe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,10 @@ What changed in each release, one line per change. Versions follow [Semantic Ver## [Unreleased]+### Fixes++- With native control (iOS 27), reading the screen no longer keeps failing until the phone is replugged when the phone's accessibility service stops answering; it is restarted on its own (#152).+## [0.2.8] - 2026-11-18### Newdiff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex af7d910..e52c0fa 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -6,6 +6,10 @@## [Unreleased]+### 修复++- 原生控制(iOS 27)下,手机上的无障碍服务不再应答时,读界面不会再一直失败到重新插线为止;会自动把它重启(#152)。+## [0.2.8] - 2026-11-18### 新功能diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex e895742..959b6c9 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -441,6 +441,8 @@ pub(crate) struct PerDevice {pub repeats: crate::tools::Repeats,/// 最近一个操作开始的时间:原生控制等界面稳定时,从这之后的推送算起pub acted_at: Option<Instant>,+ /// 原生控制:上次因为无障碍服务不应答而重启手机上 axauditd 的时间(`tools::native::AX_RESTART_EVERY` 内只重启一次)+ pub ax_restarted: Option<Instant>,/// How long the request being handled spent unlocking the phone first ([`Daemon::ensure_unlocked`]); taken by/// [`Daemon::dispatch`], which says so in the answerpub unlocked: Option<Duration>,diff --git a/crates/ictl-daemon/src/tools/native.rs b/crates/ictl-daemon/src/tools/native.rsindex a3c522a..2f60b13 100644--- a/crates/ictl-daemon/src/tools/native.rs+++ b/crates/ictl-daemon/src/tools/native.rs@@ -15,6 +15,8 @@ use crate::config::IosBackend;/// A read of the screen waits at most this long for a tree (the first one of a session comes in about a second)pub(crate) const AX_WAIT: Duration = Duration::from_secs(5);+/// 无障碍服务不应答时,同一台设备这么久内最多重启一次 axauditd:重启了还不行就照常报错,不反复结束它+pub(crate) const AX_RESTART_EVERY: Duration = Duration::from_secs(60);/// After an action, the screen is first read this long after it started: an app reacts to a tap within about/// 0.1 s, a page slides in within about 0.35 s (the second read, which confirms, comes about 0.2 s later)const REACT: Duration = Duration::from_millis(300);@@ -119,16 +121,50 @@ impl Daemon {overlays: bool,) -> crate::error::Result<ictl_device::ax::AxScreen> {let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;- let t = self- .ensure_tunnel(g, &device)- .await- .map_err(|e| ictl_l10n::trf!("读界面失败(建隧道):{e}", "Reading the screen failed (tunnel): {e}"))?;- let r = t.ax_screen(wait, overlays).await;- if r.is_err() {- t.close_ax().await;+ let mut restarted = false;+ loop {+ let t = self+ .ensure_tunnel(g, &device)+ .await+ .map_err(|e| ictl_l10n::trf!("读界面失败(建隧道):{e}", "Reading the screen failed (tunnel): {e}"))?;+ let r = t.ax_screen(wait, overlays).await;+ if r.is_err() {+ t.close_ax().await;+ }+ g.ax_used = Some(Instant::now());+ if let Err(ictl_device::DeviceError::AxUnanswered(e)) = &r+ && !restarted+ && Box::pin(self.restart_stuck_ax(g, &device, e)).await+ {+ restarted = true;+ continue;+ }+ return Ok(r.map_err(|e| ictl_l10n::trf!("读界面失败:{e}", "Reading the screen failed: {e}"))?);+ }+ }++ /// remoteAXService didn't answer: unless that was already tried within [`AX_RESTART_EVERY`], end axauditd on the+ /// phone ([`ictl_device::Tunnel::restart_ax_daemon`]). Whether it was ended, so the read is worth repeating+ async fn restart_stuck_ax(&self, g: &mut Inner, device: &ictl_device::Device, why: &str) -> bool {+ if g.dev.ax_restarted.is_some_and(|t| t.elapsed() < AX_RESTART_EVERY) {+ return false;+ }+ g.dev.ax_restarted = Some(Instant::now());+ let Ok(t) = self.ensure_tunnel(g, device).await else { return false };+ match t.restart_ax_daemon().await {+ Ok(n) if n > 0 => {+ self.log.log(&ictl_l10n::log_trf!(+ "无障碍服务没有应答({why}),已重启手机上的 axauditd",+ "The accessibility service didn't answer ({why}), restarted axauditd on the phone"+ ));+ true+ }+ Ok(_) => false,+ Err(e) => {+ tracing::info!("{}", ictl_l10n::log_trf!("重启 axauditd 失败:{e}", "Restarting axauditd failed: {e}"));+ false+ }}- g.ax_used = Some(Instant::now());- Ok(r.map_err(|e| ictl_l10n::trf!("读界面失败:{e}", "Reading the screen failed: {e}"))?)}/// A read as WDA-style XML, the screen (as turned now) and the frontmost app's process@@ -200,12 +236,23 @@ impl Daemon {/// The frontmost app's bundle ID (one request, no walk)pub(crate) async fn native_foreground(&self, g: &mut Inner) -> crate::error::Result<String> {let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;- let t = self.ensure_tunnel(g, &device).await?;- let r = t.ax_frontmost_pid(AX_WAIT).await;- if r.is_err() {- t.close_ax().await;- }- g.ax_used = Some(Instant::now());+ let mut restarted = false;+ let r = loop {+ let t = self.ensure_tunnel(g, &device).await?;+ let r = t.ax_frontmost_pid(AX_WAIT).await;+ if r.is_err() {+ t.close_ax().await;+ }+ g.ax_used = Some(Instant::now());+ if let Err(ictl_device::DeviceError::AxUnanswered(e)) = &r+ && !restarted+ && Box::pin(self.restart_stuck_ax(g, &device, e)).await+ {+ restarted = true;+ continue;+ }+ break r;+ };let pid = r.map_err(|e| ictl_l10n::trf!("读前台 App 失败:{e}", "Reading the foreground app failed: {e}"))?;self.bundle_of_pid(g, pid).await}diff --git a/crates/ictl-device/src/ax.rs b/crates/ictl-device/src/ax.rsindex 263fca2..0f23e50 100644--- a/crates/ictl-device/src/ax.rs+++ b/crates/ictl-device/src/ax.rs@@ -22,12 +22,20 @@ const OVERLAY_BUDGET: Duration = Duration::from_secs(2);impl From<ictl_ax::AxError> for DeviceError {fn from(e: ictl_ax::AxError) -> Self {match e {- ictl_ax::AxError::Timeout(what) => Self::Timeout(format!("remoteAXService: {what}")),+ ictl_ax::AxError::Timeout(what) => Self::AxUnanswered(format!("remoteAXService: {what}")),other => Self::Idevice(other.to_string()),}}}+/// After axauditd is ended, how long launchd is given before the next connection starts it again+const AX_DAEMON_RESTART: Duration = Duration::from_secs(1);++/// The phone's process behind remoteAXService+pub fn is_ax_daemon(exe: &str) -> bool {+ exe.ends_with("/AccessibilityAudit.framework/Support/axauditd")+}+/// One read of the screen#[derive(Debug, Clone)]pub struct AxScreen {@@ -68,7 +76,11 @@ impl Tunnel {limit(ictl_l10n::tr!("连接无障碍服务", "connect to the accessibility service"), CONNECT_WAIT, async {Ok(AxSession::connect(stream, CONNECT_WAIT).await?)})- .await?;+ .await+ .map_err(|e| match e {+ DeviceError::Timeout(what) => DeviceError::AxUnanswered(what),+ e => e,+ })?;self.ax = Some(s);}Ok(self.ax.as_ref().expect("just opened"))@@ -143,6 +155,23 @@ impl Tunnel {})}+ /// Ends axauditd, the phone's process behind remoteAXService; the next connection starts it again. It can get stuck+ /// (iPhone 15 Pro Max, iOS 27.2.1: after automatic unlocks and daemon restarts): every handshake then times out+ /// on `deviceAPIVersion`, a new session or tunnel doesn't help, and before this only replugging the phone did.+ /// Returns how many processes were ended (0: it wasn't running)+ pub async fn restart_ax_daemon(&mut self) -> Result<usize> {+ self.close_ax().await;+ let pids: Vec<u64> =+ self.processes().await?.into_iter().filter(|(_, exe)| is_ax_daemon(exe)).map(|(pid, _)| pid).collect();+ for pid in &pids {+ self.signal(*pid, 9).await?;+ }+ if !pids.is_empty() {+ tokio::time::sleep(AX_DAEMON_RESTART).await;+ }+ Ok(pids.len())+ }+/// The frontmost app's process (one request, no walk)pub async fn ax_frontmost_pid(&mut self, wait: Duration) -> Result<i64> {let s = self.ax().await?;@@ -182,3 +211,29 @@ async fn frontmost(s: &AxSession, wait: Duration) -> Result<ObjectRef> {}}}++#[cfg(test)]+mod wedge_tests {+ use super::*;++ /// remoteAXService not answering is an error of its own (the daemon restarts axauditd for it), worded as before+ #[test]+ fn an_unanswered_accessibility_service_is_told_apart_and_reads_as_a_timeout() {+ let e = DeviceError::from(ictl_ax::AxError::Timeout("deviceAPIVersion"));+ assert!(matches!(&e, DeviceError::AxUnanswered(w) if w == "remoteAXService: deviceAPIVersion"), "{e:?}");+ assert_eq!(e.to_string(), DeviceError::Timeout("remoteAXService: deviceAPIVersion".into()).to_string());+ }++ /// Paths as the phone lists them (iOS 27.2.1); only axauditd itself is ended+ #[test]+ fn only_axauditd_is_the_accessibility_daemon() {+ assert!(is_ax_daemon("file:///System/Library/PrivateFrameworks/AccessibilityAudit.framework/Support/axauditd"));+ for other in [+ "file:///System/Library/PrivateFrameworks/AXAssetLoader.framework/Support/axassetsd",+ "file:///System/Library/CoreServices/AccessibilityUIServer.app/AccessibilityUIServer",+ "file:///System/Library/Frameworks/MediaAccessibility.framework/XPCServices/com.apple.accessibility.mediaaccessibilityd.xpc/com.apple.accessibility.mediaaccessibilityd",+ ] {+ assert!(!is_ax_daemon(other), "{other}");+ }+ }+}diff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rsindex 6058fe3..7f9f30e 100644--- a/crates/ictl-device/src/lib.rs+++ b/crates/ictl-device/src/lib.rs@@ -117,6 +117,10 @@ pub enum DeviceError {/// 手机上的服务没在限定时间内应答。调用方应丢掉隧道重建#[error("{}", ictl_l10n::trf!("超时:{0}", "Timed out: {0}", .0))]Timeout(String),+ /// 无障碍服务(remoteAXService)没在限定时间内应答:连接、握手或请求超时。读出来和 [`Self::Timeout`] 一样。+ /// 手机上的 axauditd 卡住时就是这样,重连、重建隧道都没用,要结束它([`Tunnel::restart_ax_daemon`])+ #[error("{}", ictl_l10n::trf!("超时:{0}", "Timed out: {0}", .0))]+ AxUnanswered(String),/// 调用方给的参数不合法(例如 HID 不能输入的字符)。与连接无关,不需要重建会话#[error("{0}")]InvalidInput(String),diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.mdindex ce81e1e..be65897 100644--- a/docs/dev/regression-cases.md+++ b/docs/dev/regression-cases.md@@ -158,3 +158,4 @@| 152 | 原生控制(iOS 27):设置首页底部悬浮的搜索栏在扁平的元素树里只是一个直接挂在 Application 下的 `SearchField`,没有 WDA 树里那层 Toolbar,不算遮挡;被压在栏下的行(如「隐私与安全」在 y≈866)按名字点会点它的中心,打开的是搜索;`iphone_tap_element` 带 `scroll` 时也会停在这样的位置 | 直接挂在 Application 下、在屏幕下部 40% 的 `SearchField` 按底部悬浮栏处理:盖得住下面的行;范围按真机量的算:输入框(顶 866)往上 58 点内的点击都被栏吞掉(806 还能进下面那一行,812、820、826 都不行),左右和往下多 34 点;一半压在这片范围里的改点上面露出来的部分,整个在里面的报被挡住 | 单测 `a_native_floating_search_field_covers_the_rows_under_it`(真机导出的树 `settings-floating-search-native-ios27.xml`)+ 真机(设置首页把行滑到搜索栏下,按名字点、带 scroll 找) || 153 | 第一次启动系统 App(备忘录、提醒事项)时,系统先在另一个进程(`com.apple.PDUIApp`)里显示隐私说明页盖在上面;`/wda/apps/launch` 要等 XCTest 看到 App 到前台,一直等到 60 秒超时,接着 WDA 被判卡死重启,`iphone_launch_app` 报超时(65 秒) | 先用 `/wda/apps/launchUnattached`(不经 XCTest,发出就返回),再照旧轮询前台:前台是隐私说明页就马上报「被挡住」,结果和权限弹窗一样提示先点它的按钮;它回「failed to launch」时说明页已经出来,照样往下查;旧版 WDA 没有这个接口时退回 `/wda/apps/launch` | 单测 `a_first_launch_privacy_notice_is_reported_at_once`、`an_older_wda_without_unattached_launch_launches_as_before`、`other_launch_errors_are_errors` + 真机(iPhone 12 mini,iOS 26.4.1:没打开过的「备忘录」0.7 秒返回、WDA 不重启,0.2.7 是 65 秒并重启 WDA;冷启动「时钟」后马上点标签页照常点中)|| 154 | `iphone_tap_element` 没找到(或序号超出、整个被盖住)时什么都没点,带 `then` 却先等界面稳定 0.7~0.8 秒,再拿它点之前读的树比较,说「界面和操作前一样:操作可能没生效(点在了空白处…),不要原样再做一遍」,好像点过了 | 没点就清掉「操作前的界面」,不做比较;MCP 端看到没点到东西时不等稳定,直接用按名字点击刚读的树列元素或截图 | 真机(iPhone 12 mini,iOS 26.4.1:设置里按不存在的文字点,带 `then=elements` 和 `then=screenshot`,0.2.7 是 1.3~1.45 秒带那句提示,本分支 0.6~0.9 秒不带;只换守护进程(旧 MCP)时仍等稳定但也不带;按存在的文字点照常等稳定、说界面变了)|+| 155 | 原生控制(iOS 27):手机上的 axauditd(remoteAXService 背后的进程)卡住后,每次读界面都超时(先 `remoteAXService: request`,之后每次握手 `deviceAPIVersion`),守护进程一直「准备手机失败,稍后重试」,重连、重建隧道、重启守护进程都没用,只有重新插线才恢复。iPhone 15 Pro Max(iOS 27.2.1)上见过三次:两次在部署重启守护进程后,一次在自动解锁后 | 无障碍服务不应答单独成一种错误(`DeviceError::AxUnanswered`,文字同超时);读界面、读前台 App 碰到它时经 CoreDevice 结束 axauditd(下次连接系统自动拉起),再读一次;同一台设备一分钟内最多一次,事件日志记「已重启手机上的 axauditd」 | 单测 `an_unanswered_accessibility_service_is_told_apart_and_reads_as_a_timeout`、`only_axauditd_is_the_accessibility_daemon` + 真机(经 AppService 给 axauditd 发 SIGSTOP 冻住:main 上一直报超时,修复后下一次读界面直接成功、axauditd 换了进程号) |