From eea2eac7ab599379f34bbb4b22ac77eaabe55707 Mon Sep 17 00:00:00 2001 From: cosine <1726697408@qq.com> Date: Tue, 17 Nov 2026 15:04:33 +0800 Subject: [PATCH 1/2] feat(mcp): iphone_tap_element scrolls to find with scroll iphone_tap_element only looks at the current screen, so an item further down a long list needs the agent to swipe, list the elements and try again, one round trip at a time. scroll (down / up) and max_scrolls (default 8, at most 15) make the daemon do it: while the element isn't on screen, or is entirely covered (a row resting under the bottom toolbar), it scrolls 35% of the screen height in the middle of the screen over 1 s and reads the tree again. A 1 s stroke has almost no momentum: on an iPhone 12 mini a 300 pt finger move scrolled 618 pt at 0.3 s and 282 pt at 1 s, and a pause before lifting didn't remove the fling. When the tree no longer changes it is at the end of the list and stops. The answer says how many scrolls it took. Without scroll nothing changes on the wire, and an older daemon ignores the field. Regression case #151. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++ CHANGELOG.zh-CN.md | 4 ++ apps/iphone-control/src/viewer.rs | 3 +- crates/ictl-daemon/src/core.rs | 4 +- crates/ictl-daemon/src/tools/input.rs | 68 ++++++++++++++++++++++++-- crates/ictl-daemon/src/tools/mod.rs | 10 ++++ crates/ictl-mcp/src/lib.rs | 69 ++++++++++++++++++++++++--- crates/ictl-protocol/src/lib.rs | 23 +++++++++ docs/dev/regression-cases.md | 1 + docs/tools.md | 2 +- website/en/guide/tools.md | 2 +- website/guide/tools.md | 2 +- 12 files changed, 176 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d433e42..1451acb 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] +### New + +- `iphone_tap_element` takes `scroll` (`down` / `up`) and `max_scrolls`: when the element isn't on screen it scrolls slowly and looks again, and taps it once found. An older daemon ignores them and only looks at the current screen. + ### Improvements - An action that had to unlock the phone first says so, and how long it took (#135). diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index fa578f6..119347d 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -6,6 +6,10 @@ ## [Unreleased] +### 新功能 + +- `iphone_tap_element` 新增 `scroll`(`down` / `up`)和 `max_scrolls`:屏幕上没有时慢慢边滑边找,找到就点。旧版本守护进程会忽略它们,只在当前屏幕上找。 + ### 改进 - 操作前先自动解锁了的话,结果里会说明,并写明用了多久(#135)。 diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs index 68815be..b79a567 100644 --- a/apps/iphone-control/src/viewer.rs +++ b/apps/iphone-control/src/viewer.rs @@ -1362,6 +1362,7 @@ fn action(name: &str, b: &Value) -> Option { text: text("text")?, index: b.get("index").and_then(Value::as_u64).unwrap_or(0) as usize, max_age_ms: 0, + scroll: None, }, "wait_for" => Request::WaitFor { text: text("text")?, @@ -2022,7 +2023,7 @@ mod tests { assert_eq!(action("button", &json!({"button": "home"})), Some(Request::PressButton { button: "home".into() })); assert_eq!( action("tap_element", &json!({"text": "通用", "index": 1})), - Some(Request::TapElement { text: "通用".into(), index: 1, max_age_ms: 0 }) + Some(Request::TapElement { text: "通用".into(), index: 1, max_age_ms: 0, scroll: None }) ); assert_eq!( action("wait_for", &json!({"text": "x", "timeout": 99})), diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs index 6bc2b5b..a73960c 100644 --- a/crates/ictl-daemon/src/core.rs +++ b/crates/ictl-daemon/src/core.rs @@ -1214,8 +1214,8 @@ impl Daemon { text }), Request::Tap { x, y } => self.tap(g, x, y, view).await, - Request::TapElement { text, index, max_age_ms } => { - self.tap_element(g, &text, index, Duration::from_millis(max_age_ms)).await.map(|(t, missed)| { + Request::TapElement { text, index, max_age_ms, scroll } => { + self.tap_element(g, &text, index, Duration::from_millis(max_age_ms), scroll).await.map(|(t, missed)| { outcome.tapped_nothing = missed; t }) diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rs index 64eb36b..fee6b13 100644 --- a/crates/ictl-daemon/src/tools/input.rs +++ b/crates/ictl-daemon/src/tools/input.rs @@ -2,6 +2,27 @@ use super::*; +/// 边滑边找时每次滑多久:1 秒的慢滑停下时几乎没有惯性,内容移动和手指移动差不多(iPhone 12 mini 设置首页: +/// 手指移 300 点,0.3 秒滚了 618 点,0.6 秒 420 点,1 秒 282 点;W3C 在抬起前停一下也去不掉惯性) +pub(super) const SEARCH_SWIPE_SECONDS: f64 = 1.0; + +/// 边滑边找时算找到了:有匹配,而且要点的那个没有被整个盖住(停在底部工具栏、悬浮栏下面的还要再滑一下)。 +/// index 超出匹配个数也算找到:滑下去不会让序号变得更有意义,交给后面照常报 +fn reachable(tree: &Tree, text: &str, index: usize) -> bool { + let matches = elements::find(&tree.elements, text); + match matches.get(index) { + Some(e) => !matches!(tree.tap_point(e), TapPoint::Covered { .. }), + None => !matches.is_empty(), + } +} + +/// 边滑边找的一次滑动:屏幕正中,竖着滑 35% 屏高(前后两屏有重叠,不会漏过一行)。`down` 看下面的内容,手指往上 +pub(super) fn search_stroke(width: f64, height: f64, down: bool) -> ((f64, f64), (f64, f64)) { + let x = (width / 2.0).round(); + let (low, high) = ((height * 0.68).round(), (height * 0.33).round()); + if down { ((x, low), (x, high)) } else { ((x, high), (x, low)) } +} + impl Daemon { /// A stale pointer must neither unlock nor act on a new display. Unlock can itself /// rotate the foreground app, so take the final measurement after it completes. @@ -155,18 +176,52 @@ impl Daemon { text: &str, index: usize, max_age: Duration, + scroll: Option, ) -> crate::error::Result<(String, bool)> { self.ensure_unlocked(g).await?; - let tree = self.tree(g, max_age).await?; + let mut tree = self.tree(g, max_age).await?; + // 屏幕上没有、又要边滑边找:慢滑一小段(不带惯性,不会把要找的甩过去)、等停下再读树,找到或滑到底为止 + let mut scrolled = 0; + let mut at_end = false; + if let Some(s) = scroll { + while !reachable(&tree, text, index) && scrolled < s.max { + let screen = self.screen(g).await?; + let (from, to) = search_stroke(screen.width, screen.height, s.down); + let stroke = Box::pin(self.swipe(g, from, to, SEARCH_SWIPE_SECONDS, None, false)).await; + stroke?; + scrolled += 1; + let next = self.tree(g, Duration::ZERO).await?; + if next.close_to(&tree, STILL_TOLERANCE) { + at_end = true; + tree = next; + break; + } + tree = next; + } + } + let searched = match (scrolled, at_end) { + (0, _) => String::new(), + (n, true) => ictl_l10n::trf!("(滑了 {n} 次,已到尽头)", " (scrolled {n} times, reached the end)"), + (n, false) => ictl_l10n::trf!("(滑了 {n} 次)", " (scrolled {n} times)"), + }; // 点之前刚读的树就是操作前的界面(比操作开始前记下的更新) 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); + let hint = if scroll.is_some() { + String::new() + } else { + ictl_l10n::tr!( + ";可能在屏幕外,可带 scroll 边滑边找", + "; it may be off screen: pass scroll to look further" + ) + .to_owned() + }; return Ok(( ictl_l10n::trf!( - "{}包含 \"{text}\" 的元素,先用 iphone_list_elements 或截图看看屏幕{limited}", - "{}: no element contains \"{text}\"; look at the screen with iphone_list_elements or a screenshot first{limited}", + "{}包含 \"{text}\" 的元素{searched},先用 iphone_list_elements 或截图看看屏幕{limited}{hint}", + "{}: no element contains \"{text}\"{searched}; look at the screen with iphone_list_elements or a screenshot first{limited}{hint}", tap_missed_prefixes()[0] ), true, @@ -216,7 +271,12 @@ impl Daemon { } else { String::new() }; - Ok((ictl_l10n::trf!("已点击 {}{note}{moved}", "Tapped {}{note}{moved}", e.describe()), false)) + let found = if scrolled > 0 { + ictl_l10n::trf!("(滑了 {scrolled} 次后找到)", " (found after {scrolled} scrolls)") + } else { + String::new() + }; + Ok((ictl_l10n::trf!("已点击 {}{found}{note}{moved}", "Tapped {}{found}{note}{moved}", e.describe()), false)) } pub(crate) async fn long_press( diff --git a/crates/ictl-daemon/src/tools/mod.rs b/crates/ictl-daemon/src/tools/mod.rs index a243b6c..afa4e8e 100644 --- a/crates/ictl-daemon/src/tools/mod.rs +++ b/crates/ictl-daemon/src/tools/mod.rs @@ -484,6 +484,16 @@ mod tests { assert!(super::observe::change_text(Change::Unknown).is_empty()); } + /// 边滑边找的一次滑动在屏幕正中竖着滑,往下找时手指往上;滑的距离不到半屏,前后两屏有重叠 + #[test] + fn a_search_scroll_is_a_short_vertical_stroke_in_the_middle() { + let (from, to) = input::search_stroke(375.0, 812.0, true); + assert_eq!(from, (188.0, 552.0)); + assert_eq!(to, (188.0, 268.0)); + assert!(from.1 - to.1 < 812.0 / 2.0); + assert_eq!(input::search_stroke(375.0, 812.0, false), (to, from)); + } + /// 太久以前看过的界面不拿来比;拿走以后就没了 #[test] fn seen_screens_are_taken_once() { diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs index 2d53ed2..7b01890 100644 --- a/crates/ictl-mcp/src/lib.rs +++ b/crates/ictl-mcp/src/lib.rs @@ -352,7 +352,11 @@ WDA 不可用时改用 CoreDevice HID(iOS 27 起;结果里注明「经 HID」) with_then(json!({ "text": {"type": "string", "description": ictl_l10n::tr!("元素的文字(标签或名字),先精确匹配再按包含匹配", "the element's text (label or name); exact match first, then substring")}, "index": {"type": "integer", "default": 0, - "description": ictl_l10n::tr!("匹配到多个时点第几个(从 0 开始,顺序同 iphone_list_elements)", "which match to tap if there are several (from 0, same order as iphone_list_elements)")} + "description": ictl_l10n::tr!("匹配到多个时点第几个(从 0 开始,顺序同 iphone_list_elements)", "which match to tap if there are several (from 0, same order as iphone_list_elements)")}, + "scroll": {"type": "string", "enum": ["down", "up"], + "description": ictl_l10n::tr!("当前屏幕上没有时边滑边找:down 往下找(看下面的内容),up 往上找。每次慢滑约三分之一屏、不带惯性,找到就点,滑到底(界面不再变)或滑满 max_scrolls 次还没有就停下说明。用于长列表、设置页里不在当前屏的项;不给就只在当前屏幕上找", "If it isn't on the current screen, scroll and look again: down looks further down (the content below), up further up. Each scroll is a slow third of the screen without momentum; it taps as soon as it is found, and stops and says so at the end of the list (the screen no longer changes) or after max_scrolls. For items of long lists and settings pages that are off screen; without it only the current screen is searched")}, + "max_scrolls": {"type": "integer", "default": 8, "minimum": 1, "maximum": ictl_protocol::MAX_SEARCH_SCROLLS, + "description": ictl_l10n::tr!("带 scroll 时最多滑几次,默认 8", "with scroll: at most this many scrolls, default 8")} })), &["text"], ), @@ -616,6 +620,28 @@ impl Args<'_> { } /// 工具调用 → 守护进程请求 +/// `iphone_tap_element` 的 `scroll` / `max_scrolls`:没给 scroll 时不滑 +fn scroll_search(a: &Args) -> Result, String> { + let dir = a.s_or("scroll", "")?; + let max = a.u_or("max_scrolls", 8)?; + if dir.is_empty() { + return Ok(None); + } + let down = match dir.as_str() { + "down" => true, + "up" => false, + _ => return Err(ictl_l10n::trf!("参数 scroll 要是 down 或 up", "parameter scroll must be down or up")), + }; + if max == 0 || max > ictl_protocol::MAX_SEARCH_SCROLLS as usize { + return Err(ictl_l10n::trf!( + "参数 max_scrolls 要在 1 到 {} 之间", + "parameter max_scrolls must be between 1 and {}", + ictl_protocol::MAX_SEARCH_SCROLLS + )); + } + Ok(Some(ictl_protocol::ScrollSearch { down, max: max as u32 })) +} + pub fn to_request(name: &str, args: &Map) -> Result { let a = Args(args); Ok(match name { @@ -642,7 +668,12 @@ pub fn to_request(name: &str, args: &Map) -> Result 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)?, max_age_ms: 0 }, + "iphone_tap_element" => Request::TapElement { + text: a.s("text")?, + index: a.u_or("index", 0)?, + max_age_ms: 0, + scroll: scroll_search(&a)?, + }, "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")?), @@ -798,8 +829,8 @@ pub fn batch_steps(args: &Map) -> Result, String> { let req = match to_request(tool, obj) .map_err(|e| ictl_l10n::trf!("第 {n} 步({tool}):{e}", "step {n} ({tool}): {e}"))? { - Request::TapElement { text, index, .. } if reuse => { - Request::TapElement { text, index, max_age_ms: BATCH_REUSE_MS } + Request::TapElement { text, index, scroll, .. } if reuse => { + Request::TapElement { text, index, max_age_ms: BATCH_REUSE_MS, scroll } } other => other, }; @@ -1203,6 +1234,32 @@ mod tests { with_lang(Lang::Zh, || assert!(has_cjk(instructions()))); } + /// scroll 是可选的:不给就和以前一样只看当前屏幕;方向只认 down / up,次数 1 到上限 + #[test] + fn tap_element_scroll_search_is_optional_and_checked() { + let req = |v: Value| to_request("iphone_tap_element", &args(v)); + let plain = req(json!({"text": "隐私"})).unwrap(); + assert_eq!(plain, Request::TapElement { text: "隐私".into(), index: 0, max_age_ms: 0, scroll: None }); + let down = req(json!({"text": "隐私", "scroll": "down"})).unwrap(); + let s = |down, max| Some(protocol::ScrollSearch { down, max }); + assert_eq!(down, Request::TapElement { text: "隐私".into(), index: 0, max_age_ms: 0, scroll: s(true, 8) }); + let up = req(json!({"text": "隐私", "scroll": "up", "max_scrolls": 3})).unwrap(); + assert_eq!(up, Request::TapElement { text: "隐私".into(), index: 0, max_age_ms: 0, scroll: s(false, 3) }); + for bad in [ + json!({"text": "x", "scroll": "left"}), + json!({"text": "x", "scroll": "down", "max_scrolls": 0}), + json!({"text": "x", "scroll": "down", "max_scrolls": 16}), + json!({"text": "x", "scroll": true}), + ] { + assert!(req(bad).is_err()); + } + // reused in a batch, the scroll search stays + let steps = batch_steps(&args( + json!({"reuse_elements": true, "steps": [{"tool": "iphone_tap_element", "text": "x", "scroll": "down"}]}), + )); + assert!(matches!(&steps.unwrap()[0], Step::Request { req: Request::TapElement { scroll: Some(_), .. }, .. })); + } + #[test] fn alert_check_after_actions_but_not_buttons_or_reads() { assert!(wants_alert_check(&Request::Swipe { from: (0.0, 0.0), to: (1.0, 1.0), seconds: 0.3 })); @@ -1370,7 +1427,7 @@ mod tests { steps(true)[0], Step::Request { tool: "iphone_tap_element".into(), - req: Request::TapElement { text: "One".into(), index: 0, max_age_ms: BATCH_REUSE_MS } + req: Request::TapElement { text: "One".into(), index: 0, max_age_ms: BATCH_REUSE_MS, scroll: None } } ); assert!(matches!(&steps(false)[0], Step::Request { req: Request::TapElement { max_age_ms: 0, .. }, .. })); @@ -1409,7 +1466,7 @@ mod tests { // 写成字符串的数字照收(toolkit 的 pydantic 也收) assert_eq!( to_request("iphone_tap_element", &args(json!({"text": "设置", "index": "2"}))).unwrap(), - Request::TapElement { text: "设置".into(), index: 2, max_age_ms: 0 } + Request::TapElement { text: "设置".into(), index: 2, max_age_ms: 0, scroll: None } ); assert_eq!( to_request("iphone_list_elements", &args(json!({"limit": null}))).unwrap(), diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs index b9fe2e6..d4eec4b 100644 --- a/crates/ictl-protocol/src/lib.rs +++ b/crates/ictl-protocol/src/lib.rs @@ -43,6 +43,16 @@ pub fn default_socket() -> PathBuf { } } +/// [`Request::TapElement`] 屏幕上找不到时边滑边找:`down` 看下面的内容(手指往上滑),否则看上面的;最多滑 `max` 次 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ScrollSearch { + pub down: bool, + pub max: u32, +} + +/// [`ScrollSearch::max`] 的上限:每次慢滑加等列表停下约 2.5 秒,滑满 15 次也就半分钟出头 +pub const MAX_SEARCH_SCROLLS: u32 = 15; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum TouchPhase { @@ -87,6 +97,9 @@ pub enum Request { /// 同 ListElements。调用方声明这一串点击不改变界面布局(例如在同一个键盘上连按)时才给 #[serde(default)] max_age_ms: u64, + /// 屏幕上没有时边滑边找。旧版本守护进程不认识这个字段,只在当前屏幕上找 + #[serde(default, skip_serializing_if = "Option::is_none")] + scroll: Option, }, LongPress { x: f64, @@ -903,6 +916,16 @@ mod tests { #[test] fn requests_round_trip_as_tagged_json() { + let r = Request::TapElement { text: "x".into(), index: 0, max_age_ms: 0, scroll: None }; + // without a scroll search the request is what it always was on the wire + assert_eq!(serde_json::to_string(&r).unwrap(), r#"{"op":"tap_element","text":"x","index":0,"max_age_ms":0}"#); + let r = Request::TapElement { + text: "x".into(), + index: 0, + max_age_ms: 0, + scroll: Some(ScrollSearch { down: true, max: 8 }), + }; + assert_eq!(serde_json::from_str::(&serde_json::to_string(&r).unwrap()).unwrap(), r); let r = Request::Swipe { from: (1.0, 2.0), to: (3.0, 4.0), seconds: 0.3 }; let s = serde_json::to_string(&r).unwrap(); assert!(s.starts_with(r#"{"op":"swipe""#), "{s}"); diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index 5f0a9f3..104ed5d 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -149,3 +149,4 @@ | 143 | 原生:Spotlight 打开时选中上次的搜索词,再粘贴同样的词会把它替换成自己,输入框的值不变,`iphone_type_text` 报「粘贴了…但输入框里没有这段文字」(带 `submit` 时还不按回车),其实已经输进去了 | 「允许粘贴」点过之后,输入框原来就有这段文字、1.5 秒不变,算输入成功并提示截图确认;没点过「允许粘贴」时仍报错 | 单测 `a_paste_that_replaced_the_same_text_is_told_apart_from_one_that_missed` + 真机(Spotlight 留着「设置」时再输入「设置」,`run.py` 连跑两遍);真机脚本 `scenarios.py typing` | | 144 | 设备闲置时自动锁屏,下一个操作先自动解锁(iPad 经 WDA 约 15 秒,iPhone 原生约 9 秒),结果和事件日志都没说,看着像「切换设备后第一个操作慢」 | 结果第一行(截图在说明里、出错时在报错里)写「手机锁着,先自动解锁了,用时 X 秒」,事件日志记「已自动解锁」 | 单测 `an_unlock_first_is_said_on_the_answers_first_line` + 真机(锁屏后按名字点击、截图,两台设备);真机脚本 `scenarios.py lock` | | 145 | WDA 的短探测已正常应答或返回远端错误,却不清零超时计数,三个独立慢请求仍会触发重启;连接失败反而清零。日志还把长请求和短探测均未应答写成「连续 3 次」、宣称尚未检查的 `/status` 正常,请求超时本身缺端点日志 | 只有正常响应或远端错误清零,连接失败不清零;连续无应答和长请求后的失败探测分别记录原因及实际次数;超时诊断记录方法、短路径和耗时,不记录查询参数或正文 | 单测 `answered_probe_resets_stall_count_after_each_slow_request`、`connection_error_does_not_reset_unanswered_count`、`long_request_and_failed_probe_keep_the_actual_count_and_reason`、`three_short_unanswered_requests_report_a_consecutive_stall`、`answered_session_delete_does_not_mask_a_failed_probe`、`failed_request_log_keeps_endpoint_and_time_without_query`、`successful_request_log_does_not_include_response_body`;真机:同一 iPad、同一 WDA,把只读业务请求的客户端时限缩短到 20ms,短探测保留 5s,对照修复前后各 3 轮 | +| 151 | 要点的项在长列表屏幕外(设置首页的「隐私与安全性」):`iphone_tap_element` 只看当前屏幕,Agent 只能自己滑一下、读一次元素地来回;普通 0.3 秒快滑带惯性,手指移 300 点内容滚 618 点,会把要找的甩过去;找到的那一行可能正停在底部工具栏下面,整个被盖住 | `scroll`(`down` / `up`):每次在屏幕正中慢滑 35% 屏高(1 秒,几乎不带惯性,前后两屏有重叠),等列表停下再读树;要点的匹配存在且没被整个盖住才算找到;元素树不再变化算到了尽头,停下并在结果里说滑了几次 | 单测 `tap_element_scroll_search_is_optional_and_checked`、`a_search_scroll_is_a_short_vertical_stroke_in_the_middle`、`requests_round_trip_as_tagged_json` + 真机(iPhone 12 mini,iOS 26.4.1:设置首页往下找「隐私与安全性」滑 4 次点中;滑到底后往上找「通用」滑 3 次点中;找不存在的项滑到底 6 次停下)| diff --git a/docs/tools.md b/docs/tools.md index c7ae63c..59e562f 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -19,7 +19,7 @@ Coordinates are in **points**, the same unit as the pixels of a full-screen `iph | Tool | Parameters | Notes | |---|---|---| | `iphone_tap` | `x`, `y` | For targets without text (icons, games, maps); falls back to HID when WDA is down | -| `iphone_tap_element` | `text`, `index` (default 0) | Exact label or name first, then substring. If the element's center is covered (floating toolbar, keyboard, overlay), taps an uncovered part of it; if it is fully covered, does not tap and says so | +| `iphone_tap_element` | `text`, `index` (default 0), `scroll` (`down` / `up`), `max_scrolls` (default 8, max 15) | Exact label or name first, then substring. If the element's center is covered (floating toolbar, keyboard, overlay), taps an uncovered part of it; if it is fully covered, does not tap and says so. With `scroll`, when it isn't on screen (or is fully covered) it scrolls a slow third of the screen at a time without momentum and looks again, until it is found, the screen stops changing (the end of the list) or `max_scrolls` is reached; the result says how many scrolls it took | | `iphone_long_press` | `x`, `y`, `seconds` (default 1, max 10) | Holds one finger still, then lifts: context menus, home-screen quick actions, text selection | | `iphone_swipe` | `from_x`, `from_y`, `to_x`, `to_y`, `seconds` (default 0.3, max 10) | Returns after the list has stopped scrolling (up to 2.5 s). Swipe up (`from_y` > `to_y`) to see content further down | | `iphone_type_text` | `text`, `submit` (default false) | Types into the focused field (Chinese supported); fails if no keyboard is shown. Reads the field back afterwards: dropped trailing characters are typed again; if the field still doesn't match, it reports an error and does not press Return | diff --git a/website/en/guide/tools.md b/website/en/guide/tools.md index c863000..a62c565 100644 --- a/website/en/guide/tools.md +++ b/website/en/guide/tools.md @@ -19,7 +19,7 @@ With [auto-unlock](./auto-unlock) on, `iphone_screenshot`, `iphone_list_elements | Tool | What it does | |---|---| | `iphone_tap` | Tap coordinates | -| `iphone_tap_element` | Tap by text; if the center is covered by a floating bar or the keyboard it taps a visible part, and if it's fully covered it doesn't tap | +| `iphone_tap_element` | Tap by text; if the center is covered by a floating bar or the keyboard it taps a visible part, and if it's fully covered it doesn't tap. With `scroll` (`down` / `up`) it scrolls slowly and looks again when the element isn't on screen, until it is found, the list ends or `max_scrolls` (default 8) is reached | | `iphone_long_press` | Long press; `seconds` defaults to 1, max 10 | | `iphone_swipe` | Swipe; returns once the list has stopped scrolling. `seconds` defaults to 0.3, max 10 | | `iphone_type_text` | Type into the focused field (Chinese supported), read it back and fix dropped characters; `submit` presses Return | diff --git a/website/guide/tools.md b/website/guide/tools.md index 08bf887..1236696 100644 --- a/website/guide/tools.md +++ b/website/guide/tools.md @@ -19,7 +19,7 @@ MCP 服务提供 17 个工具,开启[开发者工具](#开发者工具-显式 | 工具 | 作用 | |---|---| | `iphone_tap` | 按坐标点击 | -| `iphone_tap_element` | 按文字点击;中心被悬浮栏、键盘挡住时改点露出来的部分,整个被挡住就不点 | +| `iphone_tap_element` | 按文字点击;中心被悬浮栏、键盘挡住时改点露出来的部分,整个被挡住就不点。带 `scroll`(`down` / `up`)时,屏幕上没有就慢慢边滑边找,找到就点,滑到底或滑满 `max_scrolls`(默认 8)次为止 | | `iphone_long_press` | 长按;`seconds` 默认 1,最多 10 | | `iphone_swipe` | 滑动;列表停稳后才返回。`seconds` 默认 0.3,最多 10 | | `iphone_type_text` | 在当前输入框输入文字(支持中文),输完读回核对,丢字会补上;`submit` 时按回车 | From 1007471f1eba49e403187ce1d1dfcac5bda5126b Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:35:04 +0800 Subject: [PATCH 2/2] fix(daemon): a scroll search stops on the exact text, not a row containing it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With scroll, any row that merely contained the text ended the search on the first screen: looking for "App" on the Settings page tapped "Apple账户…" without scrolling. Now the search goes on until the exact label or name is reachable. If none turns up by the end or max_scrolls, the first row seen that contains the text is tapped (scrolling back to it when it has gone off screen), and the result says no exact match was found. Co-Authored-By: Claude Opus 5.5 --- crates/ictl-daemon/src/tools/input.rs | 90 ++++++++++++++++++++------- crates/ictl-daemon/src/tools/mod.rs | 21 +++++++ crates/ictl-mcp/src/lib.rs | 2 +- 3 files changed, 89 insertions(+), 24 deletions(-) diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rs index e079362..068a12b 100644 --- a/crates/ictl-daemon/src/tools/input.rs +++ b/crates/ictl-daemon/src/tools/input.rs @@ -18,14 +18,25 @@ pub(super) const SEARCH_SWIPE_SECONDS: f64 = 1.0; /// 边滑边找时算找到了:有匹配,而且要点的那个没有被整个盖住(停在底部工具栏、悬浮栏下面的还要再滑一下)。 /// index 超出匹配个数也算找到:滑下去不会让序号变得更有意义,交给后面照常报 -fn reachable(tree: &Tree, text: &str, index: usize) -> bool { - let matches = elements::find(&tree.elements, text); +fn reachable_in(tree: &Tree, matches: &[&elements::Element], index: usize) -> bool { match matches.get(index) { Some(e) => !matches!(tree.tap_point(e), TapPoint::Covered { .. }), None => !matches.is_empty(), } } +/// 有能点到的匹配,按 [`elements::find`]:没有文字完全相同的就算包含它的 +pub(super) fn reachable(tree: &Tree, text: &str, index: usize) -> bool { + reachable_in(tree, &elements::find(&tree.elements, text), index) +} + +/// 有能点到的、文字(标签或名字)完全相同的匹配。边滑边找只在这时停下:当前屏只有包含它的(找「App」时的 +/// 「Apple账户」)不算,要找的多半在后面 +pub(super) fn reachable_exact(tree: &Tree, text: &str, index: usize) -> bool { + let exact: Vec<_> = tree.elements.iter().filter(|e| e.label == text || e.name == text).collect(); + reachable_in(tree, &exact, index) +} + /// 边滑边找的一次滑动:屏幕正中,竖着滑 35% 屏高(前后两屏有重叠,不会漏过一行)。`down` 看下面的内容,手指往上 pub(super) fn search_stroke(width: f64, height: f64, down: bool) -> ((f64, f64), (f64, f64)) { let x = (width / 2.0).round(); @@ -252,6 +263,14 @@ impl Daemon { Ok(()) } + /// 边滑边找的一次慢滑([`search_stroke`]),等停下后读一棵新树 + async fn search_scroll(&self, g: &mut Inner, down: bool) -> crate::error::Result { + let screen = self.screen(g).await?; + let (from, to) = search_stroke(screen.width, screen.height, down); + Box::pin(self.swipe(g, Stroke { from, to, seconds: SEARCH_SWIPE_SECONDS, hold: 0.0 }, None, false)).await?; + self.tree(g, Duration::ZERO).await + } + pub(crate) async fn tap_element( &self, g: &mut Inner, @@ -262,32 +281,50 @@ impl Daemon { ) -> crate::error::Result<(String, bool)> { self.ensure_unlocked(g).await?; let mut tree = self.tree(g, max_age).await?; - // 屏幕上没有、又要边滑边找:慢滑一小段(不带惯性,不会把要找的甩过去)、等停下再读树,找到或滑到底为止 + // 屏幕上没有、又要边滑边找:慢滑一小段(不带惯性,不会把要找的甩过去)、等停下再读树, + // 找到文字完全相同的或滑到底为止。一路上记下第一次看到包含它的是滑了几次的时候 let mut scrolled = 0; + let mut back = 0; let mut at_end = false; if let Some(s) = scroll { - while !reachable(&tree, text, index) && scrolled < s.max { - let screen = self.screen(g).await?; - let (from, to) = search_stroke(screen.width, screen.height, s.down); - let stroke = - Box::pin(self.swipe(g, Stroke { from, to, seconds: SEARCH_SWIPE_SECONDS, hold: 0.0 }, None, false)) - .await; - stroke?; - scrolled += 1; - let next = self.tree(g, Duration::ZERO).await?; - if next.close_to(&tree, STILL_TOLERANCE) { - at_end = true; - tree = next; + let mut partial_at = None; + loop { + if reachable_exact(&tree, text, index) { + break; + } + if partial_at.is_none() && reachable(&tree, text, index) { + partial_at = Some(scrolled); + } + if at_end || scrolled >= s.max { break; } + let next = Box::pin(self.search_scroll(g, s.down)).await?; + scrolled += 1; + at_end = next.close_to(&tree, STILL_TOLERANCE); tree = next; } + // 没有文字完全相同的,包含它的又已经滑过去了:往回滑到看到它的地方(多滑一次,前后两屏有重叠) + if !reachable_exact(&tree, text, index) + && !reachable(&tree, text, index) + && let Some(k) = partial_at + { + while back <= scrolled - k && !reachable(&tree, text, index) { + tree = Box::pin(self.search_scroll(g, !s.down)).await?; + back += 1; + } + } } - let searched = match (scrolled, at_end) { - (0, _) => String::new(), - (n, true) => ictl_l10n::trf!("(滑了 {n} 次,已到尽头)", " (scrolled {n} times, reached the end)"), - (n, false) => ictl_l10n::trf!("(滑了 {n} 次)", " (scrolled {n} times)"), + let searched = match (scrolled, at_end, back) { + (0, ..) => String::new(), + (n, _, b @ 1..) => ictl_l10n::trf!( + "(滑了 {n} 次没有文字完全相同的,又往回滑了 {b} 次)", + " (scrolled {n} times without an exact match, then {b} back)" + ), + (n, true, 0) => ictl_l10n::trf!("(滑了 {n} 次,已到尽头)", " (scrolled {n} times, reached the end)"), + (n, false, 0) => ictl_l10n::trf!("(滑了 {n} 次)", " (scrolled {n} times)"), }; + // 边滑边找了、最后点的却不是文字完全相同的:明说,Agent 看得出这和它要找的不一样 + let partial_only = scroll.is_some() && !reachable_exact(&tree, text, index); // 点之前刚读的树就是操作前的界面(比操作开始前记下的更新) g.dev.before_action = Some(std::mem::take(&mut g.dev.seen)); let matches = elements::find(&tree.elements, text); @@ -355,10 +392,17 @@ impl Daemon { } else { String::new() }; - let found = if scrolled > 0 { - ictl_l10n::trf!("(滑了 {scrolled} 次后找到)", " (found after {scrolled} scrolls)") - } else { - String::new() + let found = match (scrolled, partial_only) { + (0, false) => String::new(), + (0, true) => { + ictl_l10n::tr!("(没有文字完全相同的,点的是包含它的)", " (no exact match, tapped one that contains it)") + .to_owned() + } + (_, true) => ictl_l10n::trf!( + "{searched}(没有文字完全相同的,点的是包含它的)", + "{searched} (no exact match, tapped one that contains it)" + ), + (n, false) => ictl_l10n::trf!("(滑了 {n} 次后找到)", " (found after {n} scrolls)"), }; Ok((ictl_l10n::trf!("已点击 {}{found}{note}{moved}", "Tapped {}{found}{note}{moved}", e.describe()), false)) } diff --git a/crates/ictl-daemon/src/tools/mod.rs b/crates/ictl-daemon/src/tools/mod.rs index f82287c..762bdb2 100644 --- a/crates/ictl-daemon/src/tools/mod.rs +++ b/crates/ictl-daemon/src/tools/mod.rs @@ -486,6 +486,27 @@ mod tests { assert!(super::observe::change_text(Change::Unknown).is_empty()); } + /// 边滑边找只在文字完全相同时停下:找「App」时屏幕上只有「Apple账户」,包含它但不算找到,要接着滑 + #[test] + fn a_scroll_search_stops_only_on_an_exact_match() { + let row = |label: &str, y: u32| { + format!( + r#""# + ) + }; + let xml = |rows: &str| { + format!( + r#"{rows}"# + ) + }; + let screen = ictl_device::ScreenSize { width: 430.0, height: 932.0 }; + let top = elements::parse_tree(&xml(&row("Apple账户、iCloud+等", 200)), screen); + assert!(input::reachable(&top, "App", 0), "a row that contains it"); + assert!(!input::reachable_exact(&top, "App", 0), "but not the one asked for"); + let bottom = elements::parse_tree(&xml(&(row("钱包与 Apple Pay", 300) + &row("App", 600))), screen); + assert!(input::reachable_exact(&bottom, "App", 0)); + } + /// 边滑边找的一次滑动在屏幕正中竖着滑,往下找时手指往上;滑的距离不到半屏,前后两屏有重叠 #[test] fn a_search_scroll_is_a_short_vertical_stroke_in_the_middle() { diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs index bedc015..9a5c09a 100644 --- a/crates/ictl-mcp/src/lib.rs +++ b/crates/ictl-mcp/src/lib.rs @@ -362,7 +362,7 @@ WDA 不可用时改用 CoreDevice HID(iOS 27 起;结果里注明「经 HID」) "index": {"type": "integer", "default": 0, "description": ictl_l10n::tr!("匹配到多个时点第几个(从 0 开始,顺序同 iphone_list_elements)", "which match to tap if there are several (from 0, same order as iphone_list_elements)")}, "scroll": {"type": "string", "enum": ["down", "up"], - "description": ictl_l10n::tr!("当前屏幕上没有时边滑边找:down 往下找(看下面的内容),up 往上找。每次慢滑约三分之一屏、不带惯性,找到就点,滑到底(界面不再变)或滑满 max_scrolls 次还没有就停下说明。用于长列表、设置页里不在当前屏的项;不给就只在当前屏幕上找", "If it isn't on the current screen, scroll and look again: down looks further down (the content below), up further up. Each scroll is a slow third of the screen without momentum; it taps as soon as it is found, and stops and says so at the end of the list (the screen no longer changes) or after max_scrolls. For items of long lists and settings pages that are off screen; without it only the current screen is searched")}, + "description": ictl_l10n::tr!("当前屏幕上没有时边滑边找:down 往下找(看下面的内容),up 往上找。每次慢滑约三分之一屏、不带惯性,找到文字完全相同的就点(当前屏只有包含它的不算,接着滑;滑完都没有完全相同的才点包含它的),滑到底(界面不再变)或滑满 max_scrolls 次还没有就停下说明。用于长列表、设置页里不在当前屏的项;不给就只在当前屏幕上找", "If it isn't on the current screen, scroll and look again: down looks further down (the content below), up further up. Each scroll is a slow third of the screen without momentum; it taps as soon as the exact text is found (a row that only contains it doesn't stop the search; if no exact match turns up, one that contains it is tapped), and stops and says so at the end of the list (the screen no longer changes) or after max_scrolls. For items of long lists and settings pages that are off screen; without it only the current screen is searched")}, "max_scrolls": {"type": "integer", "default": 8, "minimum": 1, "maximum": ictl_protocol::MAX_SEARCH_SCROLLS, "description": ictl_l10n::tr!("带 scroll 时最多滑几次,默认 8", "with scroll: at most this many scrolls, default 8")} })),