Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

feat(daemon): iphone_type_text replace: true works through WDA too (#162)

Qinghe Li0be5038bb015
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d1be8ce..23b0611 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,7 +12,7 @@ What changed in each release, one line per change. Versions follow [Semantic Ver
### 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_type_text` supports `replace: true` (empty text empties the field) and verifies the full field value before pressing Return. With native control, when it fails, the old text is left unselected; through WDA (iOS 26 and earlier, or `ICTL_IOS_BACKEND=wda`) the field is cleared first, so a failure there says the old text is gone (#162).
- `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.
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 31b9989..085ec01 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -12,7 +12,7 @@
### 新功能
-- 原生控制的 `iphone_type_text` 支持 `replace: true`(文字为空时清空输入框),核对替换后的输入框全文后才按回车;替换失败时会取消全选,原文保留。
+- `iphone_type_text` 支持 `replace: true`(文字为空时清空输入框),核对替换后的输入框全文后才按回车。原生控制下替换失败时会取消全选,原文保留;经 WDA(iOS 26 及以前,或 `ICTL_IOS_BACKEND=wda`)时先清空再输入,失败时会说明原文已删掉(#162)。
- `iphone_list_elements` 的结构化结果会说明匹配数量和是否被 `limit` 截断。
- `iphone_wait_for` 支持等待文字消失;读屏不完整时不会误报成功。
diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rs
index 068a12b..6d22c42 100644
--- a/crates/ictl-daemon/src/tools/input.rs
+++ b/crates/ictl-daemon/src/tools/input.rs
@@ -547,6 +547,27 @@ impl Daemon {
self.hid_paste(g, text, submit).await
}
+ /// Replaces the text of the focused field (`replace: true`; empty `text` empties it), and presses Return only once
+ /// the field reads back as exactly `text`: through WDA ([`wda_replace`]), or natively ([`Daemon::native_replace`])
+ pub(crate) async fn replace_text(&self, g: &mut Inner, text: &str, submit: bool) -> crate::error::Result<String> {
+ self.ensure_unlocked(g).await?;
+ let native = self.native(g);
+ if let Some(w) = self.wda(g) {
+ match wda_replace(w, text, submit).await {
+ Ok(m) => return Ok(m),
+ Err(WdaReplace::Failed(e)) => return Err(e),
+ // WDA went away before anything was changed
+ Err(WdaReplace::Untouched(e)) if !native => return Err(e.into()),
+ Err(WdaReplace::Untouched(_)) => {}
+ }
+ }
+ if native {
+ return Box::pin(self.native_replace(g, text, submit)).await;
+ }
+ // no HID way: the field can't be read without WDA
+ Err(wda_down(&g.state, g.info.as_ref()).into())
+ }
+
/// HID 输入中文等按不出来的文字:经剪贴板粘贴([`ictl_device::Tunnel::paste_text`])。
///
/// 手机会弹「允许粘贴」,WDA 不可用时读不到界面、点不了,交给调用方截图去点;剪贴板一改弹窗就消失,所以原来的内容
@@ -668,6 +689,175 @@ pub(super) async fn wait_scrolled(w: &mut WdaClient<DeviceTransport>, vertical:
}
}
+/// Why a replacement through WDA ([`wda_replace`]) stopped
+pub(super) enum WdaReplace {
+ /// WDA didn't take a request before anything was changed: natively it can still be done
+ Untouched(WdaError),
+ Failed(crate::error::Error),
+}
+
+/// After a replacement through WDA, the field is read back this many times, [`READBACK_EVERY`] apart, until it holds
+/// the text (the tree may lag the field a little)
+const READBACK_TRIES: u32 = 5;
+const READBACK_EVERY: Duration = Duration::from_millis(300);
+
+/// Field types that can be replaced: readable text. A password field can't be read back, so it is refused
+const REPLACEABLE: [&str; 3] = ["TextField", "SearchField", "TextView"];
+
+/// Replaces the focused field's text through WDA: the focused element (`/element/active`), WDA's clear, the new
+/// text as keys, and the same element read back; Return only once it holds exactly `text`. Unlike native control
+/// (select all, then paste over the selection), the old text is gone once cleared: a failure after that says so
+pub(super) async fn wda_replace<T: ictl_wda::http::Transport>(
+ w: &mut WdaClient<T>,
+ text: &str,
+ submit: bool,
+) -> Result<String, WdaReplace> {
+ use WdaReplace::{Failed, Untouched};
+ // not sent: nothing changed
+ let untouched = |e: WdaError| match e {
+ WdaError::Unavailable(_) => Untouched(e),
+ e => Failed(e.into()),
+ };
+ if !w.keyboard_shown().await.map_err(untouched)? {
+ return Err(Failed(
+ ictl_l10n::tr!(
+ "屏幕上没有键盘,先点一下要替换的输入框",
+ "No keyboard on screen; tap the field you want to replace first"
+ )
+ .into(),
+ ));
+ }
+ let field = match w.focused_field().await.map_err(untouched)? {
+ Some(f) if REPLACEABLE.contains(&f.kind.as_str()) => f,
+ Some(f) if f.kind == "SecureTextField" => {
+ return Err(Failed(
+ ictl_l10n::tr!(
+ "获得焦点的是密码框,读不出内容、核对不了,没有替换",
+ "The focused field is a password field: it can't be read back, so nothing was replaced"
+ )
+ .into(),
+ ));
+ }
+ Some(f) => {
+ return Err(Failed(
+ ictl_l10n::trf!(
+ "获得焦点的是 {},不是普通输入框,没有替换",
+ "The focused element is a {}, not a text field; nothing was replaced",
+ f.kind
+ )
+ .into(),
+ ));
+ }
+ None => {
+ return Err(Failed(
+ ictl_l10n::tr!(
+ "无法确认当前聚焦的是可读的普通输入框,没有替换文字",
+ "Couldn't identify a readable focused text field; no text was replaced"
+ )
+ .into(),
+ ));
+ }
+ };
+ let old = w.field_text(&field).await.map_err(untouched)?;
+ let mut note = String::new();
+ if old != text {
+ let gone = ictl_l10n::tr!("原来的文字已经删掉了", "the old text is gone");
+ let not_submitted = if submit { ictl_l10n::tr!(",没有按回车", ", Return not pressed") } else { "" };
+ if !old.is_empty() {
+ w.clear(&field.id).await.map_err(|e| match e {
+ WdaError::Unavailable(_) => Untouched(e),
+ e => Failed(
+ ictl_l10n::trf!(
+ "清空输入框失败({e}),原来的文字可能已经删掉了一部分{not_submitted};截图确认",
+ "Emptying the field failed ({e}); some of the old text may be gone{not_submitted}; check with a screenshot"
+ )
+ .into(),
+ ),
+ })?;
+ }
+ if !text.is_empty() {
+ w.keys(text).await.map_err(|e| {
+ Failed(
+ ictl_l10n::trf!(
+ "{gone},输入新文字失败({e}){not_submitted};截图确认",
+ "{gone}, typing the new text failed ({e}){not_submitted}; check with a screenshot"
+ )
+ .into(),
+ )
+ })?;
+ }
+ let unread = |e: WdaError| {
+ Failed(
+ ictl_l10n::trf!(
+ "{gone},替换后读不回输入框({e}){not_submitted};截图确认",
+ "{gone}, and the field couldn't be read back after the replacement ({e}){not_submitted}; check with a screenshot"
+ )
+ .into(),
+ )
+ };
+ let mut now = String::new();
+ for attempt in 0..READBACK_TRIES {
+ if attempt > 0 {
+ tokio::time::sleep(READBACK_EVERY).await;
+ }
+ now = w.field_text(&field).await.map_err(unread)?;
+ if now == text {
+ break;
+ }
+ }
+ // the app dropped the last characters (as typing sees, `verify_typed`): typed again one by one
+ if now != text
+ && let Some(rest) = text.strip_prefix(now.as_str()).filter(|r| !r.is_empty() && !now.is_empty())
+ {
+ for c in rest.chars() {
+ w.keys(&c.to_string()).await.map_err(unread)?;
+ tokio::time::sleep(Duration::from_millis(150)).await;
+ }
+ let k = rest.chars().count();
+ note = ictl_l10n::trf!(
+ "(第一次有 {k} 个字没输进去,已补上)",
+ " ({k} characters were dropped the first time and typed again)"
+ );
+ now = w.field_text(&field).await.map_err(unread)?;
+ }
+ if now != text {
+ return Err(Failed(
+ ictl_l10n::trf!(
+ "{gone},但输入框里现在是「{now}」,和要替换成的「{text}」对不上{not_submitted};截图确认后再处理",
+ "{gone}, but the field now holds “{now}”, which doesn't match “{text}”{not_submitted}; check with a screenshot before going on"
+ )
+ .into(),
+ ));
+ }
+ }
+ if submit {
+ w.keys("\n").await.map_err(|e| {
+ Failed(
+ ictl_l10n::trf!(
+ "已替换为「{text}」{note},按回车失败:{e}",
+ "Replaced the field with “{text}”{note}, pressing Return failed: {e}"
+ )
+ .into(),
+ )
+ })?;
+ }
+ Ok(replaced(text, submit, &note))
+}
+
+/// What a replacement that went through says ([`Daemon::replace_text`])
+pub(super) fn replaced(text: &str, submit: bool, note: &str) -> String {
+ let n = text.chars().count();
+ match (n, submit) {
+ (0, true) => ictl_l10n::trf!("已清空输入框{note},并按了回车", "Emptied the field{note} and pressed Return"),
+ (0, false) => ictl_l10n::trf!("已清空输入框{note}", "Emptied the field{note}"),
+ (_, true) => ictl_l10n::trf!(
+ "已替换为 {n} 个字符{note},并按了回车",
+ "Replaced the field with {n} characters{note} and pressed Return"
+ ),
+ (_, false) => ictl_l10n::trf!("已替换为 {n} 个字符{note}", "Replaced the field with {n} characters{note}"),
+ }
+}
+
/// How a missed `iphone_tap_element` result starts: the Chinese prefixes are fixed because MCP servers before 0.1.5
/// recognise them; new ones read [`crate::protocol::Outcome`] instead. Goes in 0.3.0
/// ([`crate::protocol::TEXT_FALLBACK_UNTIL`])
@@ -748,3 +938,170 @@ pub(super) async fn verify_typed(w: &mut WdaClient<DeviceTransport>, text: &str)
None => Typed::Unknown,
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::Mutex;
+
+ /// A WDA with one focused field
+ struct Fake(Mutex<Field>);
+
+ struct Field {
+ keyboard: bool,
+ kind: &'static str,
+ placeholder: &'static str,
+ value: String,
+ /// characters the app drops from the end of the next keys
+ drop_next: usize,
+ /// what the app makes of typed text
+ mangle: fn(&str) -> String,
+ /// the field doesn't answer at all (WDA gone)
+ gone: bool,
+ /// requests as `METHOD path`, and the text of every `/wda/keys`
+ seen: Vec<String>,
+ keys: Vec<String>,
+ }
+
+ impl Fake {
+ fn new(kind: &'static str, value: &str) -> Self {
+ Self(Mutex::new(Field {
+ keyboard: true,
+ kind,
+ placeholder: "搜索",
+ value: value.into(),
+ drop_next: 0,
+ mangle: str::to_owned,
+ gone: false,
+ seen: vec![],
+ keys: vec![],
+ }))
+ }
+ }
+
+ impl ictl_wda::http::Transport for &Fake {
+ async fn send(
+ &self,
+ method: &str,
+ path: &str,
+ body: Option<Vec<u8>>,
+ _: Duration,
+ ) -> std::io::Result<(u16, Vec<u8>)> {
+ let mut f = self.0.lock().unwrap();
+ if f.gone {
+ return Err(std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "refused"));
+ }
+ f.seen.push(format!("{method} {path}"));
+ let value = |v: serde_json::Value| Ok((200, serde_json::json!({ "value": v }).to_string().into_bytes()));
+ let path = path.strip_prefix("/session/S").unwrap_or(path);
+ match (method, path) {
+ ("POST", "/session") => Ok((200, br#"{"sessionId":"S"}"#.to_vec())),
+ ("POST", "/elements") => {
+ value(if f.keyboard { serde_json::json!([{"ELEMENT": "K"}]) } else { serde_json::json!([]) })
+ }
+ ("GET", "/element/active") => value(serde_json::json!({"ELEMENT": "F"})),
+ ("GET", "/element/F/attribute/type") => value(format!("XCUIElementType{}", f.kind).into()),
+ ("GET", "/element/F/attribute/placeholderValue") => value(f.placeholder.into()),
+ // an empty field reads its placeholder
+ ("GET", "/element/F/attribute/value") => {
+ value(if f.value.is_empty() { f.placeholder.into() } else { f.value.clone().into() })
+ }
+ ("POST", "/element/F/clear") => {
+ f.value.clear();
+ value(serde_json::Value::Null)
+ }
+ ("POST", "/wda/keys") => {
+ let body: serde_json::Value = serde_json::from_slice(&body.unwrap()).unwrap();
+ let typed: String = body["value"].as_array().unwrap().iter().map(|c| c.as_str().unwrap()).collect();
+ f.keys.push(typed.clone());
+ if typed != "\n" {
+ let keep = typed.chars().count().saturating_sub(std::mem::take(&mut f.drop_next));
+ let typed: String = typed.chars().take(keep).collect();
+ let typed = (f.mangle)(&typed);
+ f.value.push_str(&typed);
+ }
+ value(serde_json::Value::Null)
+ }
+ _ => Ok((404, br#"{"value":{"error":"unknown command","message":"no route"}}"#.to_vec())),
+ }
+ }
+ }
+
+ async fn replace(f: &Fake, text: &str, submit: bool) -> Result<String, String> {
+ let mut w = WdaClient::new(f);
+ wda_replace(&mut w, text, submit).await.map_err(|e| match e {
+ WdaReplace::Untouched(e) => format!("untouched: {e}"),
+ WdaReplace::Failed(e) => e.to_string(),
+ })
+ }
+
+ #[tokio::test]
+ async fn replaces_the_focused_field_then_presses_return() {
+ let f = Fake::new("SearchField", "wifi");
+ assert_eq!(replace(&f, "蓝牙", true).await.unwrap(), "已替换为 2 个字符,并按了回车");
+ let f = f.0.into_inner().unwrap();
+ assert_eq!(f.value, "蓝牙");
+ assert_eq!(f.keys, ["蓝牙", "\n"]);
+ assert!(f.seen.contains(&"POST /session/S/element/F/clear".to_owned()), "{:?}", f.seen);
+ }
+
+ #[tokio::test]
+ async fn empty_text_empties_the_field() {
+ let f = Fake::new("TextField", "wifi");
+ assert_eq!(replace(&f, "", false).await.unwrap(), "已清空输入框");
+ let f = f.0.into_inner().unwrap();
+ assert_eq!((f.value.as_str(), f.keys.len()), ("", 0));
+ }
+
+ /// The field already holds the text (or, emptying, reads its placeholder): nothing is cleared or typed
+ #[tokio::test]
+ async fn a_field_holding_the_text_is_left_alone() {
+ for (value, text) in [("wifi", "wifi"), ("", "")] {
+ let f = Fake::new("SearchField", value);
+ replace(&f, text, true).await.unwrap();
+ let f = f.0.into_inner().unwrap();
+ assert!(!f.seen.iter().any(|s| s.ends_with("/clear")), "{:?}", f.seen);
+ assert_eq!(f.keys, ["\n"]);
+ }
+ }
+
+ #[tokio::test]
+ async fn dropped_last_characters_are_typed_again() {
+ let f = Fake::new("TextField", "old");
+ f.0.lock().unwrap().drop_next = 2;
+ let r = replace(&f, "故宫博物院", false).await.unwrap();
+ assert!(r.contains("2 个字没输进去"), "{r}");
+ assert_eq!(f.0.into_inner().unwrap().value, "故宫博物院");
+ }
+
+ /// A field that doesn't read back as the text: Return isn't pressed, and the old text is said to be gone
+ #[tokio::test]
+ async fn a_mismatch_is_refused_without_return() {
+ let f = Fake::new("TextField", "wifi");
+ f.0.lock().unwrap().mangle = |s| s.to_uppercase();
+ let e = replace(&f, "bluetooth", true).await.unwrap_err();
+ assert!(e.contains("原来的文字已经删掉了") && e.contains("BLUETOOTH") && e.contains("没有按回车"), "{e}");
+ assert!(!f.0.into_inner().unwrap().keys.contains(&"\n".to_owned()));
+ }
+
+ #[tokio::test]
+ async fn password_fields_and_missing_keyboards_are_refused_untouched() {
+ let f = Fake::new("SecureTextField", "secret");
+ assert!(replace(&f, "x", true).await.unwrap_err().contains("密码框"));
+ let f = f.0.into_inner().unwrap();
+ assert_eq!((f.value.as_str(), f.keys.len()), ("secret", 0));
+
+ let f = Fake::new("TextField", "wifi");
+ f.0.lock().unwrap().keyboard = false;
+ assert!(replace(&f, "x", false).await.unwrap_err().starts_with("屏幕上没有键盘"));
+ assert!(!f.0.into_inner().unwrap().seen.iter().any(|s| s.contains("/element/active")));
+ }
+
+ /// WDA unreachable before anything was done: another way may still replace the text
+ #[tokio::test]
+ async fn an_unreachable_wda_leaves_the_field_untouched() {
+ let f = Fake::new("TextField", "wifi");
+ f.0.lock().unwrap().gone = true;
+ assert!(replace(&f, "x", false).await.unwrap_err().starts_with("untouched"));
+ }
+}
diff --git a/crates/ictl-daemon/src/tools/native.rs b/crates/ictl-daemon/src/tools/native.rs
index 711fbff..2562c0d 100644
--- a/crates/ictl-daemon/src/tools/native.rs
+++ b/crates/ictl-daemon/src/tools/native.rs
@@ -25,7 +25,7 @@ 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
+/// How long a field emptied by [`Daemon::native_replace`] 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);
@@ -666,12 +666,9 @@ 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<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?;
+ /// Replaces a single focused, readable field natively ([`Daemon::replace_text`]). Verifies the full value before
+ /// sending Return
+ pub(crate) async fn native_replace(&self, g: &mut Inner, text: &str, submit: bool) -> crate::error::Result<String> {
let before = self.ax_snapshot(g, AX_WAIT, false).await?;
if !keyboard_up(&self.snapshot_tree(g, &before).await?) {
return Err(ictl_l10n::tr!(
@@ -721,16 +718,7 @@ impl Daemon {
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"),
- })
+ Ok(input::replaced(text, submit, ""))
}
/// After select all and Delete: `target` reads as empty within [`CLEAR_WAIT`]
diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs
index 7e4122e..0f01d46 100644
--- a/crates/ictl-mcp/src/lib.rs
+++ b/crates/ictl-mcp/src/lib.rs
@@ -419,18 +419,18 @@ WDA 不可用时改用 CoreDevice HID(iOS 27 起;结果里注明「经 HID」)
t(
"iphone_type_text",
action_desc(
- ictl_l10n::tr!("在当前获得焦点的输入框里输入文字(支持中文),默认从光标处输入。原生控制可用 replace=true 替换当前普通输入框的全文(text 为空时清空)。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 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)."),
+WDA 不可用时改用 HID(iOS 27 起):美式键盘上的英文和符号直接按键;中文等经剪贴板粘贴,手机会弹「允许粘贴」,要截图后点它才粘得进去(剪贴板 45 秒后还原)。", "Type text into the focused text field (any language, including Chinese) at the cursor by default. replace=true replaces the contents of a readable focused field (empty text empties it), and presses Return only once the field reads back as exactly the text. 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")},
+ "replace": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("替换当前聚焦输入框的全文,text 为空时清空输入框。仅普通可读输入框(不含密码框);经 WDA 时先清空再输入,失败时原来的文字已删掉;默认在光标处输入", "replace all text in the focused field; with empty text, empty it. Readable fields only (not password fields); through WDA the field is emptied first, so after a failure the old text is gone; defaults to typing at the cursor")},
"submit": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("输完后按回车(搜索、发送、提交)", "press Return afterwards (search, send, submit)")}
})),
&["text"],
diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rs
index 026cb76..a3beaae 100644
--- a/crates/ictl-wda/src/client.rs
+++ b/crates/ictl-wda/src/client.rs
@@ -214,9 +214,26 @@ pub fn detection_point(screen: ScreenSize) -> (u32, u32) {
}
/// 改变手机状态的请求:没有应答时要结束会话,免得它和排在它后面的请求过一阵才执行(见 [`WdaClient::in_session`])。
-/// 读的请求(GET、`POST /elements` 找元素)不算:排在读后面的东西不会动手机,结束会话只会让下一次开会话也排到它后面
+/// 读的请求(GET、`POST /element`、`POST /elements` 找元素)不算:排在读后面的东西不会动手机,结束会话只会让下一次开会话
+/// 也排到它后面。对元素的操作(`POST /element/:id/clear`)算
fn acts(method: &str, path: &str) -> bool {
- method != "GET" && !path.starts_with("/element")
+ method != "GET" && !path.ends_with("/element") && !path.ends_with("/elements")
+}
+
+/// The element a find or `/element/active` answered: `{"ELEMENT": id, "element-6066-…": id}`
+fn element_id(v: &Value) -> Option<String> {
+ let o = v.as_object()?;
+ o.get("ELEMENT").or_else(|| o.values().next())?.as_str().map(str::to_owned)
+}
+
+/// The element with keyboard focus ([`WdaClient::focused_field`])
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct FocusedField {
+ /// WDA's id for it (`/element/:id/…`)
+ pub id: String,
+ /// The type without `XCUIElementType`: `TextField`, `SearchField`, `TextView`, `SecureTextField`…
+ pub kind: String,
+ pub placeholder: String,
}
/// 正常响应和远端错误都证明请求获得了回答;连接失败则不算。
@@ -976,6 +993,45 @@ impl<T: Transport> WdaClient<T> {
Ok(v.as_array().is_some_and(|a| !a.is_empty()))
}
+ /// The element with keyboard focus (`GET /element/active`); None when no element has it
+ pub async fn focused_field(&mut self) -> Result<Option<FocusedField>> {
+ let v = match self.in_session("GET", "/element/active", None, DEFAULT_TIMEOUT).await {
+ Ok(v) => v,
+ Err(WdaError::Remote { kind, .. }) if kind.contains("no such element") => return Ok(None),
+ Err(e) => return Err(e),
+ };
+ let Some(id) = element_id(&v) else { return Ok(None) };
+ let kind = self.attribute(&id, "type").await?;
+ let kind = kind.strip_prefix("XCUIElementType").unwrap_or(&kind).to_owned();
+ let placeholder = self.attribute(&id, "placeholderValue").await?;
+ Ok(Some(FocusedField { id, kind, placeholder }))
+ }
+
+ /// An attribute of an element as text; a missing one (`null`) reads as empty
+ pub async fn attribute(&mut self, id: &str, name: &str) -> Result<String> {
+ let v = self.in_session("GET", &format!("/element/{id}/attribute/{name}"), None, DEFAULT_TIMEOUT).await?;
+ Ok(match v {
+ Value::String(s) => s,
+ Value::Null => String::new(),
+ other => other.to_string(),
+ })
+ }
+
+ /// What the field holds: an empty field reads its placeholder as its value (Spotlight's reads «搜索»), so that
+ /// counts as empty, as with native control
+ pub async fn field_text(&mut self, f: &FocusedField) -> Result<String> {
+ let v = self.attribute(&f.id, "value").await?;
+ Ok(if !f.placeholder.is_empty() && v == f.placeholder { String::new() } else { v })
+ }
+
+ /// Empties a field (`POST /element/:id/clear`): WDA deletes the text with the keyboard until the field reads
+ /// empty, and answers an error when it doesn't (some custom fields)
+ pub async fn clear(&mut self, id: &str) -> Result<()> {
+ self.in_session("POST", &format!("/element/{id}/clear"), Some(json!({})), Duration::from_secs(60))
+ .await
+ .map(drop)
+ }
+
pub async fn keys(&mut self, text: &str) -> Result<()> {
let chars: Vec<String> = text.chars().map(String::from).collect();
self.in_session("POST", "/wda/keys", Some(json!({"value": chars})), Duration::from_secs(120)).await.map(drop)
@@ -1738,6 +1794,53 @@ mod tests {
assert_eq!(m.seen.lock().unwrap()[2].1, "/session/S/element/E1/attribute/value");
}
+ #[tokio::test]
+ async fn focused_field_reads_its_type_and_placeholder() {
+ let m = Mock::with(&[
+ (200, r#"{"sessionId":"S"}"#),
+ (200, r#"{"value":{"ELEMENT":"F1","element-6066-11e4-a52e-4f735466cecf":"F1"}}"#),
+ (200, r#"{"value":"XCUIElementTypeSearchField"}"#),
+ (200, r#"{"value":"搜索"}"#),
+ // empty: reads its placeholder
+ (200, r#"{"value":"搜索"}"#),
+ (200, r#"{"value":"wifi"}"#),
+ ]);
+ let mut c = WdaClient::new(&m);
+ let f = c.focused_field().await.unwrap().unwrap();
+ assert_eq!(f, FocusedField { id: "F1".into(), kind: "SearchField".into(), placeholder: "搜索".into() });
+ assert_eq!(c.field_text(&f).await.unwrap(), "");
+ assert_eq!(c.field_text(&f).await.unwrap(), "wifi");
+ let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect();
+ assert_eq!(
+ paths[1..4],
+ [
+ "/session/S/element/active",
+ "/session/S/element/F1/attribute/type",
+ "/session/S/element/F1/attribute/placeholderValue"
+ ]
+ );
+ }
+
+ #[tokio::test]
+ async fn no_focused_element_is_none() {
+ let m = Mock::with(&[
+ (200, r#"{"sessionId":"S"}"#),
+ (404, r#"{"value":{"error":"no such element","message":"No element is in focus"}}"#),
+ ]);
+ assert_eq!(WdaClient::new(&m).focused_field().await.unwrap(), None);
+ }
+
+ /// Finding elements reads; clearing one changes the phone (its session is ended when it doesn't answer)
+ #[test]
+ fn element_finds_read_and_element_edits_act() {
+ assert!(!acts("POST", "/elements"));
+ assert!(!acts("POST", "/element"));
+ assert!(!acts("POST", "/element/E1/elements"));
+ assert!(!acts("GET", "/element/active"));
+ assert!(acts("POST", "/element/E1/clear"));
+ assert!(acts("POST", "/wda/keys"));
+ }
+
#[test]
fn actions_body_is_one_pointer_with_steps() {
let b = actions_body(&tap_steps(10.0, 20.0, 80));
diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md
index f06dac7..ea066b1 100644
--- a/docs/dev/regression-cases.md
+++ b/docs/dev/regression-cases.md
@@ -165,3 +165,4 @@
| 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` |
+| 162 | 经 WDA 控制(iOS 26 及以前,或 `ICTL_IOS_BACKEND=wda`)时 `replace: true` 直接拒绝,调用方只能在光标处输入,得到 `wifi 蓝牙` | 经 WDA 取聚焦元素(`/element/active`),只接受普通可读输入框(密码框拒绝),WDA `clear` 后按键输入,读回同一个元素的全文一致才按回车,结尾丢字补一次;空输入框读出占位文字算空;清空后再失败时明说原文已删掉;WDA 在动手前就连不上时,原生控制可用则改走原生 | 单测 `replaces_the_focused_field_then_presses_return`、`a_mismatch_is_refused_without_return`、`focused_field_reads_its_type_and_placeholder` + 真机脚本 `scenarios.py editing`(WDA 设备) |
diff --git a/docs/tools.md b/docs/tools.md
index 1f3596f..9db17d2 100644
--- a/docs/tools.md
+++ b/docs/tools.md
@@ -22,7 +22,7 @@ Coordinates are in **points**, the same unit as the pixels of a full-screen `iph
| `iphone_tap_element` | `text`, `index` (default 0), `scroll` (`down` / `up`), `max_scrolls` (default 8, max 15) | Exact label or name first, then substring. If the element's center is covered (floating toolbar, keyboard, overlay), taps an uncovered part of it; if it is fully covered, does not tap and says so. With `scroll`, when it isn't on screen (or is fully covered) it scrolls a slow third of the screen at a time without momentum and looks again, until it is found, the screen stops changing (the end of the list) or `max_scrolls` is reached; the result says how many scrolls it took |
| `iphone_long_press` | `x`, `y`, `seconds` (default 1, max 10) | Holds one finger still, then lifts: context menus, home-screen quick actions, text selection |
| `iphone_swipe` | `from_x`, `from_y`, `to_x`, `to_y`, `seconds` (default 0.3, max 10), `hold` (default 0) | Returns after the list has stopped scrolling (up to 2.5 s). Swipe up (`from_y` > `to_y`) to see content further down. `hold` holds the finger still at the start for that many seconds before moving, to drag things that have to be long-pressed first (home-screen icons, reorderable rows); about 0.6 works, under 0.5 usually doesn't pick anything up. `seconds` + `hold` is at most 10 |
-| `iphone_type_text` | `text`, `submit` (default false) | Types into the focused field (Chinese supported); fails if no keyboard is shown. Reads the field back afterwards: dropped trailing characters are typed again; if the field still doesn't match, it reports an error and does not press Return |
+| `iphone_type_text` | `text`, `replace` (default false), `submit` (default false) | Types into the focused field (Chinese supported); fails if no keyboard is shown. Reads the field back afterwards: dropped trailing characters are typed again; if the field still doesn't match, it reports an error and does not press Return. `replace: true` replaces the whole text of a readable focused field (not a password field), and empty `text` empties it; Return is pressed only once the field reads back as exactly the text. Natively the old text is selected and pasted over, and a failure leaves it there; through WDA the field is cleared first, so after a failure the old text is gone |
| `iphone_press_button` | `button`: `home`, `volume_up`, `volume_down`, `lock` | `home` refuses to act while a system alert is on screen (it would have no effect). `home` is sent as an IOHID AC Home event and waits until the home screen is in front; `lock` presses the power key over IOHID. Each falls back to the XCTest/WebDriverAgent way if it had no effect |
| `iphone_launch_app` | `app` (bundle id or display name, e.g. `设置`) | Cold-launches the app, or brings it back to where it was if it is already running. Waits until it is in the foreground; returns early and says so if a system alert is blocking it |
| `iphone_terminate_app` | `app` | Force-quits, like swiping it away in the app switcher; unsaved input is lost. No error if it wasn't running |
diff --git a/tests/device/scenarios.py b/tests/device/scenarios.py
index 0c6fff2..a6d28a7 100644
--- a/tests/device/scenarios.py
+++ b/tests/device/scenarios.py
@@ -14,7 +14,7 @@ Scenarios (the numbers are regression cases):
selecting the device already selected, an enlarged region (#16), then=screenshot
typing typing with no keyboard up is refused and types nothing (#32); the same text typed twice into
Spotlight counts as typed the second time too (#143)
- editing replace and empty focused text on native iOS (#159), read element-limit metadata (#160),
+ editing replace and empty focused text, natively (#159) and through WDA (#162), read element-limit metadata (#160),
and wait for a visible Clock tab to disappear (#161)
fresh a tap right after a cold start isn't swallowed (#13); then=elements shows the page after the tap,
not the one before (#125)
@@ -203,32 +203,29 @@ def spotlight_queries(text: str) -> list[str]:
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})
+ 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"})
- 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)
+ 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)
await p.ok(c, "iphone_launch_app", {"app": dev.CLOCK})
tabs = await p.clock_tabs(c)