From 7bdd408ed77c63af766edb9b98759773a44ab726 Mon Sep 17 00:00:00 2001 From: MSK Date: Wed, 18 Nov 2026 19:24:39 +0800 Subject: [PATCH 1/7] feat(mcp): replace focused text, report list limits and wait for disappearance --- CHANGELOG.md | 6 + CHANGELOG.zh-CN.md | 6 + apps/iphone-control/src/viewer.rs | 2 +- apps/iphone-control/src/viewer/api.rs | 9 +- crates/ictl-ax/src/session.rs | 17 +- crates/ictl-daemon/src/core.rs | 22 ++- crates/ictl-daemon/src/tasks.rs | 10 +- crates/ictl-daemon/src/tools/native.rs | 206 +++++++++++++++++------- crates/ictl-daemon/src/tools/observe.rs | 97 +++++++++-- crates/ictl-device/src/ax.rs | 16 +- crates/ictl-device/src/hid.rs | 17 +- crates/ictl-mcp/src/lib.rs | 83 ++++++++-- crates/ictl-protocol/src/lib.rs | 20 ++- crates/ictl-wda/src/client.rs | 4 +- crates/ictl-wda/src/elements.rs | 8 +- crates/ictl-webinspector/src/lib.rs | 2 +- docs/dev/regression-cases.md | 3 + tests/device/scenarios.py | 51 +++++- website/en/guide/tools.md | 6 +- website/guide/tools.md | 6 +- 20 files changed, 476 insertions(+), 115 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a6a5df..9626b06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ What changed in each release, one line per change. Versions follow [Semantic Ver ## [Unreleased] +### New + +- With native control, `iphone_type_text` supports `replace: true` and verifies the full field value before pressing Return. +- `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 ### Fixes diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 94b320b..03a5cb6 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -6,6 +6,12 @@ ## [Unreleased] +### 新功能 + +- 原生控制的 `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.rs index ae25c72..f25bd56 100644 --- a/apps/iphone-control/src/viewer.rs +++ b/apps/iphone-control/src/viewer.rs @@ -2159,7 +2159,7 @@ 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 })); assert_eq!( els[0], json!({"type": "Button", "label": "今天", "x": 33.0, "y": 861.0, "width": 56.0, "height": 38.0}) diff --git a/apps/iphone-control/src/viewer/api.rs b/apps/iphone-control/src/viewer/api.rs index 8f00021..fe72160 100644 --- a/apps/iphone-control/src/viewer/api.rs +++ b/apps/iphone-control/src/viewer/api.rs @@ -178,7 +178,12 @@ pub(super) async fn apps(ctx: &Ctx, system: bool) -> Result { /// `keep_locked`: a read-only visitor, for whom a locked phone isn't unlocked pub(super) async fn elements(ctx: &Ctx, filter: &str, keep_locked: bool) -> Result { 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?)})) + match data_of(&ctx.socket, req).await? { + Some(protocol::Data::Elements { elements, matched_count, truncated }) => Ok(json!({ + "elements": elements, "matched_count": matched_count, "truncated": truncated, + })), + _ => Ok(json!({"elements": []})), + } } /// A system alert on the phone (a permission prompt and the like): `{ alert: null }` or @@ -204,7 +209,7 @@ pub(super) async fn alert(ctx: &Ctx, keep_locked: bool) -> Result /// 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) -> Vec { match data { - Some(protocol::Data::Elements { elements }) => { + Some(protocol::Data::Elements { elements, .. }) => { elements.iter().filter_map(|e| serde_json::to_value(e).ok()).collect() } _ => Vec::new(), diff --git a/crates/ictl-ax/src/session.rs b/crates/ictl-ax/src/session.rs index a359652..b0089d8 100644 --- a/crates/ictl-ax/src/session.rs +++ b/crates/ictl-ax/src/session.rs @@ -409,9 +409,16 @@ impl Session { let objects: Vec = 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 }; + let Some(a) = got.get(&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 { @@ -433,15 +440,15 @@ impl Session { limit: usize, budget: Duration, prune: u64, - ) -> Result> { - let (mut els, _) = self.walk(root, limit + 1, budget, prune).await?; + ) -> Result<(Vec, 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.rs index 959b6c9..dd56a95 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 @@ -1497,7 +1505,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,7 +1517,11 @@ 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() => { + Request::WaitFor { text, .. } + | Request::WaitForDisappearance { text, .. } + | Request::ReplaceText { 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 => { diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rs index 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 { | 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 { | 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.rs index 62d91bc..61fc861 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; @@ -229,8 +229,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 { - 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 +389,15 @@ impl Daemon { async fn snapshot_tree(&self, g: &mut Inner, s: &ictl_device::ax::AxScreen) -> crate::error::Result { 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 tree async fn with_overlays(&self, g: &mut Inner, mut s: ictl_device::ax::AxScreen) -> crate::error::Result { 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 +444,21 @@ impl Daemon { g: &mut Inner, text: &str, timeout: Duration, + disappeared: bool, ) -> crate::error::Result { let t0 = Instant::now(); loop { + if disappeared && self.native_locked(g).await? { + return Err(super::observe::wait_locked()); + } 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() - )); + if let Some(result) = super::observe::wait_match(&tree, text, disappeared, t0.elapsed()) { + return Ok(result); } 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, disappeared)); } - tokio::time::sleep(Duration::from_millis(300)).await; + tokio::time::sleep(Duration::from_millis(300).min(timeout.saturating_sub(t0.elapsed()))).await; } } @@ -633,6 +628,52 @@ impl Daemon { )) } + /// 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 { + 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 old = focused_text_value(&before).ok_or_else(|| { + ictl_l10n::tr!( + "无法确认当前聚焦的是可读的普通输入框,没有替换文字", + "Couldn't identify a readable focused text field; no text was replaced" + ) + })?; + if old != text { + self.hid_do(g, |h| Box::pin(h.select_all())).await?; + let old = [old.to_owned()]; + self.native_paste(g, text, Some(&old)).await?; + let after = self.ax_snapshot(g, AX_WAIT, false).await?; + if before.app_pid != after.app_pid || focused_text_value(&after) != Some(text) { + return Err(ictl_l10n::tr!( + "替换后无法核对输入框全文,未按回车;请查看手机界面", + "Couldn't verify the full field value after the replacement; Return was not pressed. Check the screen" + ).into()); + } + } + if submit { + self.hid_do(g, |h| Box::pin(h.type_ascii("\n"))).await?; + } + let n = text.chars().count(); + Ok(if submit { + ictl_l10n::trf!( + "已替换为 {n} 个字符,并按了回车", + "Replaced the field with {n} characters and pressed Return" + ) + } else { + ictl_l10n::trf!("已替换为 {n} 个字符", "Replaced the field with {n} characters") + }) + } + /// 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 @@ -655,49 +696,42 @@ 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 = 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 = 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; + if Instant::now() >= deadline { + break Pasted::Missing; + } + 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; }; - 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 +821,19 @@ impl Daemon { } } +fn focused_text_value(screen: &ictl_device::ax::AxScreen) -> Option<&str> { + if !screen.app_complete { + return None; + } + 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.value.as_str()) +} + /// The phone as [`ictl_unlock`] sees it, driven natively struct NativeScreen<'a> { d: &'a Daemon, @@ -908,6 +955,43 @@ impl Screen for NativeScreen<'_> { mod tests { use super::*; + #[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_value(&screen), Some(" 蓝牙 ")); + screen.app[0].focused = true; + assert_eq!(focused_text_value(&screen), None); + screen.app[0].focused = false; + screen.app[1].value = "••••".into(); + assert_eq!(focused_text_value(&screen), Some("••••")); + screen.app[1].xc_type = 50; // SecureTextField + assert_eq!(focused_text_value(&screen), 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.rs index 6956a77..8194034 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)> { + ) -> crate::error::Result<(String, crate::protocol::Data)> { if keep_locked { // only looking (a read-only viewer): the passcode isn't typed for it let 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,97 @@ impl Daemon { }) } - /// 等包含 `text` 的元素出现 - pub(crate) async fn wait_for(&self, g: &mut Inner, text: &str, timeout: Duration) -> crate::error::Result { + /// 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 { 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())); + if disappeared && w.locked().await? { + return Err(wait_locked()); + } + let tree = w.tree().await?; + if let Some(result) = wait_match(&tree, text, disappeared, t0.elapsed()) { + return Ok(result); } 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, disappeared)); } - 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 { + 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())) +} + +pub(super) fn wait_timeout(text: &str, timeout: Duration, disappeared: bool) -> crate::error::Error { + let seconds = timeout.as_secs_f64(); + if disappeared { + return ictl_l10n::trf!( + "{seconds:.1} 秒内没消失或无法确认已消失「{text}」,截图看看屏幕", + "\"{text}\" did not disappear within {seconds:.1} s or its absence could not be confirmed; 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 cannot be confirmed" + ) + .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#"