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
等界面稳定:游戏等没有元素树的界面改看画面;then 可只返回某块区域、可调等待上限
Derrorsa7102288dadb
diff --git a/crates/ictl-daemon/src/imaging.rs b/crates/ictl-daemon/src/imaging.rsindex 3da6d5b..12c1389 100644--- a/crates/ictl-daemon/src/imaging.rs+++ b/crates/ictl-daemon/src/imaging.rs@@ -47,6 +47,24 @@ fn filter_for(from: (u32, u32), to: (u32, u32)) -> FilterType {if to.0 > from.0 || to.1 > from.1 { FilterType::CatmullRom } else { FilterType::Triangle }}+/// 画面「指纹」:缩成 THUMB_W×THUMB_H 的灰度图。用来判断没有元素树的界面(游戏、地图)动画是否停了+pub const THUMB_W: u32 = 48;+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| format!("截图解码失败:{e}"))?;+ // 最近邻足够:只比较前后两帧,不看画质;比三角滤波快一个数量级+ Ok(img.resize_exact(THUMB_W, THUMB_H, FilterType::Nearest).into_luma8().into_raw())+}++/// 两个指纹的平均逐像素差(0~255)。尺寸不同算完全不同+pub fn thumb_diff(a: &[u8], b: &[u8]) -> f64 {+ if a.len() != b.len() || a.is_empty() {+ return 255.0;+ }+ a.iter().zip(b).map(|(x, y)| f64::from(x.abs_diff(*y))).sum::<f64>() / a.len() as f64+}+/// 整屏缩放到点尺寸:图像像素即点坐标。返回 (jpeg, 说明文字)pub fn full_screen(png: &[u8], screen: ScreenSize, via: &str) -> Result<(Vec<u8>, String), String> {let img = decode(png)?;@@ -199,6 +217,20 @@ mod tests {);}+ #[test]+ fn thumbnails_tell_still_from_changed() {+ let a = thumbnail(&png(1290, 2796)).unwrap();+ assert_eq!(a.len(), (THUMB_W * THUMB_H) as usize);+ assert_eq!(thumb_diff(&a, &a), 0.0);+ let mut out = Cursor::new(Vec::new());+ image::RgbImage::from_pixel(1290, 2796, image::Rgb([200, 200, 200]))+ .write_to(&mut out, image::ImageFormat::Png)+ .unwrap();+ let b = thumbnail(&out.into_inner()).unwrap();+ assert!(thumb_diff(&a, &b) > 50.0);+ assert_eq!(thumb_diff(&a, &[]), 255.0);+ }+#[test]fn png_size_reads_header() {assert_eq!(png_size(&png(12, 34)), Some((12, 34)));diff --git a/crates/ictl-daemon/src/tools.rs b/crates/ictl-daemon/src/tools.rsindex ccf4943..f837b12 100644--- a/crates/ictl-daemon/src/tools.rs+++ b/crates/ictl-daemon/src/tools.rs@@ -14,6 +14,10 @@ use crate::protocol::Response;/// 锁屏后至少等这么久再自动解锁:锁屏过渡没走完就唤醒,WDA 第一下上滑卡约 16 秒后报 `point.x != INFINITY`pub(crate) const LOCK_SETTLE: Duration = Duration::from_secs(3);+/// 元素少于这么多个就按画面判断是否稳定(游戏只有几个状态栏元素;普通 App 页面通常几十个)+const VISUAL_SETTLE_BELOW: usize = 12;+/// 两帧缩略图平均逐像素差低于这个值算静止(0~255)。游戏背景的轻微摆动约 1~2,消除动画几十+const VISUAL_STILL: f64 = 3.0;/// 按 Home 后最多等这么久,确认主屏到了前台const HOME_SETTLE: Duration = Duration::from_secs(2);const SPRINGBOARD: &str = "com.apple.springboard";@@ -189,33 +193,60 @@ impl Daemon {Ok(if lines.is_empty() { "没有找到带文字的元素".into() } else { lines.join("\n") } + &more)}- /// 等界面稳定:每隔一小会儿读一次元素树,连续两次一样就算稳定。读元素树时 WDA 本身也会等界面空闲。- /// 游戏这类元素很少的界面会马上判为稳定,看画面要截图+ /// 等界面稳定,最多等 `max`:+ /// - 有元素树的界面:连续两次读到的元素一样(读元素树时 WDA 本身也会等界面空闲)+ /// - 元素很少的界面(游戏、地图,画面变化不反映在元素树里):改看画面,连续两帧缩略图几乎一样。+ /// 截图约 0.2 秒一张,两帧之间再隔一点,避免两帧落在同一段静止的过渡里pub(crate) async fn settle(&self, g: &mut Inner, max: Duration) -> Result<String, String> {let t0 = Instant::now();let Some(w) = self.wda(g) else {tokio::time::sleep(max.min(Duration::from_millis(500))).await;return Ok("WDA 不可用,等了 0.5 秒".into());};- let mut prev: Option<Vec<elements::Element>> = None;+ let first = w.elements().await.map_err(|e| e.to_string())?;+ if first.len() < VISUAL_SETTLE_BELOW {+ return self.settle_visually(g, t0, max).await;+ }+ let mut prev = first;let msg = loop {+ // 读元素树时 WDA 本身会等界面空闲,两次之间不用再多等+ tokio::time::sleep(Duration::from_millis(50)).await;let cur = w.elements().await.map_err(|e| e.to_string())?;- if prev.as_ref() == Some(&cur) {+ let same = cur == prev;+ prev = cur;+ if same {break format!("界面已稳定({:.1} 秒)", t0.elapsed().as_secs_f64());}if t0.elapsed() >= max {- prev = Some(cur);break format!("{:.1} 秒内界面一直在变(可能有动画),按最后的状态返回", max.as_secs_f64());}- prev = Some(cur);- // 读元素树时 WDA 本身会等界面空闲,两次之间不用再多等- tokio::time::sleep(Duration::from_millis(50)).await;};// 紧接着的 then=elements 直接用这棵树- g.elements_cache = prev.map(|els| (Instant::now(), els));+ g.elements_cache = Some((Instant::now(), prev));Ok(msg)}+ async fn settle_visually(&self, g: &mut Inner, t0: Instant, max: Duration) -> Result<String, String> {+ let w = self.require_wda(g)?;+ let mut prev: Option<Vec<u8>> = None;+ loop {+ let png = w.screenshot_png().await.map_err(|e| e.to_string())?;+ let cur = tokio::task::spawn_blocking(move || imaging::thumbnail(&png))+ .await+ .map_err(|e| format!("图像处理任务异常:{e}"))??;+ if let Some(p) = &prev+ && imaging::thumb_diff(p, &cur) < VISUAL_STILL+ {+ return Ok(format!("画面已静止({:.1} 秒)", t0.elapsed().as_secs_f64()));+ }+ if t0.elapsed() >= max {+ return Ok(format!("{:.1} 秒内画面一直在动,按最后的状态返回", max.as_secs_f64()));+ }+ prev = Some(cur);+ tokio::time::sleep(Duration::from_millis(150)).await;+ }+ }+/// 等包含 `text` 的元素出现pub(crate) async fn wait_for(&self, g: &mut Inner, text: &str, timeout: Duration) -> Result<String, String> {self.ensure_unlocked(g).await?;diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rsindex db75732..1e74efc 100644--- a/crates/ictl-mcp/src/lib.rs+++ b/crates/ictl-mcp/src/lib.rs@@ -64,7 +64,11 @@ fn then_props() -> Value {json!({"then": {"type": "string", "enum": ["none", "elements", "screenshot"], "default": "none","description": "操作后等界面稳定,再顺带返回界面:elements=元素列表(最多 80 个),screenshot=截图。省一次单独的调用"},- "then_filter": {"type": "string", "default": "", "description": "then=elements 时只列包含这段文字的元素"}+ "then_filter": {"type": "string", "default": "", "description": "then=elements 时只列包含这段文字的元素"},+ "then_region": {"type": "array", "items": {"type": "number"}, "minItems": 4, "maxItems": 4,+ "description": "then=screenshot 时只返回这块区域的放大图 [x, y, width, height](点),例如游戏棋盘"},+ "then_settle": {"type": "number", "default": 1.5,+ "description": "顺带返回界面前最多等几秒让界面稳定(不超过 10)。游戏、地图按画面是否静止判断,消除连锁等长动画可调大,画面一静止就返回"}})}@@ -290,17 +294,41 @@ pub fn to_request(name: &str, args: &Map<String, Value>) -> Result<Request, Stripub enum Then {None,Elements(String),- Screenshot,+ Screenshot(Option<(f64, f64, f64, f64)>),}-pub fn parse_then(args: &Map<String, Value>) -> Result<Then, String> {+/// then 带的选项:返回什么 + 最多等多久让界面稳定+#[derive(Debug, Clone, PartialEq)]+pub struct ThenOpts {+ pub then: Then,+ pub settle_ms: u64,+}++pub fn parse_then(args: &Map<String, Value>) -> Result<ThenOpts, String> {let a = Args(args);- match a.s_or("then", "none")?.as_str() {- "none" | "" => Ok(Then::None),- "elements" => Ok(Then::Elements(a.s_or("then_filter", "")?)),- "screenshot" => Ok(Then::Screenshot),- other => Err(format!("then 只能是 none / elements / screenshot,不是 {other}")),+ let then = match a.s_or("then", "none")?.as_str() {+ "none" | "" => Then::None,+ "elements" => Then::Elements(a.s_or("then_filter", "")?),+ "screenshot" => {+ let region = match a.get("then_region") {+ None => None,+ Some(v) => {+ let xs: Option<Vec<f64>> = v.as_array().map(|arr| arr.iter().filter_map(number).collect());+ match xs.as_deref() {+ Some([x, y, w, h]) if *w > 0.0 && *h > 0.0 => Some((*x, *y, *w, *h)),+ _ => return Err("then_region 要是 [x, y, width, height] 四个数,宽高大于 0".into()),+ }+ }+ };+ Then::Screenshot(region)+ }+ other => return Err(format!("then 只能是 none / elements / screenshot,不是 {other}")),+ };+ let secs = a.f_or("then_settle", THEN_SETTLE_MS as f64 / 1000.0)?;+ if !(0.0..=10.0).contains(&secs) {+ return Err("then_settle 要在 0 到 10 秒之间".into());}+ Ok(ThenOpts { then, settle_ms: (secs * 1000.0) as u64 })}/// 批量里的一步@@ -397,11 +425,12 @@ impl ServerHandler for McpServer {Err(e) => return Ok(to_result(Response::error(e)).into()),};// then 只对操作类工具有意义;看界面的工具本身就是返回界面- let then = if req.is_device_action() { then } else { Then::None };let resp = self.call(&req).await;- Ok(match (resp, then) {- (Response::Text { text }, then) if then != Then::None => self.finish(text, false, then).await,- (resp, _) => to_result(resp),+ Ok(match resp {+ Response::Text { text } if req.is_device_action() && then.then != Then::None => {+ self.finish(text, false, then).await+ }+ resp => to_result(resp),}.into())}@@ -416,14 +445,15 @@ impl McpServer {}/// 操作完成后:按 then 等界面稳定,再附上元素列表或截图- async fn finish(&self, mut text: String, failed: bool, then: Then) -> CallToolResult {+ async fn finish(&self, mut text: String, failed: bool, opts: ThenOpts) -> CallToolResult {let done = |blocks: Vec<ContentBlock>| {if failed { CallToolResult::error(blocks) } else { CallToolResult::success(blocks) }};+ let then = opts.then;if then == Then::None {return done(vec![ContentBlock::text(text)]);}- match self.call(&Request::Settle { max_ms: THEN_SETTLE_MS }).await {+ match self.call(&Request::Settle { max_ms: opts.settle_ms }).await {Response::Text { text: t } => text += &format!("\n{t}"),Response::Error { message } => text += &format!("\n(等界面稳定失败:{message})"),Response::Image { .. } => {}@@ -439,7 +469,7 @@ impl McpServer {}done(vec![ContentBlock::text(text)])}- Then::Screenshot => match self.call(&Request::Screenshot { region: None }).await {+ Then::Screenshot(region) => match self.call(&Request::Screenshot { region }).await {Response::Image { jpeg_base64, caption } => done(vec![ContentBlock::text(text),ContentBlock::image(jpeg_base64, "image/jpeg"),@@ -453,7 +483,7 @@ impl McpServer {}/// 按顺序执行;某一步出错就停,说明是第几步、后面几步没执行。出错时也按 then 附上当前界面,方便看停在哪- async fn batch(&self, args: &Map<String, Value>, then: Then) -> CallToolResult {+ async fn batch(&self, args: &Map<String, Value>, then: ThenOpts) -> CallToolResult {let steps = match batch_steps(args) {Ok(s) => s,Err(e) => return to_result(Response::error(e)),@@ -559,13 +589,19 @@ mod tests {for n in ["iphone_status", "iphone_screenshot", "iphone_list_elements", "iphone_wait_for"] {assert!(!has_then(n), "{n}");}- assert_eq!(parse_then(&Map::new()).unwrap(), Then::None);+ let then = |v: Value| parse_then(&args(v)).map(|o| o.then);+ assert_eq!(parse_then(&Map::new()).unwrap(), ThenOpts { then: Then::None, settle_ms: THEN_SETTLE_MS });+ assert_eq!(then(json!({"then": "elements", "then_filter": "设置"})).unwrap(), Then::Elements("设置".into()));+ assert_eq!(then(json!({"then": "screenshot"})).unwrap(), Then::Screenshot(None));assert_eq!(- parse_then(&args(json!({"then": "elements", "then_filter": "设置"}))).unwrap(),- Then::Elements("设置".into())+ then(json!({"then": "screenshot", "then_region": [0, 295, 430, 460]})).unwrap(),+ Then::Screenshot(Some((0.0, 295.0, 430.0, 460.0))));- assert_eq!(parse_then(&args(json!({"then": "screenshot"}))).unwrap(), Then::Screenshot);- assert!(parse_then(&args(json!({"then": "video"}))).is_err());+ assert!(then(json!({"then": "screenshot", "then_region": [0, 1, 2]})).is_err());+ assert!(then(json!({"then": "screenshot", "then_region": [0, 1, 0, 5]})).is_err());+ assert!(then(json!({"then": "video"})).is_err());+ assert_eq!(parse_then(&args(json!({"then": "screenshot", "then_settle": 5}))).unwrap().settle_ms, 5000);+ assert!(parse_then(&args(json!({"then_settle": 30}))).is_err());}#[test]diff --git a/docs/capability-matrix.md b/docs/capability-matrix.mdindex a594669..0942a48 100644--- a/docs/capability-matrix.md+++ b/docs/capability-matrix.md@@ -42,7 +42,7 @@| `iphone_open_url` | WDA `/url` | WDA 会话 `/url`(idevice 未封装,自己发) | 需自写 | — || `iphone_wait_for`(新增) | 无 | 守护进程轮询元素树,出现即返回 | 已实现 | 只认元素树里的文字,游戏等没有元素的界面要截图 || `iphone_batch`(新增) | 无 | MCP 层按顺序调用守护进程,出错或按名字没点到即停;步骤先全部校验再执行;`reuse_elements` 时按名字点击复用守护进程缓存的元素树(10 秒内,任何其他操作都会让缓存作废) | 已实现 | 步骤间不看界面,只适合结果确定的连续操作;`reuse_elements` 只用于不改变布局的连按,误用时下一步多半找不到元素而停下 |-| 操作类工具的 `then` 参数(新增) | 无 | 操作后 `Settle`(连续两次元素树一样,最多 1.5 秒),再附元素列表或截图 | 已实现 | 每次多 0.5~1.3 秒等稳定,换一次往返 |+| 操作类工具的 `then` 参数(新增) | 无 | 操作后 `Settle`,再附元素列表或截图(`then_region` 只返回某块区域的放大图)。有元素树的界面看连续两次元素树是否一样;元素少于 12 个的界面(游戏、地图)改看画面:48×104 灰度缩略图连续两帧平均差 < 3 算静止。最多等 `then_settle` 秒(默认 1.5,最多 10) | 已实现 | 每次多 0.5~1.3 秒等稳定,换一次往返;画面一直有小动画的界面会等满上限 |## 3. 后台能力