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

fix(daemon): a paste over the same selected text isn't reported as failed (#133)

Qinghe Lia5b8106db54b
diff --git a/crates/ictl-daemon/src/devices.rs b/crates/ictl-daemon/src/devices.rs
index e2b72b6..cbc53c1 100644
--- a/crates/ictl-daemon/src/devices.rs
+++ b/crates/ictl-daemon/src/devices.rs
@@ -196,9 +196,14 @@ impl Daemon {
"; this device has no auto-unlock passcode, so unlock it by hand when locked (run iphone-control passcode set while it is connected)"
)
};
+ let wait = if self.cfg.ios_backend.drives_natively(Some(&target)) {
+ ictl_l10n::tr!("原生控制几秒就绪", "native control is ready in seconds")
+ } else {
+ ictl_l10n::tr!("WDA 起来要 10~60 秒", "WDA takes 10-60 seconds to start")
+ };
Ok(ictl_l10n::trf!(
- "已切换到 {label},之后固定控制这台。状态:{};WDA 起来要 10~60 秒,先用 iphone-control status 或 iphone_status 确认就绪{pin}",
- "Switched to {label}; it stays selected from now on. State: {}; WDA takes 10-60 seconds to start, check readiness with iphone-control status or iphone_status first{pin}",
+ "已切换到 {label},之后固定控制这台。状态:{};{wait},先用 iphone-control status 或 iphone_status 确认就绪{pin}",
+ "Switched to {label}; it stays selected from now on. State: {}; {wait}, check readiness with iphone-control status or iphone_status first{pin}",
g.state.describe()
))
}
diff --git a/crates/ictl-daemon/src/tools/native.rs b/crates/ictl-daemon/src/tools/native.rs
index 5b31771..a3c522a 100644
--- a/crates/ictl-daemon/src/tools/native.rs
+++ b/crates/ictl-daemon/src/tools/native.rs
@@ -20,6 +20,10 @@ pub(crate) const AX_WAIT: Duration = Duration::from_secs(5);
const REACT: Duration = Duration::from_millis(300);
/// After Cmd-V: how long for the text to show in the field, answering the paste prompt meanwhile
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
+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);
/// How long a killed app's processes may take to be gone
@@ -38,6 +42,31 @@ fn native_for(backend: IosBackend, info: Option<&DeviceInfo>) -> bool {
backend.drives_natively(info)
}
+/// What a paste did, as far as the fields show
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Pasted {
+ /// A field changed and now holds the text
+ Typed,
+ /// A field held the text before and still does, unchanged: the paste replaced the same text, or didn't go in
+ Unchanged,
+ /// A password field is on screen: its value can't be read
+ Unreadable,
+ /// No field holds the text
+ Missing,
+}
+
+/// One read of the fields after a paste, against `old`, theirs before it (None: a password field)
+fn paste_seen(now: Option<&[String]>, old: Option<&[String]>, wanted: &str) -> Pasted {
+ let (Some(now), Some(old)) = (now, old) else { return Pasted::Unreadable };
+ if !now.iter().any(|v| v.contains(wanted)) {
+ Pasted::Missing
+ } else if now != old {
+ Pasted::Typed
+ } else {
+ Pasted::Unchanged
+ }
+}
+
/// The on-screen keyboard is up: a Keyboard element, or its keys (the keyboard's process reads as the app's own
/// elements at times, then no Keyboard is made of them, `ictl_ax::xml`)
fn keyboard_up(tree: &Tree) -> bool {
@@ -516,15 +545,21 @@ impl Daemon {
note += ictl_l10n::tr!("(已替你点了「允许粘贴」)", " (“Allow Paste” was tapped for you)");
}
match typed {
- Some(true) => {}
- // a password field: its value can't be read
- None => {
+ Pasted::Typed => {}
+ Pasted::Unreadable => {
note += ictl_l10n::tr!(
"(这是密码框,读不出内容,截图确认输进去了)",
" (a password field: its contents can't be read back, check with a screenshot)"
)
}
- Some(false) => {
+ // the same text, selected, replaced by the paste (a search field keeping the last search)
+ Pasted::Unchanged => {
+ note += ictl_l10n::tr!(
+ "(输入框里原来就是这段文字,粘贴后看不出变化,截图确认)",
+ " (the field already held this text, so the paste shows no change; check with a screenshot)"
+ )
+ }
+ Pasted::Missing => {
return Err(ictl_l10n::trf!(
"粘贴了 {n} 个字符,但 {} 秒内输入框里没有这段文字{};截图看看:输入框可能没有焦点,或 App 不接受粘贴",
"Pasted {n} characters, but the field didn't show the text within {} s{}; take a screenshot: the field may not have focus, or the app doesn't take pastes",
@@ -548,14 +583,14 @@ 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 whether it showed (None: can't be read) and whether the paste prompt was answered. The
- /// pasteboard is put back before returning
+ /// on screen). Returns what the fields show and whether the paste prompt was answered. The pasteboard is put
+ /// back before returning
async fn native_paste(
&self,
g: &mut Inner,
text: &str,
old: Option<&[String]>,
- ) -> crate::error::Result<(Option<bool>, bool)> {
+ ) -> crate::error::Result<(Pasted, bool)> {
// a paste through the WDA-down path may still wait to be put back
self.restore_pasteboard(g, false).await;
self.hid(g).await?;
@@ -570,7 +605,8 @@ impl Daemon {
}
};
let deadline = Instant::now() + PASTE_WAIT;
- let mut prompt = false;
+ // when the paste prompt was last answered
+ let mut answered: Option<Instant> = None;
let wanted = text.trim();
let typed = loop {
// a whole read: the prompt brings SpringBoard to the front, but it may also come over the app (a read
@@ -578,21 +614,23 @@ impl Daemon {
let tree = self.ax_tree(g, AX_WAIT).await?;
if let Some((x, y)) = paste_allow(&tree) {
self.native_tap(g, x, y).await?;
- prompt = true;
+ answered = Some(Instant::now());
tokio::time::sleep(Duration::from_millis(300)).await;
continue;
}
- let now = elements::field_values(&tree.elements);
- match (&now, old) {
- (Some(now), Some(old)) if now.as_slice() != old && now.iter().any(|v| v.contains(wanted)) => {
- break Some(true);
- }
- (None, _) | (_, None) if Instant::now() >= deadline => break None,
- _ if Instant::now() >= deadline => break Some(false),
+ 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,
@@ -834,4 +872,18 @@ mod tests {
let other = elements::parse_tree(&xml("“备忘录”想从“微信”粘贴"), screen);
assert_eq!(paste_allow(&other), None);
}
+
+ #[test]
+ fn a_paste_that_replaced_the_same_text_is_told_apart_from_one_that_missed() {
+ let v = |s: &[&str]| s.iter().map(|s| s.to_string()).collect::<Vec<_>>();
+ // into an empty field, and after text already there
+ assert_eq!(paste_seen(Some(&v(&["设置"])), Some(&v(&[""])), "设置"), Pasted::Typed);
+ assert_eq!(paste_seen(Some(&v(&["设置设置"])), Some(&v(&["设置"])), "设置"), Pasted::Typed);
+ // Spotlight's last search, selected, replaced by the same text: nothing changes
+ assert_eq!(paste_seen(Some(&v(&["设置"])), Some(&v(&["设置"])), "设置"), Pasted::Unchanged);
+ assert_eq!(paste_seen(Some(&v(&["时钟"])), Some(&v(&["时钟"])), "设置"), Pasted::Missing);
+ assert_eq!(paste_seen(Some(&v(&[""])), Some(&v(&[""])), "设置"), Pasted::Missing);
+ assert_eq!(paste_seen(None, Some(&v(&[""])), "设置"), Pasted::Unreadable);
+ assert_eq!(paste_seen(Some(&v(&["设置"])), None, "设置"), Pasted::Unreadable);
+ }
}
diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md
index cf95628..4373bf2 100644
--- a/docs/dev/regression-cases.md
+++ b/docs/dev/regression-cases.md
@@ -146,3 +146,4 @@
| 140 | 开着后台启动(`ICTL_WDA_DETACHED=1`)用过 WDA、再切回原生控制:之前后台启动的 WDA 一直在手机上运行,state.json 里也一直记着它。原来结束它用的 DVT `kill_app` 对 WDA 无效(WDA 模式下关掉开关时,随后用 XCTest 会话启动的 WDA 会顶替它,所以那条路看不出问题) | 原生准备手机时(开发者镜像好了之后)结束记下的那个 WDA;结束一律走 AppService 的 SIGKILL,等它从进程列表消失(最多 2 秒)再忘掉;结束不了就留着记录,下次准备时再试 | 真机(切 WDA 让后台 WDA 起来,再切回原生,看日志和 state.json) |
| 141 | 开着后台启动(`ICTL_WDA_DETACHED=1`)时 `iphone-control service stop`、`service uninstall` 之后,后台启动的 WDA 还在手机上运行(它本来就不随守护进程退出,好让重启、升级不打断它),一直占着 8100 端口 | `service stop`/`uninstall` 停掉服务后(还有守护进程应答时不动),对接着的手机逐个结束记下的后台 WDA(AppService SIGKILL,等它从进程列表消失),忘掉结束了的;没接着、结束不了的留着记录,守护进程下次准备这台手机时处理。`service restart`、升级照旧不结束 | 单测 `only_the_wda_runner_with_that_pid_is_wda` + 真机(`service stop` 后进程列表里没有 WDA、记录清空;`restart` 后接上原进程) |
| 142 | 开着后台启动时切换设备:`state.json` 只记一条后台 WDA,切到另一台就被覆盖,原来那台手机上的 WDA 没人记着、继续运行,切回去时只能重新后台启动 | 每台设备各记一条(`detached_wdas`,按 UDID),切回去直接接上;最近一条照旧写进 `detached_wda` 给旧版本;旧版本留下的那一条在记下别的设备之前先迁进新表 | 单测 `each_device_keeps_its_background_wda`、`an_older_versions_background_wda_is_still_known` + 真机(iPhone ↔ iPad 来回切,日志是「接上…没有重新启动」) |
+| 143 | 原生:Spotlight 打开时选中上次的搜索词,再粘贴同样的词会把它替换成自己,输入框的值不变,`iphone_type_text` 报「粘贴了…但输入框里没有这段文字」(带 `submit` 时还不按回车),其实已经输进去了 | 「允许粘贴」点过之后,输入框原来就有这段文字、1.5 秒不变,算输入成功并提示截图确认;没点过「允许粘贴」时仍报错 | 单测 `a_paste_that_replaced_the_same_text_is_told_apart_from_one_that_missed` + 真机(Spotlight 留着「设置」时再输入「设置」,`run.py` 连跑两遍)|