Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools
Rust ai-agentautomationclaudeclaude-codedockeriosiphonelinuxmcpmcp-servermodel-context-protocolrustwebdriveragent
feat(mcp): 支持替换输入框全文、报告元素截断和等待元素消失 (#159)
MSK3ed8c6ab92fe
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6a6a5df..d1be8ce 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,16 @@ What changed in each release, one line per change. Versions follow [Semantic Ver## [Unreleased]+### Upgrade notes++- MCP tools now refuse an argument they don't take, and do nothing, instead of ignoring it. A misspelt argument, or one from a newer version, used to run the call with the default and report success: `iphone_wait_for` with `state: "disappeared"` answered that the text had appeared (#158). The error names the arguments the tool takes. This includes `then` on tools that don't list it, and on the steps of `iphone_batch` (the batch's own `then` applies).++### New++- With native control, `iphone_type_text` supports `replace: true` (empty text empties the field) and verifies the full field value before pressing Return; when it fails, the old text is left unselected.+- `iphone_list_elements` reports the match count and whether `limit` truncated the list in its structured result.+- `iphone_wait_for` can wait for text to disappear without mistaking an incomplete screen read for success.+## [0.2.9] - 2026-11-18### Fixesdiff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex 94b320b..31b9989 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -6,6 +6,16 @@## [Unreleased]+### 升级注意事项++- MCP 工具收到不认识的参数时改为报错、什么都不做,不再忽略。以前参数名拼错、或者用了新版本才有的参数,调用会按默认行为执行并报成功:`iphone_wait_for` 带 `state: "disappeared"` 时直接回答文字已出现(#158)。报错里会列出这个工具接受的参数。没有声明 `then` 的工具传 `then`、`iphone_batch` 的单个步骤里传 `then` 也会报错(批量的 `then` 写在批量本身)。++### 新功能++- 原生控制的 `iphone_type_text` 支持 `replace: true`(文字为空时清空输入框),核对替换后的输入框全文后才按回车;替换失败时会取消全选,原文保留。+- `iphone_list_elements` 的结构化结果会说明匹配数量和是否被 `limit` 截断。+- `iphone_wait_for` 支持等待文字消失;读屏不完整时不会误报成功。+## [0.2.9] - 2026-11-18### 修复diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rsindex ae25c72..bca2d8d 100644--- a/apps/iphone-control/src/viewer.rs+++ b/apps/iphone-control/src/viewer.rs@@ -2159,12 +2159,13 @@ mod tests {height: h,}).collect();- let els = element_list(Some(protocol::Data::Elements { elements }));+ let els =+ element_list(Some(protocol::Data::Elements { elements, matched_count: None, truncated: None })).elements;assert_eq!(els[0],json!({"type": "Button", "label": "今天", "x": 33.0, "y": 861.0, "width": 56.0, "height": 38.0}));- assert!(element_list(Some(protocol::Data::Alert { text: None })).is_empty());+ assert!(element_list(Some(protocol::Data::Alert { text: None })).elements.is_empty());let (frame, b) = alert_parts(&els);assert_eq!(frame, json!({"x": 80.0, "y": 306.0, "width": 270.0, "height": 320.0}));let labels: Vec<&str> = b.iter().filter_map(|v| v["label"].as_str()).collect();diff --git a/apps/iphone-control/src/viewer/api.rs b/apps/iphone-control/src/viewer/api.rsindex 8f00021..e0e7473 100644--- a/apps/iphone-control/src/viewer/api.rs+++ b/apps/iphone-control/src/viewer/api.rs@@ -178,7 +178,7 @@ pub(super) async fn apps(ctx: &Ctx, system: bool) -> Result<Value, String> {/// `keep_locked`: a read-only visitor, for whom a locked phone isn't unlockedpub(super) async fn elements(ctx: &Ctx, filter: &str, keep_locked: bool) -> Result<Value, String> {let req = Request::ListElements { filter: filter.to_owned(), limit: ELEMENT_LIMIT, max_age_ms: 0, keep_locked };- Ok(json!({"elements": element_list(data_of(&ctx.socket, req).await?)}))+ Ok(serde_json::to_value(element_list(data_of(&ctx.socket, req).await?)).expect("element list is JSON"))}/// A system alert on the phone (a permission prompt and the like): `{ alert: null }` or@@ -197,17 +197,24 @@ pub(super) async fn alert(ctx: &Ctx, keep_locked: bool) -> Result<Value, String>let req = Request::ListElements { filter: String::new(), limit: ELEMENT_LIMIT, max_age_ms: 0, keep_locked };// without its buttons the page still says there is an alertlet els = data_of(&ctx.socket, req).await.map(element_list).unwrap_or_default();- let (frame, buttons) = alert_parts(&els);+ let (frame, buttons) = alert_parts(&els.elements);Ok(json!({"alert": {"text": text, "frame": frame, "buttons": buttons}}))}/// The elements in a [`protocol::Data::Elements`] as the page's JSON: `{ type, label, x, y, width, height }`-pub(super) fn element_list(data: Option<protocol::Data>) -> Vec<Value> {+#[derive(Default, serde::Serialize)]+pub(super) struct ElementList {+ pub(super) elements: Vec<Value>,+ matched_count: Option<usize>,+ truncated: Option<bool>,+}++pub(super) fn element_list(data: Option<protocol::Data>) -> ElementList {match data {- Some(protocol::Data::Elements { elements }) => {- elements.iter().filter_map(|e| serde_json::to_value(e).ok()).collect()+ Some(protocol::Data::Elements { elements, matched_count, truncated }) => {+ ElementList { elements: elements.into_iter().map(|e| json!(e)).collect(), matched_count, truncated }}- _ => Vec::new(),+ _ => ElementList::default(),}}diff --git a/crates/ictl-ax/src/session.rs b/crates/ictl-ax/src/session.rsindex a359652..e682270 100644--- a/crates/ictl-ax/src/session.rs+++ b/crates/ictl-ax/src/session.rs@@ -397,7 +397,8 @@ impl<S: AsyncRead + AsyncWrite + Unpin + Send + 'static> Session<S> {let deadline = Instant::now() + budget;let mut attrs: HashMap<ObjectRef, Obj> = HashMap::new();let mut seen = HashSet::from([(root.pid, root.id)]);- let mut frontier: VecDeque<(ObjectRef, usize)> = VecDeque::from([(root, 0)]);+ let mut frontier = VecDeque::from([(root, 0, None)]);+ let mut missing = Vec::new();let mut complete = true;while !frontier.is_empty() {if attrs.len() >= limit || Instant::now() >= deadline {@@ -405,23 +406,50 @@ impl<S: AsyncRead + AsyncWrite + Unpin + Send + 'static> Session<S> {break;}let n = frontier.len().min(BATCH).min(limit - attrs.len());- let chunk: Vec<(ObjectRef, usize)> = frontier.drain(..n).collect();- let objects: Vec<ObjectRef> = chunk.iter().map(|(o, _)| *o).collect();+ let chunk: Vec<_> = frontier.drain(..n).collect();+ let objects: Vec<ObjectRef> = chunk.iter().map(|(o, _, _)| *o).collect();let got = self.attributes_of(&objects).await?;- for (o, depth) in chunk {- let Some(a) = got.get(&o) else { continue };+ for (o, depth, parent) in chunk {+ let Some(a) = got.get(&o) else {+ if let Some(parent) = parent {+ missing.push((parent, o));+ } else {+ complete = false;+ }+ continue;+ };let (e, kids) = tree::element(Some(o), a, None, depth);- if (depth > 0 && e.traits & prune != 0) || depth >= 40 {+ if depth > 0 && e.traits & prune != 0 {+ continue;+ }+ if depth >= 40 {+ complete &= kids.is_empty();continue;}for k in kids {if seen.insert((k.pid, k.id)) {- frontier.push_back((k, depth + 1));+ frontier.push_back((k, depth + 1, Some(o)));}}}attrs.extend(got);}+ // An attribute error alone cannot distinguish a removed child from an unreadable live one.+ // Re-read each affected parent once, only when the rest of the walk completed within budget.+ if complete && !missing.is_empty() {+ complete = false;+ if Instant::now() < deadline {+ let parents: HashSet<_> = missing.iter().map(|(parent, _)| *parent).collect();+ let parents: Vec<_> = parents.into_iter().collect();+ let fresh = self.attributes_of(&parents).await?;+ complete = missing.iter().all(|(parent, child)| {+ fresh.get(parent).is_some_and(|a| {+ let (_, kids) = tree::element(Some(*parent), a, None, 0);+ !kids.contains(child) && kids.iter().all(|k| seen.contains(&(k.pid, k.id)))+ })+ });+ }+ }Ok((tree::assemble(root, &attrs), complete))}@@ -433,15 +461,15 @@ impl<S: AsyncRead + AsyncWrite + Unpin + Send + 'static> Session<S> {limit: usize,budget: Duration,prune: u64,- ) -> Result<Vec<Element>> {- let (mut els, _) = self.walk(root, limit + 1, budget, prune).await?;+ ) -> Result<(Vec<Element>, bool)> {+ let (mut els, complete) = self.walk(root, limit + 1, budget, prune).await?;if !els.is_empty() {els.remove(0);}for e in &mut els {e.parent = e.parent.and_then(|p| p.checked_sub(1));}- Ok(els)+ Ok((els, complete))}/// Tells the phone this client no longer needs accessibility (it then closes the connection)diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex 959b6c9..a96be06 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -1216,7 +1216,7 @@ impl Daemon {.list_elements(g, &filter, limit, Duration::from_millis(max_age_ms), keep_locked).await.map(|(text, elements)| {- data = Some(crate::protocol::Data::Elements { elements });+ data = Some(elements);text}),Request::Tap { x, y, count } => self.tap(g, x, y, count, view).await,@@ -1238,6 +1238,7 @@ impl Daemon {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::PressButton { button } => self.press_button(g, &button, watched).await,Request::Touch { phase, x, y } => {return self@@ -1268,7 +1269,12 @@ impl Daemon {data = Some(crate::protocol::Data::Alert { text: alert });text}),- Request::WaitFor { text, timeout_ms } => self.wait_for(g, &text, Duration::from_millis(timeout_ms)).await,+ Request::WaitFor { text, timeout_ms } => {+ self.wait_for(g, &text, Duration::from_millis(timeout_ms), false).await+ }+ Request::WaitForDisappearance { text, timeout_ms } => {+ self.wait_for(g, &text, Duration::from_millis(timeout_ms), true).await+ }Request::Doctor => Ok(self.doctor(g).await),Request::UnlockReset => {let _ = std::fs::remove_file(self.cfg.unlock_disabled_flag());@@ -1357,6 +1363,7 @@ fn lane(req: &Request) -> Lane {| Request::LongPress { .. }| Request::Swipe { .. }| Request::TypeText { .. }+ | Request::ReplaceText { .. }| Request::PressButton { .. }| Request::Touch { .. }| Request::ListApps { .. }@@ -1366,6 +1373,7 @@ fn lane(req: &Request) -> Lane {| Request::Settle { .. }| Request::AlertCheck| Request::WaitFor { .. }+ | Request::WaitForDisappearance { .. }| Request::Doctor| Request::UnlockReset| Request::ListDevices@@ -1484,6 +1492,7 @@ 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::WebEval { expression, timeout_ms, .. }if expression.trim().is_empty() || *timeout_ms > MAX_WEB_EVAL_MS =>@@ -1497,7 +1506,9 @@ fn check_request(req: &Request) -> Result<(), String> {Request::Settle { max_ms } if *max_ms > MAX_WAIT_MS => {return Err(ictl_l10n::trf!("max_ms 不能超过 {MAX_WAIT_MS}", "max_ms can't exceed {MAX_WAIT_MS}"));}- Request::WaitFor { timeout_ms, .. } if *timeout_ms > MAX_WAIT_MS => {+ Request::WaitFor { timeout_ms, .. } | Request::WaitForDisappearance { timeout_ms, .. }+ if *timeout_ms > MAX_WAIT_MS =>+ {return Err(ictl_l10n::trf!("timeout 不能超过 {} 秒","timeout can't exceed {} seconds",@@ -1507,9 +1518,6 @@ fn check_request(req: &Request) -> Result<(), String> {Request::Touch { x, y, .. } if !x.is_finite() || !y.is_finite() => {return Err(ictl_l10n::tr!("x、y 要是有效的数", "x and y must be valid numbers").into());}- Request::WaitFor { text, .. } if text.is_empty() => {- return Err(ictl_l10n::tr!("text 不能为空", "text can't be empty").into());- }Request::AppLogs { since_secs, limit, .. } if *since_secs > 3600 || *limit == 0 || *limit > 1000 => {return Err(ictl_l10n::tr!("since 最多 3600 秒,limit 要在 1 到 1000 之间",diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rsindex 0ba22f4..c46123e 100644--- a/crates/ictl-daemon/src/tasks.rs+++ b/crates/ictl-daemon/src/tasks.rs@@ -173,7 +173,13 @@ fn ended_message() -> &'static str {/// Requests that show the agent the screen: after one, it may act again ([`TaskState::recheck`])pub(crate) fn observes(req: &Request) -> bool {- matches!(req, Request::Screenshot { .. } | Request::ListElements { .. } | Request::WaitFor { .. })+ matches!(+ req,+ Request::Screenshot { .. }+ | Request::ListElements { .. }+ | Request::WaitFor { .. }+ | Request::WaitForDisappearance { .. }+ )}/// The home screen, the lock screen and notifications: always in a task's scope (getting back from elsewhere)@@ -219,6 +225,7 @@ pub fn scope_check(req: &Request) -> Option<Check> {| Request::LongPress { .. }| Request::Swipe { .. }| Request::TypeText { .. }+ | Request::ReplaceText { .. }| Request::WebEval { .. }| Request::Touch { phase: TouchPhase::Down | TouchPhase::Move, .. } => Some(Check::Foreground),Request::InstallApp { path } => {@@ -240,6 +247,7 @@ pub fn scope_check(req: &Request) -> Option<Check> {| Request::Settle { .. }| Request::AlertCheck| Request::WaitFor { .. }+ | Request::WaitForDisappearance { .. }| Request::Daemon| Request::Doctor| Request::Resign { .. }diff --git a/crates/ictl-daemon/src/tools/native.rs b/crates/ictl-daemon/src/tools/native.rsindex 62d91bc..711fbff 100644--- a/crates/ictl-daemon/src/tools/native.rs+++ b/crates/ictl-daemon/src/tools/native.rs@@ -5,7 +5,7 @@//!//! The tools keep their WDA code; where WDA isn't there they come here when [`Daemon::native`] says so.-use ictl_device::{ClipboardRestore, DeviceInfo};+use ictl_device::DeviceInfo;use ictl_unlock::Screen;use ictl_wda::client::LockCheck;use ictl_wda::elements::View;@@ -25,6 +25,10 @@ const PASTE_WAIT: Duration = Duration::from_secs(5);/// After the paste prompt was answered, a field that already showed the text and doesn't change for this long took/// the paste as it was: the pasted text replaced the same text, selected (Spotlight keeps the last search selected)./// A paste shows in the field within about half a second of the answer+/// How long a field emptied by [`Daemon::replace_text`] may take to read as empty+const CLEAR_WAIT: Duration = Duration::from_millis(1500);+/// How often a wait for text to disappear asks lockdown whether the phone is locked (a new connection each time)+const LOCK_ASK_EVERY: Duration = Duration::from_secs(1);const PASTE_SAME_SETTLE: Duration = Duration::from_millis(1500);/// How long an app may take to come to the frontconst LAUNCH_WAIT: Duration = Duration::from_secs(8);@@ -44,6 +48,11 @@ fn native_for(backend: IosBackend, info: Option<&DeviceInfo>) -> bool {backend.drives_natively(info)}+enum PasteTarget<'a> {+ Append(Option<&'a [String]>),+ Replace(ictl_ax::ObjectRef),+}+/// What a paste did, as far as the fields show#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Pasted {@@ -229,8 +238,8 @@ impl Daemon {/// The screen's elements through remoteAXService (see [`Self::ax_read`])pub(crate) async fn ax_tree(&self, g: &mut Inner, wait: Duration) -> crate::error::Result<Tree> {- let (xml, size, _) = self.ax_read(g, wait).await?;- Ok(elements::parse_tree(&xml, size))+ let screen = self.ax_snapshot(g, wait, true).await?;+ self.snapshot_tree(g, &screen).await}/// The frontmost app's bundle ID (one request, no walk)@@ -389,13 +398,15 @@ impl Daemon {async fn snapshot_tree(&self, g: &mut Inner, s: &ictl_device::ax::AxScreen) -> crate::error::Result<Tree> {let (xml, size, _) = self.ax_render(g, s).await?;- Ok(elements::parse_tree(&xml, size))+ let mut tree = elements::parse_tree(&xml, size);+ tree.incomplete |= !s.app_complete || !s.overlays_complete;+ Ok(tree)}/// `s`, a read of the app alone, with what SpringBoard shows over it, as a treeasync fn with_overlays(&self, g: &mut Inner, mut s: ictl_device::ax::AxScreen) -> crate::error::Result<Tree> {if let Some(t) = g.tunnel.as_mut() {- s.overlays = t.ax_overlays(s.app_pid).await;+ (s.overlays, s.overlays_complete) = t.ax_overlays(s.app_pid).await;}self.snapshot_tree(g, &s).await}@@ -442,28 +453,50 @@ impl Daemon {g: &mut Inner,text: &str,timeout: Duration,+ disappeared: bool,) -> crate::error::Result<String> {+ use super::observe::Waited;let t0 = Instant::now();+ // lockdown's last answer, and when (None: it failed)+ let mut lock: Option<(Instant, Option<bool>)> = None;loop {- let tree = self.ax_tree(g, AX_WAIT).await?;- // 不算输入框里的字:刚输入的搜索词不能算「结果出来了」- if let Some(e) = elements::find_shown(&tree.elements, text).first() {- return Ok(ictl_l10n::trf!(- "已出现 {}({:.1} 秒)",- "Appeared: {} ({:.1} s)",- e.describe(),- t0.elapsed().as_secs_f64()- ));- }+ let screen = self.ax_snapshot(g, AX_WAIT, true).await?;+ let (xml, size, _) = self.ax_render(g, &screen).await?;+ let mut tree = elements::parse_tree(&xml, size);+ tree.incomplete |= !screen.app_complete || !screen.overlays_complete;+ let why = match super::observe::wait_match(&tree, text, disappeared, t0.elapsed()) {+ Some(result) if !disappeared => return Ok(result),+ Some(result) => {+ // the read first (costs nothing more), then lockdown: it says locked before the read shows the+ // lock screen, but only on a phone with a passcode, so it can't be the only check. Asked at most+ // every LOCK_ASK_EVERY (a new connection each time); a failure leaves it unknown, not the wait+ let cover = native_cover(&xml, &screen, &tree);+ if cover == Cover::Locked {+ return Err(super::observe::wait_locked());+ }+ let locked = match lock {+ Some((at, answer)) if at.elapsed() < LOCK_ASK_EVERY => answer,+ _ => {+ let answer = self.native_locked(g).await.inspect_err(|e| {+ tracing::debug!("lock state while waiting for {text:?} to disappear: {e}")+ });+ let answer = answer.ok();+ lock = Some((Instant::now(), answer));+ answer+ }+ };+ match (cover, locked) {+ (_, Some(true)) => return Err(super::observe::wait_locked()),+ (Cover::None, Some(false)) => return Ok(result),+ _ => Waited::Covered,+ }+ }+ None => Waited::after(&tree, text, disappeared),+ };if t0.elapsed() >= timeout {- return Err(ictl_l10n::trf!(- "{:.0} 秒内没出现包含 \"{text}\" 的元素,截图看看屏幕",- "No element containing \"{text}\" appeared within {:.0} s; take a screenshot to look at the screen",- timeout.as_secs_f64()- )- .into());+ return Err(super::observe::wait_timeout(text, timeout, why));}- tokio::time::sleep(Duration::from_millis(300)).await;+ tokio::time::sleep(Duration::from_millis(300).min(timeout.saturating_sub(t0.elapsed()))).await;}}@@ -591,7 +624,7 @@ impl Daemon {let old = elements::field_values(&before.elements);let mut note = String::new();if !text.is_empty() {- let (typed, prompt) = self.native_paste(g, text, old.as_deref()).await?;+ let (typed, prompt) = self.native_paste(g, text, PasteTarget::Append(old.as_deref())).await?;if prompt {note += ictl_l10n::tr!("(已替你点了「允许粘贴」)", " (“Allow Paste” was tapped for you)");}@@ -633,14 +666,102 @@ impl Daemon {))}- /// Pastes `text` and waits for it to show in a field (`old`: the fields' values before; None: a password field- /// on screen). Returns what the fields show and whether the paste prompt was answered. The pasteboard is put- /// back before returning+ /// Replace a single focused, readable field. Verify the full value before sending Return.+ pub(crate) async fn replace_text(&self, g: &mut Inner, text: &str, submit: bool) -> crate::error::Result<String> {+ if !self.native(g) || self.wda(g).is_some() {+ return Err(ictl_l10n::tr!("替换全文需要原生控制", "Replacing text requires native control").into());+ }+ self.ensure_unlocked(g).await?;+ let before = self.ax_snapshot(g, AX_WAIT, false).await?;+ if !keyboard_up(&self.snapshot_tree(g, &before).await?) {+ return Err(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(|| {+ ictl_l10n::tr!(+ "无法确认当前聚焦的是可读的普通输入框,没有替换文字",+ "Couldn't identify a readable focused text field; no text was replaced"+ )+ })?;+ 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?+ } else {+ self.native_paste(g, text, PasteTarget::Replace(target)).await?.0+ };+ if seen != Pasted::Typed {+ return Err(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!(+ "{err}(无法收起原输入框的选区,请在重试前查看屏幕:{cause})",+ "{err} (couldn't collapse the original selection; inspect the screen before retrying: {cause})"+ )+ .into());+ }+ return Err(err);+ }+ }+ if submit {+ self.hid_do(g, |h| Box::pin(h.type_ascii("\n"))).await?;+ }+ let n = text.chars().count();+ Ok(match (n, submit) {+ (0, true) => ictl_l10n::tr!("已清空输入框,并按了回车", "Emptied the field and pressed Return").into(),+ (0, false) => ictl_l10n::tr!("已清空输入框", "Emptied the field").into(),+ (_, true) => ictl_l10n::trf!(+ "已替换为 {n} 个字符,并按了回车",+ "Replaced the field with {n} characters and pressed Return"+ ),+ (_, false) => ictl_l10n::trf!("已替换为 {n} 个字符", "Replaced the field with {n} characters"),+ })+ }++ /// After select all and Delete: `target` reads as empty within [`CLEAR_WAIT`]+ async fn native_field_emptied(&self, g: &mut Inner, target: ictl_ax::ObjectRef) -> crate::error::Result<Pasted> {+ let deadline = Instant::now() + CLEAR_WAIT;+ loop {+ let screen = self.ax_snapshot(g, AX_WAIT, false).await?;+ let seen = replacement_seen(&screen, target, "");+ if seen == Pasted::Typed || Instant::now() >= deadline {+ return Ok(seen);+ }+ tokio::time::sleep(Duration::from_millis(150)).await;+ }+ }++ async fn collapse_field_selection(&self, g: &mut Inner, target: ictl_ax::ObjectRef) -> crate::error::Result<()> {+ let screen = self.ax_snapshot(g, AX_WAIT, true).await?;+ if focused_text_field(&screen).and_then(|f| f.object) != Some(target)+ || self.snapshot_tree(g, &screen).await?.alert().is_some()+ {+ return Err(ictl_l10n::tr!("输入焦点已改变或被弹窗遮挡", "Focus changed or an alert is in front").into());+ }+ self.hid_do(g, |h| Box::pin(h.collapse_selection())).await+ }++ /// Answer the system paste prompt and verify the requested edit before restoring the clipboard.async fn native_paste(&self,g: &mut Inner,text: &str,- old: Option<&[String]>,+ target: PasteTarget<'_>,) -> crate::error::Result<(Pasted, bool)> {// a paste through the WDA-down path may still wait to be put backself.restore_pasteboard(g, false).await;@@ -655,49 +776,45 @@ impl Daemon {return Err(ictl_l10n::trf!("粘贴失败:{e}", "Paste failed: {e}").into());}};- let deadline = Instant::now() + PASTE_WAIT;- // when the paste prompt was last answered- let mut answered: Option<Instant> = None;- let wanted = text.trim();- let typed = loop {- // a whole read: the prompt brings SpringBoard to the front, but it may also come over the app (a read- // of the app alone missed it once in a regression run, and the paste never went in)- let tree = self.ax_tree(g, AX_WAIT).await?;- if let Some((x, y)) = paste_allow(&tree) {- self.native_tap(g, x, y).await?;- answered = Some(Instant::now());- tokio::time::sleep(Duration::from_millis(300)).await;- continue;- }- let seen = paste_seen(elements::field_values(&tree.elements).as_deref(), old, wanted);- match seen {- Pasted::Typed => 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- Pasted::Unchanged if Instant::now() >= deadline => break Pasted::Missing,- _ if Instant::now() >= deadline => break seen,- _ => {}- }- tokio::time::sleep(Duration::from_millis(250)).await;- };- let prompt = answered.is_some();- if let Some(p) = pending {- let restored = match g.tunnel.as_mut() {- Some(t) => Box::pin(t.restore_pasteboard(p)).await,- None => ClipboardRestore::Failed("no tunnel".into()),+ g.dev.pending_paste = pending.map(|p| (Instant::now(), p));+ let result = async {+ let deadline = Instant::now() + PASTE_WAIT;+ // when the paste prompt was last answered+ let mut answered: Option<Instant> = 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?;+ answered = Some(Instant::now());+ tokio::time::sleep(Duration::from_millis(300)).await;+ if Instant::now() >= deadline {+ break Pasted::Missing;+ }+ continue;+ }+ let seen = match target {+ PasteTarget::Append(old) => {+ paste_seen(elements::field_values(&tree.elements).as_deref(), old, text.trim())+ }+ PasteTarget::Replace(object) => replacement_seen(&screen, object, text),+ };+ match seen {+ Pasted::Typed => 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+ Pasted::Unchanged if Instant::now() >= deadline => break Pasted::Missing,+ _ if Instant::now() >= deadline => break seen,+ _ => {}+ }+ tokio::time::sleep(Duration::from_millis(250)).await;};- if let ClipboardRestore::Failed(e) = restored {- tracing::warn!(- "{}",- ictl_l10n::log_trf!(- "粘贴后还原剪贴板失败:{e}",- "Restoring the pasteboard after the paste failed: {e}"- )- );- }+ Ok((typed, answered.is_some()))}- Ok((typed, prompt))+ .await;+ self.restore_pasteboard(g, false).await;+ result}/// Launches `bundle_id` in front (with `url`, the link for it to open) and waits for it to be there@@ -787,6 +904,69 @@ impl Daemon {}}+/// What is over the screen in a native read, for a wait for text to disappear+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Cover {+ /// An app, or SpringBoard's home screen or Spotlight: what it shows is the screen+ None,+ /// The lock screen, known by its marks ([`elements::cover_sheet`])+ Locked,+ /// Notification center, control center, or the lock screen without the marks [`elements::cover_sheet`] knows it+ /// by, as it often reads natively: SpringBoard in front without app icons (6-7 elements: date, time,+ /// notifications, flashlight, camera; iPhone19,7, iOS 27.2.1), or another process in front with the lock+ /// screen's buttons ([`cover_mark`]). Lockdown says locked only on a phone with a passcode+ Other,+}++fn native_cover(xml: &str, screen: &ictl_device::ax::AxScreen, tree: &Tree) -> Cover {+ match elements::cover_sheet(xml) {+ elements::CoverSheet::Locked => Cover::Locked,+ elements::CoverSheet::NotificationCenter => Cover::Other,+ elements::CoverSheet::None if screen.springboard_front && !unlocked_springboard(tree) => Cover::Other,+ elements::CoverSheet::None if tree.elements.iter().any(cover_mark) => Cover::Other,+ elements::CoverSheet::None => Cover::None,+ }+}++/// An element only the lock screen and notification center show, whichever process is in front: the flashlight+/// and camera buttons at the bottom, and the sleep lock screen's own elements. During a sleep focus the lock screen+/// is another process (`SleepLockScreen`), not SpringBoard, with SpringBoard's elements over it (iPhone19,7, iOS+/// 27.2.1, 2026-11-19 00:04)+fn cover_mark(e: &elements::Element) -> bool {+ e.name == "flashlight-orb-button"+ || e.name.starts_with("system-orb-button-")+ || e.name.starts_with("UIA.SleepLockScreen")+}++/// SpringBoard in front, recognisably unlocked: the home screen (app icons) or Spotlight+fn unlocked_springboard(tree: &Tree) -> bool {+ tree.elements.iter().any(|e| e.kind == "Icon" || e.name == "SpotlightSearchField")+}++fn focused_text_field(screen: &ictl_device::ax::AxScreen) -> Option<&ictl_ax::Element> {+ let mut fields = screen.app.iter().filter(|e| {+ // Raw AX retains focus and exact text, including whitespace. The shared XML has been normalized for display.+ e.focused && matches!(ictl_ax::xml::kind(e), "TextField" | "TextView" | "SearchField" | "SecureTextField")+ });+ let f = fields.next()?;+ (fields.next().is_none() && f.enabled && f.visible && ictl_ax::xml::kind(f) != "SecureTextField").then_some(f)+}++/// What a field holds: an empty field reads its placeholder as its value natively (Spotlight's empty field reads+/// «搜索»), so that counts as empty. A field holding exactly its placeholder's words reads as empty too: rare, and+/// replacing it with other text still works (only emptying it is then taken as done already)+fn shown_text(f: &ictl_ax::Element) -> &str {+ if !f.placeholder.is_empty() && f.value == f.placeholder { "" } else { &f.value }+}++fn replacement_seen(screen: &ictl_device::ax::AxScreen, target: ictl_ax::ObjectRef, text: &str) -> Pasted {+ if focused_text_field(screen).is_some_and(|f| f.object == Some(target) && shown_text(f) == text) {+ Pasted::Typed+ } else {+ Pasted::Missing+ }+}+/// The phone as [`ictl_unlock`] sees it, driven nativelystruct NativeScreen<'a> {d: &'a Daemon,@@ -908,6 +1088,100 @@ impl Screen for NativeScreen<'_> {mod tests {use super::*;+ #[test]+ fn only_a_recognisable_unlocked_springboard_can_confirm_absence() {+ let screen = |springboard_front| ictl_device::ax::AxScreen {+ app: Vec::new(),+ app_complete: true,+ overlays: Vec::new(),+ overlays_complete: true,+ app_pid: 1,+ springboard_front,+ at: Instant::now(),+ };+ let cover = |markers: &str, springboard_front| {+ let xml = format!(r#"<App>{markers}</App>"#);+ let tree = elements::parse_tree(&xml, ScreenSize { width: 390.0, height: 844.0 });+ native_cover(&xml, &screen(springboard_front), &tree)+ };+ let icon = r#"<XCUIElementTypeIcon type="Icon" label="Clock" x="10" y="10" width="54" height="54"/>"#;+ // the home screen+ assert_eq!(cover(icon, true), Cover::None);+ // the lock screen by its marks, in front or not+ assert_eq!(cover(r#"<Other name="proud-lock"/>"#, true), Cover::Locked);+ assert_eq!(cover(r#"<Other name="proud-lock"/>"#, false), Cover::Locked);+ // notification center pulled over an app+ assert_eq!(cover(&format!(r#"{icon}<Other name="lockscreen-date-view"/>"#), false), Cover::Other);+ // the lock screen as read natively: no marks, SpringBoard in front, no icons+ let lock = r#"<XCUIElementTypeStaticText label="22:53" x="120" y="120" width="200" height="90"/>+<XCUIElementTypeButton label="手电筒" x="40" y="860" width="50" height="50"/>"#;+ assert_eq!(cover(lock, true), Cover::Other);+ // an app in front: its own screen, whatever is on it+ assert_eq!(cover(lock, false), Cover::None);+ // the sleep lock screen: another process in front, SpringBoard's flashlight and camera over it+ let sleep = r#"<XCUIElementTypeButton label="无闹钟" name="UIA.SleepLockScreen.Alarm.Button" x="100" y="300" width="200" height="50"/>+<XCUIElementTypeStaticText label="00:04" x="120" y="120" width="200" height="90"/>+<XCUIElementTypeButton label="手电筒" name="flashlight-orb-button" x="40" y="760" width="50" height="50"/>+<XCUIElementTypeButton label="相机" name="system-orb-button-com.apple.camera.deeplink.button" x="350" y="760" width="50" height="50"/>"#;+ assert_eq!(cover(sleep, false), Cover::Other);+ let orb = r#"<XCUIElementTypeButton label="手电筒" name="flashlight-orb-button" x="40" y="760" width="50" height="50"/>"#;+ assert_eq!(cover(orb, false), Cover::Other);+ }++ #[test]+ fn replacing_text_requires_one_readable_focused_field() {+ let mut screen = ictl_device::ax::AxScreen {+ app: vec![+ ictl_ax::Element {+ xc_type: 49,+ value: "old".into(),+ visible: true,+ enabled: true,+ ..Default::default()+ },+ ictl_ax::Element {+ xc_type: 49,+ value: " 蓝牙 ".into(),+ focused: true,+ visible: true,+ enabled: true,+ ..Default::default()+ },+ ],+ app_complete: true,+ overlays: Vec::new(),+ overlays_complete: true,+ app_pid: 1,+ springboard_front: false,+ at: Instant::now(),+ };+ assert_eq!(focused_text_field(&screen).map(|f| f.value.as_str()), Some(" 蓝牙 "));+ let target = ictl_ax::ObjectRef { pid: 1, id: 2, is_app: false };+ screen.app[1].object = Some(target);+ screen.app[1].value = "wifi".into();+ screen.app[0].value = "wi".into();+ screen.app_complete = false;+ assert_eq!(replacement_seen(&screen, target, "wi"), Pasted::Missing);+ screen.app[1].value = "wi".into();+ assert_eq!(replacement_seen(&screen, target, "wi"), Pasted::Typed);+ assert_eq!(replacement_seen(&screen, ictl_ax::ObjectRef { id: 3, ..target }, "wi"), Pasted::Missing);+ // emptied: the field reads its placeholder as its value+ screen.app[1].placeholder = "搜索".into();+ screen.app[1].value = "搜索".into();+ assert_eq!(replacement_seen(&screen, target, ""), Pasted::Typed);+ screen.app[1].value = "搜索结果".into();+ assert_eq!(replacement_seen(&screen, target, ""), Pasted::Missing);+ screen.app[1].value = "wi".into();+ screen.app[1].placeholder = String::new();+ screen.app[0].focused = true;+ assert_eq!(focused_text_field(&screen).map(|f| f.value.as_str()), None);+ screen.app[0].focused = false;+ screen.app[1].value = "••••".into();+ assert_eq!(focused_text_field(&screen).map(|f| f.value.as_str()), Some("••••"));+ screen.app[1].xc_type = 50; // SecureTextField+ assert_eq!(focused_text_field(&screen).map(|f| f.value.as_str()), None);+ }+/// The HID session isn't closed right after a touch (the phone takes the touch back): the rest of/// `TOUCH_LANDS` is waited out first, and nothing when no touch was sent or it was long enough ago#[test]diff --git a/crates/ictl-daemon/src/tools/observe.rs b/crates/ictl-daemon/src/tools/observe.rsindex 6956a77..f27c9ae 100644--- a/crates/ictl-daemon/src/tools/observe.rs+++ b/crates/ictl-daemon/src/tools/observe.rs@@ -31,7 +31,7 @@ impl Daemon {limit: usize,max_age: Duration,keep_locked: bool,- ) -> crate::error::Result<(String, Vec<ElementData>)> {+ ) -> crate::error::Result<(String, crate::protocol::Data)> {if keep_locked {// only looking (a read-only viewer): the passcode isn't typed for itlet native = self.native(g);@@ -54,8 +54,14 @@ impl Daemon {let shown: Vec<&elements::Element> =if filter.is_empty() { els.iter().collect() } else { elements::filter(&els, filter) };let lines: Vec<_> = shown.iter().take(limit).map(|e| e.describe()).collect();- let data = shown.iter().take(limit).map(|e| element_data(e)).collect();- let more = if shown.len() > limit {+ let matched_count = shown.len();+ let truncated = matched_count > limit;+ let data = crate::protocol::Data::Elements {+ elements: shown.iter().take(limit).map(|e| element_data(e)).collect(),+ matched_count: Some(matched_count),+ truncated: Some(truncated),+ };+ let more = if truncated {ictl_l10n::trf!("\n……另有 {} 个未列出,可用 filter 缩小范围","\n…{} more not listed, narrow it down with filter",@@ -238,32 +244,168 @@ impl Daemon {})}- /// 等包含 `text` 的元素出现- pub(crate) async fn wait_for(&self, g: &mut Inner, text: &str, timeout: Duration) -> crate::error::Result<String> {+ /// Wait for text to appear or to be absent from a successfully read screen.+ pub(crate) async fn wait_for(+ &self,+ g: &mut Inner,+ text: &str,+ timeout: Duration,+ disappeared: bool,+ ) -> crate::error::Result<String> {self.ensure_unlocked(g).await?;let t0 = Instant::now();if self.wda(g).is_none() && self.native(g) {- return Box::pin(self.native_wait_for(g, text, timeout)).await;+ return Box::pin(self.native_wait_for(g, text, timeout, disappeared)).await;}let w = self.require_wda(g)?;// 轮询时不等界面空闲:页面还在加载、播放动画时每次读树也只要约 0.2 秒w.begin_polling().await?;let r = async {loop {- let els = w.elements().await.map_err(|e| e.to_string())?;- // 不算输入框里的字:刚输入的搜索词不能算「结果出来了」- if let Some(e) = elements::find_shown(&els, text).first() {- return Ok(ictl_l10n::trf!("已出现 {}({:.1} 秒)", "Appeared: {} ({:.1} s)", e.describe(), t0.elapsed().as_secs_f64()));- }+ let tree = w.tree().await?;+ let why = match wait_match(&tree, text, disappeared, t0.elapsed()) {+ Some(result) if !disappeared => return Ok(result),+ // the lock screen lacks the text too: asked only when it would count as gone+ Some(result) => match w.check_lock(None, true).await {+ Ok(c) if c.locked => return Err(wait_locked()),+ Ok(c) if !c.uncertain => return Ok(result),+ Ok(_) => Waited::Covered,+ // not known whether locked: not gone yet, asked again on the next read+ Err(e) => {+ tracing::debug!("lock state while waiting for {text:?} to disappear: {e}");+ Waited::Covered+ }+ },+ None => Waited::after(&tree, text, disappeared),+ };if t0.elapsed() >= timeout {- return Err(ictl_l10n::trf!("{:.0} 秒内没出现包含 \"{text}\" 的元素,截图看看屏幕", "No element containing \"{text}\" appeared within {:.0} s; take a screenshot to look at the screen", timeout.as_secs_f64()));+ return Err(wait_timeout(text, timeout, why));}- tokio::time::sleep(Duration::from_millis(300)).await;+ tokio::time::sleep(Duration::from_millis(300).min(timeout.saturating_sub(t0.elapsed()))).await;}}.await;w.end_polling().await;- Ok(r?)+ r+ }+}++pub(super) fn wait_match(tree: &Tree, text: &str, disappeared: bool, elapsed: Duration) -> Option<String> {+ let matches = elements::find_shown(&tree.elements, text);+ let elapsed = elapsed.as_secs_f64();+ if disappeared {+ if matches.is_empty() && !tree.incomplete && !tree.elements.is_empty() {+ return Some(ictl_l10n::trf!(+ "已消失「{text}」({elapsed:.1} 秒)",+ "Disappeared: \"{text}\" ({elapsed:.1} s)"+ ));+ }+ return None;+ }+ matches+ .first()+ .map(|e| ictl_l10n::trf!("已出现 {}({elapsed:.1} 秒)", "Appeared: {} ({elapsed:.1} s)", e.describe()))+}++/// Why [`Daemon::wait_for`] isn't done after the last read, for its timeout to say+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum Waited {+ /// Waiting for text to appear: it hasn't+ NotAppeared,+ /// Waiting for it to disappear: it was read, still there+ Present,+ /// Not seen, but the read can't tell it is gone: nothing read, or cut short ([`wait_match`])+ Unread,+ /// Not seen, but something is over the screen (notification center, control center, a lock screen not known+ /// by its marks), or whether the phone is locked couldn't be found out+ Covered,+}++impl Waited {+ /// A read where the text didn't count as appeared, or as gone ([`wait_match`] gave nothing)+ pub(super) fn after(tree: &Tree, text: &str, disappeared: bool) -> Self {+ if !disappeared {+ Self::NotAppeared+ } else if elements::find_shown(&tree.elements, text).is_empty() {+ Self::Unread+ } else {+ Self::Present+ }+ }+}++pub(super) fn wait_timeout(text: &str, timeout: Duration, why: Waited) -> crate::error::Error {+ let seconds = timeout.as_secs_f64();+ match why {+ Waited::NotAppeared => {}+ Waited::Present => {+ return ictl_l10n::trf!(+ "{seconds:.1} 秒内「{text}」没消失,截图看看屏幕",+ "\"{text}\" did not disappear within {seconds:.1} s; take a screenshot"+ )+ .into();+ }+ Waited::Unread => {+ return ictl_l10n::trf!(+ "{seconds:.1} 秒内无法确认「{text}」已消失:界面没读到或没读全(元素太多、读得太慢),截图看看屏幕",+ "Couldn't confirm within {seconds:.1} s that \"{text}\" disappeared: the screen wasn't read, or not in full (too many elements, a slow read); take a screenshot"+ )+ .into();+ }+ Waited::Covered => {+ return ictl_l10n::trf!(+ "{seconds:.1} 秒内无法确认「{text}」已消失:屏幕被通知中心、控制中心或锁屏挡着,或查不到是否锁屏,截图看看屏幕",+ "Couldn't confirm within {seconds:.1} s that \"{text}\" disappeared: notification center, control center or the lock screen is over the screen, or the lock state couldn't be found out; take a screenshot"+ )+ .into();+ }+ }+ ictl_l10n::trf!(+ "{seconds:.0} 秒内没出现包含 \"{text}\" 的元素,截图看看屏幕",+ "No element containing \"{text}\" appeared within {seconds:.0} s; take a screenshot to look at the screen"+ )+ .into()+}++pub(super) fn wait_locked() -> crate::error::Error {+ ictl_l10n::tr!(+ "等待时手机锁屏了,无法确认文字已消失;解锁后再等",+ "The phone locked while waiting, so disappearance can't be confirmed; wait again once it is unlocked"+ )+ .into()+}++#[cfg(test)]+mod wait_tests {+ use super::*;++ #[test]+ fn disappearance_requires_a_readable_complete_screen_without_the_target() {+ let screen = ScreenSize { width: 390.0, height: 844.0 };+ let mut tree = elements::parse_tree(r#"<Button label="Clock" x="0" y="0" width="80" height="40"/>"#, screen);+ assert!(wait_match(&tree, "Clock", false, Duration::ZERO).is_some());+ assert!(wait_match(&tree, "Clock", true, Duration::ZERO).is_none());+ assert!(wait_match(&tree, "Timer", true, Duration::ZERO).is_some());+ tree.incomplete = true;+ assert!(wait_match(&tree, "Timer", true, Duration::ZERO).is_none());+ assert!(wait_match(&Tree::default(), "Timer", true, Duration::ZERO).is_none());+ }++ /// The timeout says why: still there, not read in full, or not appeared+ #[test]+ fn a_timeout_tells_present_from_unread() {+ let screen = ScreenSize { width: 390.0, height: 844.0 };+ let mut tree = elements::parse_tree(r#"<Button label="Clock" x="0" y="0" width="80" height="40"/>"#, screen);+ assert_eq!(Waited::after(&tree, "Clock", true), Waited::Present);+ assert_eq!(Waited::after(&tree, "Clock", false), Waited::NotAppeared);+ tree.incomplete = true;+ assert_eq!(Waited::after(&tree, "Timer", true), Waited::Unread);+ // read even though cut short: it is still there+ assert_eq!(Waited::after(&tree, "Clock", true), Waited::Present);+ assert_eq!(Waited::after(&Tree::default(), "Timer", true), Waited::Unread);+ let msg = |w| wait_timeout("Clock", Duration::from_secs(2), w).to_string();+ let all = [Waited::NotAppeared, Waited::Present, Waited::Unread, Waited::Covered].map(msg);+ assert!(all.iter().collect::<std::collections::HashSet<_>>().len() == 4, "{all:?}");}}diff --git a/crates/ictl-device/src/ax.rs b/crates/ictl-device/src/ax.rsindex 56fef5a..b3ed87c 100644--- a/crates/ictl-device/src/ax.rs+++ b/crates/ictl-device/src/ax.rs@@ -41,8 +41,11 @@ pub fn is_ax_daemon(exe: &str) -> bool {pub struct AxScreen {/// The frontmost application's tree, its element firstpub app: Vec<Element>,+ /// Whether the walk reached the end rather than a node or time limit.+ pub app_complete: bool,/// What SpringBoard shows over the app (alerts, banners, its status bar); empty when SpringBoard is the apppub overlays: Vec<Element>,+ pub overlays_complete: bool,pub app_pid: i64,/// SpringBoard is the app in front (the home screen, the lock screen, or a question it asks over an app)pub springboard_front: bool,@@ -120,10 +123,12 @@ impl Tunnel {tracing::debug!("remoteAXService: app {} reads no elements on a new session either", app.pid);return Err(nothing_read());}- let overlays = if overlays { self.ax_overlays(app.pid).await } else { Vec::new() };+ let (overlays, overlays_complete) = if overlays { self.ax_overlays(app.pid).await } else { (Vec::new(), true) };Ok(AxScreen {app: elements,+ app_complete: complete,overlays,+ overlays_complete,app_pid: app.pid,springboard_front: sb == Some(app.pid),at: Instant::now(),@@ -132,8 +137,11 @@ impl Tunnel {/// What SpringBoard shows over the app of process `app_pid` (alerts, banners, its status bar); empty when/// SpringBoard is that app, or can't be read- pub async fn ax_overlays(&mut self, app_pid: i64) -> Vec<Element> {- let Some(sb) = self.springboard_pid().await.filter(|sb| *sb != app_pid) else { return Vec::new() };+ pub async fn ax_overlays(&mut self, app_pid: i64) -> (Vec<Element>, bool) {+ let Some(sb) = self.springboard_pid().await else { return (Vec::new(), false) };+ if sb == app_pid {+ return (Vec::new(), true);+ }let r = async {let root = match self.springboard_app {Some(o) => o,@@ -152,7 +160,7 @@ impl Tunnel {r.unwrap_or_else(|e| {tracing::debug!("SpringBoard's elements: {e}");self.springboard_app = None;- Vec::new()+ (Vec::new(), false)})}diff --git a/crates/ictl-device/src/hid.rs b/crates/ictl-device/src/hid.rsindex 1593b69..7a15afc 100644--- a/crates/ictl-device/src/hid.rs+++ b/crates/ictl-device/src/hid.rs@@ -106,6 +106,7 @@ const KEY_LEFT_SHIFT: u64 = 0xE1;/// 左 Command(HID usage Left GUI)const KEY_LEFT_GUI: u64 = 0xE3;const KEY_V: u64 = 0x19;+const KEY_A: u64 = 0x04;pub struct HidSession {/// 设备竖放时的尺寸:HID 触摸坐标按竖放归一化@@ -267,14 +268,33 @@ impl HidSession {/// 按 Cmd-V(硬件键盘的粘贴):按住 Cmd,按一下 V,松开 Cmd。手机不确认收到,粘没粘上只能看屏幕/// (iPhone16,2 / iOS 27.2.1 实测会触发粘贴,见 [`crate::Tunnel::paste_text`])pub async fn paste_shortcut(&mut self) -> Result<()> {- limit(ictl_l10n::tr!("HID 粘贴", "HID paste"), Duration::from_secs(10), async {+ self.command_shortcut(KEY_V, ictl_l10n::tr!("HID 粘贴", "HID paste")).await+ }++ pub async fn select_all(&mut self) -> Result<()> {+ self.command_shortcut(KEY_A, ictl_l10n::tr!("HID 全选", "HID select all")).await+ }++ /// Delete (Backspace): with text selected, deletes it+ pub async fn delete_backward(&mut self) -> Result<()> {+ const DELETE: u64 = 0x2a;+ limit("HID Delete", Duration::from_secs(10), self.send_keys(vec![(DELETE, false)])).await+ }++ pub async fn collapse_selection(&mut self) -> Result<()> {+ const RIGHT_ARROW: u64 = 0x4f;+ limit("HID Right Arrow", Duration::from_secs(10), self.send_keys(vec![(RIGHT_ARROW, false)])).await+ }++ async fn command_shortcut(&mut self, key: u64, name: &str) -> Result<()> {+ limit(name, Duration::from_secs(10), async {self.indigo.send_keyboard(KEY_LEFT_GUI, ButtonState::Down).await?;let r = async {- self.indigo.send_keyboard(KEY_V, ButtonState::Down).await?;- self.indigo.send_keyboard(KEY_V, ButtonState::Up).await+ self.indigo.send_keyboard(key, ButtonState::Down).await?;+ self.indigo.send_keyboard(key, ButtonState::Up).await}.await;- // V 没发出去也要松开 Cmd:一直按着的话,后面的按键都会变成快捷键+ // Release Cmd even when the key event failed.let up = self.indigo.send_keyboard(KEY_LEFT_GUI, ButtonState::Up).await;r?;Ok(up?)diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rsindex 8ef0e3f..7e4122e 100644--- a/crates/ictl-mcp/src/lib.rs+++ b/crates/ictl-mcp/src/lib.rs@@ -317,12 +317,13 @@ WDA 不可用时会说明哪些功能受影响(读元素、按名字点击、启json!({"filter": {"type": "string", "default": "","description": ictl_l10n::tr!("只返回类型/标签/名字/值里包含这段文字的元素(不区分大小写),例如 SearchField、Button、登录", "Only return elements whose type/label/name/value contains this text (case-insensitive), e.g. SearchField, Button, Login")},- "limit": {"type": "integer", "default": 150, "description": ictl_l10n::tr!("最多列几个,多出的只报数量", "Maximum number of elements to list; the rest are only counted")}+ "limit": {"type": "integer", "default": 150, "description": ictl_l10n::tr!("最多列几个,结构化结果包含匹配总数和截断标记", "Maximum number of elements to return; structured output reports the count and whether it was truncated")}}),&[],),looking(ictl_l10n::tr!("列出界面元素", "List UI elements")),- ),+ )+ .with_raw_output_schema(std::sync::Arc::new(elements_output_schema())),t("iphone_tap",action_desc(@@ -418,17 +419,18 @@ WDA 不可用时改用 CoreDevice HID(iOS 27 起;结果里注明「经 HID」)t("iphone_type_text",action_desc(- ictl_l10n::tr!("在当前获得焦点的输入框里输入文字(支持中文),从光标处输入,不会清空原有内容。submit=true 时末尾按回车。\n\n\+ ictl_l10n::tr!("在当前获得焦点的输入框里输入文字(支持中文),默认从光标处输入。原生控制可用 replace=true 替换当前普通输入框的全文(text 为空时清空)。submit=true 时末尾按回车。\n\n\何时用:搜索框、表单、聊天框等。要先点中输入框让键盘弹出;屏幕上没有键盘时报错,什么都不输。\回车可能会发送消息或提交表单,发送前先向用户确认。\n\n\行为:输完会读回输入框核对,少了结尾几个字会自动补上;对不上就报错,也不按回车。\-WDA 不可用时改用 HID(iOS 27 起):美式键盘上的英文和符号直接按键;中文等经剪贴板粘贴,手机会弹「允许粘贴」,要截图后点它才粘得进去(剪贴板 45 秒后还原)。", "Type text into the focused text field (any language, including Chinese) at the cursor, without clearing what is already there. With submit=true it presses Return at the end.\n\nWhen to use: search boxes, forms, chat fields. Tap the field first so the keyboard comes up; with no keyboard on screen it fails and types nothing. Return may send a message or submit a form, so ask the user before sending.\n\nBehavior: it reads the field back afterwards; dropped trailing characters are typed again. If it still doesn't match, it reports an error and doesn't press Return. If WDA is unavailable it uses HID instead (iOS 27+): English letters and symbols of a US keyboard are typed as keys, anything else is pasted through the pasteboard, and the phone asks to “Allow Paste”: take a screenshot and tap it to let the text in (the pasteboard is put back after 45 s)."),+WDA 不可用时改用 HID(iOS 27 起):美式键盘上的英文和符号直接按键;中文等经剪贴板粘贴,手机会弹「允许粘贴」,要截图后点它才粘得进去(剪贴板 45 秒后还原)。", "Type text into the focused text field (any language, including Chinese) at the cursor by default. On native control, replace=true replaces the contents of a readable focused field (empty text empties it). With submit=true it presses Return at the end.\n\nWhen to use: search boxes, forms, chat fields. Tap the field first so the keyboard comes up; with no keyboard on screen it fails and types nothing. Return may send a message or submit a form, so ask the user before sending.\n\nBehavior: it reads the field back afterwards; dropped trailing characters are typed again. If it still doesn't match, it reports an error and doesn't press Return. If WDA is unavailable it uses HID instead (iOS 27+): English letters and symbols of a US keyboard are typed as keys, anything else is pasted through the pasteboard, and the phone asks to “Allow Paste”: take a screenshot and tap it to let the text in (the pasteboard is put back after 45 s)."),ictl_l10n::tr!("已输入 4 个字符,并按了回车", "Typed 4 characters and pressed Return"),true,),schema(with_then(json!({"text": {"type": "string", "description": ictl_l10n::tr!("要输入的文字", "the text to type")},+ "replace": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("替换当前聚焦输入框的全文,text 为空时清空输入框。仅原生控制、普通可读输入框(不含密码框);默认在光标处输入", "replace all text in the focused field; with empty text, empty it. Native control, readable fields only (not password fields); defaults to typing at the cursor")},"submit": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("输完后按回车(搜索、发送、提交)", "press Return afterwards (search, send, submit)")}})),&["text"],@@ -507,14 +509,15 @@ WDA 不可用时改用 HID(iOS 27 起):美式键盘上的英文和符号直接),t("iphone_wait_for",- ictl_l10n::tr!("等包含某段文字的界面元素出现(例如页面加载完、搜索结果出来、弹窗出现),出现就立即返回找到的元素和用时;超时报错。\n\n\+ ictl_l10n::tr!("等含指定文字的元素出现或消失。默认等出现;state=disappeared 时等当前界面没有匹配项。超时报错。\n\n\何时用:操作后要等加载时代替反复截图轮询,每 0.3 秒查一次,不占上下文。输入框里的字不算(刚输入的搜索词不会被当成结果)。\-需要 WDA。只读:不改变界面,但配置了锁屏密码时会先解锁。", "Wait until a UI element containing some text appears (a page finished loading, search results arrived, an alert appeared); returns the element and the time taken as soon as it appears, or an error on timeout.\n\nWhen to use: after an action, to wait for loading instead of polling with screenshots; it checks every 0.3 s and uses no context meanwhile. Text inside input fields doesn't count (a search term just typed isn't taken for a result). Needs WDA. Read-only: doesn't change the screen, but unlocks the phone first if a passcode is configured.")+只读:不改变界面,但配置了锁屏密码时会先解锁。", "Wait for visible UI text to appear (the default), or use state=disappeared to wait for a screen without a match. Returns an error on timeout.\n\nWhen to use: after an action, to wait for loading instead of polling with screenshots; it checks every 0.3 s and uses no context meanwhile. Text inside input fields doesn't count (a search term just typed isn't taken for a result). Read-only: doesn't change the screen, but unlocks the phone first if a passcode is configured.").into(),schema(json!({"text": {"type": "string", "description": ictl_l10n::tr!("要等的文字,元素的标签/名字/值包含它就算出现", "the text to wait for; it counts as appeared when an element's label/name/value contains it")},- "timeout": {"type": "number", "default": 5, "description": ictl_l10n::tr!("最多等几秒(不超过 30)", "maximum seconds to wait (up to 30)")}+ "timeout": {"type": "number", "default": 5, "description": ictl_l10n::tr!("最多等几秒(不超过 30)", "maximum seconds to wait (up to 30)")},+ "state": {"type": "string", "enum": ["appeared", "disappeared"], "default": "appeared", "description": ictl_l10n::tr!("等文字出现或从当前界面消失", "wait for the text to appear or disappear from the visible screen")}}),&["text"],),@@ -702,7 +705,15 @@ pub fn to_request(name: &str, args: &Map<String, Value>) -> Result<Request, Striseconds: a.f_or("seconds", 0.3)?,hold: a.f_or("hold", 0.0)?,},- "iphone_type_text" => Request::TypeText { text: a.s("text")?, submit: a.b_or("submit", false)? },+ "iphone_type_text" => {+ let text = a.s("text")?;+ let submit = a.b_or("submit", false)?;+ if a.b_or("replace", false)? {+ Request::ReplaceText { text, submit }+ } else {+ Request::TypeText { text, submit }+ }+ }"iphone_press_button" => Request::PressButton { button: a.s("button")? },"iphone_list_apps" => Request::ListApps { include_system: a.b_or("include_system", false)? },"iphone_launch_app" => Request::LaunchApp { app: a.s("app")? },@@ -741,7 +752,19 @@ pub fn to_request(name: &str, args: &Map<String, Value>) -> Result<Request, Striictl_l10n::tr!("timeout 要在 0 到 30 秒之间", "timeout must be between 0 and 30 seconds").into());}- Request::WaitFor { text: a.s("text")?, timeout_ms: (secs * 1000.0) as u64 }+ let text = a.s("text")?;+ let timeout_ms = (secs * 1000.0) as u64;+ match a.s_or("state", "appeared")?.as_str() {+ "appeared" => Request::WaitFor { text, timeout_ms },+ "disappeared" => Request::WaitForDisappearance { text, timeout_ms },+ _ => {+ return Err(ictl_l10n::tr!(+ "state 只能是 appeared 或 disappeared",+ "state must be appeared or disappeared"+ )+ .into());+ }+ }}other => return Err(ictl_l10n::trf!("未知工具 {other}", "unknown tool {other}")),})@@ -801,6 +824,52 @@ pub fn parse_then(args: &Map<String, Value>) -> Result<ThenOpts, String> {Ok(ThenOpts { then, settle_ms: (secs * 1000.0) as u64 })}+/// Each tool's argument names: the properties of its input schema, the developer tools' and+/// [`task::CONFIRM_TOOL`]'s included+static ARG_NAMES: std::sync::LazyLock<std::collections::HashMap<String, Vec<String>>> =+ std::sync::LazyLock::new(|| {+ tools_with(true)+ .into_iter()+ .chain([confirm_tool()])+ .map(|t| {+ let names = t+ .input_schema+ .get("properties")+ .and_then(Value::as_object)+ .map(|p| p.keys().cloned().collect())+ .unwrap_or_default();+ (t.name.to_string(), names)+ })+ .collect()+ });++/// Refuses an argument `tool` doesn't take, before anything is done. Unknown arguments used to be dropped: a call+/// with a misspelt name, or with one this version doesn't have yet, ran with the default instead and reported success+/// (`iphone_wait_for` with `state: "disappeared"` answered “appeared” at once, #158). `extra`: names taken besides the+/// schema's (a batch step's `tool`); `then` and the like are only taken where the schema lists them, so not in a+/// batch's steps (the batch's own then applies). A tool this server doesn't know is left to the call to refuse+pub fn check_args(tool: &str, args: &Map<String, Value>, extra: &[&str], then: bool) -> Result<(), String> {+ let Some(names) = ARG_NAMES.get(tool) else { return Ok(()) };+ let then_names = ["then", "then_filter", "then_region", "then_settle"];+ let takes = |k: &str| (names.iter().any(|n| n == k) && (then || !then_names.contains(&k))) || extra.contains(&k);+ let mut unknown: Vec<&str> = args.keys().map(String::as_str).filter(|k| !takes(k)).collect();+ if unknown.is_empty() {+ return Ok(());+ }+ unknown.sort_unstable();+ let mut known: Vec<&str> =+ names.iter().map(String::as_str).filter(|k| takes(k)).chain(extra.iter().copied()).collect();+ known.sort_unstable();+ known.dedup();+ let sep = ictl_l10n::tr!("、", ", ");+ let known = if known.is_empty() { ictl_l10n::tr!("(无)", "(none)").to_owned() } else { known.join(sep) };+ Err(ictl_l10n::trf!(+ "{tool} 没有参数 {},什么都没做;它的参数:{known}",+ "{tool} has no argument {}, nothing was done; its arguments: {known}",+ unknown.join(sep)+ ))+}+/// 批量里的一步#[derive(Debug, Clone, PartialEq)]pub enum Step {@@ -840,6 +909,12 @@ pub fn batch_steps(args: &Map<String, Value>) -> Result<Vec<Step>, String> {));}if tool == "wait" {+ if let Some(k) = obj.keys().find(|k| !matches!(k.as_str(), "tool" | "seconds")) {+ return Err(ictl_l10n::trf!(+ "第 {n} 步:wait 没有参数 {k},它的参数:tool、seconds",+ "step {n}: wait has no argument {k}; its arguments: tool, seconds"+ ));+ }let secs = Args(obj).f("seconds").map_err(|e| ictl_l10n::trf!("第 {n} 步:{e}", "step {n}: {e}"))?;if !(0.0..=5.0).contains(&secs) {return Err(ictl_l10n::trf!(@@ -849,7 +924,8 @@ pub fn batch_steps(args: &Map<String, Value>) -> Result<Vec<Step>, String> {}return Ok(Step::Wait(std::time::Duration::from_secs_f64(secs)));}- let req = match to_request(tool, obj)+ let req = match check_args(tool, obj, &["tool"], false)+ .and_then(|()| to_request(tool, obj)).map_err(|e| ictl_l10n::trf!("第 {n} 步({tool}):{e}", "step {n} ({tool}): {e}"))?{Request::TapElement { text, index, scroll, .. } if reuse => {@@ -857,6 +933,8 @@ pub fn batch_steps(args: &Map<String, Value>) -> Result<Vec<Step>, String> {}other => other,};+ req.check_required_text()+ .map_err(|e| ictl_l10n::trf!("第 {n} 步({tool}):{e}", "step {n} ({tool}): {e}"))?;Ok(Step::Request { tool: tool.to_owned(), req })}).collect::<Result<_, String>>()?;@@ -903,6 +981,7 @@ pub fn wants_alert_check(req: &Request) -> bool {| Request::LongPress { .. }| Request::Swipe { .. }| Request::TypeText { .. }+ | Request::ReplaceText { .. }| Request::LaunchApp { .. }| Request::OpenUrl { .. } => true,// 按键见 PressButton 自己的弹窗处理;切换设备后新设备的 WDA 还没起来,查不了弹窗;@@ -923,6 +1002,7 @@ pub fn wants_alert_check(req: &Request) -> bool {| Request::Settle { .. }| Request::AlertCheck| Request::WaitFor { .. }+ | Request::WaitForDisappearance { .. }| Request::Daemon| Request::Doctor| Request::Resign { .. }@@ -946,10 +1026,44 @@ pub fn wants_alert_check(req: &Request) -> bool {}}+/// The shape of [`with_elements`]' 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<String, Value> {+ let element = json!({+ "type": "object",+ "properties": {+ "type": {"type": "string"}, "label": {"type": "string"},+ "x": {"type": "number"}, "y": {"type": "number"}, "width": {"type": "number"}, "height": {"type": "number"}+ }+ });+ let v = json!({+ "type": "object",+ "properties": {+ "type": {"const": "elements"},+ "elements": {"type": "array", "items": element,+ "description": "the elements listed, at most limit; x/y the top left corner in points"},+ "matched_count": {"type": "integer", "description": "how many elements matched filter in this read, before limit"},+ "truncated": {"type": "boolean", "description": "matched_count is more than limit: some weren't listed"}+ },+ "required": ["elements"]+ });+ v.as_object().cloned().unwrap_or_default()+}++fn with_elements(mut result: CallToolResult, data: Option<protocol::Data>) -> CallToolResult {+ if let Some(data @ protocol::Data::Elements { .. }) = data {+ result.structured_content = serde_json::to_value(data).ok();+ }+ result+}+/// 守护进程响应 → MCP 结果。错误走工具错误(is_error),文字原样给客户端pub fn to_result(r: Response) -> CallToolResult {match r {- Response::Text { text, .. } => CallToolResult::success(vec![ContentBlock::text(text)]),+ Response::Text { text, data, .. } => {+ with_elements(CallToolResult::success(vec![ContentBlock::text(text)]), data)+ }Response::Image { jpeg_base64, caption } => {CallToolResult::success(vec![ContentBlock::image(jpeg_base64, "image/jpeg"), ContentBlock::text(caption)])}@@ -1031,6 +1145,9 @@ impl McpServer {let args = request.arguments.clone().unwrap_or_default();let work = async {if request.name == task::CONFIRM_TOOL {+ if let Err(e) = check_args(&request.name, &args, &[], false) {+ return Ok(CallToolResult::error(vec![ContentBlock::text(e)]).into());+ }let r = match task::confirm(&self.socket, &args).await {Ok(m) => CallToolResult::success(vec![ContentBlock::text(m)]),Err(m) => CallToolResult::error(vec![ContentBlock::text(m)]),@@ -1071,6 +1188,9 @@ impl McpServer {async fn call_tool_inner(&self, request: CallToolRequestParams) -> Result<CallToolResponse, ErrorData> {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());+ }let then = match parse_then(&args) {Ok(t) => t,Err(e) => return Ok(to_result(Response::error(e)).into()),@@ -1169,9 +1289,11 @@ impl McpServer {}).await{- Response::Text { text: t, .. } => {+ Response::Text { text: t, data, .. } => {text +=- &ictl_l10n::trf!("\n--- 操作后的界面 ---\n{t}", "\n--- Screen after the action ---\n{t}")+ &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);}Response::Error { message, .. } => {text += &ictl_l10n::trf!("\n(读界面失败:{message})", "\n(reading the screen failed: {message})")@@ -1497,6 +1619,61 @@ mod tests {assert!(parse_then(&args(json!({"then_settle": 30}))).is_err());}+ /// #158: an argument the tool doesn't take is refused, not dropped (a wait for disappearance ran as a wait for+ /// appearance and answered at once)+ #[test]+ fn unknown_arguments_are_refused() {+ // an argument from another version (here: misspelt) is refused and the tool's own are listed+ let e = check_args("iphone_wait_for", &args(json!({"text": "飞行模式", "until": "disappeared"})), &[], true)+ .unwrap_err();+ assert!(e.contains("until") && e.contains("state") && e.contains("timeout"), "{e}");+ assert!(check_args("iphone_wait_for", &args(json!({"text": "x", "state": "disappeared"})), &[], true).is_ok());+ assert!(check_args("iphone_type_text", &args(json!({"text": "", "replace": true})), &[], true).is_ok());+ // misspelt+ assert!(check_args("iphone_type_text", &args(json!({"text": "a", "sumbit": true})), &[], true).is_err());+ // every documented argument, then on an action, null for a default+ assert!(+ check_args(+ "iphone_type_text",+ &args(json!({"text": "a", "submit": true, "then": "elements",+ "then_filter": "x", "then_settle": 1})),+ &[],+ true+ )+ .is_ok()+ );+ assert!(check_args("iphone_list_elements", &args(json!({"limit": null})), &[], true).is_ok());+ // then only where the schema lists it+ assert!(check_args("iphone_screenshot", &args(json!({"then": "elements"})), &[], true).is_err());+ assert!(check_args("iphone_status", &args(json!({})), &[], true).is_ok());+ assert!(check_args("iphone_batch", &args(json!({"steps": [], "then": "screenshot"})), &[], true).is_ok());+ // developer tools and the confirm tool have their own; a tool this server doesn't know is left alone+ assert!(check_args("iphone_web_eval", &args(json!({"expression": "1", "timeout": 2})), &[], true).is_ok());+ assert!(+ check_args(task::CONFIRM_TOOL, &args(json!({"action": "a", "detail": "b", "x": 1})), &[], false).is_err()+ );+ assert!(check_args("no_such_tool", &args(json!({"x": 1})), &[], true).is_ok());+ }++ #[test]+ fn batch_steps_refuse_unknown_arguments() {+ let bad = |step: Value| batch_steps(&args(json!({"steps": [step]}))).unwrap_err();+ let e = bad(json!({"tool": "iphone_wait_for", "text": "x", "until": "disappeared"}));+ assert!(e.contains("第 1 步") && e.contains("until"), "{e}");+ // a step's then would be ignored (the batch's then applies): refused, not dropped+ assert!(bad(json!({"tool": "iphone_tap", "x": 1, "y": 2, "then": "elements"})).contains("then"));+ assert!(bad(json!({"tool": "wait", "seconds": 1, "secs": 2})).contains("secs"));+ }++ #[test]+ fn element_lists_declare_their_output_schema() {+ let tools = standard_tools();+ let declared: Vec<_> = tools.iter().filter(|t| t.output_schema.is_some()).map(|t| &*t.name).collect();+ assert_eq!(declared, ["iphone_list_elements"]);+ let schema = tools.iter().find(|t| t.name == "iphone_list_elements").and_then(|t| t.output_schema.clone());+ assert_eq!(schema.unwrap()["required"], json!(["elements"]));+ }+#[test]fn batch_steps_are_checked_before_anything_runs() {let steps = batch_steps(&args(json!({"steps": [@@ -1574,6 +1751,38 @@ mod tests {assert!(to_request("iphone_wait_for", &args(json!({"text": "x", "timeout": 60}))).is_err());}+ #[test]+ fn text_replacement_is_forwarded_only_when_requested() {+ let changed = to_request("iphone_type_text", &args(json!({"text": "蓝牙", "replace": true}))).unwrap();+ assert_eq!(serde_json::to_value(changed).unwrap()["op"], "replace_text");+ let default = to_request("iphone_type_text", &args(json!({"text": "蓝牙"}))).unwrap();+ assert_eq!(serde_json::to_value(default).unwrap()["op"], "type_text");+ }++ #[test]+ fn wait_for_accepts_disappeared_and_rejects_unknown_state() {+ let req = to_request("iphone_wait_for", &args(json!({"text": "设置", "state": "disappeared"}))).unwrap();+ assert_eq!(serde_json::to_value(req).unwrap()["op"], "wait_for_disappearance");+ assert!(to_request("iphone_wait_for", &args(json!({"text": "设置", "state": "any"}))).is_err());+ }++ #[test]+ fn element_limit_is_reported_in_structured_content() {+ let reply: Response = serde_json::from_value(json!({+ "kind": "text", "text": "one element, 16 more",+ "data": {+ "type": "elements",+ "elements": [{"type":"Button","label":"设置","x":16,"y":16,"width":44,"height":44}],+ "matched_count": 17, "truncated": true+ }+ }))+ .unwrap();+ let result = serde_json::to_value(to_result(reply)).unwrap();+ assert_eq!(result["structuredContent"]["elements"].as_array().unwrap().len(), 1);+ assert_eq!(result["structuredContent"]["matched_count"], 17);+ assert_eq!(result["structuredContent"]["truncated"], true);+ }+#[test]fn wrong_typed_parameters_are_errors_not_defaults() {let args = |v: Value| v.as_object().unwrap().clone();diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rsindex 48c0daf..b23e8f1 100644--- a/crates/ictl-protocol/src/lib.rs+++ b/crates/ictl-protocol/src/lib.rs@@ -142,6 +142,11 @@ pub enum Request {text: String,submit: bool,},+ /// A separate operation so an older daemon cannot silently insert the text instead.+ ReplaceText {+ text: String,+ submit: bool,+ },PressButton {button: String,},@@ -178,6 +183,10 @@ pub enum Request {text: String,timeout_ms: u64,},+ WaitForDisappearance {+ text: String,+ timeout_ms: u64,+ },/// 运维:守护进程和设备的状态快照(JSON 文本)Daemon,/// 运维:逐层诊断,返回多行文字@@ -386,6 +395,11 @@ pub enum Data {Status(StatusData),Elements {elements: Vec<ElementData>,+ /// Matches in the observed tree before the caller's limit. Older daemons do not report this.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ matched_count: Option<usize>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ truncated: Option<bool>,},Apps {apps: Vec<AppData>,@@ -451,6 +465,17 @@ impl Response {}impl Request {+ /// Shared by the daemon and the MCP batch preflight, before any earlier steps run.+ pub fn check_required_text(&self) -> Result<(), String> {+ match self {+ // an empty ReplaceText empties the field+ Self::WaitFor { text, .. } | Self::WaitForDisappearance { text, .. } if text.is_empty() => {+ Err(ictl_l10n::tr!("text 不能为空", "text can't be empty").into())+ }+ _ => Ok(()),+ }+ }+/// 会改变手机状态的操作。守护进程忙时排队太久就放弃,免得点击落到已经变了的屏幕上/// Every variant is listed (no `_`), so a new request type has to be classified herepub fn is_device_action(&self) -> bool {@@ -461,6 +486,7 @@ impl Request {| Self::LongPress { .. }| Self::Swipe { .. }| Self::TypeText { .. }+ | Self::ReplaceText { .. }| Self::PressButton { .. }| Self::Touch { .. }| Self::LaunchApp { .. }@@ -478,6 +504,7 @@ impl Request {| Self::Settle { .. }| Self::AlertCheck| Self::WaitFor { .. }+ | Self::WaitForDisappearance { .. }| Self::Daemon| Self::Doctor| Self::Resign { .. }@@ -1018,7 +1045,9 @@ mod tests {assert!(s.contains(r#""data":{"type":"status","wda_ready":true"#), "{s}");assert_eq!(serde_json::from_str::<Response>(&s).unwrap(), r);let el = ElementData { kind: "Button".into(), label: "OK".into(), x: 1.0, y: 2.0, width: 3.0, height: 4.0 };- let v = serde_json::to_value(Data::Elements { elements: vec![el] }).unwrap();+ let v =+ serde_json::to_value(Data::Elements { elements: vec![el], matched_count: Some(1), truncated: Some(false) })+ .unwrap();assert_eq!(v["elements"][0]["type"], "Button", "the page reads `type`");assert!(!serde_json::to_string(&Response::text_with("x", Outcome::default())).unwrap().contains("data"));}diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rsindex a13890c..026cb76 100644--- a/crates/ictl-wda/src/client.rs+++ b/crates/ictl-wda/src/client.rs@@ -811,7 +811,9 @@ impl<T: Transport> WdaClient<T> {pub async fn tree(&mut self) -> Result<elements::Tree> {let view = self.view().await?;self.move_detection_point(view.screen).await;- Ok(elements::parse_tree(&self.source_xml().await?, view))+ let mut tree = elements::parse_tree(&self.source_xml().await?, view);+ tree.incomplete |= SNAPSHOT_LEVELS[self.snapshot_read].children.is_some();+ Ok(tree)}/// 把 WDA 判断前台 App 的点(appium setting `activeAppDetectionPoint`)挪到 [`detection_point`],每个客户端做一次。diff --git a/crates/ictl-wda/src/elements.rs b/crates/ictl-wda/src/elements.rsindex 2fee7f4..cbc069b 100644--- a/crates/ictl-wda/src/elements.rs+++ b/crates/ictl-wda/src/elements.rs@@ -217,6 +217,8 @@ pub struct Tree {blockers: Vec<Blocker>,/// 屏幕上有转圈的加载指示(ActivityIndicator,有没有文字都算)pub loading: bool,+ /// Some nodes may not have been observed. Missing text on this tree does not prove absence.+ pub incomplete: bool,}/// 按名字点击时实际点哪里@@ -481,7 +483,10 @@ pub fn parse_tree(xml: &str, view: impl Into<View>) -> Tree {}continue;}- Ok(Event::Eof) => break,+ Ok(Event::Eof) => {+ tree.incomplete = !stack.is_empty();+ break;+ }Err(e) => {// 解析到一半出错:已解析的照常返回,但要留痕,否则「没找到元素」看起来像真结果tracing::warn!(@@ -492,6 +497,7 @@ pub fn parse_tree(xml: &str, view: impl Into<View>) -> Tree {reader.buffer_position()));+ tree.incomplete = true;break;}Ok(_) => continue,diff --git a/crates/ictl-webinspector/src/lib.rs b/crates/ictl-webinspector/src/lib.rsindex be54082..788380f 100644--- a/crates/ictl-webinspector/src/lib.rs+++ b/crates/ictl-webinspector/src/lib.rs@@ -221,7 +221,7 @@ impl WebInspector {// a DOM node or similar serializes to {}; its description ("body", "div#app") says morelet empty = v["result"]["value"].as_object().is_some_and(|o| o.is_empty());let plain = r["result"]["className"] == "Object" || r["result"]["subtype"] == "array";- if v["result"].get("value").is_some() && !(empty && !plain) { v } else { r }+ if v["result"].get("value").is_some() && (!empty || plain) { v } else { r }};Ok(eval_result(&r))}diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.mdindex e8e3277..f06dac7 100644--- a/docs/dev/regression-cases.md+++ b/docs/dev/regression-cases.md@@ -162,3 +162,6 @@| 156 | 原生控制(iOS 27):自动解锁时密码键盘出来了,却一位都输不进去,三轮后报「调不出锁屏密码键盘」(偶尔停在第 2、3 位)。每点一个数字键就要读密码栏,读之前得先关 HID 会话(开着时手机不让无障碍服务看锁屏);点完马上关,手机不认这次触摸。时有时无:同一台手机(iPhone19,7,iOS 27.2.1)不等也能解锁了几个小时,之后每一下都丢 | 关 HID 会话前,等上一次 HID 操作发出满 `TOUCH_LANDS`(0.35 秒)。丢键期间同一个守护进程里轮流量的解锁成功数:0 毫秒 0/9,50 毫秒 0/3,100 毫秒 0/3,150 毫秒 1/3,200 毫秒 3/4,250 毫秒 5/5,350 毫秒 3/3 | 单测 `the_hid_session_stays_open_until_the_last_touch_has_landed` + 真机脚本 `scenarios.py lock` || 157 | 原生:守护进程闲置 30 秒关掉 HID 会话后,在主屏幕上按 Home、马上启动 App,App 到了前台又被送回主屏幕(7/8);守护进程刚启动后 `run.py` 第一轮常因此失败。#130 的 0.6 秒是从调用 HID 算起的,重开会话(屏幕媒体流,约 0.6 秒)把它用完了,按下后一点没等 | 先开好 HID 会话,再从按下 Home 算 0.6 秒 | 真机(iPhone19,7,iOS 27.2.1:闲置后 Home 再启动时钟,0.2.8 是 7/8 回到主屏幕,会话开着时 0/8);真机脚本 `scenarios.py idle` || 158 | 原生控制(iOS 27):axauditd 的另一种卡法:前台 App 一个元素都读不到(连 Application 元素都没有),换新会话也一样,SpringBoard 照常读得出来,也不超时,所以 #155 的重启不触发;读界面、按名字点击、启动 App 都报「读界面失败:超时:没有读到界面元素」,重启守护进程、结束 App 重开都没用,结束 axauditd 后马上恢复(iPhone19,7,iOS 27.2.1,见过一次) | 重连后前台 App 仍一个元素都读不到时按无障碍服务不应答处理(`DeviceError::AxUnanswered`,文字不变),走 #155 的重启(一分钟内最多一次);锁屏在 HID 媒体流下读到的是 1 个元素(#126),不算 | 单测 `an_app_read_with_no_elements_is_an_unanswered_accessibility_service` + 真机(没能按需复现卡住;默认步骤和场景跑下来不误触发重启,事件日志没有「已重启手机上的 axauditd」) |+| 159 | 普通输入框里已有文字时,输入新词会保留原文,调用方没有显式的替换语义 | 原生控制的 `replace: true` 替换聚焦的普通输入框,按原输入框全文核对(新词是原文一部分时也是,如 `wifi` → `wi`),全文不符不触发回车,并取消全选;`text` 为空时清空 | 单测 `replacing_text_requires_one_readable_focused_field` + 真机脚本 `scenarios.py editing` |+| 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` |diff --git a/tests/device/scenarios.py b/tests/device/scenarios.pyindex 12252dc..0c6fff2 100644--- a/tests/device/scenarios.py+++ b/tests/device/scenarios.py@@ -14,6 +14,8 @@ Scenarios (the numbers are regression cases):selecting the device already selected, an enlarged region (#16), then=screenshottyping typing with no keyboard up is refused and types nothing (#32); the same text typed twice intoSpotlight counts as typed the second time too (#143)+ editing replace and empty focused text on native iOS (#159), 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,not the one before (#125)batch iphone_batch runs its steps in order and answers for each; a tap that found nothing stops it and@@ -193,6 +195,66 @@ async def typing(p: Phone):await p.home(c)+def spotlight_queries(text: str) -> list[str]:+ # describe() prints a field value only once when it equals the label.+ return [e.value if e.value is not None else e.label for e in dev.elements(text)+ if e.kind in ("SearchField", "TextField")]+++async def editing(p: Phone):+ c = "editing"+ if p.d.native:+ try:+ await p.spotlight(c)+ await p.ok(c, "iphone_type_text", {"text": "wifi"})+ before = await p.ok(c, "iphone_list_elements", {"filter": "SearchField"})+ if not check("#159", "Spotlight query is wifi before replacement",+ spotlight_queries(before) == ["wifi"], before):+ return+ for wanted in ("wi", "蓝牙"):+ err, answer, dt, _ = await p.call("iphone_type_text", {"text": wanted, "replace": True})+ 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):+ 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})+ readback = await p.ok(c, "iphone_list_elements", {"filter": "SearchField"})+ check("#159", f"replace with empty text empties the Spotlight query ({dt:.2f}s)",+ not err and says(answer, dev.T("已清空", "Emptied")) and "蓝牙" not in readback,+ answer if err else readback)+ finally:+ await p.home(c)+ err, answer, _, _ = await p.call("iphone_type_text", {"text": "蓝牙", "replace": True, "submit": True})+ check("#159", "replacement without a keyboard is refused", err and says(answer, dev.NO_KEYBOARD), answer)+ else:+ print(f"SKIP [{c}] #159 replacement needs native control", flush=True)++ await p.ok(c, "iphone_launch_app", {"app": dev.CLOCK})+ tabs = await p.clock_tabs(c)+ if not tabs:+ return+ for limit in (1, 500):+ res = await asyncio.wait_for(p.s.call_tool("iphone_list_elements", {"limit": limit}), 30)+ data = res.structured_content or {}+ count = len(data.get("elements", []))+ matched = data.get("matched_count")+ expected = limit == 1+ check("#160", f"element limit {limit} reports truncation",+ not res.is_error and isinstance(matched, int) and matched > 1 and count == min(matched, limit)+ and data.get("truncated") is expected,+ f"returned={count} matched={matched} truncated={data.get('truncated')}")++ target = {"text": tabs[0].label, "state": "disappeared", "timeout": 2}+ err, answer, dt, _ = await p.call("iphone_wait_for", target)+ check("#161", f"still-visible Clock tab times out ({dt:.2f}s)",+ err and says(answer, dev.T("没消失", "did not disappear")), answer)+ await p.home(c)+ err, answer, dt, _ = await p.call("iphone_wait_for", target)+ check("#161", f"Clock tab is gone after leaving the app ({dt:.2f}s)",+ not err and says(answer, dev.T("已消失", "Disappeared")), answer)++async def fresh(p: Phone):c = "fresh"await p.home(c)@@ -371,7 +433,8 @@ async def lock(p: Phone):SCENARIOS = {- "tools": tools, "typing": typing, "fresh": fresh, "batch": batch, "menu": menu, "idle": idle, "url": url, "lock": lock+ "tools": tools, "typing": typing, "editing": editing, "fresh": fresh, "batch": batch,+ "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.mdindex f4f05e3..ef5f19a 100644--- a/website/en/guide/tools.md+++ b/website/en/guide/tools.md@@ -8,8 +8,8 @@ The MCP server provides 17 tools, 23 with the [developer tools](#developer-tools|---|---|| `iphone_status` | Ready or not, native or WDA, locked or not, foreground app, screen size || `iphone_screenshot` | Screenshot; with `x`, `y`, `width`, `height` it returns an enlarged region for small text and icons |-| `iphone_list_elements` | Elements with text: type, text, center, size; `filter` by text or type |-| `iphone_wait_for` | Wait until some text appears (page loaded, dialog shown); text inside input fields doesn't count. `timeout` defaults to 5 seconds, max 30 |+| `iphone_list_elements` | Elements with text: type, text, center, size; `filter` by text or type. Structured output includes `matched_count` in the observed tree and `truncated` when `limit` omitted matches. These fields are also returned with action and batch `then: "elements"`. |+| `iphone_wait_for` | Wait for text to appear by default. With `state: "disappeared"`, wait for a screen without a match. Edited values in input fields do not count. `timeout` defaults to 5 seconds, max 30 || `iphone_list_apps` | Installed apps; read-only, no `then` |With [auto-unlock](./auto-unlock) on, `iphone_screenshot`, `iphone_list_elements` and `iphone_wait_for` also unlock a locked phone first. They are marked read-only because they don't change what's on screen. `iphone_status` and `iphone_list_apps` don't unlock it.@@ -22,7 +22,7 @@ With [auto-unlock](./auto-unlock) on, `iphone_screenshot`, `iphone_list_elements| `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 |-| `iphone_type_text` | Type into the focused field (Chinese supported), read it back and fix dropped characters; `submit` presses Return |+| `iphone_type_text` | Type into the focused field (Chinese supported), read it back and fix dropped characters; `submit` presses Return. With native control, `replace: true` replaces the text of a focused, readable field (empty `text` empties it) and verifies the whole value before pressing Return || `iphone_press_button` | `home`, `volume_up`, `volume_down`, `lock` || `iphone_launch_app` / `iphone_terminate_app` | Launch / quit an app by name (e.g. `设置`) or bundle id || `iphone_open_url` | Open a link or URL scheme |diff --git a/website/guide/tools.md b/website/guide/tools.mdindex 5a5526e..24b26b1 100644--- a/website/guide/tools.md+++ b/website/guide/tools.md@@ -8,8 +8,8 @@ MCP 服务提供 17 个工具,开启[开发者工具](#开发者工具-显式|---|---|| `iphone_status` | 是否就绪、控制方式(原生或 WDA)、是否锁屏、前台 App、屏幕尺寸 || `iphone_screenshot` | 截图;给出 `x`、`y`、`width`、`height` 时只返回这块区域的放大图,看清小字和小图标 |-| `iphone_list_elements` | 列出屏幕上带文字的元素:类型、文字、中心点、尺寸;`filter` 可按文字或类型筛选 |-| `iphone_wait_for` | 等某段文字出现(页面加载完、弹窗出现),出现就返回;输入框里的字不算。`timeout` 默认 5 秒,最多 30 秒 |+| `iphone_list_elements` | 列出屏幕上带文字的元素:类型、文字、中心点、尺寸;`filter` 可按文字或类型筛选。结构化输出含 `matched_count`(本次读到且匹配的元素数)和 `truncated`(是否受 `limit` 截断);操作和批量的 `then: "elements"` 也返回这两个字段 |+| `iphone_wait_for` | 默认等文字出现。`state: "disappeared"` 等当前界面不再匹配。输入框里正在编辑的字不计入匹配。`timeout` 默认 5 秒,最多 30 秒 || `iphone_list_apps` | 已安装的 App;只读,没有 `then` |开启[自动解锁](./auto-unlock)时,手机锁着的话,`iphone_screenshot`、`iphone_list_elements`、`iphone_wait_for` 也会先解锁。这些工具标为「只读」,指的是不改界面内容。`iphone_status`、`iphone_list_apps` 不会解锁。@@ -22,7 +22,7 @@ MCP 服务提供 17 个工具,开启[开发者工具](#开发者工具-显式| `iphone_tap_element` | 按文字点击;中心被悬浮栏、键盘挡住时改点露出来的部分,整个被挡住就不点。带 `scroll`(`down` / `up`)时,屏幕上没有就慢慢边滑边找,找到就点,滑到底或滑满 `max_scrolls`(默认 8)次为止 || `iphone_long_press` | 长按;`seconds` 默认 1,最多 10 || `iphone_swipe` | 滑动;列表停稳后才返回。`seconds` 默认 0.3,最多 10。`hold` 先在起点按住几秒再移动,用来拖动要先长按才拿得起来的东西(主屏幕图标、可排序的列表项),0.6 左右即可 |-| `iphone_type_text` | 在当前输入框输入文字(支持中文),输完读回核对,丢字会补上;`submit` 时按回车 |+| `iphone_type_text` | 在当前输入框输入文字(支持中文),输完读回核对,丢字会补上;`submit` 时按回车。原生控制下 `replace: true` 替换当前普通输入框的全文(`text` 为空时清空),核对全文后才会按回车 || `iphone_press_button` | `home`、`volume_up`、`volume_down`、`lock` || `iphone_launch_app` / `iphone_terminate_app` | 启动 / 结束 App,可以用名字(如「设置」)或 Bundle ID || `iphone_open_url` | 打开链接或 URL Scheme |