diff --git a/CHANGELOG.md b/CHANGELOG.md index 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 ### Fixes diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 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.rs index 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.rs index 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 { /// `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?)})) + 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 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 alert let 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) -> Vec { +#[derive(Default, serde::Serialize)] +pub(super) struct ElementList { + pub(super) elements: Vec, + matched_count: Option, + truncated: Option, +} + +pub(super) fn element_list(data: Option) -> 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.rs index a359652..e682270 100644 --- a/crates/ictl-ax/src/session.rs +++ b/crates/ictl-ax/src/session.rs @@ -397,7 +397,8 @@ impl Session { let deadline = Instant::now() + budget; let mut attrs: HashMap = 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 Session { break; } let n = frontier.len().min(BATCH).min(limit - attrs.len()); - let chunk: Vec<(ObjectRef, usize)> = frontier.drain(..n).collect(); - let objects: Vec = chunk.iter().map(|(o, _)| *o).collect(); + let chunk: Vec<_> = frontier.drain(..n).collect(); + 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 }; + 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 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..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.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..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 front const 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 { - 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 { 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 +453,50 @@ impl Daemon { g: &mut Inner, text: &str, timeout: Duration, + disappeared: bool, ) -> crate::error::Result { + use super::observe::Waited; let t0 = Instant::now(); + // lockdown's last answer, and when (None: it failed) + let mut lock: Option<(Instant, Option)> = 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 { + 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 { + 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 back self.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 = 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 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 natively struct 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#"{markers}"#); + let tree = elements::parse_tree(&xml, ScreenSize { width: 390.0, height: 844.0 }); + native_cover(&xml, &screen(springboard_front), &tree) + }; + let icon = r#""#; + // the home screen + assert_eq!(cover(icon, true), Cover::None); + // the lock screen by its marks, in front or not + assert_eq!(cover(r#""#, true), Cover::Locked); + assert_eq!(cover(r#""#, false), Cover::Locked); + // notification center pulled over an app + assert_eq!(cover(&format!(r#"{icon}"#), false), Cover::Other); + // the lock screen as read natively: no marks, SpringBoard in front, no icons + let lock = r#" +"#; + 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#" + + +"#; + assert_eq!(cover(sleep, false), Cover::Other); + let orb = r#""#; + 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.rs index 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)> { + ) -> 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,168 @@ 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())); - } + 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 { + 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#"