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

元素树复用、等界面稳定提速;批量里按名字没点到就停

Derrors66ec4971db76
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index a25a944..cfd25fb 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -113,6 +113,8 @@ pub(crate) struct Inner {
pub last_lock: Option<Instant>,
/// HID 会话最近一次使用的时间;空闲超过 [`crate::supervise::HID_IDLE`] 就关掉(它持有屏幕媒体流)
pub hid_used: Option<Instant>,
+ /// 最近一次读到的元素树。只在调用方允许(max_age_ms)时复用;改变界面的操作做完就清掉
+ pub elements_cache: Option<(Instant, Vec<ictl_wda::Element>)>,
pub dedup: Dedup,
pub next_resign: Instant,
pub next_session_check: Instant,
@@ -172,6 +174,7 @@ impl Daemon {
offline_since: Some(now),
last_lock: None,
hid_used: None,
+ elements_cache: None,
dedup: Dedup::default(),
// 启动一分钟后再做第一次重签检查和会话验证,先让设备就绪
next_resign: now + Duration::from_secs(60),
@@ -234,6 +237,7 @@ impl Daemon {
r.stop();
}
g.wda = None;
+ g.elements_cache = None;
drop_tunnel(g).await;
g.wda_misses.reset();
}
@@ -308,6 +312,9 @@ impl Daemon {
STALE.as_secs()
));
}
+ // 改变界面的操作做完后缓存的元素树就作废;只有调用方声明「不改变布局」的按名字点击(max_age_ms > 0)保留
+ let keeps_cache = matches!(req, Request::TapElement { max_age_ms, .. } if max_age_ms > 0);
+ let invalidates = req.is_device_action() && !keeps_cache;
let r = match req {
Request::Status => Ok(self.status_text(g).await),
Request::Screenshot { region } => {
@@ -315,9 +322,13 @@ impl Daemon {
self.publish(g);
return resp;
}
- Request::ListElements { filter, limit } => self.list_elements(g, &filter, limit).await,
+ Request::ListElements { filter, limit, max_age_ms } => {
+ self.list_elements(g, &filter, limit, Duration::from_millis(max_age_ms)).await
+ }
Request::Tap { x, y } => self.tap(g, x, y).await,
- Request::TapElement { text, index } => self.tap_element(g, &text, index).await,
+ Request::TapElement { text, index, max_age_ms } => {
+ self.tap_element(g, &text, index, Duration::from_millis(max_age_ms)).await
+ }
Request::LongPress { x, y, seconds } => self.long_press(g, x, y, seconds).await,
Request::Swipe { from, to, seconds } => self.swipe(g, from, to, seconds).await,
Request::TypeText { text, submit } => self.type_text(g, &text, submit).await,
@@ -339,6 +350,9 @@ impl Daemon {
}
Request::Daemon | Request::Resign { .. } => unreachable!("上面已处理"),
};
+ if invalidates {
+ g.elements_cache = None;
+ }
self.publish(g);
r.map(Response::text).unwrap_or_else(Response::error)
}
diff --git a/crates/ictl-daemon/src/tools.rs b/crates/ictl-daemon/src/tools.rs
index 3aafd5d..ccf4943 100644
--- a/crates/ictl-daemon/src/tools.rs
+++ b/crates/ictl-daemon/src/tools.rs
@@ -156,9 +156,28 @@ impl Daemon {
Ok(Response::Image { jpeg_base64: base64::engine::general_purpose::STANDARD.encode(jpeg), caption })
}
- pub(crate) async fn list_elements(&self, g: &mut Inner, filter: &str, limit: usize) -> Result<String, String> {
- self.ensure_unlocked(g).await?;
+ /// 当前界面的元素树。缓存不超过 `max_age` 就直接用(0 = 总是重读);重读的结果写回缓存
+ async fn tree(&self, g: &mut Inner, max_age: Duration) -> Result<Vec<elements::Element>, String> {
+ if !max_age.is_zero()
+ && let Some((t, els)) = &g.elements_cache
+ && t.elapsed() <= max_age
+ {
+ return Ok(els.clone());
+ }
let els = self.require_wda(g)?.elements().await.map_err(|e| e.to_string())?;
+ g.elements_cache = Some((Instant::now(), els.clone()));
+ Ok(els)
+ }
+
+ pub(crate) async fn list_elements(
+ &self,
+ g: &mut Inner,
+ filter: &str,
+ limit: usize,
+ max_age: Duration,
+ ) -> Result<String, String> {
+ self.ensure_unlocked(g).await?;
+ let els = self.tree(g, max_age).await?;
let shown: Vec<&elements::Element> =
if filter.is_empty() { els.iter().collect() } else { elements::filter(&els, filter) };
let lines: Vec<_> = shown.iter().take(limit).map(|e| e.describe()).collect();
@@ -178,19 +197,23 @@ impl Daemon {
tokio::time::sleep(max.min(Duration::from_millis(500))).await;
return Ok("WDA 不可用,等了 0.5 秒".into());
};
- let mut prev: Option<Vec<String>> = None;
- loop {
- let cur: Vec<String> =
- w.elements().await.map_err(|e| e.to_string())?.iter().map(elements::Element::describe).collect();
+ let mut prev: Option<Vec<elements::Element>> = None;
+ let msg = loop {
+ let cur = w.elements().await.map_err(|e| e.to_string())?;
if prev.as_ref() == Some(&cur) {
- return Ok(format!("界面已稳定({:.1} 秒)", t0.elapsed().as_secs_f64()));
+ break format!("界面已稳定({:.1} 秒)", t0.elapsed().as_secs_f64());
}
if t0.elapsed() >= max {
- return Ok(format!("{:.1} 秒内界面一直在变(可能有动画),按最后的状态返回", max.as_secs_f64()));
+ prev = Some(cur);
+ break format!("{:.1} 秒内界面一直在变(可能有动画),按最后的状态返回", max.as_secs_f64());
}
prev = Some(cur);
- tokio::time::sleep(Duration::from_millis(150)).await;
- }
+ // 读元素树时 WDA 本身会等界面空闲,两次之间不用再多等
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ };
+ // 紧接着的 then=elements 直接用这棵树
+ g.elements_cache = prev.map(|els| (Instant::now(), els));
+ Ok(msg)
}
/// 等包含 `text` 的元素出现
@@ -225,10 +248,15 @@ impl Daemon {
Ok(format!("已点击 {pos}(经 HID)"))
}
- pub(crate) async fn tap_element(&self, g: &mut Inner, text: &str, index: usize) -> Result<String, String> {
+ pub(crate) async fn tap_element(
+ &self,
+ g: &mut Inner,
+ text: &str,
+ index: usize,
+ max_age: Duration,
+ ) -> Result<String, String> {
self.ensure_unlocked(g).await?;
- let w = self.require_wda(g)?;
- let els = w.elements().await.map_err(|e| e.to_string())?;
+ let els = self.tree(g, max_age).await?;
let matches = elements::find(&els, text);
if matches.is_empty() {
return Ok(format!("没找到包含 \"{text}\" 的元素,先用 iphone_list_elements 或截图看看屏幕"));
@@ -238,7 +266,7 @@ impl Daemon {
return Ok(format!("只匹配到 {} 个:\n{}", matches.len(), list.join("\n")));
}
let e = matches[index];
- w.tap(e.center.0 as f64, e.center.1 as f64).await.map_err(|e| e.to_string())?;
+ self.require_wda(g)?.tap(e.center.0 as f64, e.center.1 as f64).await.map_err(|e| e.to_string())?;
let note = if matches.len() > 1 {
format!("(共匹配 {} 个,点的是第 {index} 个)", matches.len())
} else {
diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs
index 644949b..db75732 100644
--- a/crates/ictl-mcp/src/lib.rs
+++ b/crates/ictl-mcp/src/lib.rs
@@ -42,6 +42,8 @@ pub const THEN_LIMIT: usize = 80;
pub const THEN_SETTLE_MS: u64 = 1500;
/// 一次批量最多几步
pub const BATCH_MAX_STEPS: usize = 20;
+/// reuse_elements 时按名字点击复用多旧的元素树(毫秒)
+pub const BATCH_REUSE_MS: u64 = 10_000;
/// 批量里能用的工具:改变界面的操作和等待;看界面用 then
pub const BATCH_TOOLS: [&str; 11] = [
"iphone_tap",
@@ -180,9 +182,11 @@ iphone_wait_for,以及 {\"tool\": \"wait\", \"seconds\": 秒数}(不超过 5)。
适合确定的连续操作;每步的结果不确定(例如点了以后不知道会跳到哪)时,还是一步步来。\n\
then 同其他操作工具:全部做完后顺带返回界面。",
schema(
- with_then(
- json!({"steps": {"type": "array", "items": {"type": "object"}, "description": "要执行的步骤"}}),
- ),
+ with_then(json!({
+ "steps": {"type": "array", "items": {"type": "object"}, "description": "要执行的步骤"},
+ "reuse_elements": {"type": "boolean", "default": false,
+ "description": "这批操作不改变界面布局时(例如在同一个键盘上连按)设为 true:按名字点击复用最近读到的元素树,每步省 0.3~0.8 秒。会跳转页面的不要用,否则可能点到旧位置"}
+ })),
&["steps"],
),
),
@@ -253,9 +257,11 @@ pub fn to_request(name: &str, args: &Map<String, Value>) -> Result<Request, Stri
};
Request::Screenshot { region }
}
- "iphone_list_elements" => Request::ListElements { filter: a.s_or("filter", "")?, limit: a.u_or("limit", 150)? },
+ "iphone_list_elements" => {
+ Request::ListElements { filter: a.s_or("filter", "")?, limit: a.u_or("limit", 150)?, max_age_ms: 0 }
+ }
"iphone_tap" => Request::Tap { x: a.f("x")?, y: a.f("y")? },
- "iphone_tap_element" => Request::TapElement { text: a.s("text")?, index: a.u_or("index", 0)? },
+ "iphone_tap_element" => Request::TapElement { text: a.s("text")?, index: a.u_or("index", 0)?, max_age_ms: 0 },
"iphone_long_press" => Request::LongPress { x: a.f("x")?, y: a.f("y")?, seconds: a.f_or("seconds", 1.0)? },
"iphone_swipe" => Request::Swipe {
from: (a.f("from_x")?, a.f("from_y")?),
@@ -307,6 +313,7 @@ pub enum Step {
/// 检查并转换批量步骤(一步都不执行就先把参数错误全挡掉)
pub fn batch_steps(args: &Map<String, Value>) -> Result<Vec<Step>, String> {
let steps = args.get("steps").and_then(Value::as_array).ok_or("缺少 steps(数组)")?;
+ let reuse = Args(args).b_or("reuse_elements", false)?;
if steps.is_empty() || steps.len() > BATCH_MAX_STEPS {
return Err(format!("steps 要有 1 到 {BATCH_MAX_STEPS} 步"));
}
@@ -327,12 +334,22 @@ pub fn batch_steps(args: &Map<String, Value>) -> Result<Vec<Step>, String> {
}
return Ok(Step::Wait(std::time::Duration::from_secs_f64(secs)));
}
- let req = to_request(tool, obj).map_err(|e| format!("第 {n} 步({tool}):{e}"))?;
+ let req = match to_request(tool, obj).map_err(|e| format!("第 {n} 步({tool}):{e}"))? {
+ Request::TapElement { text, index, .. } if reuse => {
+ Request::TapElement { text, index, max_age_ms: BATCH_REUSE_MS }
+ }
+ other => other,
+ };
Ok(Step::Request { tool: tool.to_owned(), req })
})
.collect()
}
+/// tap_element 的结果是不是「没点到」(没找到、或 index 超出匹配个数)
+pub fn tap_missed(text: &str) -> bool {
+ text.starts_with("没找到") || text.starts_with("只匹配到")
+}
+
/// 守护进程响应 → MCP 结果。错误走工具错误(is_error),文字原样给客户端
pub fn to_result(r: Response) -> CallToolResult {
match r {
@@ -413,7 +430,9 @@ impl McpServer {
}
match then {
Then::Elements(filter) => {
- match self.call(&Request::ListElements { filter, limit: THEN_LIMIT }).await {
+ // Settle 刚读过元素树,直接用它
+ match self.call(&Request::ListElements { filter, limit: THEN_LIMIT, max_age_ms: THEN_SETTLE_MS }).await
+ {
Response::Text { text: t } => text += &format!("\n--- 操作后的界面 ---\n{t}"),
Response::Error { message } => text += &format!("\n(读界面失败:{message})"),
Response::Image { .. } => {}
@@ -449,6 +468,14 @@ impl McpServer {
lines.push(format!("{n}. wait → 等了 {} 秒", d.as_secs_f64()));
}
Step::Request { tool, req } => match self.call(&req).await {
+ // 按名字没点到(toolkit 兼容:单独调用时是普通结果)在批量里要停下:后面的步骤都建立在它点中的前提上
+ Response::Text { text } if tool == "iphone_tap_element" && tap_missed(&text) => {
+ lines.push(format!("{n}. {tool} → {text}"));
+ if n < total {
+ lines.push(format!("第 {n} 步没点到,后面 {} 步没有执行", total - n));
+ }
+ return self.finish(lines.join("\n"), true, then).await;
+ }
Response::Text { text } => lines.push(format!("{n}. {tool} → {text}")),
Response::Image { caption, .. } => lines.push(format!("{n}. {tool} → {caption}")),
Response::Error { message } => {
@@ -497,7 +524,7 @@ mod tests {
fn defaults_match_toolkit() {
assert_eq!(
to_request("iphone_list_elements", &Map::new()).unwrap(),
- Request::ListElements { filter: String::new(), limit: 150 }
+ Request::ListElements { filter: String::new(), limit: 150, max_age_ms: 0 }
);
assert_eq!(
to_request("iphone_swipe", &args(json!({"from_x": 1, "from_y": 2, "to_x": 3, "to_y": 4}))).unwrap(),
@@ -575,6 +602,33 @@ mod tests {
assert!(batch_steps(&args(json!({"steps": many}))).is_err());
}
+ #[test]
+ fn reuse_elements_only_affects_tap_element_steps() {
+ let steps = |reuse: bool| {
+ batch_steps(&args(json!({"reuse_elements": reuse, "steps": [
+ {"tool": "iphone_tap_element", "text": "One"},
+ {"tool": "iphone_tap", "x": 1, "y": 2}
+ ]})))
+ .unwrap()
+ };
+ assert_eq!(
+ steps(true)[0],
+ Step::Request {
+ tool: "iphone_tap_element".into(),
+ req: Request::TapElement { text: "One".into(), index: 0, max_age_ms: BATCH_REUSE_MS }
+ }
+ );
+ assert!(matches!(&steps(false)[0], Step::Request { req: Request::TapElement { max_age_ms: 0, .. }, .. }));
+ assert_eq!(steps(true)[1], steps(false)[1]);
+ }
+
+ #[test]
+ fn missed_tap_texts_are_recognised() {
+ assert!(tap_missed("没找到包含 \"x\" 的元素,先用 iphone_list_elements 或截图看看屏幕"));
+ assert!(tap_missed("只匹配到 1 个:\nButton \"x\""));
+ assert!(!tap_missed("已点击 Button \"x\""));
+ }
+
#[test]
fn wait_for_timeout_is_bounded() {
assert_eq!(
@@ -593,11 +647,11 @@ mod tests {
// 写成字符串的数字照收(toolkit 的 pydantic 也收)
assert_eq!(
to_request("iphone_tap_element", &args(json!({"text": "设置", "index": "2"}))).unwrap(),
- Request::TapElement { text: "设置".into(), index: 2 }
+ Request::TapElement { text: "设置".into(), index: 2, max_age_ms: 0 }
);
assert_eq!(
to_request("iphone_list_elements", &args(json!({"limit": null}))).unwrap(),
- Request::ListElements { filter: String::new(), limit: 150 }
+ Request::ListElements { filter: String::new(), limit: 150, max_age_ms: 0 }
);
}
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index 576e0f3..5fa63f3 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -17,6 +17,10 @@ pub enum Request {
ListElements {
filter: String,
limit: usize,
+ /// 守护进程缓存的元素树不超过这么旧就直接用,不再读(0 = 总是重读)。
+ /// 用于「等界面稳定」之后紧接着列元素:Settle 刚读过
+ #[serde(default)]
+ max_age_ms: u64,
},
Tap {
x: f64,
@@ -25,6 +29,9 @@ pub enum Request {
TapElement {
text: String,
index: usize,
+ /// 同 ListElements。调用方声明这一串点击不改变界面布局(例如在同一个键盘上连按)时才给
+ #[serde(default)]
+ max_age_ms: u64,
},
LongPress {
x: f64,
diff --git a/docs/capability-matrix.md b/docs/capability-matrix.md
index 0092bb2..a594669 100644
--- a/docs/capability-matrix.md
+++ b/docs/capability-matrix.md
@@ -41,7 +41,7 @@
| `iphone_terminate_app` | WDA `/wda/apps/terminate` | WDA `terminate_app` | 已有 | — |
| `iphone_open_url` | WDA `/url` | WDA 会话 `/url`(idevice 未封装,自己发) | 需自写 | — |
| `iphone_wait_for`(新增) | 无 | 守护进程轮询元素树,出现即返回 | 已实现 | 只认元素树里的文字,游戏等没有元素的界面要截图 |
-| `iphone_batch`(新增) | 无 | MCP 层按顺序调用守护进程,出错即停;步骤先全部校验再执行 | 已实现 | 步骤间不看界面,只适合结果确定的连续操作 |
+| `iphone_batch`(新增) | 无 | MCP 层按顺序调用守护进程,出错或按名字没点到即停;步骤先全部校验再执行;`reuse_elements` 时按名字点击复用守护进程缓存的元素树(10 秒内,任何其他操作都会让缓存作废) | 已实现 | 步骤间不看界面,只适合结果确定的连续操作;`reuse_elements` 只用于不改变布局的连按,误用时下一步多半找不到元素而停下 |
| 操作类工具的 `then` 参数(新增) | 无 | 操作后 `Settle`(连续两次元素树一样,最多 1.5 秒),再附元素列表或截图 | 已实现 | 每次多 0.5~1.3 秒等稳定,换一次往返 |
## 3. 后台能力