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
The active app is detected below banners; actions say whether the screen changed (#121)
Qinghe Lic3cec3e16624
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8e6a1ff..b8a5828 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ All notable changes to this project are documented here. The format is based on### Added- While WebDriverAgent is unavailable, `iphone_type_text` can enter Chinese and other text a US keyboard can't type: HID puts it on the phone's pasteboard (CoreDevice `pasteboardservice`, checked by reading it back) and presses Cmd-V, so the input method doesn't turn it into pinyin. iOS treats that text as coming from another app and asks “… would like to paste from dtpasteboardd” every time (iPhone 15 Pro Max, iOS 27.2.1, Notes); the answer says to take a screenshot and tap “Allow Paste”. Changing the pasteboard closes that prompt, so what was on it before is put back 45 s later (or before the next such paste, or when another device is chosen), and only if the pasted text is still there. Return isn't pressed with `submit`, since with the prompt up it would choose “Don't Allow Paste”. English letters and symbols are still typed as keys and don't touch the pasteboard.+- An action with `then` says whether the screen changed: the screen after it settles is compared with what was read just before it (an element list, a screenshot, or the tree a tap by text reads before tapping). "The same as before" adds that the action may not have taken effect and to look before trying it again. Nothing is added when the screen wasn't looked at since the action before. On a phone (iPhone 15 Pro Max, iOS 27.2.1, Settings): a tap on an empty spot said "the same", opening General and going back said "changed".### Changed@@ -25,6 +26,7 @@ All notable changes to this project are documented here. The format is based on- 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.- A tap, swipe, key or launch that WebDriverAgent didn't answer in time no longer carries on later. WDA handles requests one at a time and keeps going after we stop waiting, so an action queued behind a slow one could land on the screen long after it was reported as failed. The daemon now ends that WDA session at once (`DELETE /session`, which WDA 16.15.3 answers outside its queue and which drops what is still queued in it) and opens a new one for the next action. A read that times out keeps its session.- Reading the element tree of a screen with very many elements (long feeds and lists) no longer keeps taking as long. A read over 8 s, or one that times out, makes the next read ask WDA for a smaller snapshot (at most 150 children per element first, then half the depth and children, down to 12 levels and 60 children); a read under 1.5 s loosens it a step again. While the tree is cut short, `iphone_list_elements` and a `iphone_tap_element` that finds nothing say so.+- A tap by text, an element list or `then=elements` with a notification banner at the top read SpringBoard's tree instead of the app's (seen on a phone with the "Device Hub" banner: a button in Notes wasn't found). WDA tells the app in front by what is under one point, which by default is 20% of the short side from the top left corner: (86, 86) on a 430-point iPhone, under the banner. It is now moved to half the short side from that corner, (215, 215), once per WDA start.## [0.2.6] - 2026-11-14diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex 25cce17..43f73d4 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -9,6 +9,7 @@### 新增- WebDriverAgent 不可用时,`iphone_type_text` 也能输入中文等美式键盘按不出来的文字:经 HID 把它写进手机剪贴板(CoreDevice `pasteboardservice`,写完读回核对),再按 Cmd-V,输入法不会把它当成拼音。iOS 把这段文字当成别的 App 的,每次都会问「…想从“dtpasteboardd”粘贴」(iPhone 15 Pro Max、iOS 27.2.1 的备忘录实测);结果里会提示截图后点「允许粘贴」。剪贴板一改这个弹窗就消失,所以原来的内容 45 秒后才写回(下一次这样粘贴前、换设备时也会写回),而且只在剪贴板里还是粘贴的那段文字时才写。带 `submit` 时不按回车:弹窗还在时回车会选中「不允许粘贴」。英文和符号仍然逐键输入,不动剪贴板。+- 带 `then` 的操作会说明界面变没变:界面稳定后,和操作前刚读过的界面(元素列表、截图,或按名字点击之前读的元素树)比较。没变时提醒操作可能没生效、先看清再决定要不要重做。上一个操作之后没看过界面就不说。真机(iPhone 15 Pro Max、iOS 27.2.1 的设置):点空白处说「一样」,打开「通用」、点返回都说「有变化」。### 变更@@ -25,6 +26,7 @@- 每台设备按 Home 和锁屏该用哪种方式,现在记在 `state.json` 里,不再只放在内存。原来守护进程重启或中途控制过别的设备后,在 IOHID 的 Home 不起作用的设备上,第一次按 Home 会先用 IOHID 按,等 2 秒没回到主屏幕再补按一次:iPad mini 5 上要 4.4 秒,平时 0.8 秒。- WebDriverAgent 没有及时应答的点击、滑动、按键、启动 App,不会再过一阵才执行。WDA 一个一个处理请求,我们不等了它还会接着做,排在慢请求后面的动作可能在报了失败之后很久才落到屏幕上。现在守护进程马上结束那个 WDA 会话(`DELETE /session`:WDA 16.15.3 不排队处理它,还会丢掉这个会话里还在排队的请求),下一个动作开新会话。读超时不结束会话。- 元素特别多的界面(很长的信息流、列表)读元素树不再一直那么慢。一次读超过 8 秒或超时,下一次就让 WDA 少读一些(先限每个元素最多 150 个子元素,再把层数和子元素数减半,最少 12 层、60 个);读得快于 1.5 秒就放宽一级。元素树被截短时,`iphone_list_elements` 和没找到元素的 `iphone_tap_element` 会说明。+- 屏幕顶上弹着通知横幅时,按名字点击、读元素、`then=elements` 读到的是 SpringBoard 的元素树而不是 App 的(真机上弹着「Device Hub」横幅时,备忘录里的按钮找不到)。WDA 看屏幕上一个点下面是谁来判断前台 App,这个点默认在离左上角短边 20% 处,430 点宽的 iPhone 上是 (86, 86),正在横幅底下。现在每次 WDA 启动后挪到离左上角短边一半处,即 (215, 215)。## [0.2.6] - 2026-11-14diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex 6d90fae..64758cd 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -366,6 +366,11 @@ pub(crate) struct PerDevice {pub log_capture: Option<crate::devtools::Capture>,/// HID 粘贴前存下的剪贴板和粘贴的时间,等着写回([`Daemon::restore_pasteboard`])pub pending_paste: Option<(Instant, ictl_device::PendingRestore)>,+ /// 上一个操作做完以后读过的界面(元素树、截图的指纹)+ pub seen: crate::tools::Seen,+ /// 最近一个操作开始前的界面:操作做完、界面稳定时和它比,告诉调用方界面变没变(`Daemon::settle`)。+ /// 按名字点击会在点之前读树,用那棵树+ pub before_action: Option<crate::tools::Seen>,}pub(crate) struct Inner {@@ -1053,9 +1058,14 @@ impl Daemon {}} else {let acted = req.is_device_action();+ if acted {+ // 这个操作之前读过的界面就是「操作前」;操作期间读的(按名字点击先读树)也是操作前,操作完都不再算+ g.dev.before_action = g.dev.seen.take_fresh();+ }// boxed, like the request in `handle`: two of its large state machine on the stack overflowed a test threadlet r = Box::pin(self.dispatch(g, req, view, ctx.watched)).await;if acted {+ g.dev.seen = Default::default();*self.last_action.lock().unwrap_or_else(|p| p.into_inner()) = Some(Instant::now());}rdiff --git a/crates/ictl-daemon/src/imaging.rs b/crates/ictl-daemon/src/imaging.rsindex 70e7bff..641cdba 100644--- a/crates/ictl-daemon/src/imaging.rs+++ b/crates/ictl-daemon/src/imaging.rs@@ -57,8 +57,28 @@ pub const THUMB_H: u32 = 104;pub fn thumbnail(png: &[u8]) -> Result<Vec<u8>, String> {let img = image::load_from_memory(png).map_err(|e| ictl_l10n::trf!("截图解码失败:{e}", "Decoding the screenshot failed: {e}"))?;+ Ok(thumb_of(&img))+}++fn thumb_of(img: &DynamicImage) -> Vec<u8> {// 最近邻足够:只比较前后两帧,不看画质;比三角滤波快一个数量级- Ok(img.resize_exact(THUMB_W, THUMB_H, FilterType::Nearest).into_luma8().into_raw())+ img.resize_exact(THUMB_W, THUMB_H, FilterType::Nearest).into_luma8().into_raw()+}++/// 截图工具的回答(整屏或区域放大,见 [`full_screen`]、[`region`])和整屏的指纹,只解码一次。+/// 指纹记下来,下一个操作做完后比较画面变没变+pub fn answer(+ png: &[u8],+ screen: ScreenSize,+ rect: Option<(f64, f64, f64, f64)>,+ via: &str,+) -> Result<(Vec<u8>, String, Vec<u8>), String> {+ let img = decode(png)?;+ let (jpeg, caption) = match rect {+ None => full_screen_of(&img, screen, via)?,+ Some(r) => region_of(&img, screen, r, via)?,+ };+ Ok((jpeg, caption, thumb_of(&img)))}/// 两个指纹的平均逐像素差(0~255)。尺寸不同算完全不同@@ -118,7 +138,10 @@ pub fn thumb_motion(a: &[u8], b: &[u8]) -> Motion {/// 整屏缩放到点尺寸:图像像素即点坐标。返回 (jpeg, 说明文字)pub fn full_screen(png: &[u8], screen: ScreenSize, via: &str) -> Result<(Vec<u8>, String), String> {- let img = decode(png)?;+ full_screen_of(&decode(png)?, screen, via)+}++fn full_screen_of(img: &DynamicImage, screen: ScreenSize, via: &str) -> Result<(Vec<u8>, String), String> {let (w, h) = oriented(img.width(), img.height(), screen);let out = jpeg(&img.resize_exact(w, h, filter_for((img.width(), img.height()), (w, h))), 80)?;Ok((@@ -177,7 +200,15 @@ pub fn region(rect: (f64, f64, f64, f64),via: &str,) -> Result<(Vec<u8>, String), String> {- let img = decode(png)?;+ region_of(&decode(png)?, screen, rect, via)+}++fn region_of(+ img: &DynamicImage,+ screen: ScreenSize,+ rect: (f64, f64, f64, f64),+ via: &str,+) -> Result<(Vec<u8>, String), String> {let p = plan_zoom(img.width(), img.height(), screen, rect.0, rect.1, rect.2, rect.3)?;let (cx, cy, cw, ch) = p.crop;let mut crop = img.crop_imm(cx, cy, cw, ch);diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rsindex 568f8f2..4d87580 100644--- a/crates/ictl-daemon/src/tools/input.rs+++ b/crates/ictl-daemon/src/tools/input.rs@@ -153,6 +153,8 @@ impl Daemon {) -> crate::error::Result<(String, bool)> {self.ensure_unlocked(g).await?;let tree = self.tree(g, max_age).await?;+ // 点之前刚读的树就是操作前的界面(比操作开始前记下的更新)+ g.dev.before_action = Some(std::mem::take(&mut g.dev.seen));let matches = elements::find(&tree.elements, text);if matches.is_empty() {let limited = self.snapshot_note(g);diff --git a/crates/ictl-daemon/src/tools/mod.rs b/crates/ictl-daemon/src/tools/mod.rsindex 7cbab5d..97e0bf6 100644--- a/crates/ictl-daemon/src/tools/mod.rs+++ b/crates/ictl-daemon/src/tools/mod.rs@@ -22,6 +22,7 @@ use crate::imaging::{self, fmt_g};use crate::notify::Event;use crate::protocol::{ALERT_BLOCKING, Response, TAP_MISSED, TouchPhase};use crate::protocol::{ElementData, StatusData};+pub(crate) use observe::Seen;use observe::*;/// 锁屏后至少等这么久再自动解锁:锁屏过渡没走完就唤醒,WDA 第一下上滑卡约 16 秒后报 `point.x != INFINITY`@@ -305,14 +306,13 @@ impl Daemon {// 解码、缩放、JPEG 编码是 CPU 活(1290×2796),放到阻塞线程,不卡住主循环// 说明文字在阻塞线程里生成:带上这个请求的语言let lang = ictl_l10n::lang();- let (jpeg, caption) = tokio::task::spawn_blocking(move || {- ictl_l10n::with_lang(lang, || match region {- None => imaging::full_screen(&png, screen, via),- Some(r) => imaging::region(&png, screen, r, via),- })+ let (jpeg, caption, thumb) = tokio::task::spawn_blocking(move || {+ ictl_l10n::with_lang(lang, || imaging::answer(&png, screen, region, via))}).await.map_err(|e| ictl_l10n::trf!("图像处理任务异常:{e}", "Image processing task failed: {e}"))??;+ // 区域放大也记整屏:下一个操作做完后比的是整个画面+ g.dev.seen.saw_thumb(thumb);Ok(Response::Image { jpeg_base64: base64::engine::general_purpose::STANDARD.encode(jpeg), caption })}}@@ -365,6 +365,53 @@ mod tests {use super::keys::*;use super::*;+ /// 操作前后的界面:树比树,没有树比画面,什么都没有不说+ #[test]+ fn screen_change_is_judged_by_tree_then_picture() {+ use super::observe::{Change, Seen, compare};+ let tree = |label: &str, y: i64| {+ let xml = format!(+ r#"<XCUIElementTypeApplication type="XCUIElementTypeApplication" label="A" x="0" y="0" width="430" height="932"><XCUIElementTypeButton type="XCUIElementTypeButton" label="{label}" x="20" y="{y}" width="100" height="44"/></XCUIElementTypeApplication>"#+ );+ elements::parse_tree(+ &xml,+ elements::View { screen: ScreenSize { width: 430.0, height: 932.0 }, orientation: None },+ )+ };+ let mut before = Seen::default();+ before.saw_tree(&tree("确定", 100));+ assert_eq!(compare(&before, Some(&tree("确定", 102)), None), Change::Same, "moved within the tolerance");+ assert_eq!(compare(&before, Some(&tree("确定", 300)), None), Change::Changed);+ assert_eq!(compare(&before, Some(&tree("取消", 100)), None), Change::Changed);+ // no tree after (a game, a map): the picture, if one was taken before+ assert_eq!(compare(&before, None, Some(&[0u8; 10])), Change::Unknown);+ let n = (imaging::THUMB_W * imaging::THUMB_H) as usize;+ let mut pic = Seen::default();+ pic.saw_thumb(vec![200; n]);+ assert_eq!(compare(&pic, None, Some(&vec![200; n])), Change::Same);+ // one small area changed (a switch flipped): the mean hardly moves, the tile does+ let mut flipped = vec![200u8; n];+ for y in 0..8 {+ for x in 0..8 {+ flipped[y * imaging::THUMB_W as usize + x] = 40;+ }+ }+ assert_eq!(compare(&pic, None, Some(&flipped)), Change::Changed);+ assert_eq!(compare(&Seen::default(), Some(&tree("确定", 100)), None), Change::Unknown);+ assert!(super::observe::change_text(Change::Unknown).is_empty());+ }++ /// 太久以前看过的界面不拿来比;拿走以后就没了+ #[test]+ fn seen_screens_are_taken_once() {+ use super::observe::Seen;+ let mut s = Seen::default();+ assert!(s.take_fresh().is_none());+ s.saw_thumb(vec![1]);+ assert!(s.take_fresh().is_some());+ assert!(s.take_fresh().is_none());+ }+/// 默认先短按电源键;记过这台设备上它不灵,就先用 WDA 的。两种都会试#[test]fn a_failed_lock_says_why_not_that_wda_is_down() {diff --git a/crates/ictl-daemon/src/tools/observe.rs b/crates/ictl-daemon/src/tools/observe.rsindex a2396cb..c37e196 100644--- a/crates/ictl-daemon/src/tools/observe.rs+++ b/crates/ictl-daemon/src/tools/observe.rs@@ -9,10 +9,13 @@ impl Daemon {&& let Some((t, tree)) = &g.elements_cache&& t.elapsed() <= max_age{- return Ok(tree.clone());+ let tree = tree.clone();+ g.dev.seen.saw_tree(&tree);+ return Ok(tree);}let tree = self.require_wda(g)?.tree().await?;g.elements_cache = Some((Instant::now(), tree.clone()));+ g.dev.seen.saw_tree(&tree);Ok(tree)}@@ -86,7 +89,9 @@ impl Daemon {Polled::FewElements(first) => {// 元素很少:改看画面let note = alert_note(&first);- return Ok(self.settle_visually(g, t0, max).await? + ¬e);+ let msg = self.settle_visually(g, t0, max).await?;+ let change = self.change_note(g, None).await;+ return Ok(msg + &change + ¬e);}Polled::Done { msg, settled, tree } => (msg, settled, tree),};@@ -95,9 +100,30 @@ impl Daemon {// 加载中的页面中间是空的:只在这种时候多看一眼画面(约 0.5 秒),平常不多花时间let screen = self.screen(g).await?;let msg = if settled && middle_is_empty(&tree, screen.height) { msg + &self.motion_note(g).await } else { msg };+ let change = self.change_note(g, Some(&tree)).await;+ g.dev.seen.saw_tree(&tree);// 紧接着的 then=elements 直接用这棵树g.elements_cache = Some((Instant::now(), tree));- Ok(msg + ¬e)+ Ok(msg + &change + ¬e)+ }++ /// 操作做完、界面稳定后,和操作前([`PerDevice::before_action`](crate::core::PerDevice))比有没有变化,+ /// 接在 settle 结果后面的说明。`tree`:稳定时读到的元素树(看画面判断稳定时为 None,用记下的画面指纹)。+ /// 操作前只截过图、没读过元素树时,补截一张图来比(约 0.3 秒);操作前什么都没看过就不说+ async fn change_note(&self, g: &mut Inner, tree: Option<&Tree>) -> String {+ let Some(before) = g.dev.before_action.take() else { return String::new() };+ let mut thumb = g.dev.seen.thumb.clone();+ if before.tree.as_ref().zip(tree).is_none()+ && before.thumb.is_some()+ && thumb.is_none()+ && let Some(w) = self.wda(g)+ && let Ok(png) = w.screenshot_png().await+ && let Ok(t) = thumbnail(png).await+ {+ g.dev.seen.saw_thumb(t.clone());+ thumb = Some(t);+ }+ change_text(compare(&before, tree, thumb.as_deref()))}pub(super) async fn settle_visually(@@ -107,11 +133,12 @@ impl Daemon {max: Duration,) -> crate::error::Result<String> {let deadline = t0 + max;- let w = self.require_wda(g)?;let mut prev: Option<Vec<u8>> = None;loop {- let png = w.screenshot_png().await?;+ let png = self.require_wda(g)?.screenshot_png().await?;let cur = thumbnail(png).await?;+ // 最后一帧就是操作后的画面:和操作前比([`Self::change_note`]),也是下一个操作的「操作前」+ g.dev.seen.saw_thumb(cur.clone());if let Some(p) = &prev {let m = imaging::thumb_motion(p, &cur);if m.mean < VISUAL_STILL {@@ -282,6 +309,70 @@ pub(super) fn no_elements_text(filter: &str, total: usize) -> String {}}+/// 有人读过的界面:元素树、画面指纹(截图时记下),从上一个操作做完以后算。+/// 下一个操作开始时它就是「操作前的界面」([`PerDevice::before_action`](crate::core::PerDevice))+#[derive(Debug, Clone, Default)]+pub(crate) struct Seen {+ at: Option<Instant>,+ pub tree: Option<Tree>,+ pub thumb: Option<Vec<u8>>,+}++/// 操作前看过的界面隔了这么久就不拿来比:中间画面可能自己变了(视频、轮播、来消息)+const SEEN_FRESH: Duration = Duration::from_secs(120);++impl Seen {+ pub fn saw_tree(&mut self, tree: &Tree) {+ self.at = Some(Instant::now());+ self.tree = Some(tree.clone());+ }++ pub fn saw_thumb(&mut self, thumb: Vec<u8>) {+ self.at = Some(Instant::now());+ self.thumb = Some(thumb);+ }++ /// 拿走记下的界面;太旧或什么都没有时为 None+ pub fn take_fresh(&mut self) -> Option<Seen> {+ let s = std::mem::take(self);+ s.at.is_some_and(|t| t.elapsed() < SEEN_FRESH).then_some(s)+ }+}++/// 操作前后界面比较的结果+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum Change {+ Changed,+ Same,+ /// 没有能比的:操作前没读过树也没截过图,或者前后一个是树一个是画面+ Unknown,+}++/// 先比元素树(文字、值、大小一样,位置差不超过 [`STILL_TOLERANCE`]),没有树再比画面指纹+/// (整体和每一小块都几乎没变才算一样:只有一个开关翻过来时整体平均差很小)+pub(super) fn compare(before: &Seen, tree: Option<&Tree>, thumb: Option<&[u8]>) -> Change {+ if let (Some(a), Some(b)) = (&before.tree, tree) {+ return if a.close_to(b, STILL_TOLERANCE) { Change::Same } else { Change::Changed };+ }+ if let (Some(a), Some(b)) = (&before.thumb, thumb) {+ let m = imaging::thumb_motion(a, b);+ return if m.mean < VISUAL_STILL && m.max_tile < LOCAL_MOTION { Change::Same } else { Change::Changed };+ }+ Change::Unknown+}++pub(super) fn change_text(c: Change) -> String {+ match c {+ Change::Changed => ictl_l10n::tr!(";和操作前相比界面有变化", "; the screen changed since before the action").into(),+ Change::Same => ictl_l10n::tr!(+ ";但界面和操作前一样:操作可能没生效(点在了空白处、被别的东西挡住,或 App 还没反应过来),先截图看清再决定,不要原样再做一遍",+ "; but the screen is the same as before the action: it may not have taken effect (it hit an empty spot, something covered the target, or the app hasn't reacted yet); take a screenshot before deciding, rather than repeating the same action"+ )+ .into(),+ Change::Unknown => String::new(),+ }+}+/// An element as data: the text it shows (its label, else its name, else its value) and its boxpub(super) fn element_data(e: &elements::Element) -> ElementData {let text = [&e.label, &e.name, &e.value].into_iter().find(|s| !s.is_empty()).cloned().unwrap_or_default();diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rsindex ab7dfd5..2d53ed2 100644--- a/crates/ictl-mcp/src/lib.rs+++ b/crates/ictl-mcp/src/lib.rs@@ -71,7 +71,7 @@ pub const BATCH_TOOLS: [&str; 11] = [fn then_props() -> Value {json!({"then": {"type": "string", "enum": ["none", "elements", "screenshot"], "default": "none",- "description": ictl_l10n::tr!("操作后等界面稳定,再顺带返回界面:elements=元素列表(最多 80 个),screenshot=截图。省一次单独的调用", "After the action, wait for the screen to settle and return it: elements = element list (up to 80), screenshot = screenshot. Saves a separate call")},+ "description": ictl_l10n::tr!("操作后等界面稳定,再顺带返回界面:elements=元素列表(最多 80 个),screenshot=截图。省一次单独的调用。操作前看过界面(截图、读元素)时,还会说明和操作前相比界面变没变;没变说明操作可能没生效", "After the action, wait for the screen to settle and return it: elements = element list (up to 80), screenshot = screenshot. Saves a separate call. If the screen was looked at before the action (screenshot, element list), it also says whether the screen changed since; no change means the action may not have taken effect")},"then_filter": {"type": "string", "default": "", "description": ictl_l10n::tr!("then=elements 时只列包含这段文字的元素", "With then=elements: only list elements containing this text")},"then_region": {"type": "array", "items": {"type": "number"}, "minItems": 4, "maxItems": 4,"description": ictl_l10n::tr!("then=screenshot 时只返回这块区域的放大图 [x, y, width, height](点),例如游戏棋盘", "With then=screenshot: only return this region, enlarged, as [x, y, width, height] (points), e.g. a game board")},diff --git a/crates/ictl-unlock/src/fake.rs b/crates/ictl-unlock/src/fake.rsindex d4fa4bb..52b753f 100644--- a/crates/ictl-unlock/src/fake.rs+++ b/crates/ictl-unlock/src/fake.rs@@ -194,7 +194,12 @@ impl FakeLockScreen {("GET", "/appium/settings") => json!({"waitForIdleTimeout": s.idle.0, "animationCoolOffTimeout": s.idle.1}),("POST", "/appium/settings") => {let b = &body.unwrap()["settings"];- s.idle = (b["waitForIdleTimeout"].as_f64().unwrap(), b["animationCoolOffTimeout"].as_f64().unwrap());+ // other settings (the active app detection point) leave the wait settings as they are+ if let (Some(idle), Some(cool)) =+ (b["waitForIdleTimeout"].as_f64(), b["animationCoolOffTimeout"].as_f64())+ {+ s.idle = (idle, cool);+ }Value::Null}// iOS 27:Home 只唤醒/收起键,半截输入还在,键盘界面也还在(键隐藏但仍能按)diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rsindex a328e59..7c133b5 100644--- a/crates/ictl-wda/src/client.rs+++ b/crates/ictl-wda/src/client.rs@@ -121,6 +121,14 @@ pub fn next_snapshot_level(level: usize, took: Option<Duration>) -> usize {}}+/// WDA 判断前台 App 用的点(见 [`WdaClient::move_detection_point`]):横竖屏都在屏幕里、在通知横幅和灵动岛底下。+/// 取短边的一半,横竖都一样:竖屏在屏幕上部偏中间(430×932 的 iPhone 上是 (215, 215),横幅最低到 125 左右),+/// 横屏在中间偏左+pub fn detection_point(screen: ScreenSize) -> (u32, u32) {+ let half = (screen.width.min(screen.height) / 2.0).round() as u32;+ (half, half)+}+/// 改变手机状态的请求:没有应答时要结束会话,免得它和排在它后面的请求过一阵才执行(见 [`WdaClient::in_session`])。/// 读的请求(GET、`POST /elements` 找元素)不算:排在读后面的东西不会动手机,结束会话只会让下一次开会话也排到它后面fn acts(method: &str, path: &str) -> bool {@@ -204,6 +212,8 @@ pub struct WdaClient<T> {snapshot_applied: Option<usize>,/// 上一次读到的元素树用的上限([`Self::snapshot_note`])snapshot_read: usize,+ /// WDA 判断前台 App 的点已经挪过([`Self::detection_point`])。这个值在 WDA 进程里一直有效,换会话也不重置+ detection_point_set: bool,}impl<T: Transport> WdaClient<T> {@@ -222,6 +232,7 @@ impl<T: Transport> WdaClient<T> {snapshot_level: 0,snapshot_applied: None,snapshot_read: 0,+ detection_point_set: false,}}@@ -686,9 +697,31 @@ impl<T: Transport> WdaClient<T> {/// 元素树,带上「谁盖住谁」「有没有加载圈」等信息pub async fn tree(&mut self) -> Result<elements::Tree> {let view = self.view().await?;+ self.move_detection_point(view.screen).await;Ok(elements::parse_tree(&self.source_xml().await?, view))}+ /// 把 WDA 判断前台 App 的点(appium setting `activeAppDetectionPoint`)挪到 [`detection_point`],每个客户端做一次。+ ///+ /// WDA 读元素树、问前台 App 时,看屏幕上这个点下面的元素属于哪个进程。默认点在离左上角短边 20% 的地方+ /// (WDA 16.15.3 `FBActiveAppDetectionPoint`,430 点宽的 iPhone 上是 (86, 86)),正好在通知横幅底下:横幅弹着时+ /// 读到的是 SpringBoard 的树,按名字点 App 里的按钮就找不到(iPhone16,2 / iOS 27.2.1 的备忘录,「Device Hub」横幅)。+ /// 设不上不影响读树,只是还用默认的点;连不上 WDA 时下次再试+ async fn move_detection_point(&mut self, screen: ScreenSize) {+ if self.detection_point_set {+ return;+ }+ let (x, y) = detection_point(screen);+ let body = json!({"settings": {"activeAppDetectionPoint": format!("{x},{y}")}});+ match self.post("/appium/settings", body).await {+ Ok(_) => self.detection_point_set = true,+ Err(e) => {+ tracing::debug!("activeAppDetectionPoint: {e}");+ self.detection_point_set = !matches!(e, WdaError::Unavailable(_));+ }+ }+ }+/// 点击:一个 W3C actions 单指手势(按下 50ms),期间把等待设置临时调小。真机计时(iOS 27):/// - `/wda/tap` 先等界面空闲:主屏点图标约 1.7 秒(调小等待也没用),App 里约 0.6 秒,锁屏上约 2.9 秒/// - actions 手势做完要等动画冷却(`animationCoolOffTimeout`,默认 2 秒):App 里切标签约 1.9 秒@@ -1597,4 +1630,34 @@ mod tests {assert_eq!(t.body(5)["settings"]["snapshotMaxChildren"], i32::MAX);assert_eq!(sent.len(), 8, "the last read needs no settings: {sent:?}");}++ #[test]+ fn the_detection_point_is_below_banners_in_either_orientation() {+ assert_eq!(detection_point(ScreenSize { width: 430.0, height: 932.0 }), (215, 215));+ assert_eq!(detection_point(ScreenSize { width: 932.0, height: 430.0 }), (215, 215));+ assert_eq!(detection_point(ScreenSize { width: 744.0, height: 1133.0 }), (372, 372));+ }++ /// 第一次读元素树时挪一次判断前台 App 的点,之后不再设+ #[tokio::test]+ async fn the_first_tree_read_moves_the_detection_point_once() {+ let xml = r#"{"value":"<XCUIElementTypeApplication/>"}"#;+ let t = Script::new(vec![+ ok(r#"{"value":{"screenSize":{"width":430,"height":932}}}"#),+ ok(r#"{"sessionId":"A"}"#),+ ok(r#"{"value":"PORTRAIT"}"#),+ ok(r#"{"value":null}"#),+ ok(xml),+ ok(r#"{"value":"PORTRAIT"}"#),+ ok(xml),+ ]);+ let mut c = WdaClient::new(&t);+ c.tree().await.unwrap();+ c.tree().await.unwrap();+ let sent = t.sent();+ assert_eq!(sent[3], "POST /session/A/appium/settings", "{sent:?}");+ assert_eq!(t.body(3)["settings"], json!({"activeAppDetectionPoint": "215,215"}));+ assert_eq!(sent.len(), 7, "{sent:?}");+ assert!(sent[6].starts_with("GET /source?"));+ }}