From 8ee002999c16501f81eca7b7aea92deb867c00ba Mon Sep 17 00:00:00 2001 From: MSK Date: Mon, 23 Nov 2026 11:27:05 +0800 Subject: [PATCH 1/4] Report input delivery and collect accessible rows across screens --- CHANGELOG.md | 5 + CHANGELOG.zh-CN.md | 5 + README.md | 4 +- README.zh-CN.md | 4 +- apps/iphone-control/src/mcp_bridge.rs | 75 +++- apps/iphone-control/src/viewer.rs | 5 +- crates/ictl-daemon/src/core.rs | 90 ++++- crates/ictl-daemon/src/error.rs | 62 +++ crates/ictl-daemon/src/tasks.rs | 1 + crates/ictl-daemon/src/tools/input.rs | 376 +++++++++++------- crates/ictl-daemon/src/tools/mod.rs | 49 ++- crates/ictl-daemon/src/tools/native.rs | 165 +++++--- crates/ictl-daemon/src/tools/scroll.rs | 199 ++++++++++ crates/ictl-device/src/lib.rs | 7 +- crates/ictl-mcp/Cargo.toml | 2 +- crates/ictl-mcp/src/lib.rs | 522 ++++++++++++++++++++----- crates/ictl-protocol/src/lib.rs | 195 ++++++++- crates/ictl-wda/src/client.rs | 19 +- crates/ictl-wda/src/elements.rs | 20 +- crates/ictl-wda/src/http.rs | 19 +- crates/ictl-wda/src/lib.rs | 14 +- docs/architecture.md | 2 +- docs/dev/regression-cases.md | 3 +- docs/images/features.svg | 4 +- docs/images/features.zh-CN.svg | 4 +- docs/tools.md | 7 +- tests/device/scenarios.py | 104 ++++- website/en/guide/tools.md | 5 +- website/en/index.md | 2 +- website/guide/tools.md | 5 +- website/index.md | 2 +- 31 files changed, 1566 insertions(+), 410 deletions(-) create mode 100644 crates/ictl-daemon/src/tools/scroll.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 970f7c5e..da3e3bbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ What changed in each release, one line per change. Versions follow [Semantic Ver ## [Unreleased] +### New + +- Agents can read across several screens of a list and stop at a matching row without tapping it. +- Tap, swipe and text input results now distinguish a sent input from one that never went out or whose delivery is uncertain. + ## [0.2.10] - 2026-11-22 ### Upgrade notes diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index e9bafe69..c5698261 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -6,6 +6,11 @@ ## [Unreleased] +### 新功能 + +- Agent 可以跨屏收集列表内容,找到目标行后停留在当前页面。 +- 点击、滑动和输入文字会区分已发送、未发送和结果未知,方便 Agent 判断是否先读屏再重试。 + ## [0.2.10] - 2026-11-22 ### 升级注意事项 diff --git a/README.md b/README.md index c7dc30e5..b4ffeb1d 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Release iOS: 27+ recommended, 17+ supported Platform: Linux | macOS - MCP + MCP Rust License M8ven verified @@ -66,7 +66,7 @@ Device control has two routes, picked by iOS version: ## Features

- Device control (core): native on iOS 27+, 17 MCP tools, fewer round trips, runs unattended, a person in charge, doctor and alerts. Access: on this machine, remotely. Control page (optional) + Device control (core): native on iOS 27+, 18 MCP tools, fewer round trips, runs unattended, a person in charge, doctor and alerts. Access: on this machine, remotely. Control page (optional)

**Device control (core)** diff --git a/README.zh-CN.md b/README.zh-CN.md index ed2618b1..e01d2759 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -11,7 +11,7 @@ Release iOS:推荐 27+,17+ 可用 平台:Linux | macOS - MCP + MCP Rust License M8ven 已验证 @@ -66,7 +66,7 @@ iphone-control 在 Linux 或 macOS 上用**一个 Rust 二进制**把这些事 ## 功能特性

- 设备控制(核心):iOS 27 原生控制、17 个 MCP 工具、少走往返、无人值守、人工把关、诊断与通知。接入:本机接入、远程接入。控制台(可选) + 设备控制(核心):iOS 27 原生控制、18 个 MCP 工具、少走往返、无人值守、人工把关、诊断与通知。接入:本机接入、远程接入。控制台(可选)

**设备控制(核心)** diff --git a/apps/iphone-control/src/mcp_bridge.rs b/apps/iphone-control/src/mcp_bridge.rs index 16d51e0c..c0145cfb 100644 --- a/apps/iphone-control/src/mcp_bridge.rs +++ b/apps/iphone-control/src/mcp_bridge.rs @@ -123,7 +123,23 @@ impl Link { if let Err(e) = self.send(&msg, id.as_ref()).await { match id { Some(id) => { - let _ = self.tx.send(rpc_error(id, -32603, &e)); + let reply = if msg["method"] == "tools/call" + && msg["params"]["name"].as_str().is_some_and(ictl_mcp::reports_input) + { + // The remote daemon may have acted before the tunnel lost the reply. + json!({"jsonrpc": "2.0", "id": id, "error": { + "code": -32603, + "message": format!("{e}. {}", ictl_l10n::tr!( + "未收到远端工具结果;先读屏确认,再决定是否重试", + "No remote tool result; inspect the screen before retrying" + )), + "data": {"delivery": "unknown", "stage": "transport"} + }}) + .to_string() + } else { + rpc_error(id, -32603, &e) + }; + let _ = self.tx.send(reply); } // a notification has nobody to tell but the log (stdout is the protocol) None => eprintln!("iphone-control mcp --url: {e}"), @@ -139,7 +155,7 @@ impl Link { self.session().id = Some(sid.to_owned()); } if resp.status() == reqwest::StatusCode::ACCEPTED { - return Ok(()); + return missing_reply(id); } if !resp.status().is_success() { return Err(remote::failure(resp).await); @@ -165,24 +181,26 @@ impl Link { if let Ok(v) = serde_json::from_str::(&data) && pass(v) { - break; + return Ok(()); } } - return Ok(()); + return missing_reply(id); } let text = resp.text().await.map_err(|e| e.to_string())?; if text.trim().is_empty() { - return Ok(()); + return missing_reply(id); } - match serde_json::from_str::(&text).map_err(|e| e.to_string())? { - Value::Array(batch) => batch.into_iter().for_each(|v| { - pass(v); - }), - v => { - pass(v); + let reply = serde_json::from_str::(&text).map_err(|e| e.to_string())?; + let mut answered = false; + match reply { + Value::Array(messages) => { + for message in messages { + answered |= pass(message); + } } + message => answered = pass(message), } - Ok(()) + if answered { Ok(()) } else { missing_reply(id) } } /// Ends the session on the viewer (best effort) @@ -195,6 +213,39 @@ impl Link { } } +/// Notifications and client responses have no corresponding JSON-RPC response. +fn missing_reply(id: Option<&Value>) -> Result<(), String> { + if id.is_some() { Err("viewer closed the response without a matching JSON-RPC reply".into()) } else { Ok(()) } +} + fn rpc_error(id: Value, code: i64, message: &str) -> String { json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}}).to_string() } + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::AsyncReadExt; + + #[tokio::test] + async fn interrupted_tool_reply_reports_unknown_instead_of_hanging_or_retrying() { + let server = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", server.local_addr().unwrap()); + let peer = tokio::spawn(async move { + let (mut socket, _) = server.accept().await.unwrap(); + let mut buf = [0; 4096]; + assert!(socket.read(&mut buf).await.unwrap() > 0); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: 0\r\n\r\n") + .await + .unwrap(); + }); + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let link = Link { remote: Remote::new(&url, None, None).unwrap(), task: None, session: Mutex::default(), tx }; + link.forward(json!({"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"iphone_tap"}})).await; + let reply: Value = serde_json::from_str(&rx.try_recv().expect("client must receive a terminal reply")).unwrap(); + assert_eq!(reply["id"], 7); + assert_eq!(reply["error"]["data"]["delivery"], "unknown"); + peer.await.unwrap(); + } +} diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs index bca2d8d3..5c5ca2fe 100644 --- a/apps/iphone-control/src/viewer.rs +++ b/apps/iphone-control/src/viewer.rs @@ -1391,7 +1391,7 @@ fn action_result(req: &Request, result: Result json!({"ok": !missed, "message": text}) } Ok(Response::Image { caption, .. }) => json!({"ok": true, "message": caption}), - Ok(Response::Error { message, retry_as_gesture }) => json!({"ok": false, "message": message, + Ok(Response::Error { message, retry_as_gesture, .. }) => json!({"ok": false, "message": message, "retry_as_gesture": retry_as_gesture && matches!(req, Request::Touch { phase: TouchPhase::Down, .. })}), Err(e) => json!({"ok": false, "message": e.to_string()}), } @@ -1913,7 +1913,8 @@ mod tests { let ctx = test_ctx(temp.path(), &socket); for (phase, daemon_retry, allow) in [("down", false, false), ("down", true, true), ("move", true, false)] { let body = json!({"phase":phase, "x":1, "y":2, "view":"portrait"}); - let reply = Response::Error { message: "touch failed".into(), retry_as_gesture: daemon_retry }; + let reply = + Response::Error { message: "touch failed".into(), retry_as_gesture: daemon_retry, failure: None }; // The result comes directly from the action, with no follow-up status request. let ((_, result), req) = tokio::time::timeout(Duration::from_secs(3), async { tokio::join!( diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs index a96be065..3bdcd208 100644 --- a/crates/ictl-daemon/src/core.rs +++ b/crates/ictl-daemon/src/core.rs @@ -24,7 +24,7 @@ use crate::config::Config; use crate::eventlog::EventLog; use crate::machine::{Backoff, DeviceState, Misses}; use crate::notify::{self, Dedup, Event}; -use crate::protocol::{Request, Response}; +use crate::protocol::{Delivery, FailureStage, Request, Response}; use crate::supervise::StartOutcome; use crate::watchdog::Heartbeat; @@ -906,7 +906,7 @@ impl Daemon { return Response::text(serde_json::to_string_pretty(&s).unwrap_or_default()); } if let Err(e) = check_request(&req) { - return Response::error(e); + return Response::error(e).with_failure(Delivery::NotSent, FailureStage::Preflight); } if let Some(r) = self.tasks.handle(&req, ctx.task.as_deref(), ctx.peer, &mut ctx.gone).await { return r; @@ -915,7 +915,7 @@ impl Daemon { let (admission, waited) = match self.tasks.admit(&req, ctx.task.as_deref(), &mut ctx.expect_udid, &mut ctx.gone).await { Ok(a) => a, - Err(r) => return r, + Err(r) => return r.with_failure(Delivery::NotSent, FailureStage::Preflight), }; // a task limited to some apps: outside them, the action waits for the user (docs/task-control.md §2.6) let mut asked = false; @@ -924,7 +924,7 @@ impl Daemon { { match self.scope_gate(t, &req, ctx.task_step, &mut ctx.gone).await { Ok(a) => asked = a, - Err(r) => return r, + Err(r) => return r.with_failure(Delivery::NotSent, FailureStage::Preflight), } } // held while the task was paused or waiting for the user: the time in the queue starts now @@ -1139,12 +1139,12 @@ impl Daemon { // still let through now that it holds the lock: the task may have been paused or taken over meanwhile match self.lock_admitted(&self.inner, &req, admission, &mut queued_at, &mut ctx.gone).await { Ok(g) => g, - Err(r) => return r, + Err(r) => return r.with_failure(Delivery::NotSent, FailureStage::Preflight), } }; let g = &mut *g; if let Err(r) = admit(&req, queued_at, &ctx, g.device.as_ref().map(|d| d.udid.as_str())) { - return r; + return r.with_failure(Delivery::NotSent, FailureStage::Preflight); } let view = ctx.expect_view.as_deref(); // 改变界面的操作做完后缓存的元素树就作废;只有调用方声明「不改变布局」的按名字点击(max_age_ms > 0)保留 @@ -1155,6 +1155,10 @@ impl Daemon { if g.wda.as_ref().is_some_and(|w| w.stalled()) { self.restart_stalled_wda(g).await; } + let mut may_continue = |req: &Request| { + !ctx.gone.as_mut().is_some_and(|rx| rx.try_recv().is_ok()) + && matches!(self.tasks.still(admission, req), crate::tasks::Still::Admitted) + }; let response = if background { // an action that comes meanwhile gets the phone at once: the check is read-only, dropping it is safe let action = self.give_way.notified(); @@ -1164,7 +1168,7 @@ impl Daemon { gave_way() } else { tokio::select! { - r = Box::pin(self.dispatch(g, req, view, ctx.watched)) => r, + r = Box::pin(self.dispatch(g, req, view, ctx.watched, &mut may_continue)) => r, () = action => gave_way(), } } @@ -1178,7 +1182,7 @@ impl Daemon { g.dev.acted_at = Some(Instant::now()); } // boxed, like the request in `handle`: two of its large state machine on the stack overflowed a test thread - let r = Box::pin(self.dispatch(g, req, view, ctx.watched)).await; + let r = Box::pin(self.dispatch(g, req, view, ctx.watched, &mut may_continue)).await; if acted { g.dev.seen = Default::default(); *self.last_action.lock().unwrap_or_else(|p| p.into_inner()) = Some(Instant::now()); @@ -1192,7 +1196,14 @@ impl Daemon { response } - async fn dispatch(&self, g: &mut Inner, req: Request, view: Option<&str>, watched: bool) -> Response { + async fn dispatch( + &self, + g: &mut Inner, + req: Request, + view: Option<&str>, + watched: bool, + may_continue: &mut dyn FnMut(&Request) -> bool, + ) -> Response { // what the text reports, for clients that act on it (Response::Text.outcome) let mut outcome = crate::protocol::Outcome::default(); // the same facts as data, for programs (Response::Text.data) @@ -1219,6 +1230,12 @@ impl Daemon { data = Some(elements); text }), + Request::ScrollCollect(ref scan) => { + self.scroll_collect(g, scan, || may_continue(&req)).await.map(|(text, collection)| { + data = Some(collection); + text + }) + } Request::Tap { x, y, count } => self.tap(g, x, y, count, view).await, Request::TapSequence { points } => self.tap_sequence(g, &points).await, Request::TapElement { text, index, max_age_ms, scroll } => { @@ -1237,8 +1254,14 @@ impl Daemon { Request::Swipe { from, to, seconds, hold } => { self.swipe(g, crate::tools::Stroke { from, to, seconds, hold }, view, watched).await } - Request::TypeText { text, submit } => self.type_text(g, &text, submit).await, - Request::ReplaceText { text, submit } => Box::pin(self.replace_text(g, &text, submit)).await, + Request::TypeText { text, submit } => self.type_text(g, &text, submit, &mut outcome.field_verified).await, + Request::ReplaceText { text, submit } => { + Box::pin(self.replace_text(g, &text, submit)).await.map(|(message, delivery)| { + outcome.delivery = Some(delivery); + outcome.field_verified = Some(true); + message + }) + } Request::PressButton { button } => self.press_button(g, &button, watched).await, Request::Touch { phase, x, y } => { return self @@ -1305,7 +1328,7 @@ impl Daemon { | Request::TaskNote { .. } | Request::TaskFinish { .. } => unreachable!("other lanes"), }; - let r = r.map(|t| Response::text_data(t, outcome, data)).unwrap_or_else(Response::error); + let r = r.map(|t| Response::text_data(t, outcome, data)).unwrap_or_else(crate::error::Error::response); with_unlock_note(r, g.dev.unlocked.take()) } @@ -1359,6 +1382,7 @@ fn lane(req: &Request) -> Lane { | Request::ListElements { .. } | Request::Tap { .. } | Request::TapSequence { .. } + | Request::ScrollCollect(_) | Request::TapElement { .. } | Request::LongPress { .. } | Request::Swipe { .. } @@ -1401,7 +1425,9 @@ fn with_unlock_note(r: Response, unlocked: Option) -> Response { match r { Response::Text { text, outcome, data } => Response::Text { text: add(text), outcome, data }, Response::Image { jpeg_base64, caption } => Response::Image { jpeg_base64, caption: add(caption) }, - Response::Error { message, retry_as_gesture } => Response::Error { message: add(message), retry_as_gesture }, + Response::Error { message, retry_as_gesture, failure } => { + Response::Error { message: add(message), retry_as_gesture, failure } + } } } @@ -1494,6 +1520,12 @@ fn admit(req: &Request, queued_at: Instant, ctx: &CallCtx, controlled: Option<&s fn check_request(req: &Request) -> Result<(), String> { req.check_required_text()?; match req { + Request::ScrollCollect(scan) + if !(1..=crate::protocol::MAX_SEARCH_SCROLLS).contains(&scan.max_scrolls) + || !(1..=crate::protocol::MAX_SCROLL_ROWS).contains(&scan.limit) => + { + return Err(ictl_l10n::tr!("超出滚动或行数上限", "scroll or row limit is out of range").into()); + } Request::WebEval { expression, timeout_ms, .. } if expression.trim().is_empty() || *timeout_ms > MAX_WEB_EVAL_MS => { @@ -1557,6 +1589,30 @@ fn check_request(req: &Request) -> Result<(), String> { pub(crate) mod tests { use super::*; + #[test] + fn raw_scroll_collect_validates_scope_and_bounds() { + let mut scan = crate::protocol::ScrollCollect { + down: true, + max_scrolls: 1, + filter: String::new(), + until: String::new(), + limit: 1, + }; + let req = Request::ScrollCollect(scan.clone()); + assert!(check_request(&req).is_ok()); + assert_eq!(crate::tasks::scope_check(&req), Some(crate::tasks::Check::Foreground)); + assert!(!crate::tasks::observes(&req), "this cannot clear a takeover's observation requirement"); + let mut wire = serde_json::to_value(&req).unwrap(); + assert_eq!(serde_json::from_value::(wire.clone()).unwrap(), req); + wire["scroll"] = serde_json::json!("sideways"); + assert!(serde_json::from_value::(wire).is_err(), "unknown direct protocol fields must fail"); + for (max, limit) in [(0, 1), (16, 1), (1, 0), (1, 151)] { + scan.max_scrolls = max; + scan.limit = limit; + assert!(check_request(&Request::ScrollCollect(scan.clone())).is_err()); + } + } + /// Each device keeps its own background WDA: switching to another device and back attaches to it again, and /// `service stop` sees all of them. The last one is still written the old way for older versions #[test] @@ -1729,7 +1785,7 @@ pub(crate) mod tests { let (d, dir) = test_daemon("previous-view"); let ctx = CallCtx { expect_view: Some("old-view".into()), ..Default::default() }; let r = d.handle(Request::Tap { x: 3.0, y: 4.0, count: 1 }, Instant::now(), ctx).await; - assert!(matches!(r, Response::Error { message, retry_as_gesture: false } if message.contains("画面"))); + assert!(matches!(r, Response::Error { message, retry_as_gesture: false, .. } if message.contains("画面"))); std::fs::remove_dir_all(dir).unwrap(); } @@ -1768,7 +1824,7 @@ pub(crate) mod tests { assert_eq!(g.dev.display.as_ref().unwrap().id, id); let stale = d.touch(&mut g, phase, 20., 50., Some("old")).await.unwrap_err(); assert!( - matches!(stale, Response::Error { message, retry_as_gesture: false } if message.contains("画面") || message.contains("display changed")) + matches!(stale, Response::Error { message, retry_as_gesture: false, .. } if message.contains("画面") || message.contains("display changed")) ); } std::fs::remove_dir_all(dir).unwrap(); @@ -1784,7 +1840,9 @@ pub(crate) mod tests { drop(g); let req = Request::Touch { phase: crate::protocol::TouchPhase::Down, x: 20.0, y: 50.0 }; let response = d.handle(req, Instant::now(), ctx).await; - assert!(matches!(response, Response::Error { message, retry_as_gesture: false } if message.contains("画面"))); + assert!( + matches!(response, Response::Error { message, retry_as_gesture: false, .. } if message.contains("画面")) + ); let g = d.inner.lock().await; assert!(g.dev.display.is_none()); assert!(g.dev.touch_rotation.is_none()); diff --git a/crates/ictl-daemon/src/error.rs b/crates/ictl-daemon/src/error.rs index 88f42706..b2eab80e 100644 --- a/crates/ictl-daemon/src/error.rs +++ b/crates/ictl-daemon/src/error.rs @@ -2,6 +2,7 @@ //! for it and in its language; inside the daemon the cause stays what it was (WDA's, the device's, unlocking's), //! so `?` passes it on without turning it into a string first, and code can still look at which one it was. +use crate::protocol::{Delivery, FailureStage, Response}; use ictl_device::DeviceError; use ictl_unlock::UnlockError; use ictl_wda::WdaError; @@ -19,6 +20,47 @@ pub enum Error { /// The daemon's own message, already worded for the caller #[error("{0}")] Msg(String), + #[error("{message}")] + Action { delivery: Delivery, stage: FailureStage, message: String }, +} + +impl Error { + pub fn action(delivery: Delivery, stage: FailureStage, message: impl std::fmt::Display) -> Self { + Self::Action { delivery, stage, message: message.to_string() } + } + + pub fn preflight(message: impl std::fmt::Display) -> Self { + Self::action(Delivery::NotSent, FailureStage::Preflight, message) + } + + pub fn readback(message: impl std::fmt::Display) -> Self { + Self::action(Delivery::Sent, FailureStage::Readback, message) + } + + pub fn wda_input(e: WdaError) -> Self { + let (delivery, stage) = match e { + WdaError::BeforeInput(_) => (Delivery::NotSent, FailureStage::Preflight), + WdaError::Unavailable(_) => (Delivery::NotSent, FailureStage::Connect), + WdaError::Write(_) => (Delivery::Unknown, FailureStage::Send), + _ => (Delivery::Unknown, FailureStage::Reply), + }; + Self::action(delivery, stage, e) + } + + /// Add caller-facing context without losing the original delivery classification. + pub fn with_message(self, message: String) -> Self { + match self { + Self::Action { delivery, stage, .. } => Self::Action { delivery, stage, message }, + _ => Self::Msg(message), + } + } + + pub fn response(self) -> Response { + match self { + Self::Action { delivery, stage, message } => Response::error(message).with_failure(delivery, stage), + e => Response::error(e), + } + } } /// The daemon's result: its [`Error`] unless another is named (`Result<(), Response>`) @@ -47,6 +89,26 @@ impl From for String { mod tests { use super::*; + #[test] + fn input_stage_survives_conversion_to_a_daemon_reply() { + let tap = crate::protocol::Request::Tap { x: 0., y: 0., count: 1 }; + for (e, delivery, stage) in [ + ( + WdaError::BeforeInput(Box::new(WdaError::Timeout("session".into()))), + Delivery::NotSent, + FailureStage::Preflight, + ), + (WdaError::Unavailable("offline".into()), Delivery::NotSent, FailureStage::Connect), + (WdaError::Write("partial".into()), Delivery::Unknown, FailureStage::Send), + (WdaError::Timeout("no reply".into()), Delivery::Unknown, FailureStage::Reply), + ] { + let r = Error::wda_input(e).response(); + assert_eq!(r.delivery(&tap), delivery); + assert_eq!(r.failure_stage(), Some(stage)); + } + assert_eq!(Response::error("older daemon").delivery(&tap), Delivery::Unknown); + } + /// The caller reads the same text as before: a cause's own, or the daemon's message #[test] fn the_text_is_the_cause_s_own() { diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rs index c46123e1..e8b6ed5a 100644 --- a/crates/ictl-daemon/src/tasks.rs +++ b/crates/ictl-daemon/src/tasks.rs @@ -221,6 +221,7 @@ pub fn scope_check(req: &Request) -> Option { Request::OpenUrl { url } => Some(Check::Url(url.clone())), Request::Tap { .. } | Request::TapSequence { .. } + | Request::ScrollCollect(_) | Request::TapElement { .. } | Request::LongPress { .. } | Request::Swipe { .. } diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rs index 6d22c421..1a0d2151 100644 --- a/crates/ictl-daemon/src/tools/input.rs +++ b/crates/ictl-daemon/src/tools/input.rs @@ -89,13 +89,12 @@ impl Daemon { view: Option<&str>, ) -> crate::error::Result { if !(1..=MAX_TAP_COUNT).contains(&count) { - return Err(ictl_l10n::trf!( + return Err(Error::preflight(ictl_l10n::trf!( "count 要是 1 到 {MAX_TAP_COUNT} 的整数", "count must be a whole number from 1 to {MAX_TAP_COUNT}" - ) - .into()); + ))); } - self.prepare_coordinates(g, view, true).await?; + self.prepare_coordinates(g, view, true).await.map_err(Error::preflight)?; let pos = format!("({},{})", fmt_g(x), fmt_g(y)); let times = if count > 1 { ictl_l10n::trf!(",连点 {count} 下", ", {count} times") } else { String::new() }; if let Some(w) = self.wda(g) { @@ -104,15 +103,15 @@ impl Daemon { match r { Ok(()) => return Ok(ictl_l10n::trf!("已点击 {pos}{times}", "Tapped {pos}{times}")), Err(WdaError::Unavailable(_)) if view.is_none() => {} - Err(e) => return Err(e.into()), + Err(e) => return Err(Error::wda_input(e)), } } // natively HID is the way, not a fallback: the page's view was checked above as through WDA let native = self.native(g); if !native && view.is_some() { - return Err(wda_down(&g.state, g.info.as_ref()).into()); + return Err(Error::preflight(wda_down(&g.state, g.info.as_ref()))); } - let rot = self.hid_touch_rotation(g).await?; + let rot = self.hid_touch_rotation(g).await.map_err(Error::preflight)?; self.hid_do(g, move |h| { Box::pin(async move { h.rotation = rot; @@ -216,6 +215,7 @@ impl Daemon { return Err(Response::Error { message: wda_down(&g.state, g.info.as_ref()), retry_as_gesture: true, + failure: None, }); } None => self.hid_touch_rotation(g).await.map_err(Response::error)?, @@ -247,6 +247,7 @@ impl Daemon { return Err(Response::Error { message: message.into(), retry_as_gesture: phase == TouchPhase::Down, + failure: None, }); } }, @@ -264,7 +265,7 @@ impl Daemon { } /// 边滑边找的一次慢滑([`search_stroke`]),等停下后读一棵新树 - async fn search_scroll(&self, g: &mut Inner, down: bool) -> crate::error::Result { + pub(super) 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?; @@ -279,8 +280,8 @@ impl Daemon { max_age: Duration, scroll: Option, ) -> crate::error::Result<(String, bool)> { - self.ensure_unlocked(g).await?; - let mut tree = self.tree(g, max_age).await?; + self.ensure_unlocked(g).await.map_err(Error::preflight)?; + let mut tree = self.tree(g, max_age).await.map_err(Error::preflight)?; // 屏幕上没有、又要边滑边找:慢滑一小段(不带惯性,不会把要找的甩过去)、等停下再读树, // 找到文字完全相同的或滑到底为止。一路上记下第一次看到包含它的是滑了几次的时候 let mut scrolled = 0; @@ -298,7 +299,7 @@ impl Daemon { if at_end || scrolled >= s.max { break; } - let next = Box::pin(self.search_scroll(g, s.down)).await?; + let next = Box::pin(self.search_scroll(g, s.down)).await.map_err(Error::preflight)?; scrolled += 1; at_end = next.close_to(&tree, STILL_TOLERANCE); tree = next; @@ -309,7 +310,7 @@ impl Daemon { && let Some(k) = partial_at { while back <= scrolled - k && !reachable(&tree, text, index) { - tree = Box::pin(self.search_scroll(g, !s.down)).await?; + tree = Box::pin(self.search_scroll(g, !s.down)).await.map_err(Error::preflight)?; back += 1; } } @@ -415,12 +416,17 @@ impl Daemon { seconds: f64, view: Option<&str>, ) -> crate::error::Result { - self.prepare_coordinates(g, view, true).await?; + self.prepare_coordinates(g, view, true).await.map_err(Error::preflight)?; let native = self.native(g); match self.wda(g) { - Some(w) => w.touch_and_hold(x, y, seconds).await?, + Some(w) => w.touch_and_hold(x, y, seconds).await.map_err(Error::wda_input)?, None if native => Box::pin(self.native_long_press(g, x, y, seconds)).await?, - None => self.require_wda(g)?.touch_and_hold(x, y, seconds).await?, + None => self + .require_wda(g) + .map_err(Error::preflight)? + .touch_and_hold(x, y, seconds) + .await + .map_err(Error::wda_input)?, } Ok(ictl_l10n::trf!("已长按 ({},{}) {} 秒", "Long-pressed ({},{}) for {} s", fmt_g(x), fmt_g(y), fmt_g(seconds))) } @@ -433,7 +439,7 @@ impl Daemon { watched: bool, ) -> crate::error::Result { let Stroke { from, to, seconds, hold } = stroke; - self.prepare_coordinates(g, view, true).await?; + self.prepare_coordinates(g, view, true).await.map_err(Error::preflight)?; let mut desc = format!("({},{}) → ({},{})", fmt_g(from.0), fmt_g(from.1), fmt_g(to.0), fmt_g(to.1)); if hold > 0.0 { desc = ictl_l10n::trf!("{desc},先按住 {} 秒", "{desc}, held {} s first", fmt_g(hold)); @@ -455,14 +461,14 @@ impl Daemon { return Ok(ictl_l10n::trf!("已滑动 {desc}{note}", "Swiped {desc}{note}")); } Err(WdaError::Unavailable(_)) if view.is_none() => {} - Err(e) => return Err(e.into()), + Err(e) => return Err(Error::wda_input(e)), } } let native = self.native(g); if view.is_some() && !native { - return Err(wda_down(&g.state, g.info.as_ref()).into()); + return Err(Error::preflight(wda_down(&g.state, g.info.as_ref()))); } - let rot = self.hid_touch_rotation(g).await?; + let rot = self.hid_touch_rotation(g).await.map_err(Error::preflight)?; self.hid_do(g, move |h| { Box::pin(async move { h.rotation = rot; @@ -484,44 +490,82 @@ impl Daemon { Ok(ictl_l10n::trf!("已滑动 {desc}{note}", "Swiped {desc}{note}")) } - pub(crate) async fn type_text(&self, g: &mut Inner, text: &str, submit: bool) -> crate::error::Result { - self.ensure_unlocked(g).await?; + pub(crate) async fn type_text( + &self, + g: &mut Inner, + text: &str, + submit: bool, + field_verified: &mut Option, + ) -> crate::error::Result { + self.ensure_unlocked(g).await.map_err(Error::preflight)?; let n = text.chars().count(); + *field_verified = (!text.is_empty()).then_some(false); if let Some(w) = self.wda(g) { // /wda/keys 没有输入框获得焦点时也返回成功,其实什么都没输:先看屏幕上有没有键盘 + let mut before = None; let typed = match w.keyboard_shown().await { Ok(false) => { - return Err( - ictl_l10n::tr!("屏幕上没有键盘(没有输入框获得焦点),什么都没输;先点一下输入框,截图确认键盘出来了再输入", "No keyboard on screen (no text field has focus), nothing typed; tap a text field first and check with a screenshot that the keyboard is up").into(), - ); + return Err(Error::preflight(ictl_l10n::tr!( + "屏幕上没有键盘(没有输入框获得焦点),什么都没输;先点一下输入框,截图确认键盘出来了再输入", + "No keyboard on screen (no text field has focus), nothing typed; tap a text field first and check with a screenshot that the keyboard is up" + ))); } Ok(true) if text.is_empty() => Ok(()), - Ok(true) => w.keys(text).await, - Err(e) => Err(e), + Ok(true) => { + if text.chars().any(|c| !c.is_control()) { + before = readable_focus(w).await; + } + w.keys(text).await + } + Err(e @ WdaError::Unavailable(_)) => Err(e), + Err(e) => return Err(Error::preflight(e)), }; match typed { Ok(()) => { // 有的 App 边输入边刷新输入框,会吞掉一部分字(高德搜索框「故宫博物院」只剩「故宫博」),WDA 照样报成功: // 输完读回输入框核对,少了结尾几个字就补上;对不上就不按回车 - let note = match verify_typed(w, text).await { - Typed::Ok | Typed::Unknown => String::new(), + let field = verify_typed(w, before.as_ref(), text).await; + if !text.is_empty() { + *field_verified = Some(matches!(field, Typed::Ok | Typed::Fixed(_))); + } + let note = match field { + Typed::Ok => String::new(), + Typed::Unknown if text.chars().any(|c| !c.is_control()) => ictl_l10n::tr!( + "(无法读回输入框,请查看屏幕确认)", + " (field contents could not be verified; inspect the screen)" + ) + .into(), + Typed::Unknown => String::new(), Typed::Fixed(k) => ictl_l10n::trf!( "(第一次有 {k} 个字没输进去,已补上)", " ({k} characters were dropped the first time and typed again)" ), + Typed::FocusChanged => { + return Err(Error::readback(ictl_l10n::tr!( + "输入后焦点已改变,请查看屏幕确认;未再输入或按回车", + "Focus changed after typing. Inspect the screen; no further keys or Return were sent." + ))); + } Typed::Mismatch(now) => { - return Err(ictl_l10n::trf!( + return Err(Error::readback(ictl_l10n::trf!( "输入了 {n} 个字符,但输入框里现在是「{now}」,和要输入的「{text}」对不上(App 可能吞掉了部分字符){};截图确认后再处理", "Typed {n} characters, but the field now contains “{now}”, which doesn't match “{text}” (the app may have swallowed some characters){}; check with a screenshot before going on", if submit { ictl_l10n::tr!(",没有按回车", ", Return not pressed") } else { "" } - ).into()); + ))); } }; if submit { w.keys("\n").await.map_err(|e| { - ictl_l10n::trf!( - "文字已输入{note},按回车失败:{e}", - "Text typed{note}, pressing Return failed: {e}" + if text.is_empty() { + return Error::wda_input(e); + } + Error::action( + Delivery::Sent, + FailureStage::Send, + ictl_l10n::trf!( + "文字已输入{note},按回车失败:{e}", + "Text typed{note}, pressing Return failed: {e}" + ), ) })?; } @@ -532,11 +576,11 @@ impl Daemon { )); } Err(WdaError::Unavailable(_)) => {} - Err(e) => return Err(e.into()), + Err(e) => return Err(Error::wda_input(e)), } } if self.native(g) { - return Box::pin(self.native_type(g, text, submit)).await; + return Box::pin(self.native_type(g, text, submit, field_verified)).await; } let payload = if submit { format!("{text}\n") } else { text.to_owned() }; // 美式键盘按得出来的直接按键,不动剪贴板 @@ -549,15 +593,20 @@ impl Daemon { /// Replaces the text of the focused field (`replace: true`; empty `text` empties it), and presses Return only once /// the field reads back as exactly `text`: through WDA ([`wda_replace`]), or natively ([`Daemon::native_replace`]) - pub(crate) async fn replace_text(&self, g: &mut Inner, text: &str, submit: bool) -> crate::error::Result { - self.ensure_unlocked(g).await?; + pub(crate) async fn replace_text( + &self, + g: &mut Inner, + text: &str, + submit: bool, + ) -> crate::error::Result<(String, Delivery)> { + self.ensure_unlocked(g).await.map_err(Error::preflight)?; let native = self.native(g); if let Some(w) = self.wda(g) { match wda_replace(w, text, submit).await { Ok(m) => return Ok(m), Err(WdaReplace::Failed(e)) => return Err(e), // WDA went away before anything was changed - Err(WdaReplace::Untouched(e)) if !native => return Err(e.into()), + Err(WdaReplace::Untouched(e)) if !native => return Err(Error::wda_input(e)), Err(WdaReplace::Untouched(_)) => {} } } @@ -565,7 +614,7 @@ impl Daemon { return Box::pin(self.native_replace(g, text, submit)).await; } // no HID way: the field can't be read without WDA - Err(wda_down(&g.state, g.info.as_ref()).into()) + Err(Error::preflight(wda_down(&g.state, g.info.as_ref()))) } /// HID 输入中文等按不出来的文字:经剪贴板粘贴([`ictl_device::Tunnel::paste_text`])。 @@ -576,15 +625,19 @@ impl Daemon { async fn hid_paste(&self, g: &mut Inner, text: &str, submit: bool) -> crate::error::Result { let n = text.chars().count(); self.restore_pasteboard(g, false).await; - self.hid(g).await?; + self.hid(g).await.map_err(|e| Error::action(Delivery::NotSent, FailureStage::Connect, e))?; let r = Box::pin(g.tunnel.as_mut().expect("hid() 刚建好隧道").paste_text(text)).await; g.hid_used = Some(Instant::now()); let pending = match r { Ok(p) => p, - Err(e @ DeviceError::InvalidInput(_)) => return Err(e.into()), + Err(e @ (DeviceError::InvalidInput(_) | DeviceError::PasteNotSent(_))) => return Err(Error::preflight(e)), Err(e) => { drop_tunnel(g).await; - return Err(ictl_l10n::trf!("HID 粘贴失败:{e}", "HID paste failed: {e}").into()); + return Err(Error::action( + Delivery::Unknown, + FailureStage::Send, + ictl_l10n::trf!("HID 粘贴失败:{e}", "HID paste failed: {e}"), + )); } }; let saved = pending.is_some(); @@ -711,51 +764,39 @@ pub(super) async fn wda_replace( w: &mut WdaClient, text: &str, submit: bool, -) -> Result { +) -> Result<(String, Delivery), WdaReplace> { use WdaReplace::{Failed, Untouched}; // not sent: nothing changed let untouched = |e: WdaError| match e { WdaError::Unavailable(_) => Untouched(e), - e => Failed(e.into()), + e => Failed(Error::preflight(e)), }; if !w.keyboard_shown().await.map_err(untouched)? { - return Err(Failed( - ictl_l10n::tr!( - "屏幕上没有键盘,先点一下要替换的输入框", - "No keyboard on screen; tap the field you want to replace first" - ) - .into(), - )); + return Err(Failed(Error::preflight(ictl_l10n::tr!( + "屏幕上没有键盘,先点一下要替换的输入框", + "No keyboard on screen; tap the field you want to replace first" + )))); } let field = match w.focused_field().await.map_err(untouched)? { Some(f) if REPLACEABLE.contains(&f.kind.as_str()) => f, Some(f) if f.kind == "SecureTextField" => { - return Err(Failed( - ictl_l10n::tr!( - "获得焦点的是密码框,读不出内容、核对不了,没有替换", - "The focused field is a password field: it can't be read back, so nothing was replaced" - ) - .into(), - )); + return Err(Failed(Error::preflight(ictl_l10n::tr!( + "获得焦点的是密码框,读不出内容、核对不了,没有替换", + "The focused field is a password field: it can't be read back, so nothing was replaced" + )))); } Some(f) => { - return Err(Failed( - ictl_l10n::trf!( - "获得焦点的是 {},不是普通输入框,没有替换", - "The focused element is a {}, not a text field; nothing was replaced", - f.kind - ) - .into(), - )); + return Err(Failed(Error::preflight(ictl_l10n::trf!( + "获得焦点的是 {},不是普通输入框,没有替换", + "The focused element is a {}, not a text field; nothing was replaced", + f.kind + )))); } None => { - return Err(Failed( - ictl_l10n::tr!( - "无法确认当前聚焦的是可读的普通输入框,没有替换文字", - "Couldn't identify a readable focused text field; no text was replaced" - ) - .into(), - )); + return Err(Failed(Error::preflight(ictl_l10n::tr!( + "无法确认当前聚焦的是可读的普通输入框,没有替换文字", + "Couldn't identify a readable focused text field; no text was replaced" + )))); } }; let old = w.field_text(&field).await.map_err(untouched)?; @@ -766,34 +807,34 @@ pub(super) async fn wda_replace( if !old.is_empty() { w.clear(&field.id).await.map_err(|e| match e { WdaError::Unavailable(_) => Untouched(e), - e => Failed( - ictl_l10n::trf!( + e => { + let message = ictl_l10n::trf!( "清空输入框失败({e}),原来的文字可能已经删掉了一部分{not_submitted};截图确认", "Emptying the field failed ({e}); some of the old text may be gone{not_submitted}; check with a screenshot" - ) - .into(), - ), + ); + Failed(Error::wda_input(e).with_message(message)) + } })?; } if !text.is_empty() { w.keys(text).await.map_err(|e| { - Failed( - ictl_l10n::trf!( - "{gone},输入新文字失败({e}){not_submitted};截图确认", - "{gone}, typing the new text failed ({e}){not_submitted}; check with a screenshot" - ) - .into(), - ) + let message = ictl_l10n::trf!( + "{gone},输入新文字失败({e}){not_submitted};截图确认", + "{gone}, typing the new text failed ({e}){not_submitted}; check with a screenshot" + ); + let cause = Error::wda_input(e); + Failed(if old.is_empty() { + cause.with_message(message) + } else { + Error::action(Delivery::Unknown, FailureStage::Send, message) + }) })?; } let unread = |e: WdaError| { - Failed( - ictl_l10n::trf!( - "{gone},替换后读不回输入框({e}){not_submitted};截图确认", - "{gone}, and the field couldn't be read back after the replacement ({e}){not_submitted}; check with a screenshot" - ) - .into(), - ) + Failed(Error::readback(ictl_l10n::trf!( + "{gone},替换后读不回输入框({e}){not_submitted};截图确认", + "{gone}, and the field couldn't be read back after the replacement ({e}){not_submitted}; check with a screenshot" + ))) }; let mut now = String::new(); for attempt in 0..READBACK_TRIES { @@ -821,27 +862,27 @@ pub(super) async fn wda_replace( now = w.field_text(&field).await.map_err(unread)?; } if now != text { - return Err(Failed( - ictl_l10n::trf!( - "{gone},但输入框里现在是「{now}」,和要替换成的「{text}」对不上{not_submitted};截图确认后再处理", - "{gone}, but the field now holds “{now}”, which doesn't match “{text}”{not_submitted}; check with a screenshot before going on" - ) - .into(), - )); + return Err(Failed(Error::readback(ictl_l10n::trf!( + "{gone},但输入框里现在是「{now}」,和要替换成的「{text}」对不上{not_submitted};截图确认后再处理", + "{gone}, but the field now holds “{now}”, which doesn't match “{text}”{not_submitted}; check with a screenshot before going on" + )))); } } if submit { w.keys("\n").await.map_err(|e| { - Failed( - ictl_l10n::trf!( - "已替换为「{text}」{note},按回车失败:{e}", - "Replaced the field with “{text}”{note}, pressing Return failed: {e}" - ) - .into(), - ) + let message = ictl_l10n::trf!( + "已替换为「{text}」{note},按回车失败:{e}", + "Replaced the field with “{text}”{note}, pressing Return failed: {e}" + ); + Failed(if old == text { + Error::wda_input(e).with_message(message) + } else { + Error::action(Delivery::Sent, FailureStage::Send, message) + }) })?; } - Ok(replaced(text, submit, ¬e)) + let delivery = if old != text || submit { Delivery::Sent } else { Delivery::NotSent }; + Ok((replaced(text, submit, ¬e), delivery)) } /// What a replacement that went through says ([`Daemon::replace_text`]) @@ -875,66 +916,85 @@ pub(super) enum Typed { Fixed(usize), /// 对不上(输入框里现在的内容) Mismatch(String), + FocusChanged, } -pub(super) fn squash(s: &str) -> String { - s.chars().filter(|c| !c.is_whitespace()).collect() +/// Verification requires the entire requested insertion in the observed field. Existing digits or +/// an unrelated field changing cannot supply part of the evidence. Phone numbers may gain display spaces. +pub(super) fn newly_typed(before: &str, now: &str, text: &str) -> bool { + fn inserted(before: &str, now: &str, text: &str) -> bool { + if text.is_empty() || now.len().checked_sub(before.len()) != Some(text.len()) { + return false; + } + now.match_indices(text) + .any(|(i, _)| before.get(..i) == Some(&now[..i]) && before.get(i..) == Some(&now[i + text.len()..])) + } + if text.bytes().all(|b| b.is_ascii_digit()) { + let digits = |s: &str| s.split_whitespace().collect::(); + inserted(&digits(before), &digits(now), text) + } else { + inserted(before, now, text) + } } -/// 输入框里的内容有没有包含刚输入的文字(忽略空白:手机号之类会被自动加空格) -pub(super) fn typed_into(values: &[String], text: &str) -> bool { - let want = squash(text); - values.iter().any(|v| squash(v).contains(&want)) +/// Repair only an observed append of the exact leading characters, stable across two fresh reads. +pub(super) fn missing_suffix<'a>(before: &str, first: &str, second: &str, text: &'a str) -> Option<&'a str> { + if first != second { + return None; + } + let added = second.strip_prefix(before)?; + if added.is_empty() { + return None; + } + text.strip_prefix(added).filter(|rest| !rest.is_empty()) } -/// 输入框结尾是 `text` 的前几个字(后面的丢了):返回输进去了几个字 -pub(super) fn typed_prefix(values: &[String], text: &str) -> Option { - let chars: Vec = text.chars().collect(); - values - .iter() - .filter_map(|v| { - let v = squash(v); - (1..chars.len()).rev().find(|&k| { - let p = squash(&chars[..k].iter().collect::()); - !p.is_empty() && v.ends_with(&p) - }) - }) - .max() +/// Keep the focused field's identity and exact value, including whitespace. +async fn readable_focus(w: &mut WdaClient) -> Option<(String, String)> { + let f = w.focused_field().await.ok()??; + if !REPLACEABLE.contains(&f.kind.as_str()) { + return None; + } + let value = w.field_text(&f).await.ok()?; + Some((f.id, value)) } -pub(super) async fn verify_typed(w: &mut WdaClient, text: &str) -> Typed { - if squash(text).is_empty() { - return Typed::Unknown; - } - let mut values = None; - // 树可能比输入框慢一拍:第一次对不上隔一下再读一次,确认真的少了再补,免得补重 +async fn verify_typed(w: &mut WdaClient, before: Option<&(String, String)>, text: &str) -> Typed { + let Some((id, before)) = before else { return Typed::Unknown }; + let mut reads = Vec::with_capacity(2); for attempt in 0..2 { if attempt > 0 { tokio::time::sleep(Duration::from_millis(300)).await; } - let Some(v) = w.elements().await.ok().and_then(|e| elements::field_values(&e)) else { return Typed::Unknown }; - if v.is_empty() { - return Typed::Unknown; + let Some((now_id, now)) = readable_focus(w).await else { return Typed::Unknown }; + if now_id != *id { + return Typed::FocusChanged; } - if typed_into(&v, text) { + if newly_typed(before, &now, text) { return Typed::Ok; } - values = Some(v); + reads.push(now); } - let values = values.unwrap_or_default(); - let shown = || values.iter().find(|v| !v.is_empty()).cloned().unwrap_or_default(); - let Some(k) = typed_prefix(&values, text) else { return Typed::Mismatch(shown()) }; - // 剩下的一个字一个字慢慢补 - let rest: Vec = text.chars().skip(k).collect(); - for c in &rest { + let Some(rest) = missing_suffix(before, &reads[0], &reads[1], text) else { + return if reads[1].contains(text) && (reads[1] == *before || !reads[1].starts_with(before.as_str())) { + Typed::Unknown // replacing a selection with its original contents is indistinguishable + } else { + Typed::Mismatch(reads.pop().unwrap()) + }; + }; + for (i, c) in rest.chars().enumerate() { + if i > 0 && !w.focused_field().await.ok().flatten().is_some_and(|f| f.id == *id) { + return Typed::FocusChanged; + } if w.keys(&c.to_string()).await.is_err() { - return Typed::Mismatch(shown()); + return Typed::Mismatch(reads.pop().unwrap()); } tokio::time::sleep(Duration::from_millis(150)).await; } - match w.elements().await.ok().and_then(|e| elements::field_values(&e)) { - Some(v) if typed_into(&v, text) => Typed::Fixed(rest.len()), - Some(v) => Typed::Mismatch(v.into_iter().find(|v| !v.is_empty()).unwrap_or_default()), + match readable_focus(w).await { + Some((now_id, _)) if now_id != *id => Typed::FocusChanged, + Some((_, now)) if newly_typed(before, &now, text) => Typed::Fixed(rest.chars().count()), + Some((_, now)) => Typed::Mismatch(now), None => Typed::Unknown, } } @@ -1029,7 +1089,7 @@ mod tests { async fn replace(f: &Fake, text: &str, submit: bool) -> Result { let mut w = WdaClient::new(f); - wda_replace(&mut w, text, submit).await.map_err(|e| match e { + wda_replace(&mut w, text, submit).await.map(|(message, _)| message).map_err(|e| match e { WdaReplace::Untouched(e) => format!("untouched: {e}"), WdaReplace::Failed(e) => e.to_string(), }) @@ -1053,6 +1113,26 @@ mod tests { assert_eq!((f.value.as_str(), f.keys.len()), ("", 0)); } + #[tokio::test] + async fn replacement_reports_noop_and_field_mismatch_separately() { + let f = Fake::new("TextField", "same"); + let mut w = WdaClient::new(&f); + for (text, submit, expected) in + [("same", false, Delivery::NotSent), ("same", true, Delivery::Sent), ("", false, Delivery::Sent)] + { + let Ok((_, delivery)) = wda_replace(&mut w, text, submit).await else { panic!("replacement failed") }; + assert_eq!(delivery, expected); + } + f.0.lock().unwrap().mangle = |s| s.to_uppercase(); + let Err(WdaReplace::Failed(e)) = wda_replace(&mut w, "mismatch", true).await else { + panic!("expected a verification failure") + }; + let response = e.response(); + let req = crate::protocol::Request::ReplaceText { text: "mismatch".into(), submit: true }; + assert_eq!(response.delivery(&req), Delivery::Sent); + assert_eq!(response.field_readback(&req), Some("failed")); + } + /// The field already holds the text (or, emptying, reads its placeholder): nothing is cleared or typed #[tokio::test] async fn a_field_holding_the_text_is_left_alone() { diff --git a/crates/ictl-daemon/src/tools/mod.rs b/crates/ictl-daemon/src/tools/mod.rs index 762bdb2e..63f5bff0 100644 --- a/crates/ictl-daemon/src/tools/mod.rs +++ b/crates/ictl-daemon/src/tools/mod.rs @@ -5,6 +5,7 @@ mod keys; mod launch; mod native; mod observe; +mod scroll; pub(crate) use input::Stroke; @@ -21,9 +22,11 @@ use ictl_wda::http::DeviceTransport; use ictl_wda::{Launch, WdaClient, WdaError}; use crate::core::{Daemon, Inner, drop_tunnel, hid_supported, wda_down}; +use crate::error::Error; use crate::imaging::{self, fmt_g}; use crate::notify::Event; use crate::protocol::{ALERT_BLOCKING, Response, TAP_MISSED, TouchPhase}; +use crate::protocol::{Delivery, FailureStage}; use crate::protocol::{ElementData, StatusData}; pub(crate) use native::AX_WAIT; use observe::*; @@ -158,12 +161,12 @@ impl Daemon { /// A tap at a point: through WDA, or natively through HID async fn tap_at(&self, g: &mut Inner, x: f64, y: f64) -> crate::error::Result<()> { if let Some(w) = self.wda(g) { - return Ok(w.tap(x, y).await?); + return w.tap(x, y).await.map_err(Error::wda_input); } if self.native(g) { return Box::pin(self.native_tap(g, x, y)).await; } - Ok(self.require_wda(g)?.tap(x, y).await?) + self.require_wda(g).map_err(Error::preflight)?.tap(x, y).await.map_err(Error::wda_input) } /// 经隧道截图(WDA 不可用时)。失败就丢掉隧道,下次重建 @@ -220,15 +223,19 @@ impl Daemon { ) -> std::pin::Pin> + Send + 'h>>, { - let r = f(self.hid(g).await?).await; + let r = f(self.hid(g).await.map_err(|e| Error::action(Delivery::NotSent, FailureStage::Connect, e))?).await; g.hid_used = Some(Instant::now()); match r { Ok(()) => Ok(()), // 参数问题(例如不能输入的字符),连接没坏,不用重建 - Err(e @ DeviceError::InvalidInput(_)) => Err(e.into()), + Err(e @ DeviceError::InvalidInput(_)) => Err(Error::preflight(e)), Err(e) => { drop_tunnel(g).await; - Err(ictl_l10n::trf!("HID 命令失败: {e}", "HID command failed: {e}").into()) + Err(Error::action( + Delivery::Unknown, + FailureStage::Send, + ictl_l10n::trf!("HID 命令失败: {e}", "HID command failed: {e}"), + )) } } } @@ -623,7 +630,7 @@ mod tests { assert!(down(&swipe), "{swipe}"); // a finger: the same, and the page may still send the whole gesture once WDA is back match d.touch(&mut g, TouchPhase::Down, 20., 50., None).await { - Err(Response::Error { message, retry_as_gesture: true }) => assert!(down(&message), "{message}"), + Err(Response::Error { message, retry_as_gesture: true, .. }) => assert!(down(&message), "{message}"), other => panic!("{other:?}"), } assert!(g.dev.touch_rotation.is_none()); @@ -646,10 +653,6 @@ mod tests { assert!(hid_rotation(100, 100, fresh(Portrait)).is_err()); } - fn v(s: &[&str]) -> Vec { - s.iter().map(|x| x.to_string()).collect() - } - #[test] fn no_match_with_filter_names_the_filter() { assert_eq!(no_elements_text("", 0), "没有找到带文字的元素"); @@ -659,19 +662,23 @@ mod tests { } #[test] - fn typed_text_is_found_ignoring_spaces() { - assert!(typed_into(&v(&["搜索", "红烧肉做法"]), "红烧肉做法")); - assert!(typed_into(&v(&["130 1234 5678"]), "13012345678")); - assert!(!typed_into(&v(&["故宫博"]), "故宫博物院")); + fn input_readback_requires_new_evidence_in_the_same_field() { + assert!(newly_typed("", "130 1234 5678", "13012345678")); + assert!(!newly_typed("", "helloworld", "hello world")); + assert!(!newly_typed("", "hello", "hello ")); + assert!(newly_typed("", "hello world", "hello world")); + assert!(!newly_typed("1", "11", "11")); + assert!(newly_typed("ab", "a测b", "测")); + assert!(newly_typed("abc", "abcabc", "abc")); + assert!(!newly_typed("abc", "abc", "abc")); + assert!(!newly_typed("", "故宫博", "故宫博物院")); } #[test] - fn dropped_tail_is_detected_after_existing_text() { - assert_eq!(typed_prefix(&v(&["故宫博"]), "故宫博物院"), Some(3)); - // 输入框原来就有字 - assert_eq!(typed_prefix(&v(&["abc故宫"]), "故宫博物院"), Some(2)); - // 一个字都没进去(或者是占位文字):不猜,报对不上 - assert_eq!(typed_prefix(&v(&["搜索"]), "故宫博物院"), None); - assert_eq!(typed_prefix(&v(&[""]), "故宫"), None); + fn input_repair_requires_a_stable_new_prefix() { + assert_eq!(missing_suffix("abc", "abc故宫", "abc故宫", "故宫博物院"), Some("博物院")); + assert_eq!(missing_suffix("abc故宫", "abc故宫", "abc故宫", "故宫博物院"), None); + assert_eq!(missing_suffix("", "故", "故宫", "故宫博物院"), None); + assert_eq!(missing_suffix("abc", "def故宫", "def故宫", "故宫博物院"), None); } } diff --git a/crates/ictl-daemon/src/tools/native.rs b/crates/ictl-daemon/src/tools/native.rs index 2562c0d3..039d807e 100644 --- a/crates/ictl-daemon/src/tools/native.rs +++ b/crates/ictl-daemon/src/tools/native.rs @@ -49,7 +49,7 @@ fn native_for(backend: IosBackend, info: Option<&DeviceInfo>) -> bool { } enum PasteTarget<'a> { - Append(Option<&'a [String]>), + Append(Option<(ictl_ax::ObjectRef, &'a str)>), Replace(ictl_ax::ObjectRef), } @@ -66,15 +66,25 @@ enum Pasted { Missing, } -/// One read of the fields after a paste, against `old`, theirs before it (None: a password field) -fn paste_seen(now: Option<&[String]>, old: Option<&[String]>, wanted: &str) -> Pasted { - let (Some(now), Some(old)) = (now, old) else { return Pasted::Unreadable }; - if !now.iter().any(|v| v.contains(wanted)) { - Pasted::Missing - } else if now != old { +/// Compare only the original focused field's raw value, preserving whitespace. +fn paste_seen(now: Option<&str>, old: &str, wanted: &str) -> Pasted { + let Some(now) = now else { return Pasted::Unreadable }; + if input::newly_typed(old, now, wanted) { Pasted::Typed - } else { + } else if now == old && old.contains(wanted) { Pasted::Unchanged + } else if now.contains(wanted) && !now.starts_with(old) { + Pasted::Unreadable // a selection may have been replaced + } else { + Pasted::Missing + } +} + +fn append_seen(field: Option<&ictl_ax::Element>, object: ictl_ax::ObjectRef, old: &str, wanted: &str) -> Pasted { + match field { + Some(f) if f.object == Some(object) => paste_seen(Some(shown_text(f)), old, wanted), + Some(_) => Pasted::Missing, + None => Pasted::Unreadable, } } @@ -580,7 +590,7 @@ impl Daemon { /// A tap at a point through HID, the interface's rotation read first pub(crate) async fn native_tap(&self, g: &mut Inner, x: f64, y: f64) -> crate::error::Result<()> { - let rot = self.hid_touch_rotation(g).await?; + let rot = self.hid_touch_rotation(g).await.map_err(Error::preflight)?; self.hid_do(g, move |h| { Box::pin(async move { h.rotation = rot; @@ -597,7 +607,7 @@ impl Daemon { y: f64, seconds: f64, ) -> crate::error::Result<()> { - let rot = self.hid_touch_rotation(g).await?; + let rot = self.hid_touch_rotation(g).await.map_err(Error::preflight)?; self.hid_do(g, move |h| { Box::pin(async move { h.rotation = rot; @@ -611,29 +621,34 @@ impl Daemon { /// pasteboard is put back and Return pressed. Not as keys: HID keys go through the hardware keyboard's input /// source, which composed them as pinyin with the on-screen keyboard showing English («wifi» became marked /// pinyin «w i f i»), and the "next keyboard" button names the keyboard it switches to, not the one shown - pub(crate) async fn native_type(&self, g: &mut Inner, text: &str, submit: bool) -> crate::error::Result { + pub(crate) async fn native_type( + &self, + g: &mut Inner, + text: &str, + submit: bool, + field_verified: &mut Option, + ) -> crate::error::Result { let n = text.chars().count(); - let before = self.ax_tree_app(g).await?; - if !keyboard_up(&before) { - return Err(ictl_l10n::tr!( + let before = self.ax_snapshot(g, AX_WAIT, false).await.map_err(Error::preflight)?; + if !keyboard_up(&self.snapshot_tree(g, &before).await.map_err(Error::preflight)?) { + return Err(Error::preflight(ictl_l10n::tr!( "屏幕上没有键盘(没有输入框获得焦点),什么都没输;先点一下输入框,截图确认键盘出来了再输入", "No keyboard on screen (no text field has focus), nothing typed; tap a text field first and check with a screenshot that the keyboard is up" - ) - .into()); + ))); } - let old = elements::field_values(&before.elements); + let old = focused_text_field(&before).and_then(|f| Some((f.object?, shown_text(f)))); let mut note = String::new(); if !text.is_empty() { - let (typed, prompt) = self.native_paste(g, text, PasteTarget::Append(old.as_deref())).await?; + let (typed, prompt) = self.native_paste(g, text, PasteTarget::Append(old)).await?; if prompt { note += ictl_l10n::tr!("(已替你点了「允许粘贴」)", " (“Allow Paste” was tapped for you)"); } match typed { - Pasted::Typed => {} + Pasted::Typed => *field_verified = Some(true), Pasted::Unreadable => { note += ictl_l10n::tr!( - "(这是密码框,读不出内容,截图确认输进去了)", - " (a password field: its contents can't be read back, check with a screenshot)" + "(无法核对输入框内容,请查看屏幕确认)", + " (field contents could not be verified; inspect the screen)" ) } // the same text, selected, replaced by the paste (a search field keeping the last search) @@ -644,19 +659,25 @@ impl Daemon { ) } Pasted::Missing => { - return Err(ictl_l10n::trf!( + return Err(Error::readback(ictl_l10n::trf!( "粘贴了 {n} 个字符,但 {} 秒内输入框里没有这段文字{};截图看看:输入框可能没有焦点,或 App 不接受粘贴", "Pasted {n} characters, but the field didn't show the text within {} s{}; take a screenshot: the field may not have focus, or the app doesn't take pastes", PASTE_WAIT.as_secs(), if submit { ictl_l10n::tr!(",没有按回车", ", Return not pressed") } else { "" } - ) - .into()); + ))); } } } if submit { self.hid_do(g, |h| Box::pin(async move { h.type_ascii("\n").await })).await.map_err(|e| { - ictl_l10n::trf!("文字已输入{note},按回车失败:{e}", "Text typed{note}, pressing Return failed: {e}") + if text.is_empty() { + return e; + } + Error::action( + Delivery::Sent, + FailureStage::Send, + ictl_l10n::trf!("文字已输入{note},按回车失败:{e}", "Text typed{note}, pressing Return failed: {e}"), + ) })?; } Ok(ictl_l10n::trf!( @@ -668,57 +689,65 @@ impl Daemon { /// Replaces a single focused, readable field natively ([`Daemon::replace_text`]). Verifies the full value before /// sending Return - pub(crate) async fn native_replace(&self, g: &mut Inner, text: &str, submit: bool) -> crate::error::Result { - let before = self.ax_snapshot(g, AX_WAIT, false).await?; - if !keyboard_up(&self.snapshot_tree(g, &before).await?) { - return Err(ictl_l10n::tr!( + pub(crate) async fn native_replace( + &self, + g: &mut Inner, + text: &str, + submit: bool, + ) -> crate::error::Result<(String, Delivery)> { + let before = self.ax_snapshot(g, AX_WAIT, false).await.map_err(Error::preflight)?; + if !keyboard_up(&self.snapshot_tree(g, &before).await.map_err(Error::preflight)?) { + return Err(Error::preflight(ictl_l10n::tr!( "屏幕上没有键盘,先点一下要替换的输入框", "No keyboard on screen; tap the field you want to replace first" - ) - .into()); + ))); } - let (target, old) = - focused_text_field(&before).and_then(|f| Some((f.object?, shown_text(f)))).ok_or_else(|| { + let (target, old) = focused_text_field(&before) + .and_then(|f| Some((f.object?, shown_text(f)))) + .ok_or_else(|| { ictl_l10n::tr!( "无法确认当前聚焦的是可读的普通输入框,没有替换文字", "Couldn't identify a readable focused text field; no text was replaced" ) - })?; + }) + .map_err(Error::preflight)?; if old != text { let result = async { self.hid_do(g, |h| Box::pin(h.select_all())).await?; let seen = if text.is_empty() { // emptying: Delete takes the selection, nothing is pasted (no paste prompt) self.hid_do(g, |h| Box::pin(h.delete_backward())).await?; - self.native_field_emptied(g, target).await? + self.native_field_emptied(g, target).await.map_err(Error::readback)? } else { self.native_paste(g, text, PasteTarget::Replace(target)).await?.0 }; if seen != Pasted::Typed { - return Err(ictl_l10n::tr!( + return Err(Error::readback(ictl_l10n::tr!( "替换后无法核对输入框全文,未按回车;请查看手机界面", "Couldn't verify the full field value after the replacement; Return was not pressed" - ) - .into()); + ))); } Ok(()) } .await; if let Err(err) = result { if let Err(cause) = self.collapse_field_selection(g, target).await { - return Err(ictl_l10n::trf!( + let message = ictl_l10n::trf!( "{err}(无法收起原输入框的选区,请在重试前查看屏幕:{cause})", "{err} (couldn't collapse the original selection; inspect the screen before retrying: {cause})" - ) - .into()); + ); + return Err(err.with_message(message)); } return Err(err); } } if submit { - self.hid_do(g, |h| Box::pin(h.type_ascii("\n"))).await?; + self.hid_do(g, |h| Box::pin(h.type_ascii("\n"))) + .await + .map_err(|e| if old == text { e } else { Error::action(Delivery::Sent, FailureStage::Send, e) })?; } - Ok(input::replaced(text, submit, "")) + let delivery = if old != text || submit { Delivery::Sent } else { Delivery::NotSent }; + Ok((input::replaced(text, submit, ""), delivery)) } /// After select all and Delete: `target` reads as empty within [`CLEAR_WAIT`] @@ -753,15 +782,19 @@ impl Daemon { ) -> crate::error::Result<(Pasted, bool)> { // a paste through the WDA-down path may still wait to be put back self.restore_pasteboard(g, false).await; - self.hid(g).await?; + self.hid(g).await.map_err(|e| Error::action(Delivery::NotSent, FailureStage::Connect, e))?; let r = Box::pin(g.tunnel.as_mut().expect("hid() 刚建好隧道").paste_text(text)).await; g.hid_used = Some(Instant::now()); let pending = match r { Ok(p) => p, - Err(e @ DeviceError::InvalidInput(_)) => return Err(e.into()), + Err(e @ (DeviceError::InvalidInput(_) | DeviceError::PasteNotSent(_))) => return Err(Error::preflight(e)), Err(e) => { drop_tunnel(g).await; - return Err(ictl_l10n::trf!("粘贴失败:{e}", "Paste failed: {e}").into()); + return Err(Error::action( + Delivery::Unknown, + FailureStage::Send, + ictl_l10n::trf!("粘贴失败:{e}", "Paste failed: {e}"), + )); } }; g.dev.pending_paste = pending.map(|p| (Instant::now(), p)); @@ -770,10 +803,12 @@ impl Daemon { // when the paste prompt was last answered let mut answered: Option = None; let typed = loop { - let screen = self.ax_snapshot(g, AX_WAIT, true).await?; - let tree = self.snapshot_tree(g, &screen).await?; - if let Some((x, y)) = paste_allow(&tree) { - self.native_tap(g, x, y).await?; + let screen = self.ax_snapshot(g, AX_WAIT, true).await.map_err(Error::readback)?; + let tree = self.snapshot_tree(g, &screen).await.map_err(Error::readback)?; + if answered.is_none() + && let Some((x, y)) = paste_allow(&tree) + { + self.native_tap(g, x, y).await.map_err(|e| Error::action(Delivery::Sent, FailureStage::Send, e))?; answered = Some(Instant::now()); tokio::time::sleep(Duration::from_millis(300)).await; if Instant::now() >= deadline { @@ -782,9 +817,10 @@ impl Daemon { continue; } let seen = match target { - PasteTarget::Append(old) => { - paste_seen(elements::field_values(&tree.elements).as_deref(), old, text.trim()) + PasteTarget::Append(Some((object, old))) => { + append_seen(focused_text_field(&screen), object, old, text) } + PasteTarget::Append(None) => Pasted::Unreadable, PasteTarget::Replace(object) => replacement_seen(&screen, object, text), }; match seen { @@ -1217,15 +1253,20 @@ mod tests { #[test] fn a_paste_that_replaced_the_same_text_is_told_apart_from_one_that_missed() { - let v = |s: &[&str]| s.iter().map(|s| s.to_string()).collect::>(); - // into an empty field, and after text already there - assert_eq!(paste_seen(Some(&v(&["设置"])), Some(&v(&[""])), "设置"), Pasted::Typed); - assert_eq!(paste_seen(Some(&v(&["设置设置"])), Some(&v(&["设置"])), "设置"), Pasted::Typed); - // Spotlight's last search, selected, replaced by the same text: nothing changes - assert_eq!(paste_seen(Some(&v(&["设置"])), Some(&v(&["设置"])), "设置"), Pasted::Unchanged); - assert_eq!(paste_seen(Some(&v(&["时钟"])), Some(&v(&["时钟"])), "设置"), Pasted::Missing); - assert_eq!(paste_seen(Some(&v(&[""])), Some(&v(&[""])), "设置"), Pasted::Missing); - assert_eq!(paste_seen(None, Some(&v(&[""])), "设置"), Pasted::Unreadable); - assert_eq!(paste_seen(Some(&v(&["设置"])), None, "设置"), Pasted::Unreadable); + let mut f = ictl_ax::Element { + object: Some(ictl_ax::ObjectRef { id: 1, pid: 2, is_app: false }), + value: "设置".into(), + ..Default::default() + }; + let original = f.object.unwrap(); + assert_eq!(append_seen(Some(&f), original, "", "设置"), Pasted::Typed); + f.object.as_mut().unwrap().id += 1; + assert_eq!(append_seen(Some(&f), original, "", "设置"), Pasted::Missing); + assert_eq!(paste_seen(Some("设置"), "", "设置"), Pasted::Typed); + assert_eq!(paste_seen(Some("设置设置"), "设置", "设置"), Pasted::Typed); + assert_eq!(paste_seen(Some("设置"), "设置", "设置"), Pasted::Unchanged); + assert_eq!(paste_seen(Some("时钟"), "时钟", "设置"), Pasted::Missing); + assert_eq!(paste_seen(Some("11"), "1", "11"), Pasted::Missing); + assert_eq!(paste_seen(None, "", "设置"), Pasted::Unreadable); } } diff --git a/crates/ictl-daemon/src/tools/scroll.rs b/crates/ictl-daemon/src/tools/scroll.rs new file mode 100644 index 00000000..cdc003fa --- /dev/null +++ b/crates/ictl-daemon/src/tools/scroll.rs @@ -0,0 +1,199 @@ +//! Collect visible text as a list scrolls, retaining the final viewport for a follow-up action. + +use super::*; +use crate::protocol::{Data, ScrollCollect, ScrollMatch, ScrollRow, ScrollStop}; +use elements::Element; + +impl Daemon { + pub(crate) async fn scroll_collect( + &self, + g: &mut Inner, + scan: &ScrollCollect, + mut may_continue: impl FnMut() -> bool, + ) -> crate::error::Result<(String, Data)> { + self.ensure_unlocked(g).await?; + let filter = scan.filter.to_lowercase(); + let until = scan.until.to_lowercase(); + let limit = scan.limit; + let mut tree = self.tree(g, Duration::ZERO).await?; + let mut previous = None; + let mut rows = Vec::new(); + let mut lines = Vec::new(); + let mut scrolls = 0; + loop { + let page = visible_page(&tree, scan.down); + let matched = visible_match(&page, &until); + let before = previous.as_ref().map(|t| visible_page(t, scan.down)).unwrap_or_default(); + for e in new_rows(&before, &page).into_iter().filter(|e| e.matches_filter(&filter)).take(limit - rows.len()) + { + lines.push(e.describe_text()); + rows.push(ScrollRow { + kind: e.kind.clone(), + label: e.label.clone(), + name: e.name.clone(), + value: e.value.clone(), + }); + } + let end = previous.as_ref().is_some_and(|p| unchanged_viewport(p, &tree)); + if let Some(reason) = stop_reason(matched.is_some(), rows.len() == limit, end, scrolls == scan.max_scrolls) + { + let why = match reason { + ScrollStop::Found => ictl_l10n::tr!("找到目标", "found the target"), + ScrollStop::End => { + ictl_l10n::tr!("滚动后可见内容没有变化", "visible content stayed the same after scrolling") + } + ScrollStop::Limit => ictl_l10n::tr!("已达到行数上限", "row limit reached"), + ScrollStop::MaxScrolls => ictl_l10n::tr!("已达到滚动次数上限", "scroll limit reached"), + }; + let n = rows.len(); + let mut text = ictl_l10n::trf!( + "滑动 {scrolls} 次,收集 {n} 行,{why}", + "Scrolled {scrolls} times, collected {n} rows, {why}" + ); + let matched = matched.map(|e| { + let point = match tree.tap_point(e) { + TapPoint::Center(p) | TapPoint::Moved { at: p, .. } => p, + TapPoint::Covered { .. } => unreachable!("visible_page excludes covered rows"), + }; + text += &format!("\n{} @({},{})", e.describe_text(), point.0, point.1); + let r = e.visible; + let element = ElementData { x: r.x, y: r.y, width: r.w, height: r.h, ..element_data(e) }; + Box::new(ScrollMatch { element, point }) + }); + for line in lines { + text.push('\n'); + text.push_str(&line); + } + text += &self.snapshot_note(g); + return Ok((text, Data::ScrollCollection { stop_reason: reason, scrolls, rows, matched })); + } + // Let a gesture finish. A cancellation, pause or takeover prevents the next one. + if !may_continue() { + return Err(ictl_l10n::trf!( + "滚动已中断,已滑动 {scrolls} 次", + "Collection interrupted after {scrolls} scrolls" + ) + .into()); + } + previous = Some(tree); + tree = Box::pin(self.search_scroll(g, scan.down)).await?; + scrolls += 1; + } + } +} + +/// A truncated read can omit the rows that moved. Only two complete, populated reads can show the end. +fn unchanged_viewport(before: &Tree, after: &Tree) -> bool { + !before.incomplete && !after.incomplete && !after.elements.is_empty() && after.close_to(before, STILL_TOLERANCE) +} + +fn stop_reason(found: bool, row_limit: bool, end: bool, scroll_limit: bool) -> Option { + if found { + Some(ScrollStop::Found) + } else if row_limit { + Some(ScrollStop::Limit) + } else if end { + Some(ScrollStop::End) + } else if scroll_limit { + Some(ScrollStop::MaxScrolls) + } else { + None + } +} + +fn visible_page(tree: &Tree, down: bool) -> Vec<&Element> { + let mut page: Vec<_> = + tree.elements.iter().filter(|e| !matches!(tree.tap_point(e), TapPoint::Covered { .. })).collect(); + page.sort_by_key(|e| (if down { e.center.1 } else { -e.center.1 }, e.center.0)); + page +} + +fn visible_match<'a>(page: &[&'a Element], until: &str) -> Option<&'a Element> { + if until.is_empty() { + return None; + } + page.iter().copied().find(|e| e.contains_text(until)) +} + +/// Fixed headers and footers recur at the same location. After removing those, consecutive viewports +/// share a suffix/prefix in travel order. Comparing sequences preserves identical labels in distinct rows. +fn new_rows<'a>(before: &[&Element], page: &[&'a Element]) -> Vec<&'a Element> { + fn key(e: &Element) -> (&str, &str, &str, &str) { + (&e.kind, &e.name, &e.label, &e.value) + } + let fixed = |(a, b): (&&Element, &&Element)| key(a) == key(b) && a.center == b.center; + let head = before.iter().zip(page).take_while(|pair| fixed(*pair)).count(); + let (before, page) = (&before[head..], &page[head..]); + let tail = before.iter().rev().zip(page.iter().rev()).take_while(|pair| fixed(*pair)).count(); + let (before, page) = (&before[..before.len() - tail], &page[..page.len() - tail]); + let overlap = (1..=before.len().min(page.len())) + .rev() + .find(|&n| before[before.len() - n..].iter().zip(&page[..n]).all(|(a, b)| key(a) == key(b))) + .unwrap_or(0); + page[overlap..].to_vec() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tree(labels: &[(&str, i64)]) -> Tree { + let mut xml = String::from(""); + for (label, y) in labels { + xml += &format!( + r#""# + ); + } + xml += ""; + elements::parse_tree(&xml, ScreenSize { width: 430.0, height: 932.0 }) + } + + #[test] + fn overlap_preserves_separate_rows_in_both_directions_and_skips_fixed_content() { + let a = tree(&[("Header", 0), ("A", 100), ("Repeat", 180), ("B", 260), ("Footer", 800)]); + let b = tree(&[("Header", 0), ("Repeat", 100), ("B", 180), ("Repeat", 260), ("C", 340), ("Footer", 800)]); + let down = new_rows(&visible_page(&a, true), &visible_page(&b, true)); + assert_eq!(down.iter().map(|e| e.label.as_str()).collect::>(), ["Repeat", "C"]); + let up = new_rows(&visible_page(&b, false), &visible_page(&a, false)); + assert_eq!(up.iter().map(|e| e.label.as_str()).collect::>(), ["A"]); + assert!(new_rows(&visible_page(&a, true), &visible_page(&a, true)).is_empty()); + } + + #[test] + fn identical_rows_that_scroll_into_the_same_position_are_kept() { + let a = tree(&[("A", 100), ("Repeat", 200), ("B", 300)]); + let b = tree(&[("B", 100), ("Repeat", 200), ("C", 300)]); + let added = new_rows(&visible_page(&a, true), &visible_page(&b, true)); + assert_eq!(added.iter().map(|e| e.label.as_str()).collect::>(), ["Repeat", "C"]); + } + + #[test] + fn a_covered_row_cannot_stop_the_search() { + let xml = include_str!("../../../ictl-wda/tests/fixtures/settings-floating-search-native-ios27.xml"); + let tree = elements::parse_tree(xml, ScreenSize { width: 430.0, height: 932.0 }); + let page = visible_page(&tree, true); + assert!(visible_match(&page, "资源库").is_none()); + assert!(visible_match(&page, "相机").is_some()); + assert!(visible_match(&page, "").is_none()); + } + + #[test] + fn truncated_or_empty_viewports_do_not_establish_the_end() { + let complete = tree(&[("Header", 0)]); + let mut partial = complete.clone(); + partial.incomplete = true; + assert!(unchanged_viewport(&complete, &complete)); + assert!(!unchanged_viewport(&complete, &partial)); + assert!(!unchanged_viewport(&partial, &complete)); + assert!(!unchanged_viewport(&Tree::default(), &Tree::default())); + } + + #[test] + fn a_visible_match_wins_even_on_the_last_viewport() { + assert_eq!(stop_reason(true, true, true, true), Some(ScrollStop::Found)); + assert_eq!(stop_reason(false, true, false, false), Some(ScrollStop::Limit)); + assert_eq!(stop_reason(false, false, true, true), Some(ScrollStop::End)); + assert_eq!(stop_reason(false, false, false, true), Some(ScrollStop::MaxScrolls)); + assert_eq!(stop_reason(false, false, false, false), None); + } +} diff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rs index 7f9f30ee..96ff63a4 100644 --- a/crates/ictl-device/src/lib.rs +++ b/crates/ictl-device/src/lib.rs @@ -124,6 +124,9 @@ pub enum DeviceError { /// 调用方给的参数不合法(例如 HID 不能输入的字符)。与连接无关,不需要重建会话 #[error("{0}")] InvalidInput(String), + /// Preparing the pasteboard failed before the paste shortcut was sent. + #[error("{0}")] + PasteNotSent(String), /// 手机拒绝启动 App([`Tunnel::launch_in_background`] 回了 NSError)。签名证书被吊销时就是这样: /// 手机日志里 amfid 报 `The identity used to sign the executable is no longer valid` #[error("{}", ictl_l10n::trf!("手机拒绝启动(NSError code {0})", "The phone refused to launch it (NSError code {0})", .0))] @@ -782,7 +785,7 @@ impl Tunnel { }) .await .map_err(|e| { - DeviceError::Idevice(ictl_l10n::trf!( + DeviceError::PasteNotSent(ictl_l10n::trf!( "文字写不进剪贴板,没有粘贴:{e}", "The text couldn't be put on the pasteboard; nothing was pasted: {e}" )) @@ -792,7 +795,7 @@ impl Tunnel { if let Some(items) = &saved { write_back(adapter, handshake, items).await; } - return Err(DeviceError::Idevice( + return Err(DeviceError::PasteNotSent( ictl_l10n::tr!( "文字写进剪贴板后读回来对不上,没有粘贴", "The text read back from the pasteboard didn't match what was written; nothing was pasted" diff --git a/crates/ictl-mcp/Cargo.toml b/crates/ictl-mcp/Cargo.toml index 2479e79f..f69418bf 100644 --- a/crates/ictl-mcp/Cargo.toml +++ b/crates/ictl-mcp/Cargo.toml @@ -7,7 +7,7 @@ license.workspace = true publish.workspace = true repository.workspace = true homepage.workspace = true -description = "MCP stdio 服务(17 个 iphone_* 工具)" +description = "MCP stdio 服务(18 个 iphone_* 工具)" [dependencies] ictl-l10n.workspace = true diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs index 0f01d463..02bde386 100644 --- a/crates/ictl-mcp/src/lib.rs +++ b/crates/ictl-mcp/src/lib.rs @@ -7,7 +7,7 @@ use std::path::PathBuf; use std::time::Duration; -use ictl_protocol::{self as protocol, MAX_TAP_COUNT, Request, Response}; +use ictl_protocol::{self as protocol, Delivery, FailureStage, MAX_TAP_COUNT, Request, Response}; use rmcp::{ ErrorData, RoleServer, ServerHandler, ServiceExt, model::{ @@ -137,7 +137,7 @@ pub fn dev_tools_enabled() -> bool { .is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on")) } -/// The tools this server lists: the 17 standard ones, plus the developer tools when switched on +/// The tools this server lists: the 18 standard ones, plus the developer tools when switched on pub fn tools() -> Vec { tools_with(dev_tools_enabled()) } @@ -270,7 +270,7 @@ fn dev_tools() -> Vec { ] } -/// 17 个工具的定义(toolkit 的 13 个 + iphone_wait_for、iphone_batch、iphone_list_devices、iphone_select_device)。 +/// 18 个工具的定义(toolkit 的 13 个 + iphone_wait_for、iphone_batch、iphone_list_devices、iphone_select_device、iphone_scroll_collect)。 /// 描述可以改写,但工具名、参数、默认返回不改(docs/decisions.md D10) fn standard_tools() -> Vec { let t = |name: &'static str, desc: String, s: Map, a: ToolAnnotations| { @@ -324,6 +324,19 @@ WDA 不可用时会说明哪些功能受影响(读元素、按名字点击、启 looking(ictl_l10n::tr!("列出界面元素", "List UI elements")), ) .with_raw_output_schema(std::sync::Arc::new(elements_output_schema())), + t( + "iphone_scroll_collect", + ictl_l10n::tr!("收集连续几屏里可见的文字行,合并相邻屏的重叠内容。可用 until 找到文字就停在当前屏。只滑动,不点击。返回 rows、scrolls、stop_reason,以及找到时当前屏上的 matched。", + "Collect visible text rows across overlapping viewports. Use until to stop with a matching element on screen. Only scrolls, never taps. Returns rows, scrolls, stop_reason and the matched element on the final viewport.").into(), + schema(json!({ + "scroll": {"type": "string", "enum": ["down", "up"], "default": "down", "description": ictl_l10n::tr!("往下或往上找", "look further down or up the list")}, + "until": {"type": "string", "description": ictl_l10n::tr!("可见元素的文字、标识或值包含这段文字时停止,不区分大小写", "stop at a visible label, name or value containing this text, case-insensitive")}, + "filter": {"type": "string", "description": ictl_l10n::tr!("只收集类型或文字包含它的行。与 until 独立", "collect rows whose type or text contains this string, independent of until")}, + "limit": {"type": "integer", "minimum": 1, "maximum": protocol::MAX_SCROLL_ROWS, "default": protocol::MAX_SCROLL_ROWS, "description": ictl_l10n::tr!("最多收集几行", "stop after collecting this many rows")}, + "max_scrolls": {"type": "integer", "minimum": 1, "maximum": protocol::MAX_SEARCH_SCROLLS, "default": 8, "description": ictl_l10n::tr!("最多滚动几次", "maximum number of scrolls")} + }), &[]), + acting(ictl_l10n::tr!("滚动收集文字", "Scroll and collect text"), false, false), + ), t( "iphone_tap", action_desc( @@ -651,7 +664,11 @@ fn scroll_search(a: &Args) -> Result, String if dir.is_empty() { return Ok(None); } - let down = match dir.as_str() { + checked_scroll(&dir, max).map(Some) +} + +fn checked_scroll(dir: &str, max: usize) -> Result { + let down = match dir { "down" => true, "up" => false, _ => return Err(ictl_l10n::trf!("参数 scroll 要是 down 或 up", "parameter scroll must be down or up")), @@ -663,7 +680,7 @@ fn scroll_search(a: &Args) -> Result, String ictl_protocol::MAX_SEARCH_SCROLLS )); } - Ok(Some(ictl_protocol::ScrollSearch { down, max: max as u32 })) + Ok(protocol::ScrollSearch { down, max: max as u32 }) } pub fn to_request(name: &str, args: &Map) -> Result { @@ -691,6 +708,24 @@ pub fn to_request(name: &str, args: &Map) -> Result { + let limit = a.u_or("limit", protocol::MAX_SCROLL_ROWS)?; + if !(1..=protocol::MAX_SCROLL_ROWS).contains(&limit) { + return Err(ictl_l10n::trf!( + "limit 要在 1 到 {} 之间", + "limit must be between 1 and {}", + protocol::MAX_SCROLL_ROWS + )); + } + let scroll = checked_scroll(&a.s_or("scroll", "down")?, a.u_or("max_scrolls", 8)?)?; + Request::ScrollCollect(protocol::ScrollCollect { + down: scroll.down, + max_scrolls: scroll.max, + until: a.s_or("until", "")?, + filter: a.s_or("filter", "")?, + limit, + }) + } "iphone_tap" => Request::Tap { x: a.f("x")?, y: a.f("y")?, count: a.count("count")? }, "iphone_tap_element" => Request::TapElement { text: a.s("text")?, @@ -997,6 +1032,7 @@ pub fn wants_alert_check(req: &Request) -> bool { | Request::Status | Request::ScreenStream | Request::Screenshot { .. } + | Request::ScrollCollect(_) | Request::ListElements { .. } | Request::ListApps { .. } | Request::Settle { .. } @@ -1026,7 +1062,7 @@ pub fn wants_alert_check(req: &Request) -> bool { } } -/// The shape of [`with_elements`]' structured content, declared as `iphone_list_elements`' output schema (action +/// The shape of [`with_element_data`]' structured content, declared as `iphone_list_elements`' output schema (action /// tools give it with then=elements, but not always: a declared schema would oblige every result to carry it). /// `matched_count` and `truncated` are left out by a daemon older than them fn elements_output_schema() -> Map { @@ -1051,8 +1087,8 @@ fn elements_output_schema() -> Map { v.as_object().cloned().unwrap_or_default() } -fn with_elements(mut result: CallToolResult, data: Option) -> CallToolResult { - if let Some(data @ protocol::Data::Elements { .. }) = data { +fn with_element_data(mut result: CallToolResult, data: Option) -> CallToolResult { + if let Some(data @ (protocol::Data::Elements { .. } | protocol::Data::ScrollCollection { .. })) = data { result.structured_content = serde_json::to_value(data).ok(); } result @@ -1062,7 +1098,7 @@ fn with_elements(mut result: CallToolResult, data: Option) -> Ca pub fn to_result(r: Response) -> CallToolResult { match r { Response::Text { text, data, .. } => { - with_elements(CallToolResult::success(vec![ContentBlock::text(text)]), data) + with_element_data(CallToolResult::success(vec![ContentBlock::text(text)]), data) } Response::Image { jpeg_base64, caption } => { CallToolResult::success(vec![ContentBlock::image(jpeg_base64, "image/jpeg"), ContentBlock::text(caption)]) @@ -1071,6 +1107,43 @@ pub fn to_result(r: Response) -> CallToolResult { } } +/// Tools that expose delivery of their primary tap, gesture, or text input. +pub fn reports_input(name: &str) -> bool { + matches!(name, "iphone_tap" | "iphone_tap_element" | "iphone_type_text" | "iphone_swipe" | "iphone_long_press") +} + +fn input_error( + message: impl Into, + name: &str, + delivery: Delivery, + stage: Option, +) -> CallToolResult { + let mut message = message.into(); + if !reports_input(name) { + return to_result(Response::error(message)); + } + if delivery == Delivery::Unknown { + message += ictl_l10n::tr!( + "。输入可能已送达,请先查看屏幕再决定下一步。", + ". Input may have reached the phone. Inspect the screen before retrying." + ); + } + let mut result = to_result(Response::error(message)); + result.structured_content = + Some(json!({"delivery": delivery, "readback": {"screen": "not_requested", "settle": "not_requested"}})); + if let Some(stage) = stage { + result.structured_content.as_mut().unwrap()["stage"] = json!(stage); + } + result +} + +struct InputResult<'a> { + delivery: Delivery, + stage: Option, + field: Option<&'static str>, + udid: Option<&'a str>, +} + #[derive(Debug, Clone)] pub struct McpServer { pub socket: PathBuf, @@ -1142,6 +1215,7 @@ impl McpServer { context: RequestContext, ) -> Result { // working for a task: the daemon holds or refuses the calls; announce each so the page shows the tool + let name = request.name.clone(); let args = request.arguments.clone().unwrap_or_default(); let work = async { if request.name == task::CONFIRM_TOOL { @@ -1164,12 +1238,14 @@ impl McpServer { } r } - task::Before::Refuse(m) => Ok(CallToolResult::error(vec![ContentBlock::text(m)]).into()), + task::Before::Refuse(m) => { + Ok(input_error(m, &name, Delivery::NotSent, Some(FailureStage::Preflight)).into()) + } } }; tokio::select! { r = work => r, - _ = context.ct.cancelled() => Ok(to_result(Response::error(ictl_l10n::tr!("调用已取消", "Call cancelled"))).into()), + _ = context.ct.cancelled() => Ok(input_error(ictl_l10n::tr!("调用已取消", "Call cancelled"), &name, Delivery::Unknown, None).into()), } } @@ -1180,20 +1256,21 @@ impl McpServer { ) -> Result { // rmcp 收到取消通知只是置这个令牌,不会中止处理:自己停下。丢掉进行中的调用会断开到守护进程的连接, // 守护进程那边还在排队的请求随之放弃(protocol::call),iphone_batch 剩下的步骤也不再执行 + let name = request.name.clone(); tokio::select! { r = self.call_tool_inner(request) => r, - _ = context.ct.cancelled() => Ok(to_result(Response::error(ictl_l10n::tr!("调用已取消", "Call cancelled"))).into()), + _ = context.ct.cancelled() => Ok(input_error(ictl_l10n::tr!("调用已取消", "Call cancelled"), &name, Delivery::Unknown, None).into()), } } async fn call_tool_inner(&self, request: CallToolRequestParams) -> Result { let args = request.arguments.unwrap_or_default(); if let Err(e) = check_args(&request.name, &args, &[], true) { - return Ok(to_result(Response::error(e)).into()); + return Ok(input_error(e, &request.name, Delivery::NotSent, Some(FailureStage::Preflight)).into()); } let then = match parse_then(&args) { Ok(t) => t, - Err(e) => return Ok(to_result(Response::error(e)).into()), + Err(e) => return Ok(input_error(e, &request.name, Delivery::NotSent, Some(FailureStage::Preflight)).into()), }; if request.name == "iphone_batch" { return Ok(self.batch(&args, then).await.into()); @@ -1208,19 +1285,53 @@ impl McpServer { } let req = match to_request(&request.name, &args) { Ok(r) => r, - Err(e) => return Ok(to_result(Response::error(e)).into()), + Err(e) => return Ok(input_error(e, &request.name, Delivery::NotSent, Some(FailureStage::Preflight)).into()), }; // then 只对操作类工具有意义;看界面的工具本身就是返回界面 - let resp = self.call(&req).await; - Ok(match resp { - Response::Text { text, outcome, .. } if req.is_device_action() => { + // A single input and its readbacks must all apply to the same device. Tasks already pin theirs. + let udid = if req.reports_delivery() && !protocol::in_task() { + match self.controlled_udid().await { + Ok(id) => Some(id), + Err((message, stage)) => { + return Ok(input_error(message, &request.name, Delivery::NotSent, Some(stage)).into()); + } + } + } else { + None + }; + let resp = self.call_on(&req, udid.as_deref()).await; + let input = req.reports_delivery().then(|| InputResult { + delivery: resp.delivery(&req), + stage: resp.failure_stage(), + field: resp.field_readback(&req), + udid: udid.as_deref(), + }); + if matches!(req, Request::ScrollCollect(_)) { + return Ok(to_result(resp).into()); + } + Ok(match (resp, input) { + (Response::Error { mut message, .. }, Some(input)) => { + message += match input.delivery { + Delivery::NotSent => ictl_l10n::tr!("。目标输入未发出。", ". The requested input was not sent."), + Delivery::Unknown => ictl_l10n::tr!( + "。输入可能已送达,请先查看屏幕再决定下一步。", + ". Input may have reached the phone. Inspect the screen before retrying." + ), + Delivery::Sent => ictl_l10n::tr!( + "。输入已发出,请查看屏幕再决定下一步。", + ". Input was sent. Inspect the screen before retrying." + ), + }; + self.finish(message, true, then, false, false, Some(input)).await + } + (Response::Text { text, outcome, .. }, input) if req.is_device_action() => { // 结果里已经说了有弹窗(启动 App 被挡)就不再查 let check = wants_alert_check(&req) && !protocol::alert_reported(&text, outcome); // 按名字没点到东西:界面没动过,不用等它稳定,直接给界面(按名字点击刚读过的树) let settle = !tap_missed(&text, outcome); - self.finish(text, false, then, check, settle).await + self.finish(text, false, then, check, settle, input).await } - resp => to_result(resp), + (resp, _) => to_result(resp), } .into()) } @@ -1236,12 +1347,18 @@ impl McpServer { let wait = if matches!(req, Request::InstallApp { .. }) { 660 } else { 150 }; // in a task the daemon holds calls while the user has paused or taken over, as long as that takes let wait = (!protocol::in_task()).then(|| Duration::from_secs(wait)); - protocol::call_expecting(&self.socket, req, wait, expect_udid).await.unwrap_or_else(|e| { - Response::error(ictl_l10n::trf!( - "连不上守护进程({}):{e};确认守护进程在运行(iphone-control status)", - "Can't reach the daemon ({}): {e}; make sure the daemon is running (iphone-control status)", - self.socket.display() - )) + protocol::exchange_on(&self.socket, req, wait, expect_udid, None, None).await.unwrap_or_else(|e| { + let reason = e.source; + let message = if e.failure.stage == FailureStage::Connect { + ictl_l10n::trf!( + "连不上守护进程({}):{reason};确认守护进程在运行(iphone-control status)", + "Can't reach the daemon ({}): {reason}; make sure the daemon is running (iphone-control status)", + self.socket.display() + ) + } else { + ictl_l10n::trf!("守护进程请求失败: {reason}", "Daemon request failed: {reason}") + }; + Response::error(message).with_failure(e.failure.delivery, e.failure.stage) }) } @@ -1254,75 +1371,122 @@ impl McpServer { opts: ThenOpts, alert_check: bool, settle: bool, + input: Option>, ) -> CallToolResult { - let done = |blocks: Vec| { - if failed { CallToolResult::error(blocks) } else { CallToolResult::success(blocks) } - }; - let then = opts.then; - if then == Then::None { - if alert_check && let Response::Text { text: t, .. } = self.call(&Request::AlertCheck).await { - text += &t; - } - return done(vec![ContentBlock::text(text)]); - } - if settle { - match self.call(&Request::Settle { max_ms: opts.settle_ms }).await { - Response::Text { text: t, .. } => text += &format!("\n{t}"), - Response::Error { message, .. } => { - text += &ictl_l10n::trf!( - "\n(等界面稳定失败:{message})", - "\n(waiting for the screen to settle failed: {message})" - ) + let expect_udid = input.as_ref().and_then(|i| i.udid); + let mut elements = None; + let mut readback = json!({"settle": "not_requested", "screen": "not_requested"}); + let mut image = None; + if opts.then == Then::None { + if alert_check { + match self.call_on(&Request::AlertCheck, expect_udid).await { + Response::Text { text: t, .. } => { + text += &t; + readback["alert"] = "ok".into(); + } + Response::Error { message, .. } if input.is_some() => { + text += &ictl_l10n::trf!("\n(检查弹窗失败:{message})", "\n(alert check failed: {message})"); + readback["alert"] = "failed".into(); + } + _ => readback["alert"] = "failed".into(), } - Response::Image { .. } => {} } - } - match then { - Then::Elements(filter) => { - // Settle 刚读过元素树,直接用它 - match self - .call(&Request::ListElements { - filter, - limit: THEN_LIMIT, - max_age_ms: THEN_SETTLE_MS, - keep_locked: false, - }) - .await - { - Response::Text { text: t, data, .. } => { - text += - &ictl_l10n::trf!("\n--- 操作后的界面 ---\n{t}", "\n--- Screen after the action ---\n{t}"); - let result = done(vec![ContentBlock::text(text)]); - return with_elements(result, data); + } else { + if settle { + match self.call_on(&Request::Settle { max_ms: opts.settle_ms }, expect_udid).await { + Response::Text { text: t, .. } => { + text += &format!("\n{t}"); + readback["settle"] = "ok".into(); } Response::Error { message, .. } => { - text += &ictl_l10n::trf!("\n(读界面失败:{message})", "\n(reading the screen failed: {message})") + text += &ictl_l10n::trf!( + "\n(等界面稳定失败:{message})", + "\n(waiting for the screen to settle failed: {message})" + ); + readback["settle"] = "failed".into(); } - Response::Image { .. } => {} + _ => readback["settle"] = "failed".into(), + } + } + let read = match opts.then { + Then::Elements(filter) => { + Request::ListElements { filter, limit: THEN_LIMIT, max_age_ms: THEN_SETTLE_MS, keep_locked: false } + } + Then::Screenshot(region) => Request::Screenshot { region }, + Then::None => unreachable!(), + }; + let screen = match self.call_on(&read, expect_udid).await { + Response::Text { text: t, data, .. } if matches!(read, Request::ListElements { .. }) => { + elements = data; + text += &ictl_l10n::trf!("\n--- 操作后的界面 ---\n{t}", "\n--- Screen after the action ---\n{t}"); + "ok" } - done(vec![ContentBlock::text(text)]) + Response::Image { jpeg_base64, caption } if matches!(read, Request::Screenshot { .. }) => { + image = Some((jpeg_base64, caption)); + "ok" + } + Response::Error { message, .. } => { + text += &ictl_l10n::trf!("\n(读界面失败:{message})", "\n(reading the screen failed: {message})"); + "failed" + } + _ => { + text += ictl_l10n::tr!("\n(未收到请求的界面)", "\n(The requested screen was not returned.)"); + "failed" + } + }; + readback["screen"] = screen.into(); + } + let read_failed = readback.as_object().unwrap().values().any(|v| v == "failed"); + if input.is_some() && read_failed && !failed { + text += ictl_l10n::tr!( + "\n请单独读取屏幕确认结果,避免重复之前的输入。", + "\nRead the screen separately before repeating any input." + ); + } + let mut blocks = vec![ContentBlock::text(text)]; + if let Some((jpeg, caption)) = image { + blocks.push(ContentBlock::image(jpeg, "image/jpeg")); + blocks.push(ContentBlock::text(caption)); + } + let mut result = if failed { CallToolResult::error(blocks) } else { CallToolResult::success(blocks) }; + result = with_element_data(result, elements); + if let Some(input) = input { + let data = result.structured_content.get_or_insert_with(|| json!({})); + data["delivery"] = json!(input.delivery); + data["readback"] = readback; + if let Some(field) = input.field { + data["readback"]["field"] = field.into(); + } + if let Some(stage) = input.stage.or_else(|| (read_failed && !failed).then_some(FailureStage::Readback)) { + data["stage"] = json!(stage); } - 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"), - ContentBlock::text(caption), - ]), - Response::Error { message, .. } => done(vec![ContentBlock::text(ictl_l10n::trf!( - "{text}\n(截图失败:{message})", - "{text}\n(screenshot failed: {message})" - ))]), - Response::Text { text: t, .. } => done(vec![ContentBlock::text(format!("{text}\n{t}"))]), - }, - Then::None => unreachable!("上面已返回"), } + result } - /// 守护进程正在控制的设备的 UDID;读不到(没接设备、连不上)返回 None - async fn controlled_udid(&self) -> Option { - let Response::Text { text, .. } = self.call(&Request::Daemon).await else { return None }; - let v: Value = serde_json::from_str(&text).ok()?; - v["device"]["udid"].as_str().filter(|u| !u.is_empty()).map(str::to_owned) + /// The cached daemon snapshot includes device.udid on older daemons as well. + async fn controlled_udid(&self) -> Result { + match self.call(&Request::Daemon).await { + Response::Text { text, .. } => { + if let Ok(snapshot) = serde_json::from_str::(&text) + && let Some(id) = snapshot["device"]["udid"].as_str().filter(|id| !id.is_empty()) + { + return Ok(id.to_owned()); + } + } + Response::Error { message, failure, .. } => { + return Err((message, failure.map_or(FailureStage::Preflight, |f| f.stage))); + } + Response::Image { .. } => {} + } + Err(( + ictl_l10n::tr!( + "无法确定当前控制的设备,操作未执行", + "Cannot identify the controlled device; action not sent" + ) + .into(), + FailureStage::Preflight, + )) } /// 按顺序执行;某一步出错就停,说明是第几步、后面几步没执行。出错时也按 then 附上当前界面,方便看停在哪 @@ -1333,7 +1497,7 @@ impl McpServer { }; let total = steps.len(); // 每一步都要求还是开始时控制的那台:自动选设备时拔掉它会改控另一台,剩下的步骤不能落到那台上 - let udid = self.controlled_udid().await; + let udid = self.controlled_udid().await.ok(); let mut lines = Vec::new(); // 最后一步是不是需要查弹窗的操作 let mut check = false; @@ -1357,7 +1521,7 @@ impl McpServer { total - n )); } - return self.finish(lines.join("\n"), true, then, false, true).await; + return self.finish(lines.join("\n"), true, then, false, true, None).await; } Response::Text { text, outcome, .. } => { check = wants_alert_check(&req) && !protocol::alert_reported(&text, outcome); @@ -1373,12 +1537,12 @@ impl McpServer { total - n )); } - return self.finish(lines.join("\n"), true, then, true, true).await; + return self.finish(lines.join("\n"), true, then, true, true, None).await; } }, } } - self.finish(lines.join("\n"), false, then, check, true).await + self.finish(lines.join("\n"), false, then, check, true, None).await } } @@ -1397,6 +1561,128 @@ mod tests { v.as_object().cloned().unwrap() } + #[tokio::test] + async fn input_delivery_is_independent_of_field_and_screen_readback() { + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + let socket = PathBuf::from(format!("/tmp/ictl-single-input-{}.sock", std::process::id())); + let server = McpServer { socket: socket.clone(), task: false }; + let call = |name, args: Value| { + let req = CallToolRequestParams::new(name).with_arguments(args.as_object().unwrap().clone()); + let server = &server; + async move { + let CallToolResponse::Complete(result) = server.call_tool_inner(req).await.unwrap() else { panic!() }; + result + } + }; + let tap = json!({"x": 1, "y": 2}); + let unavailable = call("iphone_tap", tap.clone()).await; + let data = unavailable.structured_content.unwrap(); + assert_eq!(data["delivery"], "not_sent"); + assert_eq!(data["stage"], "connect"); + + let listener = tokio::net::UnixListener::bind(&socket).unwrap(); + let exchanges = [ + ("tap", None), // request reached daemon, reply lost + ("tap", Some(Response::text("Tapped"))), + ("settle", Some(Response::text("Settled"))), + ("screenshot", Some(Response::error("controlled device changed to phone-B"))), + ("tap", Some(Response::text("Tapped"))), + ("settle", Some(Response::error("lost settle"))), + ( + "list_elements", + Some(Response::text_data( + "items", + Default::default(), + Some(protocol::Data::Elements { elements: vec![], matched_count: Some(3), truncated: Some(true) }), + )), + ), + ( + "type_text", + Some(Response::text_with( + "Typed", + protocol::Outcome { field_verified: Some(false), ..Default::default() }, + )), + ), + ("alert_check", Some(Response::text(""))), + ("type_text", Some(Response::error("field mismatch").with_failure(Delivery::Sent, FailureStage::Readback))), + ( + "tap_element", + Some(Response::text_with("No match", protocol::Outcome { tapped_nothing: true, ..Default::default() })), + ), + ("alert_check", Some(Response::text(""))), + ]; + let daemon = async { + let mut first_snapshot = true; + for (op, reply) in exchanges { + let mut peer = loop { + let (mut peer, _) = listener.accept().await.unwrap(); + let mut line = String::new(); + BufReader::new(&mut peer).read_line(&mut line).await.unwrap(); + let request: Value = serde_json::from_str(&line).unwrap(); + if request["op"] == "daemon" { + // Old daemon snapshot: only the controlled device's UDID is needed. + let snapshot = if std::mem::take(&mut first_snapshot) { + Response::text(r#"{"device":null}"#) + } else { + Response::text(r#"{"device":{"udid":"phone-A"}}"#) + }; + peer.write_all(format!("{}\n", json!(snapshot)).as_bytes()).await.unwrap(); + continue; + } + assert_eq!(request["op"], op); + assert_eq!(request[protocol::EXPECT_UDID], "phone-A", "{request}"); + break peer; + }; + if let Some(reply) = reply { + peer.write_all(format!("{}\n", json!(reply)).as_bytes()).await.unwrap(); + } + } + }; + let actions = async { + let missing = call("iphone_tap", tap.clone()).await; + let data = missing.structured_content.unwrap(); + assert_eq!(data["delivery"], "not_sent"); + assert_eq!(data["stage"], "preflight"); + + let lost = call("iphone_tap", tap).await; + assert_eq!(lost.is_error, Some(true)); + let data = lost.structured_content.unwrap(); + assert_eq!(data["delivery"], "unknown"); + assert_eq!(data["stage"], "reply"); + + let tapped = call("iphone_tap", json!({"x":1,"y":2,"then":"screenshot"})).await; + assert_ne!(tapped.is_error, Some(true)); + let data = tapped.structured_content.unwrap(); + assert_eq!(data["delivery"], "sent"); + assert_eq!(data["stage"], "readback"); + assert_eq!(data["readback"], json!({"settle":"ok", "screen":"failed"})); + + let listed = call("iphone_tap", json!({"x":1,"y":2,"then":"elements"})).await; + assert_ne!(listed.is_error, Some(true)); + let data = listed.structured_content.unwrap(); + assert_eq!(data["delivery"], "sent"); + assert_eq!(data["readback"], json!({"settle":"failed", "screen":"ok"})); + assert_eq!(data["matched_count"], 3); + assert_eq!(data["truncated"], true); + + let text = json!({"text":"x"}); + let typed = call("iphone_type_text", text.clone()).await.structured_content.unwrap(); + assert_eq!(typed["delivery"], "sent"); + assert_eq!(typed["readback"]["field"], "unverified"); + let mismatch = call("iphone_type_text", text.clone()).await; + assert_eq!(mismatch.is_error, Some(true)); + let data = mismatch.structured_content.unwrap(); + assert_eq!(data["delivery"], "sent"); + assert_eq!(data["readback"]["field"], "failed"); + + let missed = call("iphone_tap_element", text).await; + assert_ne!(missed.is_error, Some(true)); + assert_eq!(missed.structured_content.unwrap()["delivery"], "not_sent"); + }; + tokio::time::timeout(Duration::from_secs(4), async { tokio::join!(daemon, actions) }).await.unwrap(); + std::fs::remove_file(socket).unwrap(); + } + fn has_cjk(s: &str) -> bool { s.chars().any(|c| matches!(c, '\u{3000}'..='\u{303f}' | '\u{4e00}'..='\u{9fff}' | '\u{ff00}'..='\u{ffef}')) } @@ -1499,6 +1785,59 @@ mod tests { assert_eq!(steps, Ok(vec![Step::Request { tool: "iphone_tap".into(), req }])); } + #[test] + fn scroll_collection_is_bounded_and_changes_the_viewport() { + let req = |v| { + let args = args(v); + check_args("iphone_scroll_collect", &args, &[], true)?; + to_request("iphone_scroll_collect", &args) + }; + let r = + req(json!({"scroll": "up", "max_scrolls": 1, "filter": "Cell", "until": "General", "limit": 3})).unwrap(); + assert_eq!( + r, + Request::ScrollCollect(protocol::ScrollCollect { + down: false, + max_scrolls: 1, + filter: "Cell".into(), + until: "General".into(), + limit: 3, + }) + ); + assert!(r.is_device_action()); + assert!(req(json!({})).is_ok()); + for bad in [ + json!({"scroll":"left"}), + json!({"max_scrolls":0}), + json!({"max_scrolls":16}), + json!({"limit":0}), + json!({"limit":151}), + json!({"limit":2.5}), + json!({"max_scroll":2}), + ] { + assert!(req(bad.clone()).is_err(), "{bad}"); + } + let result = to_result(Response::text_data( + "row limit reached", + Default::default(), + Some(protocol::Data::ScrollCollection { + stop_reason: protocol::ScrollStop::Limit, + scrolls: 2, + rows: vec![protocol::ScrollRow { + kind: "Cell".into(), + label: "One".into(), + name: "".into(), + value: "".into(), + }], + matched: None, + }), + )); + let data = result.structured_content.unwrap(); + assert_eq!(data["stop_reason"], "limit"); + assert_eq!(data["rows"][0]["label"], "One"); + assert!(data["matched"].is_null()); + } + #[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, hold: 0.0 })); @@ -1511,14 +1850,15 @@ mod tests { #[test] fn toolkit_tools_plus_wait_for_batch_and_devices() { let names: Vec<_> = tools().iter().map(|t| t.name.to_string()).collect(); - assert_eq!(names.len(), 17); + assert_eq!(names.len(), 18); // the developer tools only with IPHONE_CONTROL_DEV_TOOLS - let dev: Vec<_> = tools_with(true).iter().skip(17).map(|t| t.name.to_string()).collect(); + let dev: Vec<_> = tools_with(true).iter().skip(18).map(|t| t.name.to_string()).collect(); assert_eq!(dev, DEV_TOOLS); - assert_eq!(tools_with(false).len(), 17); + assert_eq!(tools_with(false).len(), 18); for n in [ "iphone_status", "iphone_screenshot", + "iphone_scroll_collect", "iphone_tap_element", "iphone_open_url", "iphone_list_devices", diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs index b23e8f17..3b2af950 100644 --- a/crates/ictl-protocol/src/lib.rs +++ b/crates/ictl-protocol/src/lib.rs @@ -52,6 +52,18 @@ pub struct ScrollSearch { /// [`ScrollSearch::max`] 的上限:每次慢滑加等列表停下约 2.5 秒,滑满 15 次也就半分钟出头 pub const MAX_SEARCH_SCROLLS: u32 = 15; +pub const MAX_SCROLL_ROWS: usize = 150; + +/// Bounds and matching rules for a standalone list scan. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ScrollCollect { + pub down: bool, + pub max_scrolls: u32, + pub filter: String, + pub until: String, + pub limit: usize, +} fn is_zero(v: &f64) -> bool { *v == 0.0 @@ -104,6 +116,8 @@ pub enum Request { #[serde(default, skip_serializing_if = "std::ops::Not::not")] keep_locked: bool, }, + /// Inspect successive visible viewports, leaving a matching element on screen. + ScrollCollect(ScrollCollect), Tap { x: f64, y: f64, @@ -373,9 +387,36 @@ pub enum Response { /// The touch Down could not open a HID session and sent no contact report. #[serde(default, skip_serializing_if = "std::ops::Not::not")] retry_as_gesture: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + failure: Option, }, } +/// Delivery of the requested input. Acknowledging the input does not verify its effect on screen. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Delivery { + NotSent, + Unknown, + Sent, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FailureStage { + Preflight, + Connect, + Send, + Reply, + Readback, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ActionFailure { + pub delivery: Delivery, + pub stage: FailureStage, +} + /// Facts about a [`Response::Text`] that clients act on (see [`tapped_nothing`], [`alert_reported`]) #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Outcome { @@ -385,6 +426,12 @@ pub struct Outcome { /// The text already reports a system alert blocking the screen #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub alert_reported: bool, + /// Non-empty text input: whether a subsequent field read saw the requested text. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub field_verified: Option, + /// A replacement can verify the desired value without sending any input. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub delivery: Option, } /// What [`Request::Status`], [`Request::ListElements`], [`Request::ListApps`] and [`Request::AlertCheck`] report, as @@ -401,6 +448,12 @@ pub enum Data { #[serde(default, skip_serializing_if = "Option::is_none")] truncated: Option, }, + ScrollCollection { + stop_reason: ScrollStop, + scrolls: u32, + rows: Vec, + matched: Option>, + }, Apps { apps: Vec, }, @@ -441,6 +494,34 @@ pub struct ElementData { pub height: f64, } +/// The names are stable across daemon and MCP languages. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ScrollStop { + Found, + End, + MaxScrolls, + Limit, +} + +/// The matched element's visible bounds and an uncovered point in the final viewport. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ScrollMatch { + #[serde(flatten)] + pub element: ElementData, + pub point: (f64, f64), +} + +/// A row observed along the way. Its original screen coordinates can already be stale. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ScrollRow { + #[serde(rename = "type")] + pub kind: String, + pub label: String, + pub name: String, + pub value: String, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct AppData { pub name: String, @@ -460,11 +541,70 @@ impl Response { Self::Text { text: s.into(), outcome: Some(outcome), data } } pub fn error(s: impl Into) -> Self { - Self::Error { message: s.into(), retry_as_gesture: false } + Self::Error { message: s.into(), retry_as_gesture: false, failure: None } + } + pub fn with_failure(mut self, delivery: Delivery, stage: FailureStage) -> Self { + if let Self::Error { failure, .. } = &mut self { + *failure = Some(ActionFailure { delivery, stage }); + } + self + } + + pub fn failure_stage(&self) -> Option { + match self { + Self::Error { failure, .. } => failure.map(|f| f.stage), + _ => None, + } + } + + pub fn field_readback(&self, req: &Request) -> Option<&'static str> { + if !matches!(req, Request::ReplaceText { .. }) + && !matches!(req, Request::TypeText { text, .. } if !text.is_empty()) + { + return None; + } + match self { + Self::Text { outcome: Some(o), .. } => o.field_verified.map(|v| if v { "verified" } else { "unverified" }), + Self::Error { failure: Some(f), .. } if f.stage == FailureStage::Readback => Some("failed"), + _ => None, + } + } + + /// For callers reporting a device action. Older daemons have no error classification. + pub fn delivery(&self, req: &Request) -> Delivery { + match self { + Self::Text { text, outcome, .. } + if matches!(req, Request::TapElement { .. }) && tapped_nothing(text, *outcome) => + { + Delivery::NotSent + } + Self::Text { .. } if matches!(req, Request::TypeText { text, submit: false } if text.is_empty()) => { + Delivery::NotSent + } + Self::Text { outcome, .. } if matches!(req, Request::ReplaceText { .. }) => { + outcome.and_then(|o| o.delivery).unwrap_or(Delivery::Unknown) + } + Self::Text { .. } if req.reports_delivery() => Delivery::Sent, + Self::Error { failure: Some(f), .. } => f.delivery, + _ => Delivery::Unknown, + } } } impl Request { + /// Inputs whose normal reply acknowledges sending the requested gesture or text. + pub fn reports_delivery(&self) -> bool { + matches!( + self, + Self::Tap { .. } + | Self::TapElement { .. } + | Self::TypeText { .. } + | Self::ReplaceText { .. } + | Self::Swipe { .. } + | Self::LongPress { .. } + ) + } + /// Shared by the daemon and the MCP batch preflight, before any earlier steps run. pub fn check_required_text(&self) -> Result<(), String> { match self { @@ -481,6 +621,7 @@ impl Request { pub fn is_device_action(&self) -> bool { match self { Self::Tap { .. } + | Self::ScrollCollect(_) | Self::TapElement { .. } | Self::TapSequence { .. } | Self::LongPress { .. } @@ -757,7 +898,7 @@ pub async fn call_background( req: &Request, timeout: Option, ) -> std::io::Result { - exchange_on(socket, req, timeout, None, None, Some(BACKGROUND)).await + exchange_on(socket, req, timeout, None, None, Some(BACKGROUND)).await.map_err(|e| e.source) } /// 同 [`call`];`expect_udid` 见 [`EXPECT_UDID`] @@ -767,7 +908,7 @@ pub async fn call_expecting( timeout: Option, expect_udid: Option<&str>, ) -> std::io::Result { - exchange_on(socket, req, timeout, expect_udid, None, None).await + exchange_on(socket, req, timeout, expect_udid, None, None).await.map_err(|e| e.source) } /// [`call_expecting`] for someone watching the screen ([`WATCHED`]) @@ -777,7 +918,7 @@ pub async fn call_watched( timeout: Option, expect_udid: Option<&str>, ) -> std::io::Result { - exchange_on(socket, req, timeout, expect_udid, None, Some(WATCHED)).await + exchange_on(socket, req, timeout, expect_udid, None, Some(WATCHED)).await.map_err(|e| e.source) } /// Send a coordinate action only if this device and its measured geometry still match. Only the control page sends @@ -789,21 +930,32 @@ pub async fn call_in_view( udid: &str, view: &str, ) -> std::io::Result { - exchange_on(socket, req, timeout, Some(udid), Some(view), Some(WATCHED)).await + exchange_on(socket, req, timeout, Some(udid), Some(view), Some(WATCHED)).await.map_err(|e| e.source) +} + +/// Transport failure with the phase of this single exchange. Once writing begins, a missing +/// reply cannot tell the caller whether the daemon acted. +#[derive(Debug)] +pub struct ExchangeError { + pub source: std::io::Error, + pub failure: ActionFailure, } -async fn exchange_on( +/// Like the convenience call functions above, retaining transport phase for action results. +pub async fn exchange_on( socket: &std::path::Path, req: &Request, timeout: Option, expect_udid: Option<&str>, expect_view: Option<&str>, flag: Option<&str>, -) -> std::io::Result { +) -> Result { use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + let mut stage = FailureStage::Connect; let exchange = async { let stream = connect(socket).await?; let (r, mut w) = stream.into_split(); + stage = FailureStage::Preflight; let mut v = serde_json::to_value(req)?; if let Some(o) = v.as_object_mut() { o.insert(CANCEL_ON_CLOSE.into(), true.into()); @@ -822,20 +974,29 @@ async fn exchange_on( } let mut line = v.to_string(); line.push('\n'); + stage = FailureStage::Send; w.write_all(line.as_bytes()).await?; + stage = FailureStage::Reply; let mut resp = String::new(); BufReader::new(r).read_line(&mut resp).await?; serde_json::from_str(&resp).map_err(std::io::Error::other) }; - match timeout { + let result = match timeout { None => exchange.await, - Some(t) => tokio::time::timeout(t, exchange).await.map_err(|_| { - std::io::Error::new( + Some(t) => tokio::time::timeout(t, exchange).await.unwrap_or_else(|_| { + Err(std::io::Error::new( std::io::ErrorKind::TimedOut, ictl_l10n::trf!("守护进程 {} 秒内没有应答(可能正忙,例如正在启动 WDA 或重签)", "The daemon didn't answer within {} seconds (it may be busy, for example starting WDA or re-signing)", t.as_secs()), - ) - })?, - } + )) + }), + }; + result.map_err(|source| { + let delivery = match stage { + FailureStage::Connect | FailureStage::Preflight => Delivery::NotSent, + _ => Delivery::Unknown, + }; + ExchangeError { source, failure: ActionFailure { delivery, stage } } + }) } fn add_task_keys(o: &mut serde_json::Map) { @@ -940,6 +1101,14 @@ pub async fn task_list(socket: &std::path::Path) -> Result, String mod tests { use super::*; + #[test] + fn empty_input_only_sends_a_key_with_submit() { + let reply = Response::text("ok"); + for (submit, delivery) in [(false, Delivery::NotSent), (true, Delivery::Sent)] { + assert_eq!(reply.delivery(&Request::TypeText { text: String::new(), submit }), delivery); + } + } + /// 不带 count 的点击(旧版本客户端)按 1 下;count 为 1 时不写进请求,旧版本守护进程收到的和以前一样 #[test] fn a_tap_without_count_is_one_tap_on_the_wire() { diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rs index a3beaaeb..ca399489 100644 --- a/crates/ictl-wda/src/client.rs +++ b/crates/ictl-wda/src/client.rs @@ -428,6 +428,7 @@ impl WdaClient { let body = body.map(|b| b.to_string().into_bytes()); let (status, raw) = self.transport.send(method, path, body, timeout).await.map_err(|e| match e.kind() { std::io::ErrorKind::TimedOut => WdaError::Timeout(e.to_string()), + crate::http::WRITE_FAILED => WdaError::Write(e.to_string()), crate::http::AFTER_SENT => WdaError::Interrupted(e.to_string()), _ => WdaError::Unavailable(e.to_string()), })?; @@ -507,12 +508,15 @@ impl WdaClient { timeout: Duration, ) -> Result { for attempt in 0..2 { - let sid = self.session_id().await?; - let abandon = acts(method, path).then_some(sid.as_str()); + let input = acts(method, path); + let sid = self.session_id().await.map_err(|e| if input { e.before_input() } else { e })?; + let abandon = input.then_some(sid.as_str()); let r = self.call_or_abandon(method, &format!("/session/{sid}{path}"), body.clone(), timeout, abandon).await; match r { - Err(WdaError::Remote { kind, .. }) if attempt == 0 && kind.contains("session") => self.session = None, + Err(WdaError::Remote { kind, .. }) if attempt == 0 && kind == "invalid session id" => { + self.session = None + } Err(e) if abandon.is_some() && e.no_answer() => { self.forget_session(); return Err(e); @@ -908,8 +912,8 @@ impl WdaClient { /// only to change them again right after would cost two round trips /// `hold_ms` > 0 holds the finger still at `from` first ([`drag_steps`]) pub async fn swipe_into_polling(&mut self, from: (f64, f64), to: (f64, f64), hold_ms: u64, ms: u64) -> Result<()> { - self.baseline().await?; - self.set_idle_settings(IdleSettings::NO_COOL_OFF).await?; + self.baseline().await.map_err(WdaError::before_input)?; + self.set_idle_settings(IdleSettings::NO_COOL_OFF).await.map_err(WdaError::before_input)?; let r = self.actions(&drag_steps(from, to, hold_ms, ms)).await; if r.is_err() { self.end_polling().await; @@ -957,8 +961,8 @@ impl WdaClient { } async fn quick_actions(&mut self, body: Value, during: IdleSettings) -> Result<()> { - let baseline = self.baseline().await?; - self.set_idle_settings(during).await?; + let baseline = self.baseline().await.map_err(WdaError::before_input)?; + self.set_idle_settings(during).await.map_err(WdaError::before_input)?; let r = self.post("/actions", body).await.map(drop); if let Err(e) = self.set_idle_settings(baseline).await { tracing::warn!( @@ -1519,6 +1523,7 @@ mod tests { } let kind = |k| async move { WdaClient::new(Fails(k)).active_app().await }; assert!(matches!(kind(crate::http::AFTER_SENT).await, Err(WdaError::Interrupted(_)))); + assert!(matches!(kind(crate::http::WRITE_FAILED).await, Err(WdaError::Write(_)))); assert!(matches!(kind(std::io::ErrorKind::TimedOut).await, Err(WdaError::Timeout(_)))); assert!(matches!(kind(std::io::ErrorKind::NotConnected).await, Err(WdaError::Unavailable(_)))); // 应答了但不是 JSON:WDA 收到了请求 diff --git a/crates/ictl-wda/src/elements.rs b/crates/ictl-wda/src/elements.rs index cbc069bb..b8de2d6b 100644 --- a/crates/ictl-wda/src/elements.rs +++ b/crates/ictl-wda/src/elements.rs @@ -393,12 +393,26 @@ fn clip(s: &str, max: usize, keep: usize) -> String { } impl Element { + /// `needle` is already lowercase so a page of elements can share it. + pub fn matches_filter(&self, needle: &str) -> bool { + self.contains_text(needle) || self.kind.to_lowercase().contains(needle) + } + + pub fn contains_text(&self, needle: &str) -> bool { + needle.is_empty() || self.haystack().contains(needle) + } + fn haystack(&self) -> String { format!("{} {} {}", self.label, self.name, self.value).to_lowercase() } /// 与 toolkit 相同的一行描述:`Button "显示与亮度" id="..." @(215,676) 390x53`。超长的文字和标识截断 pub fn describe(&self) -> String { + format!("{} @({},{}) {}x{}", self.describe_text(), self.center.0, self.center.1, self.size.0, self.size.1) + } + + /// Text and identifier without a position. Suitable for rows collected from earlier viewports. + pub fn describe_text(&self) -> String { let text = [&self.label, &self.name, &self.value].into_iter().find(|s| !s.is_empty()).cloned().unwrap_or_default(); let mut s = format!("{} \"{}\"", self.kind, clip(&text, 80, 60)); @@ -414,7 +428,7 @@ impl Element { let v: String = self.value.chars().take(60).collect(); s += &format!(" value=\"{v}\""); } - s + &format!(" @({},{}) {}x{}", self.center.0, self.center.1, self.size.0, self.size.1) + s } } @@ -673,7 +687,7 @@ pub fn parse_tree(xml: &str, view: impl Into) -> Tree { /// 类型/标签/名字/值里包含 `text` 的元素(不区分大小写)。列元素时筛选用,可以按类型筛(如 `SearchField`) pub fn filter<'a>(elements: &'a [Element], text: &str) -> Vec<&'a Element> { let t = text.to_lowercase(); - elements.iter().filter(|e| e.haystack().contains(&t) || e.kind.to_lowercase().contains(&t)).collect() + elements.iter().filter(|e| e.matches_filter(&t)).collect() } /// 按文字找元素:先找标签或名字完全相同的,没有再找标签/名字/值包含该文字的(不看类型) @@ -683,7 +697,7 @@ pub fn find<'a>(elements: &'a [Element], text: &str) -> Vec<&'a Element> { return exact; } let t = text.to_lowercase(); - elements.iter().filter(|e| e.haystack().contains(&t)).collect() + elements.iter().filter(|e| e.contains_text(&t)).collect() } /// 等某段文字出现时用:同 [`find`],但不算输入框里的内容(刚输入的搜索词不能算「结果出来了」) diff --git a/crates/ictl-wda/src/http.rs b/crates/ictl-wda/src/http.rs index 1671f691..31f63f59 100644 --- a/crates/ictl-wda/src/http.rs +++ b/crates/ictl-wda/src/http.rs @@ -15,7 +15,7 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt}; /// /// 错误的 kind 区分请求有没有送到 WDA(决定能不能退到 HID 重做): /// [`ErrorKind::TimedOut`](std::io::ErrorKind::TimedOut) 是发出后没在时限内应答, -/// [`AFTER_SENT`] 是发出后连接断了或响应不完整、看不懂;其他 kind 都表示请求没送到 +/// [`AFTER_SENT`] 是读应答出错,[注入请求写入失败](WRITE_FAILED) 也可能已经送达;其他 kind 都表示请求没送到 pub trait Transport: Send + Sync { fn send( &self, @@ -43,7 +43,10 @@ impl DeviceTransport { /// 连上之后的超时是「请求已发出、手机可能还在执行」,不能退到 HID 重做一遍 const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); -/// 请求已经整个发出、之后读响应出错的 kind:WDA 可能已经执行了这个操作 +/// Writing or flushing failed after opening the device connection. +pub const WRITE_FAILED: std::io::ErrorKind = std::io::ErrorKind::BrokenPipe; + +/// Failure while reading the reply to a written request. pub const AFTER_SENT: std::io::ErrorKind = std::io::ErrorKind::ConnectionAborted; fn after_sent(e: std::io::Error) -> std::io::Error { @@ -111,11 +114,13 @@ impl DeviceTransport { ictl_l10n::tr!("连接没有套接字", "the connection has no socket"), ) })?; + let mut written = false; let fut = async { - // 没写完 WDA 不会处理(HTTP 请求不完整),算没送到 - let not_sent = |e: std::io::Error| std::io::Error::new(std::io::ErrorKind::NotConnected, e.to_string()); - sock.write_all(&req).await.map_err(not_sent)?; - sock.flush().await.map_err(not_sent)?; + // After writing starts, a failed write/flush isn't evidence that the phone didn't act. + let write_failed = |e: std::io::Error| std::io::Error::new(WRITE_FAILED, e); + sock.write_all(&req).await.map_err(write_failed)?; + sock.flush().await.map_err(write_failed)?; + written = true; // WDA 收到 `Connection: close` 也不关连接,不能读到 EOF:读够一个完整响应就停。 // 头部只解析一次;正文按 Content-Length 判断,chunked 只在收到结束块后才完整解一次 let mut buf = Vec::new(); @@ -143,7 +148,7 @@ impl DeviceTransport { }; tokio::time::timeout(timeout, fut).await.map_err(|_| { std::io::Error::new( - std::io::ErrorKind::TimedOut, + if written { std::io::ErrorKind::TimedOut } else { WRITE_FAILED }, ictl_l10n::trf!("请求超时({} 秒)", "request timed out ({} s)", timeout.as_secs_f64()), ) })? diff --git a/crates/ictl-wda/src/lib.rs b/crates/ictl-wda/src/lib.rs index 9a29b331..54d7a312 100644 --- a/crates/ictl-wda/src/lib.rs +++ b/crates/ictl-wda/src/lib.rs @@ -20,6 +20,12 @@ pub enum WdaError { /// 连不上 WDA(runner 没了、端口不通):可以退到 HID 重做 #[error("{}", ictl_l10n::trf!("WDA 不可用:{0}", "WDA unavailable: {0}", .0))] Unavailable(String), + /// Writing or flushing failed after the connection opened. Replaying could duplicate input. + #[error("{}", ictl_l10n::trf!("写入 WDA 请求失败:{0}", "Writing the WDA request failed: {0}", .0))] + Write(String), + /// A preparatory WDA call failed before the requested input was dispatched. + #[error(transparent)] + BeforeInput(Box), /// 请求已经发出但没在时限内应答:手机可能还在执行,不能退到 HID 再做一遍 #[error("{}", ictl_l10n::trf!("WDA 请求超时(请求已发出,手机可能仍在执行,先截图确认):{0}", "WDA request timed out (it was sent, the phone may still be carrying it out; take a screenshot first): {0}", .0))] Timeout(String), @@ -43,9 +49,15 @@ pub enum WdaError { pub type Result = std::result::Result; impl WdaError { + pub(crate) fn before_input(self) -> Self { + match self { + Self::Unavailable(_) | Self::BeforeInput(_) => self, + e => Self::BeforeInput(Box::new(e)), + } + } /// 请求送到了 WDA,却没有完整的应答(超时,或应答到一半断了)。WDA 回了一个错误不算:它还在办事 pub fn no_answer(&self) -> bool { - matches!(self, Self::Timeout(_) | Self::Interrupted(_)) + matches!(self, Self::Timeout(_) | Self::Interrupted(_) | Self::Write(_)) } } diff --git a/docs/architecture.md b/docs/architecture.md index 06d45082..bf3f6dba 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -134,7 +134,7 @@ | `ictl-sign` | Apple ID 登录(含双重认证交互)、会话持久化、注册设备、App ID、描述文件、签名 `.app`/`.ipa`(**包括 `.xctest`**;bundle 逻辑改写自 plume_utils)、签后自检 | vendored 的 `plume_core`/`plume_store`(MPL-2.0/MIT;经 plume_core 用 vendored 的 `omnisette` 和打过补丁的 `apple-codesign`) | | `ictl-unlock` | 锁屏密码键盘定位、逐位输入并核对密码栏、从第 2 位起先写停用标记 | `ictl-wda` | | `ictl-daemon` | `core`(共享状态、请求分发、快照)、`supervise`(巡检、后台启动 WDA、重签、会话检查)、`tools`(工具的实现、HID 后备)、`devtools`(日志采集、崩溃报告、安装、卸载)、`web`(Web Inspector 工具,保留一条连接复用)、`devices`(列出、选择设备)、`doctor`;通知(Bark/Telegram)、截图缩放/裁剪、控制接口服务端 | 以上全部、`tokio`、`reqwest`、`image` | -| `ictl-mcp` | MCP stdio 服务,`iphone_*` 工具 17 个,开启开发者工具后 23 个:toolkit 的 13 个 + `iphone_wait_for`、`iphone_batch`、`iphone_list_devices`、`iphone_select_device`,以及 6 个可选的开发者工具(D13);操作类工具可带 `then` 顺带返回操作后的界面;任务里另有 `iphone_confirm`;经控制接口调用守护进程。同一套工具也给控制台的 `/mcp` 用(`http_service`,Streamable HTTP) | `ictl-protocol`、`ictl-l10n`、`rmcp`(`server`、`transport-io`、`transport-streamable-http-server`)、`http` | +| `ictl-mcp` | MCP stdio 服务,`iphone_*` 工具 18 个,开启开发者工具后 24 个:toolkit 的 13 个 + `iphone_wait_for`、`iphone_batch`、`iphone_list_devices`、`iphone_select_device`、`iphone_scroll_collect`,以及 6 个可选的开发者工具(D13);操作类工具可带 `then` 顺带返回操作后的界面;任务里另有 `iphone_confirm`;经控制接口调用守护进程。同一套工具也给控制台的 `/mcp` 用(`http_service`,Streamable HTTP) | `ictl-protocol`、`ictl-l10n`、`rmcp`(`server`、`transport-io`、`transport-streamable-http-server`)、`http` | | `apps/iphone-control` | CLI 入口(`main.rs`;和守护进程打交道的公共函数在 `client.rs`,控制台、引导和更新器都用它):不带命令时是首次运行引导或状态(`guide.rs`)、`daemon`、`mcp`、`mcp-config`、`status`、`doctor`、`setup [--reconfigure]`、`service`(`service.rs`:launchd / systemd 用户服务)、`login`、`sign`、`resign`、`passcode`、`unlock-reset`、`devices`、`select`、`wda-bridge`、`viewer`(`viewer.rs`:本机控制台网页,实时画面、设备面板;`video/`:画面的 H.264 编码(外部 ffmpeg)和 MJPEG 去重;`agent.rs`:页面上的 AI 任务,`viewer.html` 是页面)、`viewer token …`(命名令牌、只读令牌)、`task …`(`task.rs`、`remote.rs`)、`mcp --url`(`mcp_bridge.rs`)、`update …`(`update.rs`、`update/`:签名清单、事务式替换)、`completions`、`notify-test`;隐藏的 `debug ` 真机诊断(原第 0 步 spike,不经守护进程;feature `debug-cmds`,默认不编译) | `clap` | 依赖方向:`apps` → `ictl-daemon` / `ictl-mcp`,还直接依赖 `ictl-device`、`ictl-sign`;`ictl-daemon` → `ictl-unlock` → `ictl-wda` → `ictl-device`;`ictl-daemon` 还直接依赖 `ictl-webinspector`、`ictl-sign` 和 `ictl-protocol`。`ictl-device` 也依赖 `ictl-webinspector`(打开连接)。`ictl-mcp` 只依赖 `ictl-protocol` 和 `ictl-l10n`,不依赖守护进程和设备层。`ictl-l10n` 不依赖其他 crate,除 `ictl-webinspector` 外都用它。`apps` 的 `debug`(feature `debug-cmds`)直接调用 `ictl-device`、`ictl-wda`。 diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index ea066b17..5b176019 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -51,7 +51,7 @@ | 45 | WDA 在横屏时就绪,记下的是横屏尺寸,之后 HID 换算错 | state.json 只存竖放尺寸和对应的 UDID,换算时再按当前方向转 | 真机(iOS 27,横屏下启动 WDA,再让它掉线后点击) | | 46 | 浏览器里的其他网页向 `viewer` 发请求,借它操作手机 | 操作要求 `Origin` 是页面本身、内容类型是 JSON;`Host` 必须是回环地址 | 单测(`actions_need_own_origin_and_json`) | | 47 | `viewer` 开着时 `select` 到别的设备,点击落到用户没在看的手机上 | 每个操作带启动时的 UDID,守护进程控制的不是这台就拒绝 | 单测(`request_for_another_device_is_refused`)+ 真机(`viewer` 开着时 `select` 另一台,再点击) | -| 48 | 不需要开发者工具的 agent 多读工具说明,或没开时也能调用 | 开关关闭时工具列表还是 17 个,调用这些工具报错并说明要设 `IPHONE_CONTROL_DEV_TOOLS=1` | 单测(工具列表:`toolkit_tools_plus_wait_for_batch_and_devices`);调用被拒:代码审查(`call_tool` 里的判断,还没有单测) | +| 48 | 不需要开发者工具的 agent 多读工具说明,或没开时也能调用 | 开关关闭时工具列表有 18 个,调用这些工具报错并说明要设 `IPHONE_CONTROL_DEV_TOOLS=1` | 单测(工具列表:`toolkit_tools_plus_wait_for_batch_and_devices`);调用被拒:代码审查(`call_tool` 里的判断,还没有单测) | | 49 | os_log 开着 Debug 时手机上每个进程都产生 Debug 消息(约 650 行/秒),手势变慢、失败 | 只要默认、Error、Fault 级别(约 80 行/秒) | 真机(`iphone_app_logs` 采集时跑回归脚本默认步骤,和不采集时对比耗时) | | 50 | 日志采集的缓冲把内存撑大(全部进程,每秒几十行) | 行数和总量都封顶(20,000 行、8 MB),单行截断,结果说明最早一行是多久前 | 单测(`buffer_is_bounded_by_size`) | | 51 | 每次调用重开 Web Inspector 连接:约 8 秒一次,几轮后手机不再报告 Safari,要重启 Safari | 复用一条连接;只有连接层的错误才重开,页面超时或页面报错不断开 | 单测(`only_a_page_timeout_keeps_the_connection`)+ 真机(连续多次 `iphone_web_targets`、`iphone_web_eval` 都快且找得到页面;重启 Safari 后仍能找到) | @@ -166,3 +166,4 @@ | 160 | 元素列表超出 `limit` 时机器无法从结构化结果判断是否截断 | 同时返回本次匹配数和截断标记,保留原有文本结果 | 单测 `element_limit_is_reported_in_structured_content` + 真机脚本 `scenarios.py editing` | | 161 | 等待文字消失的请求被当成等待出现 | `state: "disappeared"` 等待可读界面不再匹配,读取失败或未读完整不算成功 | 单测 `disappearance_requires_a_readable_complete_screen_without_the_target` + 真机脚本 `scenarios.py editing` | | 162 | 经 WDA 控制(iOS 26 及以前,或 `ICTL_IOS_BACKEND=wda`)时 `replace: true` 直接拒绝,调用方只能在光标处输入,得到 `wifi 蓝牙` | 经 WDA 取聚焦元素(`/element/active`),只接受普通可读输入框(密码框拒绝),WDA `clear` 后按键输入,读回同一个元素的全文一致才按回车,结尾丢字补一次;空输入框读出占位文字算空;清空后再失败时明说原文已删掉;WDA 在动手前就连不上时,原生控制可用则改走原生 | 单测 `replaces_the_focused_field_then_presses_return`、`a_mismatch_is_refused_without_return`、`focused_field_reads_its_type_and_placeholder` + 真机脚本 `scenarios.py editing`(WDA 设备) | +| 163 | Viewer 已收到输入请求,返回结果前连接中断,客户端可能一直等待或重复输入 | 客户端结束该调用,报告投递状态未知,提示先查看手机 | 单测 `interrupted_tool_reply_reports_unknown_instead_of_hanging_or_retrying` | diff --git a/docs/images/features.svg b/docs/images/features.svg index 0e8fe881..80cf11c7 100644 --- a/docs/images/features.svg +++ b/docs/images/features.svg @@ -1,4 +1,4 @@ - + @@ -24,7 +24,7 @@ - 17 MCP tools + 18 MCP tools Screenshots, taps, swipes, text input, buttons, apps, URLs, element tree. diff --git a/docs/images/features.zh-CN.svg b/docs/images/features.zh-CN.svg index d7c0f4ce..8d896077 100644 --- a/docs/images/features.zh-CN.svg +++ b/docs/images/features.zh-CN.svg @@ -1,4 +1,4 @@ - + @@ -24,7 +24,7 @@ - 17 个 MCP 工具 + 18 个 MCP 工具 截图、点击、滑动、输入中文 按键、管理 App、读元素树 diff --git a/docs/tools.md b/docs/tools.md index 9db17d29..c4147c35 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1,6 +1,6 @@ # MCP tools -The MCP server (`iphone-control mcp`) exposes 17 tools (23 with the [developer tools](#developer-tools-opt-in)). The tool descriptions the agent sees, and every result text, are in Simplified Chinese by default, or in English with `IPHONE_CONTROL_LANG=en` (see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration)); this page is the English reference. The definitions live in [`crates/ictl-mcp/src/lib.rs`](../crates/ictl-mcp/src/lib.rs). +The MCP server (`iphone-control mcp`) exposes 18 tools (24 with the [developer tools](#developer-tools-opt-in)). The tool descriptions the agent sees, and every result text, are in Simplified Chinese by default, or in English with `IPHONE_CONTROL_LANG=en` (see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration)); this page is the English reference. The definitions live in [`crates/ictl-mcp/src/lib.rs`](../crates/ictl-mcp/src/lib.rs). Coordinates are in **points**, the same unit as the pixels of a full-screen `iphone_screenshot` (for example 430×932 on an iPhone 15 Pro Max), so an agent can read a position off a screenshot and tap it directly. Coordinates follow the current screen orientation: after a rotation the same spot has different coordinates, so take a new screenshot. Screen sizes differ per device (an iPad mini 5 is 768×1024 in portrait); don't assume 430×932. @@ -19,6 +19,7 @@ Coordinates are in **points**, the same unit as the pixels of a full-screen `iph | Tool | Parameters | Notes | |---|---|---| | `iphone_tap` | `x`, `y`, `count` (default 1, max 10) | For targets without text (icons, games, maps); falls back to HID when WDA is down. `count` taps the same point that many times in one gesture, about 0.1 s apart: 2 is a double tap (also turns on Caps Lock on the keyboard's Shift key); for hidden entries that need several taps in a short time, which separate calls or `iphone_batch` are too slow for | +| `iphone_scroll_collect` | `scroll` (down by default, or up), `filter`, `until`, `max_scrolls` (default 8, max 15), `limit` (default/max 150) | Collects rows in travel order and merges overlapping rows on adjacent screens. Identical accessibility rows can make the overlap ambiguous. Stops on a visible text match (`found`), an unchanged screen (`end`), `max_scrolls`, or the row `limit`. The matched element includes an uncovered `point` in the final viewport. The phone stays there without a tap. | | `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), `hold` (default 0) | Returns after the list has stopped scrolling (up to 2.5 s). Swipe up (`from_y` > `to_y`) to see content further down. `hold` holds the finger still at the start for that many seconds before moving, to drag things that have to be long-pressed first (home-screen icons, reorderable rows); about 0.6 works, under 0.5 usually doesn't pick anything up. `seconds` + `hold` is at most 10 | @@ -28,6 +29,8 @@ Coordinates are in **points**, the same unit as the pixels of a full-screen `iph | `iphone_terminate_app` | `app` | Force-quits, like swiping it away in the app switcher; unsaved input is lost. No error if it wasn't running | | `iphone_open_url` | `url` | Web pages open in the default browser; URL schemes open their app | +Taps, long presses, swipes and text input report the delivery of the requested input in `structuredContent.delivery`. With `not_sent` you can reconsider the input and retry. With `unknown`, inspect the phone first because the input may already have taken effect. With `sent`, the input was dispatched. When using `then`, check `readback` separately. + ## Several devices Only one device is controlled at a time; every other tool acts on it. With one device connected nothing changes. @@ -77,7 +80,7 @@ Every tool carries MCP annotations: the six read-only tools (`iphone_status`, `i ## Returning the screen after an action: `then` -The tools under *Acting* and `iphone_batch` accept the following options. `iphone_select_device` does not: use `iphone_status` after switching to check that WDA is ready. +The input tools under *Acting* and `iphone_batch` accept the following options. `iphone_scroll_collect` returns its own collection and final match. `iphone_select_device` does not: use `iphone_status` after switching to check that WDA is ready. | Parameter | Meaning | |---|---| diff --git a/tests/device/scenarios.py b/tests/device/scenarios.py index 7ba7744f..9cbc9512 100644 --- a/tests/device/scenarios.py +++ b/tests/device/scenarios.py @@ -14,6 +14,8 @@ selecting the device already selected, an enlarged region (#16), then=screenshot typing typing with no keyboard up is refused and types nothing (#32); the same text typed twice into Spotlight counts as typed the second time too (#143) + delivery one Clock tab tap reports delivery and returns its selected state; a missing target leaves it selected + collect find a Clock tab without tapping it, then collect Settings rows from two different viewports editing replace and empty focused text, natively (#159) and through WDA (#162), read element-limit metadata (#160), and wait for a visible Clock tab to disappear (#161) fresh a tap right after a cold start isn't swallowed (#13); then=elements shows the page after the tap, @@ -33,7 +35,7 @@ (`iphone-control devices` says whether one is saved; `iphone-control passcode set` saves it), the phone counts a wrong attempt and automatic unlocking is switched off. Make sure of it, then pass --lock. -Everything else is harmless by design: Home, Clock, Spotlight, screenshots. Nothing is sent, bought, deleted or +Everything else is harmless by design: Home, Clock, Spotlight, scrolling Settings, screenshots. Nothing is sent, bought, deleted or changed. Environment: MCP_CMD, MCP_URL, SHOTS_DIR as for run.py. Exit code 1 if any check failed. Paste the output into the pull request (CONTRIBUTING.md, "Required tests"). """ @@ -87,13 +89,17 @@ def __init__(self, session, d: dev.Device): self.s = session self.d = d - async def call(self, name: str, args: dict | None = None, timeout: float = 90): - t = time.time() + async def result(self, name: str, args: dict | None = None, timeout: float = 90): res = await asyncio.wait_for(self.s.call_tool(name, args or {}), timeout) - dt = time.time() - t text = "\n".join(c.text for c in res.content if c.type == "text") if dev.manual_unlock_required(text, bool(res.is_error)): raise dev.ManualUnlockRequired(text) + return res, text + + async def call(self, name: str, args: dict | None = None, timeout: float = 90): + t = time.time() + res, text = await self.result(name, args, timeout) + dt = time.time() - t sizes = [dev.jpeg_size(base64.b64decode(c.data)) for c in res.content if c.type == "image"] return bool(res.is_error), text, dt, sizes @@ -213,10 +219,12 @@ async def editing(p: Phone): spotlight_queries(before) == ["wifi"], before): return for wanted in ("wi", "蓝牙"): - err, answer, dt, _ = await p.call("iphone_type_text", {"text": wanted, "replace": True}) + res, answer = await p.result("iphone_type_text", {"text": wanted, "replace": True}) + data = res.structured_content or {} readback = await p.ok(c, "iphone_list_elements", {"filter": "SearchField"}) - if not check("#159", f"replace the focused Spotlight query with {wanted!r} ({dt:.2f}s)", - not err and spotlight_queries(readback) == [wanted], answer if err else readback): + if not check("#159", f"replace the focused Spotlight query with {wanted!r} and verify its field", + not res.is_error and data.get("delivery") == "sent" and data.get("readback", {}).get("field") == "verified" + and spotlight_queries(readback) == [wanted], f"delivery={data.get('delivery')} readback={data.get('readback')} {answer}"): return # empty text empties it; the empty field reads its placeholder as its value err, answer, dt, _ = await p.call("iphone_type_text", {"text": "", "replace": True}) @@ -254,6 +262,86 @@ async def editing(p: Phone): not err and says(answer, dev.T("已消失", "Disappeared")), answer) +async def delivery(p: Phone): + c = "delivery" + await p.ok(c, "iphone_launch_app", {"app": dev.CLOCK}) + tabs = await p.clock_tabs(c) + if not tabs: + return + was = next(t for t in tabs if t.value == "1") + target = next(t for t in tabs if t.value != "1") + try: + res, text = await p.result("iphone_tap", {"x": target.x, "y": target.y, "then": "elements", "then_filter": "Button"}) + data = res.structured_content or {} + check(c, "one tap reports sent, reads the screen and selects the requested Clock tab", + not res.is_error and data.get("delivery") == "sent" and data.get("readback", {}).get("screen") == "ok" + and any(e.get("label") == target.label for e in data.get("elements", [])) + and selected(text, target.label), f"delivery={data.get('delivery')} readback={data.get('readback')} {text}") + + res, text = await p.result("iphone_tap_element", {"text": MISSING}) + data = res.structured_content or {} + now = await p.clock_tabs(c) + check(c, "a missing tap target reports not_sent and leaves the tab selected", + not res.is_error and says(text, dev.NOT_FOUND) and data.get("delivery") == "not_sent" + and any(t.label == target.label and t.value == "1" for t in now), f"delivery={data.get('delivery')} {text}") + finally: + await p.ok(c, "iphone_tap_element", {"text": was.label}) + await p.home(c) + + +def list_rows(items: list[dict]) -> set[tuple[str, str]]: + # Across native and WDA a Settings row can be a button, cell or its text child. + return {(e["type"], e["label"]) for e in items + if e.get("type") in ("Button", "Cell", "StaticText") and e.get("label")} + + +async def collect(p: Phone): + c = "collect" + try: + await p.ok(c, "iphone_launch_app", {"app": dev.CLOCK}) + tabs = await p.clock_tabs(c) + if not tabs: + return + was = next(t for t in tabs if t.value == "1") + target = next(t for t in tabs if t.value != "1") + res, text = await p.result("iphone_scroll_collect", {"until": target.label}) + data = res.structured_content or {} + check(c, "a visible Clock tab is found on the first screen", + not res.is_error and data.get("stop_reason") == "found" and data.get("scrolls") == 0 + and (data.get("matched") or {}).get("label") == target.label, text) + now = await p.clock_tabs(c) + check(c, "finding the tab leaves the original tab selected", + any(t.label == was.label and t.value == "1" for t in now)) + + await p.ok(c, "iphone_launch_app", {"app": dev.SETTINGS}) + for direction in ("down", "up"): + before, _ = await p.result("iphone_list_elements", {"limit": 500}) + res, text = await p.result("iphone_scroll_collect", {"scroll": direction, "until": MISSING, "max_scrolls": 1}) + after, _ = await p.result("iphone_list_elements", {"limit": 500}) + data = res.structured_content or {} + if not check(c, f"one scroll {direction} stops at the bound or the list end with no match", + not res.is_error and data.get("stop_reason") in ("max_scrolls", "end") + and data.get("scrolls") == 1 and data.get("matched") is None, text.splitlines()[0] if text else ""): + return + start = before.structured_content or {} + end = after.structured_content or {} + if not check(c, "both independent viewport reads are complete", + not before.is_error and not after.is_error and start.get("truncated") is False + and end.get("truncated") is False): + return + first, last = list_rows(start["elements"]), list_rows(end["elements"]) + collected = list_rows(data["rows"]) + old, new = (first - last) & collected, (last - first) & collected + if first - last and last - first: + check(c, "the collection includes rows unique to each independently observed viewport", + bool(old and new), f"{len(old)} first-screen-only, {len(new)} final-screen-only") + return + # Settings may reopen at the bottom. Try the opposite direction once. + check(c, "one collection includes rows unique to each independently observed viewport", False) + finally: + await p.home(c) + + async def fresh(p: Phone): c = "fresh" await p.home(c) @@ -433,7 +521,7 @@ async def lock(p: Phone): SCENARIOS = { "tools": tools, "typing": typing, "editing": editing, "fresh": fresh, "batch": batch, - "menu": menu, "idle": idle, "url": url, "lock": lock + "delivery": delivery, "collect": collect, "menu": menu, "idle": idle, "url": url, "lock": lock } OPT_IN = {"lock": "--lock", "url": "--url"} diff --git a/website/en/guide/tools.md b/website/en/guide/tools.md index ef5f19a1..57381717 100644 --- a/website/en/guide/tools.md +++ b/website/en/guide/tools.md @@ -1,6 +1,6 @@ # Tools -The MCP server provides 17 tools, 23 with the [developer tools](#developer-tools-opt-in). Coordinates are in **points**, matching the pixels of a full-screen screenshot (430×932 on an iPhone 15 Pro Max), so the agent can tap what it reads off a screenshot. Coordinates follow the screen orientation: after a rotation the same spot has different coordinates, so take a new screenshot. Screen sizes differ per device; an iPad mini 5 is 768×1024 in portrait. +The MCP server provides 18 tools, 24 with the [developer tools](#developer-tools-opt-in). Coordinates are in **points**, matching the pixels of a full-screen screenshot (430×932 on an iPhone 15 Pro Max), so the agent can tap what it reads off a screenshot. Coordinates follow the screen orientation: after a rotation the same spot has different coordinates, so take a new screenshot. Screen sizes differ per device; an iPad mini 5 is 768×1024 in portrait. ## Looking at the screen @@ -19,6 +19,7 @@ With [auto-unlock](./auto-unlock) on, `iphone_screenshot`, `iphone_list_elements | Tool | What it does | |---|---| | `iphone_tap` | Tap coordinates; `count` taps the same point several times (double tap, entries that need quick repeated taps) | +| `iphone_scroll_collect` | Scroll through a list, collect matching rows and optionally stop when text appears. The phone stays on the final viewport. | | `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. `hold` holds still at the start for that many seconds before moving, to drag things that need a long press first (home-screen icons, reorderable rows); about 0.6 works | @@ -28,6 +29,8 @@ With [auto-unlock](./auto-unlock) on, `iphone_screenshot`, `iphone_list_elements | `iphone_open_url` | Open a link or URL scheme | | `iphone_batch` | Run up to 20 steps in one call, stopping at the first error. When every step is a coordinate tap, `one_gesture` taps them in turn within one gesture, for pressing keys on one keyboard. If the MCP client cancels the call, the remaining steps don't run; with no device selected, it also stops with an error if the controlled device changes | +Taps, long presses, swipes and text input report the delivery of the requested input in `structuredContent.delivery`. With `not_sent` you can reconsider the input and retry. With `unknown`, inspect the phone first because the input may already have taken effect. With `sent`, the input was dispatched. When using `then`, check `readback` separately. + ## Several devices Only one device is controlled at a time; every other tool acts on it. With one device connected you can ignore these. diff --git a/website/en/index.md b/website/en/index.md index 84325b60..e5c8b17d 100644 --- a/website/en/index.md +++ b/website/en/index.md @@ -22,7 +22,7 @@ hero: features: - icon: 🤖 title: Tools for agents - details: Screenshots, on-screen elements, tap by text, swipe, typing (Chinese too), apps, waiting for pages, multi-step batches — 17 MCP tools; actions can return the settled screen + details: Screenshots, on-screen elements, tap by text, swipe, typing (Chinese too), apps, waiting for pages, multi-step batches — 18 MCP tools; actions can return the settled screen - icon: ⚡ title: Native on iOS 27 details: iOS 27 and later are controlled natively by default — nothing installed on the phone, no Apple ID, no signing, ready in seconds. Recommended diff --git a/website/guide/tools.md b/website/guide/tools.md index 24b26b17..d6e2d8f9 100644 --- a/website/guide/tools.md +++ b/website/guide/tools.md @@ -1,6 +1,6 @@ # 工具一览 -MCP 服务提供 17 个工具,开启[开发者工具](#开发者工具-显式开启)后 23 个。坐标单位是**点**,和整屏截图的像素一一对应(iPhone 15 Pro Max 是 430×932),agent 从截图上读到的位置可以直接点。坐标随屏幕方向变化:转屏后同一个位置的坐标不同,要重新截图。不同设备屏幕尺寸不同,iPad mini 5 竖放是 768×1024。 +MCP 服务提供 18 个工具,开启[开发者工具](#开发者工具-显式开启)后 24 个。坐标单位是**点**,和整屏截图的像素一一对应(iPhone 15 Pro Max 是 430×932),agent 从截图上读到的位置可以直接点。坐标随屏幕方向变化:转屏后同一个位置的坐标不同,要重新截图。不同设备屏幕尺寸不同,iPad mini 5 竖放是 768×1024。 ## 看屏幕 @@ -19,6 +19,7 @@ MCP 服务提供 17 个工具,开启[开发者工具](#开发者工具-显式 | 工具 | 作用 | |---|---| | `iphone_tap` | 按坐标点击;`count` 在同一点连点(双击、要短时间内连点几下的入口) | +| `iphone_scroll_collect` | 逐屏滚动收集列表行,支持按文字过滤和看到目标就停止。结果包含停止原因,手机停留在最后一屏。 | | `iphone_tap_element` | 按文字点击;中心被悬浮栏、键盘挡住时改点露出来的部分,整个被挡住就不点。带 `scroll`(`down` / `up`)时,屏幕上没有就慢慢边滑边找,找到就点,滑到底或滑满 `max_scrolls`(默认 8)次为止 | | `iphone_long_press` | 长按;`seconds` 默认 1,最多 10 | | `iphone_swipe` | 滑动;列表停稳后才返回。`seconds` 默认 0.3,最多 10。`hold` 先在起点按住几秒再移动,用来拖动要先长按才拿得起来的东西(主屏幕图标、可排序的列表项),0.6 左右即可 | @@ -28,6 +29,8 @@ MCP 服务提供 17 个工具,开启[开发者工具](#开发者工具-显式 | `iphone_open_url` | 打开链接或 URL Scheme | | `iphone_batch` | 一次执行最多 20 步,出错就停。步骤全是坐标点击时,`one_gesture` 把它们放进一个手势里依次点完,适合在同一个键盘上连按。MCP 客户端取消调用时,剩下的步骤不再执行;没选定设备时,执行中控制的设备变了也会停下报错 | +点击、长按、滑动和输入会在 `structuredContent.delivery` 返回目标输入的发送状态。收到 `not_sent` 时可以重新评估是否重试;收到 `unknown` 时先读屏,因为操作可能已经生效。`sent` 表示输入已发送。使用 `then` 时,`readback` 另外报告回读结果。 + ## 接着多台设备 同一时间只控制一台,其他工具都作用在它上面。只接着一台时不用管这两个工具。 diff --git a/website/index.md b/website/index.md index 3680a833..8d85ea00 100644 --- a/website/index.md +++ b/website/index.md @@ -22,7 +22,7 @@ hero: features: - icon: 🤖 title: 给 AI 用的工具 - details: 截图、读屏幕元素、按文字点击、滑动、输入中文、启动 App、等页面加载、一次执行多步,共 17 个 MCP 工具;操作后顺带返回稳定后的界面 + details: 截图、读屏幕元素、按文字点击、滑动、输入中文、启动 App、等页面加载、一次执行多步,共 18 个 MCP 工具;操作后顺带返回稳定后的界面 - icon: ⚡ title: iOS 27 原生控制 details: iOS 27 及以上默认原生控制:手机上什么都不装,不用 Apple ID、不用签名,几秒就绪。推荐用 iOS 27 及以上的设备 From 95fe042f9df974f07938c9067fc322562fa510b5 Mon Sep 17 00:00:00 2001 From: MSK Date: Mon, 23 Nov 2026 11:28:39 +0800 Subject: [PATCH 2/4] Link the changelog entries to PR 170 --- CHANGELOG.md | 4 ++-- CHANGELOG.zh-CN.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da3e3bbf..ab70337d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,8 @@ What changed in each release, one line per change. Versions follow [Semantic Ver ### New -- Agents can read across several screens of a list and stop at a matching row without tapping it. -- Tap, swipe and text input results now distinguish a sent input from one that never went out or whose delivery is uncertain. +- Agents can read across several screens of a list and stop at a matching row without tapping it (#170). +- Tap, swipe and text input results now distinguish a sent input from one that never went out or whose delivery is uncertain (#170). ## [0.2.10] - 2026-11-22 diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index c5698261..00cd5215 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -8,8 +8,8 @@ ### 新功能 -- Agent 可以跨屏收集列表内容,找到目标行后停留在当前页面。 -- 点击、滑动和输入文字会区分已发送、未发送和结果未知,方便 Agent 判断是否先读屏再重试。 +- Agent 可以跨屏收集列表内容,找到目标行后停留在当前页面 (#170)。 +- 点击、滑动和输入文字会区分已发送、未发送和结果未知,方便 Agent 判断是否先读屏再重试 (#170)。 ## [0.2.10] - 2026-11-22 From b9cdfe600a33980e28d2c5889a365e382434c84e Mon Sep 17 00:00:00 2001 From: MSK Date: Mon, 23 Nov 2026 17:13:40 +0800 Subject: [PATCH 3/4] Fix input retries, readback and interrupted scroll results --- apps/iphone-control/src/mcp_bridge.rs | 89 ++++++++++++++++++++++---- crates/ictl-daemon/src/tools/input.rs | 64 +++++++++++++++--- crates/ictl-daemon/src/tools/mod.rs | 6 ++ crates/ictl-daemon/src/tools/native.rs | 18 ++++-- crates/ictl-daemon/src/tools/scroll.rs | 10 +-- crates/ictl-mcp/src/lib.rs | 43 +++++++++---- crates/ictl-protocol/src/lib.rs | 1 + crates/ictl-wda/src/client.rs | 9 ++- docs/dev/regression-cases.md | 1 + docs/tools.md | 2 +- website/en/guide/tools.md | 2 +- website/guide/tools.md | 2 +- 12 files changed, 195 insertions(+), 52 deletions(-) diff --git a/apps/iphone-control/src/mcp_bridge.rs b/apps/iphone-control/src/mcp_bridge.rs index c0145cfb..00bda685 100644 --- a/apps/iphone-control/src/mcp_bridge.rs +++ b/apps/iphone-control/src/mcp_bridge.rs @@ -91,6 +91,17 @@ where Ok(()) } +struct ForwardError { + message: String, + delivery: protocol::Delivery, +} + +impl From for ForwardError { + fn from(message: String) -> Self { + Self { message, delivery: protocol::Delivery::Unknown } + } +} + struct Link { remote: Remote, task: Option, @@ -126,31 +137,42 @@ impl Link { let reply = if msg["method"] == "tools/call" && msg["params"]["name"].as_str().is_some_and(ictl_mcp::reports_input) { - // The remote daemon may have acted before the tunnel lost the reply. - json!({"jsonrpc": "2.0", "id": id, "error": { - "code": -32603, - "message": format!("{e}. {}", ictl_l10n::tr!( + let hint = if e.delivery == protocol::Delivery::NotSent { + ictl_l10n::tr!("输入未发出", "The input was not sent") + } else { + ictl_l10n::tr!( "未收到远端工具结果;先读屏确认,再决定是否重试", "No remote tool result; inspect the screen before retrying" - )), - "data": {"delivery": "unknown", "stage": "transport"} + ) + }; + json!({"jsonrpc": "2.0", "id": id, "error": { + "code": -32603, + "message": format!("{}. {hint}", e.message.trim_end_matches(['.', '。'])), + "data": {"delivery": e.delivery, "stage": "transport"} }}) .to_string() } else { - rpc_error(id, -32603, &e) + rpc_error(id, -32603, &e.message) }; let _ = self.tx.send(reply); } // a notification has nobody to tell but the log (stdout is the protocol) - None => eprintln!("iphone-control mcp --url: {e}"), + None => eprintln!("iphone-control mcp --url: {}", e.message), } } } - async fn send(&self, msg: &Value, id: Option<&Value>) -> Result<(), String> { + async fn send(&self, msg: &Value, id: Option<&Value>) -> Result<(), ForwardError> { let r = self.remote.request(reqwest::Method::POST, "/mcp"); let r = self.with_headers(r).header(reqwest::header::ACCEPT, "application/json, text/event-stream").json(msg); - let resp = r.send().await.map_err(|e| format!("{}: {e}", self.remote.base()))?; + let resp = r.send().await.map_err(|e| ForwardError { + delivery: if e.is_connect() || e.is_builder() { + protocol::Delivery::NotSent + } else { + protocol::Delivery::Unknown + }, + message: format!("{}: {e}", self.remote.base()), + })?; if let Some(sid) = resp.headers().get("mcp-session-id").and_then(|v| v.to_str().ok()) { self.session().id = Some(sid.to_owned()); } @@ -158,7 +180,11 @@ impl Link { return missing_reply(id); } if !resp.status().is_success() { - return Err(remote::failure(resp).await); + let delivery = match resp.status().as_u16() { + 401 | 403 | 404 => protocol::Delivery::NotSent, + _ => protocol::Delivery::Unknown, + }; + return Err(ForwardError { message: remote::failure(resp).await, delivery }); } let initialize = msg["method"] == "initialize"; let pass = |v: Value| { @@ -214,8 +240,12 @@ impl Link { } /// Notifications and client responses have no corresponding JSON-RPC response. -fn missing_reply(id: Option<&Value>) -> Result<(), String> { - if id.is_some() { Err("viewer closed the response without a matching JSON-RPC reply".into()) } else { Ok(()) } +fn missing_reply(id: Option<&Value>) -> Result<(), ForwardError> { + if id.is_some() { + Err(String::from("viewer closed the response without a matching JSON-RPC reply").into()) + } else { + Ok(()) + } } fn rpc_error(id: Value, code: i64, message: &str) -> String { @@ -227,6 +257,39 @@ mod tests { use super::*; use tokio::io::AsyncReadExt; + #[tokio::test] + async fn rejected_or_unreachable_input_is_not_sent_but_a_gateway_failure_is_unknown() { + for (status, delivery) in [ + (None, "not_sent"), + (Some(401), "not_sent"), + (Some(403), "not_sent"), + (Some(404), "not_sent"), + (Some(502), "unknown"), + ] { + let server = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", server.local_addr().unwrap()); + if let Some(status) = status { + tokio::spawn(async move { + let (mut socket, _) = server.accept().await.unwrap(); + let mut buf = [0; 4096]; + assert!(socket.read(&mut buf).await.unwrap() > 0); + socket + .write_all(format!("HTTP/1.1 {status} Error\r\nContent-Length: 0\r\n\r\n").as_bytes()) + .await + .unwrap(); + }); + } else { + drop(server); + } + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let link = + Link { remote: Remote::new(&url, None, None).unwrap(), task: None, session: Mutex::default(), tx }; + link.forward(json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"iphone_tap"}})).await; + let reply: Value = serde_json::from_str(&rx.try_recv().unwrap()).unwrap(); + assert_eq!(reply["error"]["data"]["delivery"], delivery); + } + } + #[tokio::test] async fn interrupted_tool_reply_reports_unknown_instead_of_hanging_or_retrying() { let server = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rs index 1a0d2151..9f40cce2 100644 --- a/crates/ictl-daemon/src/tools/input.rs +++ b/crates/ictl-daemon/src/tools/input.rs @@ -266,7 +266,7 @@ impl Daemon { /// 边滑边找的一次慢滑([`search_stroke`]),等停下后读一棵新树 pub(super) async fn search_scroll(&self, g: &mut Inner, down: bool) -> crate::error::Result { - let screen = self.screen(g).await?; + let screen = self.screen(g).await.map_err(Error::preflight)?; 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 @@ -288,6 +288,13 @@ impl Daemon { let mut back = 0; let mut at_end = false; if let Some(s) = scroll { + let failed_scroll = |e: Error, completed: u32| { + let message = ictl_l10n::trf!( + "查找目标时滚动失败(此前已完成 {completed} 次滑动),尚未点击目标;请查看屏幕:{e}", + "Scroll search failed after {completed} completed swipes; the target was not tapped. Inspect the screen: {e}" + ); + e.with_message(message) + }; let mut partial_at = None; loop { if reachable_exact(&tree, text, index) { @@ -299,7 +306,7 @@ impl Daemon { if at_end || scrolled >= s.max { break; } - let next = Box::pin(self.search_scroll(g, s.down)).await.map_err(Error::preflight)?; + let next = Box::pin(self.search_scroll(g, s.down)).await.map_err(|e| failed_scroll(e, scrolled))?; scrolled += 1; at_end = next.close_to(&tree, STILL_TOLERANCE); tree = next; @@ -310,7 +317,9 @@ impl Daemon { && let Some(k) = partial_at { while back <= scrolled - k && !reachable(&tree, text, index) { - tree = Box::pin(self.search_scroll(g, !s.down)).await.map_err(Error::preflight)?; + tree = Box::pin(self.search_scroll(g, !s.down)) + .await + .map_err(|e| failed_scroll(e, scrolled + back))?; back += 1; } } @@ -848,7 +857,7 @@ pub(super) async fn wda_replace( } // the app dropped the last characters (as typing sees, `verify_typed`): typed again one by one if now != text - && let Some(rest) = text.strip_prefix(now.as_str()).filter(|r| !r.is_empty() && !now.is_empty()) + && let Some(rest) = repairable_suffix(text, &now) { for c in rest.chars() { w.keys(&c.to_string()).await.map_err(unread)?; @@ -939,18 +948,31 @@ pub(super) fn newly_typed(before: &str, now: &str, text: &str) -> bool { /// Repair only an observed append of the exact leading characters, stable across two fresh reads. pub(super) fn missing_suffix<'a>(before: &str, first: &str, second: &str, text: &'a str) -> Option<&'a str> { + if !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit()) { + let strip_spaces = |s: &str| s.split_whitespace().collect::(); + let first = strip_spaces(first); + let second = strip_spaces(second); + if first != second { + return None; + } + return repairable_suffix(text, second.strip_prefix(&strip_spaces(before))?); + } if first != second { return None; } - let added = second.strip_prefix(before)?; - if added.is_empty() { + repairable_suffix(text, second.strip_prefix(before)?) +} + +/// A missing Return or Tab can mean the first one already submitted or moved focus. +fn repairable_suffix<'a>(text: &'a str, observed: &str) -> Option<&'a str> { + if observed.is_empty() || text.chars().any(char::is_control) { return None; } - text.strip_prefix(added).filter(|rest| !rest.is_empty()) + text.strip_prefix(observed).filter(|rest| !rest.is_empty() && !rest.chars().any(char::is_whitespace)) } /// Keep the focused field's identity and exact value, including whitespace. -async fn readable_focus(w: &mut WdaClient) -> Option<(String, String)> { +async fn readable_focus(w: &mut WdaClient) -> Option<(String, String)> { let f = w.focused_field().await.ok()??; if !REPLACEABLE.contains(&f.kind.as_str()) { return None; @@ -959,7 +981,11 @@ async fn readable_focus(w: &mut WdaClient) -> Option<(String, S Some((f.id, value)) } -async fn verify_typed(w: &mut WdaClient, before: Option<&(String, String)>, text: &str) -> Typed { +async fn verify_typed( + w: &mut WdaClient, + before: Option<&(String, String)>, + text: &str, +) -> Typed { let Some((id, before)) = before else { return Typed::Unknown }; let mut reads = Vec::with_capacity(2); for attempt in 0..2 { @@ -973,6 +999,10 @@ async fn verify_typed(w: &mut WdaClient, before: Option<&(Strin if newly_typed(before, &now, text) { return Typed::Ok; } + if text != text.trim() && newly_typed(before, &now, text.trim()) { + // The visible text arrived, but the field cannot confirm the surrounding whitespace. + return Typed::Unknown; + } reads.push(now); } let Some(rest) = missing_suffix(before, &reads[0], &reads[1], text) else { @@ -1095,6 +1125,22 @@ mod tests { }) } + #[tokio::test] + async fn a_single_line_field_never_receives_a_second_return_during_repair() { + let f = Fake::new("TextField", ""); + f.0.lock().unwrap().mangle = |s| s.trim_end().to_owned(); + let mut w = WdaClient::new(&f); + let before = readable_focus(&mut w).await.unwrap(); + w.keys("hi\n").await.unwrap(); + assert_eq!(verify_typed(&mut w, Some(&before), "hi\n").await, Typed::Unknown); + assert_eq!(f.0.lock().unwrap().keys, ["hi\n"]); + + let f = Fake::new("TextField", ""); + f.0.lock().unwrap().mangle = |s| s.trim_end().to_owned(); + assert!(replace(&f, "hi\n", false).await.is_err()); + assert_eq!(f.0.lock().unwrap().keys, ["hi\n"]); + } + #[tokio::test] async fn replaces_the_focused_field_then_presses_return() { let f = Fake::new("SearchField", "wifi"); diff --git a/crates/ictl-daemon/src/tools/mod.rs b/crates/ictl-daemon/src/tools/mod.rs index 63f5bff0..6fe7beab 100644 --- a/crates/ictl-daemon/src/tools/mod.rs +++ b/crates/ictl-daemon/src/tools/mod.rs @@ -680,5 +680,11 @@ mod tests { assert_eq!(missing_suffix("abc故宫", "abc故宫", "abc故宫", "故宫博物院"), None); assert_eq!(missing_suffix("", "故", "故宫", "故宫博物院"), None); assert_eq!(missing_suffix("abc", "def故宫", "def故宫", "故宫博物院"), None); + for text in ["hi\n", "hi\t", "hi ", "hi\nmore"] { + assert_eq!(missing_suffix("", "hi", "hi", text), None); + } + assert_eq!(missing_suffix("", "138 0013 8", "13800138", "13800138000"), Some("000")); + assert_eq!(missing_suffix("138 00", "138 0013 8", "13800138", "138000"), Some("000")); + assert_eq!(missing_suffix("", "138 00", "138001", "13800138"), None); } } diff --git a/crates/ictl-daemon/src/tools/native.rs b/crates/ictl-daemon/src/tools/native.rs index 039d807e..6609a156 100644 --- a/crates/ictl-daemon/src/tools/native.rs +++ b/crates/ictl-daemon/src/tools/native.rs @@ -58,6 +58,8 @@ enum PasteTarget<'a> { enum Pasted { /// A field changed and now holds the text Typed, + /// The field shows the insertion with surrounding whitespace removed. + Trimmed, /// A field held the text before and still does, unchanged: the paste replaced the same text, or didn't go in Unchanged, /// A password field is on screen: its value can't be read @@ -71,7 +73,9 @@ fn paste_seen(now: Option<&str>, old: &str, wanted: &str) -> Pasted { let Some(now) = now else { return Pasted::Unreadable }; if input::newly_typed(old, now, wanted) { Pasted::Typed - } else if now == old && old.contains(wanted) { + } else if wanted != wanted.trim() && input::newly_typed(old, now, wanted.trim()) { + Pasted::Trimmed + } else if now == old && !wanted.trim().is_empty() && old.contains(wanted.trim()) { Pasted::Unchanged } else if now.contains(wanted) && !now.starts_with(old) { Pasted::Unreadable // a selection may have been replaced @@ -645,7 +649,7 @@ impl Daemon { } match typed { Pasted::Typed => *field_verified = Some(true), - Pasted::Unreadable => { + Pasted::Trimmed | Pasted::Unreadable => { note += ictl_l10n::tr!( "(无法核对输入框内容,请查看屏幕确认)", " (field contents could not be verified; inspect the screen)" @@ -805,9 +809,7 @@ impl Daemon { let typed = loop { let screen = self.ax_snapshot(g, AX_WAIT, true).await.map_err(Error::readback)?; let tree = self.snapshot_tree(g, &screen).await.map_err(Error::readback)?; - if answered.is_none() - && let Some((x, y)) = paste_allow(&tree) - { + if let Some((x, y)) = paste_allow(&tree) { self.native_tap(g, x, y).await.map_err(|e| Error::action(Delivery::Sent, FailureStage::Send, e))?; answered = Some(Instant::now()); tokio::time::sleep(Duration::from_millis(300)).await; @@ -824,7 +826,7 @@ impl Daemon { PasteTarget::Replace(object) => replacement_seen(&screen, object, text), }; match seen { - Pasted::Typed => break seen, + Pasted::Typed | Pasted::Trimmed => break seen, // only once the prompt was answered: before that, the paste hasn't gone in yet Pasted::Unchanged if answered.is_some_and(|t| t.elapsed() >= PASTE_SAME_SETTLE) => break seen, // never asked: iOS asks for every paste of ours, so nothing may have been pasted at all @@ -1268,5 +1270,9 @@ mod tests { assert_eq!(paste_seen(Some("时钟"), "时钟", "设置"), Pasted::Missing); assert_eq!(paste_seen(Some("11"), "1", "11"), Pasted::Missing); assert_eq!(paste_seen(None, "", "设置"), Pasted::Unreadable); + assert_eq!(paste_seen(Some("北京"), "", "北京\n"), Pasted::Trimmed); + assert_eq!(paste_seen(Some("北京"), "", " 北京 "), Pasted::Trimmed); + assert_eq!(paste_seen(Some("北京"), "北京", "北京 "), Pasted::Unchanged); + assert_eq!(paste_seen(Some(""), "", " "), Pasted::Missing); } } diff --git a/crates/ictl-daemon/src/tools/scroll.rs b/crates/ictl-daemon/src/tools/scroll.rs index cdc003fa..3282fade 100644 --- a/crates/ictl-daemon/src/tools/scroll.rs +++ b/crates/ictl-daemon/src/tools/scroll.rs @@ -36,8 +36,10 @@ impl Daemon { } let end = previous.as_ref().is_some_and(|p| unchanged_viewport(p, &tree)); if let Some(reason) = stop_reason(matched.is_some(), rows.len() == limit, end, scrolls == scan.max_scrolls) + .or_else(|| (!may_continue()).then_some(ScrollStop::Interrupted)) { let why = match reason { + ScrollStop::Interrupted => ictl_l10n::tr!("滚动已中断", "collection interrupted"), ScrollStop::Found => ictl_l10n::tr!("找到目标", "found the target"), ScrollStop::End => { ictl_l10n::tr!("滚动后可见内容没有变化", "visible content stayed the same after scrolling") @@ -67,14 +69,6 @@ impl Daemon { text += &self.snapshot_note(g); return Ok((text, Data::ScrollCollection { stop_reason: reason, scrolls, rows, matched })); } - // Let a gesture finish. A cancellation, pause or takeover prevents the next one. - if !may_continue() { - return Err(ictl_l10n::trf!( - "滚动已中断,已滑动 {scrolls} 次", - "Collection interrupted after {scrolls} scrolls" - ) - .into()); - } previous = Some(tree); tree = Box::pin(self.search_scroll(g, scan.down)).await?; scrolls += 1; diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs index 02bde386..4b4c91c3 100644 --- a/crates/ictl-mcp/src/lib.rs +++ b/crates/ictl-mcp/src/lib.rs @@ -1137,6 +1137,23 @@ fn input_error( result } +fn add_delivery_hint(message: &mut String, delivery: Delivery) { + let lower = message.to_ascii_lowercase(); + let already_guided = + ["inspect the screen", "take a screenshot", "check with a screenshot", "查看屏幕", "截图确认", "截图看看"] + .iter() + .any(|hint| lower.contains(hint)); + message.truncate(message.trim_end().trim_end_matches(['.', '。']).len()); + message.push_str(match delivery { + Delivery::NotSent => ictl_l10n::tr!("。目标输入未发出。", ". The requested input was not sent."), + Delivery::Unknown => ictl_l10n::tr!("。输入可能已送达。", ". Input may have reached the phone."), + Delivery::Sent => ictl_l10n::tr!("。输入已发出。", ". Input was sent."), + }); + if !already_guided && delivery != Delivery::NotSent { + message.push_str(ictl_l10n::tr!("请先查看屏幕再决定下一步。", " Inspect the screen before retrying.")); + } +} + struct InputResult<'a> { delivery: Delivery, stage: Option, @@ -1311,17 +1328,7 @@ impl McpServer { } Ok(match (resp, input) { (Response::Error { mut message, .. }, Some(input)) => { - message += match input.delivery { - Delivery::NotSent => ictl_l10n::tr!("。目标输入未发出。", ". The requested input was not sent."), - Delivery::Unknown => ictl_l10n::tr!( - "。输入可能已送达,请先查看屏幕再决定下一步。", - ". Input may have reached the phone. Inspect the screen before retrying." - ), - Delivery::Sent => ictl_l10n::tr!( - "。输入已发出,请查看屏幕再决定下一步。", - ". Input was sent. Inspect the screen before retrying." - ), - }; + add_delivery_hint(&mut message, input.delivery); self.finish(message, true, then, false, false, Some(input)).await } (Response::Text { text, outcome, .. }, input) if req.is_device_action() => { @@ -1689,6 +1696,20 @@ mod tests { /// With IPHONE_CONTROL_LANG=en nothing the agent reads up front is Chinese: instructions, tool /// descriptions, titles and parameter docs (only examples of Chinese input may stay) + #[test] + fn delivery_hints_do_not_repeat_punctuation_or_existing_screen_guidance() { + ictl_l10n::with_lang(ictl_l10n::Lang::En, || { + let mut message = "Focus changed. Inspect the screen.".to_owned(); + add_delivery_hint(&mut message, Delivery::Sent); + assert_eq!(message, "Focus changed. Inspect the screen. Input was sent."); + }); + ictl_l10n::with_lang(ictl_l10n::Lang::Zh, || { + let mut message = "请求超时,请先截图确认。".to_owned(); + add_delivery_hint(&mut message, Delivery::Unknown); + assert_eq!(message, "请求超时,请先截图确认。输入可能已送达。"); + }); + } + #[test] fn english_tool_definitions_have_no_chinese() { use ictl_l10n::{Lang, with_lang}; diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs index 3b2af950..8997da0f 100644 --- a/crates/ictl-protocol/src/lib.rs +++ b/crates/ictl-protocol/src/lib.rs @@ -498,6 +498,7 @@ pub struct ElementData { #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ScrollStop { + Interrupted, Found, End, MaxScrolls, diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rs index ca399489..5e8b78c1 100644 --- a/crates/ictl-wda/src/client.rs +++ b/crates/ictl-wda/src/client.rs @@ -428,7 +428,7 @@ impl WdaClient { let body = body.map(|b| b.to_string().into_bytes()); let (status, raw) = self.transport.send(method, path, body, timeout).await.map_err(|e| match e.kind() { std::io::ErrorKind::TimedOut => WdaError::Timeout(e.to_string()), - crate::http::WRITE_FAILED => WdaError::Write(e.to_string()), + crate::http::WRITE_FAILED if acts(method, path) => WdaError::Write(e.to_string()), crate::http::AFTER_SENT => WdaError::Interrupted(e.to_string()), _ => WdaError::Unavailable(e.to_string()), })?; @@ -1523,7 +1523,12 @@ mod tests { } let kind = |k| async move { WdaClient::new(Fails(k)).active_app().await }; assert!(matches!(kind(crate::http::AFTER_SENT).await, Err(WdaError::Interrupted(_)))); - assert!(matches!(kind(crate::http::WRITE_FAILED).await, Err(WdaError::Write(_)))); + assert!(matches!(kind(crate::http::WRITE_FAILED).await, Err(WdaError::Unavailable(_)))); + let client = WdaClient::new(Fails(crate::http::WRITE_FAILED)); + for (path, acts) in [("/session/1/element", false), ("/session/1/wda/keys", true)] { + let error = client.send("POST", path, None, Duration::from_secs(1)).await.unwrap_err(); + assert!(if acts { matches!(error, WdaError::Write(_)) } else { matches!(error, WdaError::Unavailable(_)) }); + } assert!(matches!(kind(std::io::ErrorKind::TimedOut).await, Err(WdaError::Timeout(_)))); assert!(matches!(kind(std::io::ErrorKind::NotConnected).await, Err(WdaError::Unavailable(_)))); // 应答了但不是 JSON:WDA 收到了请求 diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index 5b176019..804797ee 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -167,3 +167,4 @@ | 161 | 等待文字消失的请求被当成等待出现 | `state: "disappeared"` 等待可读界面不再匹配,读取失败或未读完整不算成功 | 单测 `disappearance_requires_a_readable_complete_screen_without_the_target` + 真机脚本 `scenarios.py editing` | | 162 | 经 WDA 控制(iOS 26 及以前,或 `ICTL_IOS_BACKEND=wda`)时 `replace: true` 直接拒绝,调用方只能在光标处输入,得到 `wifi 蓝牙` | 经 WDA 取聚焦元素(`/element/active`),只接受普通可读输入框(密码框拒绝),WDA `clear` 后按键输入,读回同一个元素的全文一致才按回车,结尾丢字补一次;空输入框读出占位文字算空;清空后再失败时明说原文已删掉;WDA 在动手前就连不上时,原生控制可用则改走原生 | 单测 `replaces_the_focused_field_then_presses_return`、`a_mismatch_is_refused_without_return`、`focused_field_reads_its_type_and_placeholder` + 真机脚本 `scenarios.py editing`(WDA 设备) | | 163 | Viewer 已收到输入请求,返回结果前连接中断,客户端可能一直等待或重复输入 | 客户端结束该调用,报告投递状态未知,提示先查看手机 | 单测 `interrupted_tool_reply_reports_unknown_instead_of_hanging_or_retrying` | +| 164 | WDA 输入以换行结尾,单行框只显示正文,补字可能再按一次回车 | 核对同一输入框,不自动重发回车、制表符或无法确认的空白;数字框格式化后仍可补齐缺失的数字 | 单测 `a_single_line_field_never_receives_a_second_return_during_repair`、`input_repair_requires_a_stable_new_prefix` | diff --git a/docs/tools.md b/docs/tools.md index c4147c35..21e557d1 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`, `count` (default 1, max 10) | For targets without text (icons, games, maps); falls back to HID when WDA is down. `count` taps the same point that many times in one gesture, about 0.1 s apart: 2 is a double tap (also turns on Caps Lock on the keyboard's Shift key); for hidden entries that need several taps in a short time, which separate calls or `iphone_batch` are too slow for | -| `iphone_scroll_collect` | `scroll` (down by default, or up), `filter`, `until`, `max_scrolls` (default 8, max 15), `limit` (default/max 150) | Collects rows in travel order and merges overlapping rows on adjacent screens. Identical accessibility rows can make the overlap ambiguous. Stops on a visible text match (`found`), an unchanged screen (`end`), `max_scrolls`, or the row `limit`. The matched element includes an uncovered `point` in the final viewport. The phone stays there without a tap. | +| `iphone_scroll_collect` | `scroll` (down by default, or up), `filter`, `until`, `max_scrolls` (default 8, max 15), `limit` (default/max 150) | Collects rows in travel order and merges overlapping rows on adjacent screens. Identical accessibility rows can make the overlap ambiguous. Stops on a visible text match (`found`), an unchanged screen (`end`), `max_scrolls`, or the row `limit`. An interrupted scan returns its collected rows with `interrupted` if the caller is still connected. The matched element includes an uncovered `point` in the final viewport. The phone stays there without a tap. | | `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), `hold` (default 0) | Returns after the list has stopped scrolling (up to 2.5 s). Swipe up (`from_y` > `to_y`) to see content further down. `hold` holds the finger still at the start for that many seconds before moving, to drag things that have to be long-pressed first (home-screen icons, reorderable rows); about 0.6 works, under 0.5 usually doesn't pick anything up. `seconds` + `hold` is at most 10 | diff --git a/website/en/guide/tools.md b/website/en/guide/tools.md index 57381717..98573d15 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; `count` taps the same point several times (double tap, entries that need quick repeated taps) | -| `iphone_scroll_collect` | Scroll through a list, collect matching rows and optionally stop when text appears. The phone stays on the final viewport. | +| `iphone_scroll_collect` | Scroll through a list, collect matching rows and optionally stop when text appears. On pause or takeover, a connected caller receives the rows collected so far and the stop reason `interrupted`. The phone stays on the final viewport. | | `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. `hold` holds still at the start for that many seconds before moving, to drag things that need a long press first (home-screen icons, reorderable rows); about 0.6 works | diff --git a/website/guide/tools.md b/website/guide/tools.md index d6e2d8f9..e52b7ed1 100644 --- a/website/guide/tools.md +++ b/website/guide/tools.md @@ -19,7 +19,7 @@ MCP 服务提供 18 个工具,开启[开发者工具](#开发者工具-显式 | 工具 | 作用 | |---|---| | `iphone_tap` | 按坐标点击;`count` 在同一点连点(双击、要短时间内连点几下的入口) | -| `iphone_scroll_collect` | 逐屏滚动收集列表行,支持按文字过滤和看到目标就停止。结果包含停止原因,手机停留在最后一屏。 | +| `iphone_scroll_collect` | 逐屏滚动收集列表行,支持按文字过滤和看到目标就停止。操作被暂停或接管时,仍连接的客户端会收到已读到的行和停止原因 `interrupted`。手机停留在最后一屏。 | | `iphone_tap_element` | 按文字点击;中心被悬浮栏、键盘挡住时改点露出来的部分,整个被挡住就不点。带 `scroll`(`down` / `up`)时,屏幕上没有就慢慢边滑边找,找到就点,滑到底或滑满 `max_scrolls`(默认 8)次为止 | | `iphone_long_press` | 长按;`seconds` 默认 1,最多 10 | | `iphone_swipe` | 滑动;列表停稳后才返回。`seconds` 默认 0.3,最多 10。`hold` 先在起点按住几秒再移动,用来拖动要先长按才拿得起来的东西(主屏幕图标、可排序的列表项),0.6 左右即可 | From c04af204b479b4085b5424d44fe8caef71124cb2 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:05:54 +0800 Subject: [PATCH 4/4] fix: device-test findings: newline paste, WDA readback cost, list duplicates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found by running this branch on an iPhone 15 Pro Max (iOS 27.2.1, native) and an iPad mini 5 (iPadOS 26.7.3, WDA, landscape) against main: - Natively, iphone_type_text "北京\n" failed with "the field didn't show the text" although Spotlight showed 北京: a single-line field turns a pasted newline into a space (it reads «北京 »), which the trimmed comparison didn't accept. A field that differs only in whitespace is now Trimmed (readback unverified), as intended; main had accepted it. «北京\n上海» (reads «北京 上海») too. - Through WDA, checking the field after typing read the focused element four requests at a time, twice, 0.3 s apart, and typing over a selected search (Spotlight keeps its last one) can never match: typing 设置 took 4.39 s against main's 2.55 s. A reread now asks only which element has focus and its value (WdaClient::active_element), and a first read that settles the case (a selection replaced) answers at once. - iphone_scroll_collect collected rows twice. Settings' large title collapses into the navigation bar, so the next viewport didn't start with the end of the previous one: a few elements may now lie between the overlap and the ends. Through WDA on an iPad split view no two viewports overlapped at all, and the 150-row limit came after two or three swipes: a detail row's Cell, label and chevron have middles a point apart, in an order that turned round as the list moved; the sidebar's navigation bar and search field stay put while its rows pass under them, between the rows in travel order; and the column that didn't scroll interleaves with the one that did. Elements are now ordered row by row (left to right within a row); when the tree has scroll areas only their content is matched, and the rest (bars, the list's own container) is new only when the previous viewport had nothing like it; the column that stayed is left out. A tree read natively has no scroll areas and is matched whole, as before. `x` picks where to swipe, so an iPad sidebar can be scanned. - The bridge's "no matching JSON-RPC reply" message comes in both languages, and in Chinese it joins its hint with 。 (it read «…回复. 未收到远端工具结果…»); the Chinese changelog's parentheses; D10 counts 18 tools. Regression cases 165-167. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.zh-CN.md | 4 +- apps/iphone-control/src/mcp_bridge.rs | 13 +- crates/ictl-daemon/src/core.rs | 9 + crates/ictl-daemon/src/tools/input.rs | 164 ++++++++++---- crates/ictl-daemon/src/tools/native.rs | 15 +- crates/ictl-daemon/src/tools/scroll.rs | 294 +++++++++++++++++++++++-- crates/ictl-mcp/src/lib.rs | 14 +- crates/ictl-protocol/src/lib.rs | 6 +- crates/ictl-wda/src/client.rs | 17 +- crates/ictl-wda/src/elements.rs | 6 + docs/decisions.md | 2 +- docs/dev/regression-cases.md | 3 + docs/tools.md | 2 +- website/en/guide/tools.md | 2 +- website/guide/tools.md | 2 +- 15 files changed, 479 insertions(+), 74 deletions(-) diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 952f9bcc..62d5f7a2 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -8,8 +8,8 @@ ### 新功能 -- Agent 可以跨屏收集列表内容,找到目标行后停留在当前页面 (#170)。 -- 点击、滑动和输入文字会区分已发送、未发送和结果未知,方便 Agent 判断是否先读屏再重试 (#170)。 +- Agent 可以跨屏收集列表内容,找到目标行后停留在当前页面(#170)。 +- 点击、滑动和输入文字会区分已发送、未发送和结果未知,方便 Agent 判断是否先读屏再重试(#170)。 ## [0.2.11] - 2026-11-23 diff --git a/apps/iphone-control/src/mcp_bridge.rs b/apps/iphone-control/src/mcp_bridge.rs index 00bda685..b9eb641e 100644 --- a/apps/iphone-control/src/mcp_bridge.rs +++ b/apps/iphone-control/src/mcp_bridge.rs @@ -147,7 +147,11 @@ impl Link { }; json!({"jsonrpc": "2.0", "id": id, "error": { "code": -32603, - "message": format!("{}. {hint}", e.message.trim_end_matches(['.', '。'])), + "message": ictl_l10n::trf!( + "{}。{hint}", + "{}. {hint}", + e.message.trim_end_matches(['.', '。']) + ), "data": {"delivery": e.delivery, "stage": "transport"} }}) .to_string() @@ -242,7 +246,12 @@ impl Link { /// Notifications and client responses have no corresponding JSON-RPC response. fn missing_reply(id: Option<&Value>) -> Result<(), ForwardError> { if id.is_some() { - Err(String::from("viewer closed the response without a matching JSON-RPC reply").into()) + Err(ictl_l10n::tr!( + "控制台关闭了响应,没有对应的 JSON-RPC 回复", + "viewer closed the response without a matching JSON-RPC reply" + ) + .to_owned() + .into()) } else { Ok(()) } diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs index 3bdcd208..ad6b1e4f 100644 --- a/crates/ictl-daemon/src/core.rs +++ b/crates/ictl-daemon/src/core.rs @@ -1526,6 +1526,9 @@ fn check_request(req: &Request) -> Result<(), String> { { return Err(ictl_l10n::tr!("超出滚动或行数上限", "scroll or row limit is out of range").into()); } + Request::ScrollCollect(scan) if scan.x.is_some_and(|x| !x.is_finite() || x < 0.0) => { + return Err(ictl_l10n::tr!("x 不能是负数", "x can't be negative").into()); + } Request::WebEval { expression, timeout_ms, .. } if expression.trim().is_empty() || *timeout_ms > MAX_WEB_EVAL_MS => { @@ -1597,6 +1600,7 @@ pub(crate) mod tests { filter: String::new(), until: String::new(), limit: 1, + x: None, }; let req = Request::ScrollCollect(scan.clone()); assert!(check_request(&req).is_ok()); @@ -1611,6 +1615,11 @@ pub(crate) mod tests { scan.limit = limit; assert!(check_request(&Request::ScrollCollect(scan.clone())).is_err()); } + (scan.max_scrolls, scan.limit) = (1, 1); + for (x, ok) in [(Some(160.0), true), (Some(0.0), true), (Some(-1.0), false), (Some(f64::NAN), false)] { + scan.x = x; + assert_eq!(check_request(&Request::ScrollCollect(scan.clone())).is_ok(), ok, "{x:?}"); + } } /// Each device keeps its own background WDA: switching to another device and back attaches to it again, and diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rs index 9f40cce2..cf29b604 100644 --- a/crates/ictl-daemon/src/tools/input.rs +++ b/crates/ictl-daemon/src/tools/input.rs @@ -264,10 +264,14 @@ impl Daemon { Ok(()) } - /// 边滑边找的一次慢滑([`search_stroke`]),等停下后读一棵新树 - pub(super) async fn search_scroll(&self, g: &mut Inner, down: bool) -> crate::error::Result { + /// 边滑边找的一次慢滑([`search_stroke`]),等停下后读一棵新树。`x`:在这个横坐标上滑(iPad 分栏界面的左栏), + /// 不给就是屏幕正中 + pub(super) async fn search_scroll(&self, g: &mut Inner, down: bool, x: Option) -> crate::error::Result { let screen = self.screen(g).await.map_err(Error::preflight)?; - let (from, to) = search_stroke(screen.width, screen.height, down); + let (mut from, mut to) = search_stroke(screen.width, screen.height, down); + if let Some(x) = x { + (from.0, to.0) = (x, x); + } Box::pin(self.swipe(g, Stroke { from, to, seconds: SEARCH_SWIPE_SECONDS, hold: 0.0 }, None, false)).await?; self.tree(g, Duration::ZERO).await } @@ -306,7 +310,8 @@ impl Daemon { if at_end || scrolled >= s.max { break; } - let next = Box::pin(self.search_scroll(g, s.down)).await.map_err(|e| failed_scroll(e, scrolled))?; + let next = + Box::pin(self.search_scroll(g, s.down, None)).await.map_err(|e| failed_scroll(e, scrolled))?; scrolled += 1; at_end = next.close_to(&tree, STILL_TOLERANCE); tree = next; @@ -317,7 +322,7 @@ impl Daemon { && let Some(k) = partial_at { while back <= scrolled - k && !reachable(&tree, text, index) { - tree = Box::pin(self.search_scroll(g, !s.down)) + tree = Box::pin(self.search_scroll(g, !s.down, None)) .await .map_err(|e| failed_scroll(e, scrolled + back))?; back += 1; @@ -946,6 +951,19 @@ pub(super) fn newly_typed(before: &str, now: &str, text: &str) -> bool { } } +/// The text arrived, but not the whitespace it was sent with: a single-line field turns a pasted newline into a +/// space («北京\n» reads «北京 », «北京\n上海» reads «北京 上海»; Spotlight, iPhone 15 Pro Max, iOS 27.2.1), and leading +/// or trailing whitespace can be dropped. [`newly_typed`] with all whitespace left out +pub(super) fn typed_but_whitespace(before: &str, now: &str, text: &str) -> bool { + let text = bare(text); + !text.is_empty() && newly_typed(&bare(before), &bare(now), &text) +} + +/// `s` without its whitespace +pub(super) fn bare(s: &str) -> String { + s.chars().filter(|c| !c.is_whitespace()).collect() +} + /// Repair only an observed append of the exact leading characters, stable across two fresh reads. pub(super) fn missing_suffix<'a>(before: &str, first: &str, second: &str, text: &'a str) -> Option<&'a str> { if !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit()) { @@ -971,49 +989,81 @@ fn repairable_suffix<'a>(text: &'a str, observed: &str) -> Option<&'a str> { text.strip_prefix(observed).filter(|rest| !rest.is_empty() && !rest.chars().any(char::is_whitespace)) } -/// Keep the focused field's identity and exact value, including whitespace. -async fn readable_focus(w: &mut WdaClient) -> Option<(String, String)> { - let f = w.focused_field().await.ok()??; - if !REPLACEABLE.contains(&f.kind.as_str()) { +/// The focused field before typing: which element it is, its placeholder, and its exact value, whitespace included +pub(super) struct Focus { + field: ictl_wda::client::FocusedField, + value: String, +} + +/// Four requests: the element, its type and placeholder ([`WdaClient::focused_field`]), its value. [`reread`] takes two +async fn readable_focus(w: &mut WdaClient) -> Option { + let field = w.focused_field().await.ok()??; + if !REPLACEABLE.contains(&field.kind.as_str()) { return None; } - let value = w.field_text(&f).await.ok()?; - Some((f.id, value)) + let value = w.field_text(&field).await.ok()?; + Some(Focus { field, value }) } -async fn verify_typed( - w: &mut WdaClient, - before: Option<&(String, String)>, - text: &str, -) -> Typed { - let Some((id, before)) = before else { return Typed::Unknown }; +/// What [`reread`] found +enum Reread { + Value(String), + /// Another readable field has focus now + Moved, + /// No readable field has focus, or WDA didn't answer + Unreadable, +} + +/// The field [`readable_focus`] found, once more. Its type and placeholder don't change, so only which element has +/// focus and its value are asked: two requests instead of four (each about 0.15 s through WDA on an iPad mini 5) +async fn reread(w: &mut WdaClient, f: &Focus) -> Reread { + match w.active_element().await { + Ok(Some(id)) if id == f.field.id => {} + // as `readable_focus` judges it: another text field (focus changed) or anything else (can't tell) + Ok(Some(_)) => { + return match w.focused_field().await { + Ok(Some(o)) if REPLACEABLE.contains(&o.kind.as_str()) => Reread::Moved, + _ => Reread::Unreadable, + }; + } + Ok(None) | Err(_) => return Reread::Unreadable, + } + w.field_text(&f.field).await.map_or(Reread::Unreadable, Reread::Value) +} + +async fn verify_typed(w: &mut WdaClient, before: Option<&Focus>, text: &str) -> Typed { + let Some(f) = before else { return Typed::Unknown }; + let before = f.value.as_str(); let mut reads = Vec::with_capacity(2); for attempt in 0..2 { if attempt > 0 { tokio::time::sleep(Duration::from_millis(300)).await; } - let Some((now_id, now)) = readable_focus(w).await else { return Typed::Unknown }; - if now_id != *id { - return Typed::FocusChanged; - } + let now = match reread(w, f).await { + Reread::Value(now) => now, + Reread::Moved => return Typed::FocusChanged, + Reread::Unreadable => return Typed::Unknown, + }; if newly_typed(before, &now, text) { return Typed::Ok; } - if text != text.trim() && newly_typed(before, &now, text.trim()) { - // The visible text arrived, but the field cannot confirm the surrounding whitespace. + if typed_but_whitespace(before, &now, text) { + // The visible text arrived, but the field cannot confirm the whitespace it was sent with. + return Typed::Unknown; + } + if now.contains(text) && (now == before || !now.starts_with(before)) { + // Replacing a selection (a search field keeps its last search, selected) can't be told apart from the + // text having been there, and reading again can't tell either: answer now. Reading twice more and waiting + // in between made typing into Spotlight about 1.8 s slower through WDA (iPad mini 5) return Typed::Unknown; } reads.push(now); } let Some(rest) = missing_suffix(before, &reads[0], &reads[1], text) else { - return if reads[1].contains(text) && (reads[1] == *before || !reads[1].starts_with(before.as_str())) { - Typed::Unknown // replacing a selection with its original contents is indistinguishable - } else { - Typed::Mismatch(reads.pop().unwrap()) - }; + return Typed::Mismatch(reads.pop().unwrap()); }; for (i, c) in rest.chars().enumerate() { - if i > 0 && !w.focused_field().await.ok().flatten().is_some_and(|f| f.id == *id) { + if i > 0 && !w.active_element().await.ok().flatten().is_some_and(|id| id == f.field.id) { return Typed::FocusChanged; } if w.keys(&c.to_string()).await.is_err() { @@ -1021,11 +1071,11 @@ async fn verify_typed( } tokio::time::sleep(Duration::from_millis(150)).await; } - match readable_focus(w).await { - Some((now_id, _)) if now_id != *id => Typed::FocusChanged, - Some((_, now)) if newly_typed(before, &now, text) => Typed::Fixed(rest.chars().count()), - Some((_, now)) => Typed::Mismatch(now), - None => Typed::Unknown, + match reread(w, f).await { + Reread::Moved => Typed::FocusChanged, + Reread::Value(now) if newly_typed(before, &now, text) => Typed::Fixed(rest.chars().count()), + Reread::Value(now) => Typed::Mismatch(now), + Reread::Unreadable => Typed::Unknown, } } @@ -1048,6 +1098,8 @@ mod tests { mangle: fn(&str) -> String, /// the field doesn't answer at all (WDA gone) gone: bool, + /// its text is selected: the next keys replace it (a search field keeps its last search, selected) + selected: bool, /// requests as `METHOD path`, and the text of every `/wda/keys` seen: Vec, keys: Vec, @@ -1063,6 +1115,7 @@ mod tests { drop_next: 0, mangle: str::to_owned, gone: false, + selected: false, seen: vec![], keys: vec![], })) @@ -1105,6 +1158,9 @@ mod tests { let typed: String = body["value"].as_array().unwrap().iter().map(|c| c.as_str().unwrap()).collect(); f.keys.push(typed.clone()); if typed != "\n" { + if std::mem::take(&mut f.selected) { + f.value.clear(); + } let keep = typed.chars().count().saturating_sub(std::mem::take(&mut f.drop_next)); let typed: String = typed.chars().take(keep).collect(); let typed = (f.mangle)(&typed); @@ -1127,13 +1183,17 @@ mod tests { #[tokio::test] async fn a_single_line_field_never_receives_a_second_return_during_repair() { - let f = Fake::new("TextField", ""); - f.0.lock().unwrap().mangle = |s| s.trim_end().to_owned(); - let mut w = WdaClient::new(&f); - let before = readable_focus(&mut w).await.unwrap(); - w.keys("hi\n").await.unwrap(); - assert_eq!(verify_typed(&mut w, Some(&before), "hi\n").await, Typed::Unknown); - assert_eq!(f.0.lock().unwrap().keys, ["hi\n"]); + // a newline dropped, or turned into a space (Spotlight does that with pasted text) + let mangles: [fn(&str) -> String; 2] = [|s| s.trim_end().to_owned(), |s| s.replace('\n', " ")]; + for mangle in mangles { + let f = Fake::new("TextField", ""); + f.0.lock().unwrap().mangle = mangle; + let mut w = WdaClient::new(&f); + let before = readable_focus(&mut w).await.unwrap(); + w.keys("hi\n").await.unwrap(); + assert_eq!(verify_typed(&mut w, Some(&before), "hi\n").await, Typed::Unknown); + assert_eq!(f.0.lock().unwrap().keys, ["hi\n"]); + } let f = Fake::new("TextField", ""); f.0.lock().unwrap().mangle = |s| s.trim_end().to_owned(); @@ -1141,6 +1201,28 @@ mod tests { assert_eq!(f.0.lock().unwrap().keys, ["hi\n"]); } + /// Typing over a selection can't be told apart from the text having been there, and reading again can't tell + /// either: one reread of the field already known (which element has focus, its value) answers, with no wait and no + /// second read (they made typing into Spotlight about 1.8 s slower through WDA on an iPad mini 5) + #[tokio::test] + async fn typing_over_a_selection_is_judged_after_one_reread() { + for (old, text) in [("设置", "设置"), ("wifi", "设置")] { + let f = Fake::new("SearchField", old); + f.0.lock().unwrap().selected = true; + let mut w = WdaClient::new(&f); + let before = readable_focus(&mut w).await.unwrap(); + w.keys(text).await.unwrap(); + let asked = f.0.lock().unwrap().seen.len(); + assert_eq!(verify_typed(&mut w, Some(&before), text).await, Typed::Unknown); + let field = f.0.into_inner().unwrap(); + assert_eq!(field.value, text); + assert_eq!( + field.seen[asked..], + ["GET /session/S/element/active", "GET /session/S/element/F/attribute/value"] + ); + } + } + #[tokio::test] async fn replaces_the_focused_field_then_presses_return() { let f = Fake::new("SearchField", "wifi"); diff --git a/crates/ictl-daemon/src/tools/native.rs b/crates/ictl-daemon/src/tools/native.rs index 6609a156..99eb84d2 100644 --- a/crates/ictl-daemon/src/tools/native.rs +++ b/crates/ictl-daemon/src/tools/native.rs @@ -68,16 +68,18 @@ enum Pasted { Missing, } -/// Compare only the original focused field's raw value, preserving whitespace. +/// Compare only the original focused field's raw value, preserving whitespace. Whitespace the field changed (a +/// single-line field turns a pasted newline into a space) makes it [`Pasted::Trimmed`], not missing fn paste_seen(now: Option<&str>, old: &str, wanted: &str) -> Pasted { let Some(now) = now else { return Pasted::Unreadable }; + let shown = input::bare(wanted); if input::newly_typed(old, now, wanted) { Pasted::Typed - } else if wanted != wanted.trim() && input::newly_typed(old, now, wanted.trim()) { + } else if input::typed_but_whitespace(old, now, wanted) { Pasted::Trimmed - } else if now == old && !wanted.trim().is_empty() && old.contains(wanted.trim()) { + } else if now == old && !shown.is_empty() && input::bare(old).contains(&shown) { Pasted::Unchanged - } else if now.contains(wanted) && !now.starts_with(old) { + } else if !shown.is_empty() && input::bare(now).contains(&shown) && !now.starts_with(old) { Pasted::Unreadable // a selection may have been replaced } else { Pasted::Missing @@ -1272,6 +1274,11 @@ mod tests { assert_eq!(paste_seen(None, "", "设置"), Pasted::Unreadable); assert_eq!(paste_seen(Some("北京"), "", "北京\n"), Pasted::Trimmed); assert_eq!(paste_seen(Some("北京"), "", " 北京 "), Pasted::Trimmed); + // what Spotlight's single-line field makes of a pasted newline (iPhone 15 Pro Max, iOS 27.2.1): a space + assert_eq!(paste_seen(Some("北京 "), "", "北京\n"), Pasted::Trimmed); + assert_eq!(paste_seen(Some("北京 上海"), "", "北京\n上海"), Pasted::Trimmed); + assert_eq!(paste_seen(Some("abc def "), "abc", " def\n"), Pasted::Trimmed); + assert_eq!(paste_seen(Some("北京 "), "设置", "北京\n"), Pasted::Unreadable); assert_eq!(paste_seen(Some("北京"), "北京", "北京 "), Pasted::Unchanged); assert_eq!(paste_seen(Some(""), "", " "), Pasted::Missing); } diff --git a/crates/ictl-daemon/src/tools/scroll.rs b/crates/ictl-daemon/src/tools/scroll.rs index 3282fade..ee11f4e2 100644 --- a/crates/ictl-daemon/src/tools/scroll.rs +++ b/crates/ictl-daemon/src/tools/scroll.rs @@ -12,6 +12,16 @@ impl Daemon { mut may_continue: impl FnMut() -> bool, ) -> crate::error::Result<(String, Data)> { self.ensure_unlocked(g).await?; + if let Some(x) = scan.x { + let width = self.screen(g).await.map_err(Error::preflight)?.width; + if x > width { + return Err(Error::preflight(ictl_l10n::trf!( + "x 超出了屏幕宽度({} 点),什么都没做", + "x is past the screen's width ({} points); nothing was done", + width + ))); + } + } let filter = scan.filter.to_lowercase(); let until = scan.until.to_lowercase(); let limit = scan.limit; @@ -70,7 +80,7 @@ impl Daemon { return Ok((text, Data::ScrollCollection { stop_reason: reason, scrolls, rows, matched })); } previous = Some(tree); - tree = Box::pin(self.search_scroll(g, scan.down)).await?; + tree = Box::pin(self.search_scroll(g, scan.down, scan.x)).await?; scrolls += 1; } } @@ -95,11 +105,37 @@ fn stop_reason(found: bool, row_limit: bool, end: bool, scroll_limit: bool) -> O } } +/// The visible elements in travel order: row by row, each row left to right fn visible_page(tree: &Tree, down: bool) -> Vec<&Element> { + let along = |e: &Element| if down { row_y(e) } else { -row_y(e) }; let mut page: Vec<_> = tree.elements.iter().filter(|e| !matches!(tree.tap_point(e), TapPoint::Covered { .. })).collect(); - page.sort_by_key(|e| (if down { e.center.1 } else { -e.center.1 }, e.center.0)); - page + page.sort_by(|a, b| along(a).total_cmp(&along(b)).then(a.center.0.cmp(&b.center.0))); + // One row's elements (an iPad's Cell, its label and its chevron) lie a point apart along the swipe, in an order + // that changed as the list moved, so no two viewports overlapped (Settings, iPad mini 5): they're one row + let mut rows: Vec> = Vec::new(); + for e in page { + match rows.last_mut() { + Some(row) if along(e) - along(row[0]) <= ROW_SLOP => row.push(e), + _ => rows.push(vec![e]), + } + } + rows.into_iter() + .flat_map(|mut row| { + row.sort_by_key(|e| e.center.0); + row + }) + .collect() +} + +/// How far apart along a swipe the elements of one row may lie ([`visible_page`]) +const ROW_SLOP: f64 = 4.0; + +/// The middle of an element's whole frame along a swipe: one the screen's edge cuts off still lines up with the rest of +/// its row +fn row_y(e: &Element) -> f64 { + let (v, h) = (e.visible, e.size.1 as f64); + if v.y <= 0.0 && v.h < h { v.y + v.h - h / 2.0 } else { v.y + h / 2.0 } } fn visible_match<'a>(page: &[&'a Element], until: &str) -> Option<&'a Element> { @@ -109,22 +145,109 @@ fn visible_match<'a>(page: &[&'a Element], until: &str) -> Option<&'a Element> { page.iter().copied().find(|e| e.contains_text(until)) } -/// Fixed headers and footers recur at the same location. After removing those, consecutive viewports -/// share a suffix/prefix in travel order. Comparing sequences preserves identical labels in distinct rows. +fn key(e: &Element) -> (&str, &str, &str, &str) { + (&e.kind, &e.name, &e.label, &e.value) +} + +/// How many elements may lie between the overlap of two viewports and the ends it is looked for at ([`new_rows`]) +const SKIP: usize = 3; + +/// Only a scroll area's content moves with a swipe. Bars and the rest (a navigation bar and the search field in it, the +/// list's own container, a dimming overlay) stay or change on their own anywhere in travel order: an iPad sidebar's +/// rows pass under its search field, so the viewports' rows didn't line up. The rows are matched without them, and +/// they're new only when the previous viewport had nothing like them. A tree read natively has no scroll areas: it's +/// matched whole fn new_rows<'a>(before: &[&Element], page: &[&'a Element]) -> Vec<&'a Element> { - fn key(e: &Element) -> (&str, &str, &str, &str) { - (&e.kind, &e.name, &e.label, &e.value) + if !page.iter().any(|e| e.in_scroll()) { + return overlap_rows(before, page); } + let rows = overlap_rows( + &before.iter().copied().filter(|e| e.in_scroll()).collect::>(), + &page.iter().copied().filter(|e| e.in_scroll()).collect::>(), + ); + page.iter() + .copied() + .filter(|e| { + if e.in_scroll() { + rows.iter().any(|r| std::ptr::eq(*r, *e)) + } else { + !before.iter().any(|b| key(b) == key(e)) + } + }) + .collect() +} + +/// Fixed headers and footers recur at the same location. After removing those, consecutive viewports +/// share a suffix/prefix in travel order. Comparing sequences preserves identical labels in distinct rows. +fn overlap_rows<'a>(before: &[&Element], page: &[&'a Element]) -> Vec<&'a Element> { + let (before, page) = without_still_column(before, page); let fixed = |(a, b): (&&Element, &&Element)| key(a) == key(b) && a.center == b.center; - let head = before.iter().zip(page).take_while(|pair| fixed(*pair)).count(); + let head = before.iter().zip(&page).take_while(|pair| fixed(*pair)).count(); let (before, page) = (&before[head..], &page[head..]); let tail = before.iter().rev().zip(page.iter().rev()).take_while(|pair| fixed(*pair)).count(); let (before, page) = (&before[..before.len() - tail], &page[..page.len() - tail]); - let overlap = (1..=before.len().min(page.len())) - .rev() - .find(|&n| before[before.len() - n..].iter().zip(&page[..n]).all(|(a, b)| key(a) == key(b))) - .unwrap_or(0); - page[overlap..].to_vec() + // The longest run of the previous viewport's end at the start of this one. A few elements may lie outside it: a + // large title collapses into the navigation bar as a list moves (Settings, iOS 27), so the next viewport starts + // with the title; scrolling back up to the top, the previous viewport ends with it + let mut best = (0, 0, 0); // the overlap, skipped at the end of `before`, skipped at the start of `page` + for j in 0..=SKIP.min(before.len()) { + let b = &before[..before.len() - j]; + for k in 0..=SKIP.min(page.len()) { + let p = &page[k..]; + let n = (1..=b.len().min(p.len())) + .rev() + .find(|&n| b[b.len() - n..].iter().zip(&p[..n]).all(|(x, y)| key(x) == key(y))) + .unwrap_or(0); + if n > best.0 { + best = (n, j, k); + } + } + } + let (n, j, k) = best; + if n == 0 { + return page.to_vec(); + } + // skipped at the start of this viewport, above the overlap: new only if the previous one had nothing like it + let lead = page[..k].iter().copied().filter(|e| !before.iter().any(|b| key(b) == key(e))); + // skipped at the end of the previous viewport: the same element moved (the title), not a new one, when it turns up + let mut moved: Vec<_> = before[before.len() - j..].iter().map(|e| key(e)).collect(); + let rest = page[k + n..].iter().copied().filter(|e| match moved.iter().position(|m| *m == key(e)) { + Some(i) => { + moved.swap_remove(i); + false + } + None => true, + }); + lead.chain(rest).collect() +} + +/// An iPad split view scrolls one column; the other keeps its rows where they were, interleaved with the scrolled +/// column's in travel order, so the two viewports share no suffix and prefix and everything read as new (Settings, +/// iPad mini 5 in landscape: the 150-row limit after two scrolls). Leaves out of both the elements that kept their +/// place outside every column that moved: where elements seen in both viewports are at another place now +fn without_still_column<'b, 'a>(before: &[&'b Element], page: &[&'a Element]) -> (Vec<&'b Element>, Vec<&'a Element>) { + fn span(e: &Element) -> (f64, f64) { + (e.visible.x, e.visible.x + e.visible.w) + } + fn stayed(e: &Element, other: &[&Element]) -> bool { + other.iter().any(|o| key(o) == key(e) && o.center == e.center) + } + let moved: Vec<(f64, f64)> = page + .iter() + .filter(|e| before.iter().any(|b| key(b) == key(e)) && !stayed(e, before)) + .map(|e| span(e)) + .collect(); + if moved.is_empty() { + return (before.to_vec(), page.to_vec()); + } + let still = |e: &Element, other: &[&Element]| { + let (left, right) = span(e); + stayed(e, other) && !moved.iter().any(|&(l, r)| left < r && l < right) + }; + ( + before.iter().copied().filter(|e| !still(e, page)).collect(), + page.iter().copied().filter(|e| !still(e, before)).collect(), + ) } #[cfg(test)] @@ -153,6 +276,151 @@ mod tests { assert!(new_rows(&visible_page(&a, true), &visible_page(&a, true)).is_empty()); } + /// Elements as `(type, label, x, y, width)`, 30 high, on a screen of `size` + fn screen(size: (f64, f64), items: &[(&str, &str, i64, i64, i64)]) -> Tree { + let mut xml = String::from(""); + for (kind, label, x, y, w) in items { + xml += &format!( + r#""# + ); + } + xml += ""; + elements::parse_tree(&xml, ScreenSize { width: size.0, height: size.1 }) + } + + fn labels<'a>(rows: &[&'a Element]) -> Vec<&'a str> { + rows.iter().map(|e| e.label.as_str()).collect() + } + + /// Settings' large title collapses into the navigation bar as the list moves (iPhone 15 Pro Max, iOS 27.2.1): the + /// next viewport starts with the title somewhere else, then the rows the previous one ended with. Those were + /// collected again (个人热点, 电池, VPN, 通用 and 无障碍 twice); scrolling back up, the title opens out again + #[test] + fn a_title_collapsing_into_the_navigation_bar_does_not_repeat_the_overlap() { + let phone = (430.0, 932.0); + let row = |label, y| ("Button", label, 10, y, 410); + let top = screen( + phone, + &[ + ("StaticText", "设置", 20, 100, 129), + row("A", 200), + row("B", 260), + row("C", 320), + row("D", 380), + row("E", 440), + row("F", 500), + ("SearchField", "搜索", 10, 850, 410), + ], + ); + let next = screen( + phone, + &[ + ("StaticText", "设置", 150, 50, 129), + row("D", 140), + row("E", 200), + row("F", 260), + row("G", 320), + row("H", 380), + ("SearchField", "搜索", 10, 850, 410), + ], + ); + assert_eq!(labels(&new_rows(&visible_page(&top, true), &visible_page(&next, true))), ["G", "H"]); + assert_eq!(labels(&new_rows(&visible_page(&next, false), &visible_page(&top, false))), ["C", "B", "A"]); + } + + /// An iPad split view scrolls the column swiped in; the sidebar's rows stay put, interleaved with the moving ones + /// in travel order (Settings, iPad mini 5 in landscape: the 150-row limit after two scrolls, everything twice) + #[test] + fn a_column_that_did_not_scroll_is_not_collected_again() { + let ipad = (1024.0, 768.0); + let side = + |i: i64| ("Button", ["S1", "S2", "S3", "S4", "S5", "S6", "S7", "S8"][i as usize], 20, 100 + 50 * i, 290); + let pane = |n: i64, y| { + ( + "Button", + ["R0", "R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8", "R9", "R10", "R11"][n as usize], + 340, + y, + 660, + ) + }; + let mut first: Vec<_> = (0..8).map(side).collect(); + first.extend((1..=8).map(|n| pane(n, 50 + 50 * n))); + let mut second: Vec<_> = (0..8).map(side).collect(); + second.extend((4..=11).map(|n| pane(n, 50 * (n - 2)))); + let (first, second) = (screen(ipad, &first), screen(ipad, &second)); + assert_eq!(labels(&new_rows(&visible_page(&first, true), &visible_page(&second, true))), ["R9", "R10", "R11"]); + // the sidebar scrolled instead (`x` inside it), the pane stayed + let mut first: Vec<_> = (1..=8).map(|n| pane(n, 50 + 50 * n)).collect(); + first.extend((0..5).map(|i| ("Button", ["S1", "S2", "S3", "S4", "S5"][i as usize], 20, 100 + 50 * i, 290))); + let mut second: Vec<_> = (1..=8).map(|n| pane(n, 50 + 50 * n)).collect(); + second.extend((0..5).map(|i| ("Button", ["S3", "S4", "S5", "S6", "S7"][i as usize], 20, 100 + 50 * i, 290))); + let (first, second) = (screen(ipad, &first), screen(ipad, &second)); + assert_eq!(labels(&new_rows(&visible_page(&first, true), &visible_page(&second, true))), ["S6", "S7"]); + } + + /// An iPad split view as WDA reads it (Settings, iPad mini 5, iPadOS 26.7.3, landscape), in its document order: the + /// sidebar's navigation bar with the search field, the sidebar's rows in a CollectionView, the detail pane's + /// navigation bar, its rows in a Table, each a Cell with its label and a chevron. The rows are `(label, top)` + fn split_view(side: &[(String, f64)], pane: &[(String, f64)]) -> Tree { + fn el(kind: &str, label: &str, (x, y, w, h): (f64, f64, f64, f64), inner: &str) -> String { + format!( + r#"{inner}"# + ) + } + let side: String = side.iter().map(|(label, y)| el("Button", label, (26.0, *y, 288.0, 50.0), "")).collect(); + let pane: String = pane + .iter() + .map(|(label, y)| { + let inner = el("Button", label, (362.0, y + 12.0, 97.0, 28.0), "") + + &el("Button", "chevron", (979.0, y + 19.0, 9.0, 13.0), ""); + el("Cell", label, (346.0, *y, 662.0, 51.0), &inner) + }) + .collect(); + let search = el("SearchField", "搜索", (26.0, 87.0, 288.0, 38.0), ""); + let screen = [ + el("NavigationBar", "设置", (10.0, 32.0, 320.0, 108.0), &search), + el("CollectionView", "边栏", (10.0, 32.0, 320.0, 726.0), &side), + el("NavigationBar", "通用", (0.0, 32.0, 1024.0, 54.0), ""), + el("Table", "", (346.0, 0.0, 678.0, 768.0), &pane), + ] + .concat(); + let xml = el("Application", "设置", (0.0, 0.0, 1024.0, 768.0), &screen); + elements::parse_tree(&xml, ScreenSize { width: 1024.0, height: 768.0 }) + } + + /// Rows `{prefix}{n}` for `n` in `ns`, the first at `top`, `pitch` apart + fn numbered(prefix: &str, ns: std::ops::RangeInclusive, top: f64, pitch: f64) -> Vec<(String, f64)> { + let first = *ns.start(); + ns.map(|n| (format!("{prefix}{n}"), top + pitch * (n - first) as f64)).collect() + } + + fn described(rows: &[&Element]) -> Vec { + rows.iter().map(|e| format!("{} {}", e.kind, e.label)).collect() + } + + /// Through WDA an iPad split view has scroll areas (Settings, iPad mini 5, iPadOS 26.7.3, landscape). A detail + /// row's Cell, label and chevron have middles a point apart, in an order that turned round as the list moved; the + /// sidebar's navigation bar and search field stay put while its rows pass under them, between the rows in travel + /// order. No two viewports overlapped: every swipe collected all it saw again (the 150-row limit after three) + #[test] + fn rows_are_matched_in_the_scroll_area_one_row_at_a_time() { + // swiped in the middle: the detail pane moves 251 points, the sidebar stays + let side = numbered("S", 1..=12, 140.0, 50.0); + let first = split_view(&side, &numbered("R", 1..=9, 297.0, 51.0)); + let second = split_view(&side, &numbered("R", 1..=14, 46.0, 51.0)); + let want: Vec<_> = + (10..=14).flat_map(|n| [format!("Button R{n}"), format!("Cell R{n}"), "Button chevron".into()]).collect(); + assert_eq!(described(&new_rows(&visible_page(&first, true), &visible_page(&second, true))), want); + assert!(new_rows(&visible_page(&second, false), &visible_page(&first, false)).is_empty()); + // swiped in the sidebar (`x` inside it): its rows move 253 points, two of them above its search field + let pane = numbered("R", 1..=9, 297.0, 51.0); + let first = split_view(&numbered("S", 1..=12, 140.0, 50.0), &pane); + let second = split_view(&numbered("S", 1..=17, -113.0, 50.0), &pane); + let want: Vec<_> = (13..=17).map(|n| format!("Button S{n}")).collect(); + assert_eq!(described(&new_rows(&visible_page(&first, true), &visible_page(&second, true))), want); + } + #[test] fn identical_rows_that_scroll_into_the_same_position_are_kept() { let a = tree(&[("A", 100), ("Repeat", 200), ("B", 300)]); diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs index 4b4c91c3..bd1b5492 100644 --- a/crates/ictl-mcp/src/lib.rs +++ b/crates/ictl-mcp/src/lib.rs @@ -333,7 +333,8 @@ WDA 不可用时会说明哪些功能受影响(读元素、按名字点击、启 "until": {"type": "string", "description": ictl_l10n::tr!("可见元素的文字、标识或值包含这段文字时停止,不区分大小写", "stop at a visible label, name or value containing this text, case-insensitive")}, "filter": {"type": "string", "description": ictl_l10n::tr!("只收集类型或文字包含它的行。与 until 独立", "collect rows whose type or text contains this string, independent of until")}, "limit": {"type": "integer", "minimum": 1, "maximum": protocol::MAX_SCROLL_ROWS, "default": protocol::MAX_SCROLL_ROWS, "description": ictl_l10n::tr!("最多收集几行", "stop after collecting this many rows")}, - "max_scrolls": {"type": "integer", "minimum": 1, "maximum": protocol::MAX_SEARCH_SCROLLS, "default": 8, "description": ictl_l10n::tr!("最多滚动几次", "maximum number of scrolls")} + "max_scrolls": {"type": "integer", "minimum": 1, "maximum": protocol::MAX_SEARCH_SCROLLS, "default": 8, "description": ictl_l10n::tr!("最多滚动几次", "maximum number of scrolls")}, + "x": {"type": "number", "minimum": 0, "description": ictl_l10n::tr!("在哪个横坐标上下滑(点),默认屏幕正中。iPad 分栏界面(设置、邮件)只滚动手指所在的那一栏:要滚左栏,给左栏里的横坐标", "where to swipe across, in points from the left; the middle of the screen by default. An iPad split view (Settings, Mail) scrolls only the column swiped in: for the sidebar, an x inside it")} }), &[]), acting(ictl_l10n::tr!("滚动收集文字", "Scroll and collect text"), false, false), ), @@ -718,12 +719,17 @@ pub fn to_request(name: &str, args: &Map) -> Result Request::Tap { x: a.f("x")?, y: a.f("y")?, count: a.count("count")? }, @@ -1823,8 +1829,12 @@ mod tests { filter: "Cell".into(), until: "General".into(), limit: 3, + x: None, }) ); + // an iPad split view's sidebar + let Request::ScrollCollect(scan) = req(json!({"x": 160})).unwrap() else { panic!() }; + assert_eq!(scan.x, Some(160.0)); assert!(r.is_device_action()); assert!(req(json!({})).is_ok()); for bad in [ @@ -1834,6 +1844,8 @@ mod tests { json!({"limit":0}), json!({"limit":151}), json!({"limit":2.5}), + json!({"x":-1}), + json!({"x":"sidebar"}), json!({"max_scroll":2}), ] { assert!(req(bad.clone()).is_err(), "{bad}"); diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs index 8997da0f..c2f8ae2a 100644 --- a/crates/ictl-protocol/src/lib.rs +++ b/crates/ictl-protocol/src/lib.rs @@ -55,7 +55,7 @@ pub const MAX_SEARCH_SCROLLS: u32 = 15; pub const MAX_SCROLL_ROWS: usize = 150; /// Bounds and matching rules for a standalone list scan. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ScrollCollect { pub down: bool, @@ -63,6 +63,10 @@ pub struct ScrollCollect { pub filter: String, pub until: String, pub limit: usize, + /// Where to swipe across, in points from the left; the middle of the screen if not given. An iPad split view + /// scrolls the column swiped in: the sidebar needs an x inside it + #[serde(default, skip_serializing_if = "Option::is_none")] + pub x: Option, } fn is_zero(v: &f64) -> bool { diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rs index 5e8b78c1..7aefa9f8 100644 --- a/crates/ictl-wda/src/client.rs +++ b/crates/ictl-wda/src/client.rs @@ -999,18 +999,23 @@ impl WdaClient { /// The element with keyboard focus (`GET /element/active`); None when no element has it pub async fn focused_field(&mut self) -> Result> { - let v = match self.in_session("GET", "/element/active", None, DEFAULT_TIMEOUT).await { - Ok(v) => v, - Err(WdaError::Remote { kind, .. }) if kind.contains("no such element") => return Ok(None), - Err(e) => return Err(e), - }; - let Some(id) = element_id(&v) else { return Ok(None) }; + let Some(id) = self.active_element().await? else { return Ok(None) }; let kind = self.attribute(&id, "type").await?; let kind = kind.strip_prefix("XCUIElementType").unwrap_or(&kind).to_owned(); let placeholder = self.attribute(&id, "placeholderValue").await?; Ok(Some(FocusedField { id, kind, placeholder })) } + /// The id of the element with keyboard focus (`GET /element/active`), one request; nothing has focus: `None`. + /// Rereading a field already known ([`Self::focused_field`] takes three) only needs this and its value + pub async fn active_element(&mut self) -> Result> { + match self.in_session("GET", "/element/active", None, DEFAULT_TIMEOUT).await { + Ok(v) => Ok(element_id(&v)), + Err(WdaError::Remote { kind, .. }) if kind.contains("no such element") => Ok(None), + Err(e) => Err(e), + } + } + /// An attribute of an element as text; a missing one (`null`) reads as empty pub async fn attribute(&mut self, id: &str, name: &str) -> Result { let v = self.in_session("GET", &format!("/element/{id}/attribute/{name}"), None, DEFAULT_TIMEOUT).await?; diff --git a/crates/ictl-wda/src/elements.rs b/crates/ictl-wda/src/elements.rs index b8de2d6b..635dc0f8 100644 --- a/crates/ictl-wda/src/elements.rs +++ b/crates/ictl-wda/src/elements.rs @@ -393,6 +393,12 @@ fn clip(s: &str, max: usize, keep: usize) -> String { } impl Element { + /// Inside a scroll area's content (a list's rows, a page): what a swipe moves. Bars, a scroll area itself and + /// what lies outside one don't move with it. A tree read natively has no scroll areas: nothing is + pub fn in_scroll(&self) -> bool { + self.layer == Layer::Scroll + } + /// `needle` is already lowercase so a page of elements can share it. pub fn matches_filter(&self, needle: &str) -> bool { self.contains_text(needle) || self.kind.to_lowercase().contains(needle) diff --git a/docs/decisions.md b/docs/decisions.md index 255adb96..3ac6d42b 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -61,7 +61,7 @@ ## D10:与 toolkit 工具接口一致 -- **决定**:现在共 17 个 MCP 工具,其中来自 toolkit 的 13 个,工具名、参数、返回文本格式保持与 toolkit 一致。 +- **决定**:现在共 18 个 MCP 工具,其中来自 toolkit 的 13 个,工具名、参数、返回文本格式保持与 toolkit 一致。 - **理由**:切换时 agent 侧零改动;toolkit 的回归脚本可直接用于验收。 - **补充(2026-11-01)**:只做向后兼容的扩展,不改已有工具的名字、参数和默认返回。为减少 agent 往返(每次往返是一轮模型推理, 真机观察约 8~13 秒,远大于工具本身的 0.3~1.5 秒),操作类工具加可选参数 `then`(`elements` / `screenshot`:等界面稳定后 diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index 804797ee..57c1c0e2 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -168,3 +168,6 @@ | 162 | 经 WDA 控制(iOS 26 及以前,或 `ICTL_IOS_BACKEND=wda`)时 `replace: true` 直接拒绝,调用方只能在光标处输入,得到 `wifi 蓝牙` | 经 WDA 取聚焦元素(`/element/active`),只接受普通可读输入框(密码框拒绝),WDA `clear` 后按键输入,读回同一个元素的全文一致才按回车,结尾丢字补一次;空输入框读出占位文字算空;清空后再失败时明说原文已删掉;WDA 在动手前就连不上时,原生控制可用则改走原生 | 单测 `replaces_the_focused_field_then_presses_return`、`a_mismatch_is_refused_without_return`、`focused_field_reads_its_type_and_placeholder` + 真机脚本 `scenarios.py editing`(WDA 设备) | | 163 | Viewer 已收到输入请求,返回结果前连接中断,客户端可能一直等待或重复输入 | 客户端结束该调用,报告投递状态未知,提示先查看手机 | 单测 `interrupted_tool_reply_reports_unknown_instead_of_hanging_or_retrying` | | 164 | WDA 输入以换行结尾,单行框只显示正文,补字可能再按一次回车 | 核对同一输入框,不自动重发回车、制表符或无法确认的空白;数字框格式化后仍可补齐缺失的数字 | 单测 `a_single_line_field_never_receives_a_second_return_during_repair`、`input_repair_requires_a_stable_new_prefix` | +| 165 | 原生输入以换行结尾的文字(`北京\n`):单行输入框把粘贴进来的换行变成空格,读回是「北京 」,和要输入的对不上,报「输入框里没有这段文字」,agent 可能再输一遍(iPhone 15 Pro Max,iOS 27.2.1,Spotlight) | 只差空白时按「文字已到、空白核对不了」处理(readback 为 `unverified`),不报错;中间的换行(`北京\n上海` 读回「北京 上海」)也一样 | 单测 `a_paste_that_replaced_the_same_text_is_told_apart_from_one_that_missed` + 真机(Spotlight 输入 `北京\n`,`readback.field` 不是 `failed`) | +| 166 | WDA 输入后核对:替换选中的文字(搜索框保留上次的搜索并选中)时读两遍、每遍 4 个请求再等 0.3 秒,往 Spotlight 输入比 main 慢约 1.8 秒(iPad mini 5,`run.py` 第 12 步) | 复读只问聚焦的元素和它的值(2 个请求);读一次就能下结论的(替换了选中的文字)不再读第二遍 | 单测 `typing_over_a_selection_is_judged_after_one_reread` + 真机(iPad 上 `run.py --repeat 5` 和 main 对比) | +| 167 | `iphone_scroll_collect` 重复收行:设置的大标题滑动时收起到导航栏,下一屏开头对不上上一屏结尾,几行被收两遍;iPad 分栏界面(WDA)只有一栏在滚,两栏的行交错;同一行的 Cell、文字和 chevron 中心差 1 点,滑动后先后顺序会变;左栏的导航栏和搜索框不动,行从它们底下滑过、夹在行中间。两屏完全对不上,整屏都算新行,滑两三次就到 150 行上限,左栏也滚不到 | 同一行的元素归成一行、行内从左到右;树里有滚动区域时只拿滚动区域里的内容比对,栏等其他元素上一屏没有同样的才算新行;没在滚的那一栏不参与比对,重叠的两头各可隔开几个元素(挪了位置的标题不算新行);`x` 指定在哪一栏滑 | 单测 `a_title_collapsing_into_the_navigation_bar_does_not_repeat_the_overlap`、`a_column_that_did_not_scroll_is_not_collected_again`、`rows_are_matched_in_the_scroll_area_one_row_at_a_time` + 真机(iPhone 设置整页收集无重复;iPad 设置默认在正中滑、`x` 在左栏滑都不重复,`x` 在左栏找到「隐私与安全」) | diff --git a/docs/tools.md b/docs/tools.md index 21e557d1..270d630b 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`, `count` (default 1, max 10) | For targets without text (icons, games, maps); falls back to HID when WDA is down. `count` taps the same point that many times in one gesture, about 0.1 s apart: 2 is a double tap (also turns on Caps Lock on the keyboard's Shift key); for hidden entries that need several taps in a short time, which separate calls or `iphone_batch` are too slow for | -| `iphone_scroll_collect` | `scroll` (down by default, or up), `filter`, `until`, `max_scrolls` (default 8, max 15), `limit` (default/max 150) | Collects rows in travel order and merges overlapping rows on adjacent screens. Identical accessibility rows can make the overlap ambiguous. Stops on a visible text match (`found`), an unchanged screen (`end`), `max_scrolls`, or the row `limit`. An interrupted scan returns its collected rows with `interrupted` if the caller is still connected. The matched element includes an uncovered `point` in the final viewport. The phone stays there without a tap. | +| `iphone_scroll_collect` | `scroll` (down by default, or up), `filter`, `until`, `max_scrolls` (default 8, max 15), `limit` (default/max 150), `x` | Collects rows in travel order and merges overlapping rows on adjacent screens. Identical accessibility rows can make the overlap ambiguous. Swipes in the middle of the screen, or at `x`: an iPad split view (Settings, Mail) scrolls only the column swiped in, so for the sidebar give an `x` inside it; the column that didn't move isn't collected again. Stops on a visible text match (`found`), an unchanged screen (`end`), `max_scrolls`, or the row `limit`. An interrupted scan returns its collected rows with `interrupted` if the caller is still connected. The matched element includes an uncovered `point` in the final viewport. The phone stays there without a tap. | | `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), `hold` (default 0) | Returns after the list has stopped scrolling (up to 2.5 s). Swipe up (`from_y` > `to_y`) to see content further down. `hold` holds the finger still at the start for that many seconds before moving, to drag things that have to be long-pressed first (home-screen icons, reorderable rows); about 0.6 works, under 0.5 usually doesn't pick anything up. `seconds` + `hold` is at most 10 | diff --git a/website/en/guide/tools.md b/website/en/guide/tools.md index 98573d15..5c5a467d 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; `count` taps the same point several times (double tap, entries that need quick repeated taps) | -| `iphone_scroll_collect` | Scroll through a list, collect matching rows and optionally stop when text appears. On pause or takeover, a connected caller receives the rows collected so far and the stop reason `interrupted`. The phone stays on the final viewport. | +| `iphone_scroll_collect` | Scroll through a list, collect matching rows and optionally stop when text appears. Swipes in the middle of the screen; on an iPad split view (Settings, Mail) `x` picks the column to scroll, such as the sidebar. On pause or takeover, a connected caller receives the rows collected so far and the stop reason `interrupted`. The phone stays on the final viewport. | | `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. `hold` holds still at the start for that many seconds before moving, to drag things that need a long press first (home-screen icons, reorderable rows); about 0.6 works | diff --git a/website/guide/tools.md b/website/guide/tools.md index e52b7ed1..1321e248 100644 --- a/website/guide/tools.md +++ b/website/guide/tools.md @@ -19,7 +19,7 @@ MCP 服务提供 18 个工具,开启[开发者工具](#开发者工具-显式 | 工具 | 作用 | |---|---| | `iphone_tap` | 按坐标点击;`count` 在同一点连点(双击、要短时间内连点几下的入口) | -| `iphone_scroll_collect` | 逐屏滚动收集列表行,支持按文字过滤和看到目标就停止。操作被暂停或接管时,仍连接的客户端会收到已读到的行和停止原因 `interrupted`。手机停留在最后一屏。 | +| `iphone_scroll_collect` | 逐屏滚动收集列表行,支持按文字过滤和看到目标就停止。默认在屏幕正中滑动;iPad 分栏界面(设置、邮件)用 `x` 指定滚动哪一栏,比如左栏。操作被暂停或接管时,仍连接的客户端会收到已读到的行和停止原因 `interrupted`。手机停留在最后一屏。 | | `iphone_tap_element` | 按文字点击;中心被悬浮栏、键盘挡住时改点露出来的部分,整个被挡住就不点。带 `scroll`(`down` / `up`)时,屏幕上没有就慢慢边滑边找,找到就点,滑到底或滑满 `max_scrolls`(默认 8)次为止 | | `iphone_long_press` | 长按;`seconds` 默认 1,最多 10 | | `iphone_swipe` | 滑动;列表停稳后才返回。`seconds` 默认 0.3,最多 10。`hold` 先在起点按住几秒再移动,用来拖动要先长按才拿得起来的东西(主屏幕图标、可排序的列表项),0.6 左右即可 |