Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools
Rust ai-agentautomationclaudeclaude-codedockeriosiphonelinuxmcpmcp-servermodel-context-protocolrustwebdriveragent
HID pastes non-ASCII text; WDA drops actions it didn't answer and reads huge trees with limits (#118)
Qinghe Lidb73215e4e01
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dd9447f..999a257 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,12 +6,18 @@ All notable changes to this project are documented here. The format is based on## [Unreleased]+### Added++- While WebDriverAgent is unavailable, `iphone_type_text` can enter Chinese and other text a US keyboard can't type: HID puts it on the phone's pasteboard (CoreDevice `pasteboardservice`, checked by reading it back) and presses Cmd-V, so the input method doesn't turn it into pinyin. iOS treats that text as coming from another app and asks “… would like to paste from dtpasteboardd” every time (iPhone 15 Pro Max, iOS 27.2.1, Notes); the answer says to take a screenshot and tap “Allow Paste”. Changing the pasteboard closes that prompt, so what was on it before is put back 45 s later (or before the next such paste, or when another device is chosen), and only if the pasted text is still there. Return isn't pressed with `submit`, since with the prompt up it would choose “Don't Allow Paste”. English letters and symbols are still typed as keys and don't touch the pasteboard.+### Fixed- A tap or swipe a minute or more after the last one no longer waits for the screen size to be measured again first: that takes WDA 0.95 s on an iPad mini 5 (iPadOS 26.7.3), where the first tap after a pause took 1.7 s instead of 0.9. The size is now measured again in the background while nobody acts (only Display Zoom changes it), and on rotation as before.- A control page whose H.264 or the phone's own video didn't show a first frame within 9 s (the viewer or daemon restarting, the encoder starting up) used MJPEG until it was reloaded; it now tries again after 30 s, 1 min and 2 min. A picture the viewer said isn't available still isn't tried again.- A swipe on the control page through WDA no longer waits for the list to stop before answering (reading the element tree again and again, up to 2.5 s): the person at the page sees it. On an iPad mini 5 a swipe took 3.1 s, now 1.6–2.3 s. Agents (MCP, CLI) still wait, so their next tap doesn't land on a moving list.- The way Home and locking work on each device is kept in `state.json` instead of only in memory. After the daemon restarted, or another device was controlled meanwhile, the first Home on a device where IOHID's Home doesn't work tried it, waited 2 s for the home screen and pressed again: 4.4 s instead of 0.8 on an iPad mini 5.+- A tap, swipe, key or launch that WebDriverAgent didn't answer in time no longer carries on later. WDA handles requests one at a time and keeps going after we stop waiting, so an action queued behind a slow one could land on the screen long after it was reported as failed. The daemon now ends that WDA session at once (`DELETE /session`, which WDA 16.15.3 answers outside its queue and which drops what is still queued in it) and opens a new one for the next action. A read that times out keeps its session.+- Reading the element tree of a screen with very many elements (long feeds and lists) no longer keeps taking as long. A read over 8 s, or one that times out, makes the next read ask WDA for a smaller snapshot (at most 150 children per element first, then half the depth and children, down to 12 levels and 60 children); a read under 1.5 s loosens it a step again. While the tree is cut short, `iphone_list_elements` and a `iphone_tap_element` that finds nothing say so.## [0.2.6] - 2026-11-14diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex a55f395..4da619c 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -6,12 +6,18 @@## [Unreleased]+### 新增++- WebDriverAgent 不可用时,`iphone_type_text` 也能输入中文等美式键盘按不出来的文字:经 HID 把它写进手机剪贴板(CoreDevice `pasteboardservice`,写完读回核对),再按 Cmd-V,输入法不会把它当成拼音。iOS 把这段文字当成别的 App 的,每次都会问「…想从“dtpasteboardd”粘贴」(iPhone 15 Pro Max、iOS 27.2.1 的备忘录实测);结果里会提示截图后点「允许粘贴」。剪贴板一改这个弹窗就消失,所以原来的内容 45 秒后才写回(下一次这样粘贴前、换设备时也会写回),而且只在剪贴板里还是粘贴的那段文字时才写。带 `submit` 时不按回车:弹窗还在时回车会选中「不允许粘贴」。英文和符号仍然逐键输入,不动剪贴板。+### 修复- 隔了一分钟以上的点按、滑动不再先等重新读屏幕尺寸:iPad mini 5(iPadOS 26.7.3)上 WDA 读一次要 0.95 秒,停一会儿后的第一次点按要 1.7 秒,平时 0.9 秒。尺寸现在在没人操作时于后台重读(只有「显示缩放」会改变它),转屏时照旧马上重读。- 控制台页面的 H.264 或手机自己的视频 9 秒内没出第一帧时(控制台服务或守护进程正在重启、编码器正在启动),原来一直用 MJPEG 直到刷新页面;现在 30 秒、1 分钟、2 分钟后各再试一次。控制台服务明确说不可用的画面仍然不再试。- 控制台上经 WDA 的滑动不再等列表停下才返回(原来要反复读元素树,最多 2.5 秒):页面前的人看得见。iPad mini 5 上一次滑动从 3.1 秒降到 1.6–2.3 秒。Agent(MCP、命令行)仍然等,免得下一次点击落在还在滚的列表上。- 每台设备按 Home 和锁屏该用哪种方式,现在记在 `state.json` 里,不再只放在内存。原来守护进程重启或中途控制过别的设备后,在 IOHID 的 Home 不起作用的设备上,第一次按 Home 会先用 IOHID 按,等 2 秒没回到主屏幕再补按一次:iPad mini 5 上要 4.4 秒,平时 0.8 秒。+- WebDriverAgent 没有及时应答的点击、滑动、按键、启动 App,不会再过一阵才执行。WDA 一个一个处理请求,我们不等了它还会接着做,排在慢请求后面的动作可能在报了失败之后很久才落到屏幕上。现在守护进程马上结束那个 WDA 会话(`DELETE /session`:WDA 16.15.3 不排队处理它,还会丢掉这个会话里还在排队的请求),下一个动作开新会话。读超时不结束会话。+- 元素特别多的界面(很长的信息流、列表)读元素树不再一直那么慢。一次读超过 8 秒或超时,下一次就让 WDA 少读一些(先限每个元素最多 150 个子元素,再把层数和子元素数减半,最少 12 层、60 个);读得快于 1.5 秒就放宽一级。元素树被截短时,`iphone_list_elements` 和没找到元素的 `iphone_tap_element` 会说明。## [0.2.6] - 2026-11-14diff --git a/apps/iphone-control/src/debug.rs b/apps/iphone-control/src/debug.rsindex e05173e..d1c164c 100644--- a/apps/iphone-control/src/debug.rs+++ b/apps/iphone-control/src/debug.rs@@ -30,6 +30,16 @@ enum Check {},/// 2. HID:媒体流 + universalhidservice tap,再按 Home(以截图对比为准,调用成功不代表生效)Hid { x: f64, y: f64 },+ /// 2a. HID 键盘:逐键输入美式键盘按得出来的文字(先在手机上点中一个输入框,以截图为准)+ Type { text: String },+ /// 2b. HID 粘贴:存下剪贴板、写入文字、按 Cmd-V,等一会再还原剪贴板(先在手机上点中一个输入框;+ /// 手机会弹「允许粘贴」,要在还原之前点掉,以截图为准)+ Paste {+ text: String,+ /// 按完 Cmd-V 后等几秒还原剪贴板+ #[arg(long, default_value_t = 30)]+ restore_after: u64,+ },/// 3. 截图:screencaptureservice PNGScreenshot { out: PathBuf },/// 4. 隧道稳定性:同一条隧道持续截图 N 分钟@@ -246,6 +256,42 @@ pub async fn run(udid: Option<&str>, args: DebugArgs) -> anyhow::Result<()> {));}+ Check::Type { text } => {+ let mut t = device.open_tunnel().await?;+ let r = async {+ let hid = t.hid(screen, ictl_device::FULL_BITRATE).await?;+ hid.type_ascii(&text).await+ }+ .await;+ t.close().await;+ r?;+ println!("{}", ictl_l10n::tr!("已发出按键", "Keys sent"));+ }+ Check::Paste { text, restore_after } => {+ let mut t = device.open_tunnel().await?;+ let r = async {+ t.hid(screen, ictl_device::FULL_BITRATE).await?;+ let pending = t.paste_text(&text).await?;+ println!(+ "{}",+ ictl_l10n::trf!(+ "已按 Cmd-V:在手机上点「允许粘贴」,{restore_after} 秒后还原剪贴板",+ "Cmd-V pressed: tap “Allow Paste” on the phone; the pasteboard is restored in {restore_after} s"+ )+ );+ tokio::time::sleep(Duration::from_secs(restore_after)).await;+ Ok::<_, ictl_device::DeviceError>(match pending {+ Some(p) => format!("{:?}", t.restore_pasteboard(p).await),+ None => {+ ictl_l10n::tr!("原来的剪贴板没存下,不还原", "The old pasteboard wasn't saved; not restored")+ .into()+ }+ })+ }+ .await;+ t.close().await;+ println!("{}", r?);+ }Check::Screenshot { out } => {let mut t = device.open_tunnel().await?;let t0 = Instant::now();diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex 8af3e21..6d90fae 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -364,6 +364,8 @@ pub(crate) struct PerDevice {pub apps: HashMap<bool, Vec<AppInfo>>,/// Log capture for `AppLogs` (developer tools), started by the first requestpub log_capture: Option<crate::devtools::Capture>,+ /// HID 粘贴前存下的剪贴板和粘贴的时间,等着写回([`Daemon::restore_pasteboard`])+ pub pending_paste: Option<(Instant, ictl_device::PendingRestore)>,}pub(crate) struct Inner {@@ -711,6 +713,10 @@ impl Daemon {/// 不再控制当前这台(断开、重新接入、换设备):停掉它的会话,清掉关于它的一切pub(crate) async fn forget_device(&self, g: &mut Inner) {+ // 还连着就先把 HID 粘贴前的剪贴板写回去:之后就没人管它了+ if g.dev.pending_paste.is_some() && g.tunnel.is_some() {+ self.restore_pasteboard(g, false).await;+ }self.drop_session(g).await;g.dev = PerDevice::default();}diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rsindex 41665a4..b35f94a 100644--- a/crates/ictl-daemon/src/supervise.rs+++ b/crates/ictl-daemon/src/supervise.rs@@ -113,6 +113,7 @@ impl Daemon {));}+ self.restore_pasteboard(g, true).await;self.poll_start(g).await;let devices = match ictl_device::list_devices().await {diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rsindex 05283cd..568f8f2 100644--- a/crates/ictl-daemon/src/tools/input.rs+++ b/crates/ictl-daemon/src/tools/input.rs@@ -155,10 +155,11 @@ impl Daemon {let tree = self.tree(g, max_age).await?;let matches = elements::find(&tree.elements, text);if matches.is_empty() {+ let limited = self.snapshot_note(g);return Ok((ictl_l10n::trf!(- "{}包含 \"{text}\" 的元素,先用 iphone_list_elements 或截图看看屏幕",- "{}: no element contains \"{text}\"; look at the screen with iphone_list_elements or a screenshot first",+ "{}包含 \"{text}\" 的元素,先用 iphone_list_elements 或截图看看屏幕{limited}",+ "{}: no element contains \"{text}\"; look at the screen with iphone_list_elements or a screenshot first{limited}",tap_missed_prefixes()[0]),true,@@ -321,16 +322,95 @@ impl Daemon {}}let payload = if submit { format!("{text}\n") } else { text.to_owned() };- // 先检查,一个都不输;不打开 HID 会话- if let Some(c) = payload.chars().find(|c| ascii_to_usage(*c).is_none()) {- return Err(ictl_l10n::trf!(- "WDA 不可用,HID 只能输入美式键盘上的英文和符号,不能输入 {c:?}",- "WDA unavailable; HID can only type English letters and symbols of a US keyboard, not {c:?}"+ // 美式键盘按得出来的直接按键,不动剪贴板+ if payload.chars().all(|c| ascii_to_usage(c).is_some()) {+ self.hid_do(g, move |h| Box::pin(async move { h.type_ascii(&payload).await })).await?;+ return Ok(ictl_l10n::trf!("已输入 {n} 个字符(经 HID)", "Typed {n} characters (via HID)"));+ }+ self.hid_paste(g, text, submit).await+ }++ /// HID 输入中文等按不出来的文字:经剪贴板粘贴([`ictl_device::Tunnel::paste_text`])。+ ///+ /// 手机会弹「允许粘贴」,WDA 不可用时读不到界面、点不了,交给调用方截图去点;剪贴板一改弹窗就消失,所以原来的内容+ /// 先存在守护进程里,[`PASTE_RESTORE_AFTER`] 后由巡检写回(下一次粘贴前、换设备前也会写回,见 [`Daemon::restore_pasteboard`])。+ /// 弹窗还在时按回车会选中「不允许粘贴」,所以要回车也不按,让调用方粘上以后再按+ async fn hid_paste(&self, g: &mut Inner, text: &str, submit: bool) -> crate::error::Result<String> {+ let n = text.chars().count();+ self.restore_pasteboard(g, false).await;+ self.hid(g).await?;+ let r = g.tunnel.as_mut().expect("hid() 刚建好隧道").paste_text(text).await;+ g.hid_used = Some(Instant::now());+ let pending = match r {+ Ok(p) => p,+ Err(e @ DeviceError::InvalidInput(_)) => return Err(e.into()),+ Err(e) => {+ drop_tunnel(g).await;+ return Err(ictl_l10n::trf!("HID 粘贴失败:{e}", "HID paste failed: {e}").into());+ }+ };+ let saved = pending.is_some();+ g.dev.pending_paste = pending.map(|p| (Instant::now(), p));+ let secs = PASTE_RESTORE_AFTER.as_secs();+ let clipboard = if saved {+ ictl_l10n::trf!(+ "剪贴板原来的内容 {secs} 秒后还原,还原后这个弹窗会消失(那时还没点就要重新输入)",+ "the pasteboard's old contents are put back in {secs} s, which closes that prompt (if it is still up then, type the text again)"+ )+ } else {+ ictl_l10n::tr!(+ "剪贴板原来的内容读不出来或不能原样写回,之后剪贴板里留着这段文字",+ "the pasteboard's old contents couldn't be read or written back as they were, so it keeps this text")- .into());+ .into()+ };+ let enter = if submit {+ ictl_l10n::tr!(+ "。没有按回车(弹窗还在时回车会选中「不允许粘贴」):粘上以后用 iphone_type_text 输入 \"\\n\" 按回车",+ ". Return wasn't pressed (with the prompt up it would choose “Don't Allow Paste”): once the text is in, type \"\\n\" with iphone_type_text"+ )+ } else {+ ""+ };+ Ok(ictl_l10n::trf!(+ "已按 Cmd-V 粘贴 {n} 个字符(经 HID 和剪贴板;WDA 不可用,读不到界面)。手机会弹「…想从“dtpasteboardd”粘贴」:截图,点「允许粘贴」文字才会进去(点「不允许粘贴」就不粘),再截图确认;{clipboard}{enter}",+ "Pressed Cmd-V to paste {n} characters (via HID and the pasteboard; WDA is unavailable, so the screen can't be read). The phone asks “… would like to paste from dtpasteboardd”: take a screenshot and tap “Allow Paste” to let the text in (“Don't Allow Paste” keeps it out), then check with another screenshot; {clipboard}{enter}"+ ))+ }++ /// 把 HID 粘贴前存下的剪贴板写回去([`Self::hid_paste`])。`due_only`:只在粘贴过了 [`PASTE_RESTORE_AFTER`] 时写+ /// (巡检用)。写回失败不重试:剪贴板不归我们管,留着粘贴的文字比反复改它好+ pub(crate) async fn restore_pasteboard(&self, g: &mut Inner, due_only: bool) {+ let Some((at, _)) = &g.dev.pending_paste else { return };+ if due_only && at.elapsed() < PASTE_RESTORE_AFTER {+ return;+ }+ let Some((_, p)) = g.dev.pending_paste.take() else { return };+ let Some(device) = g.device.clone() else { return };+ let r = match self.ensure_tunnel(g, &device).await {+ Ok(t) => t.restore_pasteboard(p).await,+ Err(e) => ClipboardRestore::Failed(e.to_string()),+ };+ match r {+ ClipboardRestore::Restored => tracing::info!(+ "{}",+ ictl_l10n::log_tr!("HID 粘贴前的剪贴板已还原", "Pasteboard from before the HID paste restored")+ ),+ ClipboardRestore::ChangedMeanwhile => tracing::info!(+ "{}",+ ictl_l10n::log_tr!(+ "HID 粘贴后剪贴板被改过,没有还原",+ "The pasteboard changed after the HID paste; not restored"+ )+ ),+ ClipboardRestore::Failed(e) => tracing::warn!(+ "{}",+ ictl_l10n::log_trf!(+ "还原 HID 粘贴前的剪贴板失败:{e}",+ "Restoring the pasteboard from before the HID paste failed: {e}"+ )+ ),}- self.hid_do(g, move |h| Box::pin(async move { h.type_ascii(&payload).await })).await?;- Ok(ictl_l10n::trf!("已输入 {n} 个字符(经 HID)", "Typed {n} characters (via HID)"))}}diff --git a/crates/ictl-daemon/src/tools/mod.rs b/crates/ictl-daemon/src/tools/mod.rsindex 3eaf282..7cbab5d 100644--- a/crates/ictl-daemon/src/tools/mod.rs+++ b/crates/ictl-daemon/src/tools/mod.rs@@ -8,7 +8,9 @@ mod observe;use std::time::{Duration, Instant};use base64::Engine;-use ictl_device::{AppInfo, Button, DeviceError, HidSession, Rotation, ScreenSize, apps, hid::ascii_to_usage};+use ictl_device::{+ AppInfo, Button, ClipboardRestore, DeviceError, HidSession, Rotation, ScreenSize, apps, hid::ascii_to_usage,+};use ictl_unlock::UnlockError;use ictl_wda::client::SPRINGBOARD;use ictl_wda::elements::{self, TapPoint, Tree};@@ -38,9 +40,11 @@ const SCROLL_SETTLE: Duration = Duration::from_millis(2500);/// 滑动时读到的树这么久之内还能当 settle 比较的起点const SWIPED_TREE_FRESH: Duration = Duration::from_secs(1);/// WDA 不可用时 status 里说明哪些功能用不了-const NEEDS_WDA: &str = "读界面元素、按名字点击、启动 App、输入中文要等 WDA 恢复";-const NEEDS_WDA_EN: &str =- "reading elements, tapping by text, launching apps and typing non-ASCII text wait until WDA is back";+const NEEDS_WDA: &str =+ "读界面元素、按名字点击、启动 App 要等 WDA 恢复;输入中文改经剪贴板粘贴,要点手机弹出的「允许粘贴」";+const NEEDS_WDA_EN: &str = "reading elements, tapping by text and launching apps wait until WDA is back; non-ASCII text is pasted through the pasteboard instead, which needs a tap on the phone's “Allow Paste” prompt";+/// HID 粘贴后过这么久还原剪贴板:留时间给调用方截图、点「允许粘贴」(Poki 等 45 秒)+pub(crate) const PASTE_RESTORE_AFTER: Duration = Duration::from_secs(45);/// 按 Home 后最多等这么久,确认主屏到了前台(iPhone 12 mini 上 IOHID 的 Home 约 1.3~1.5 秒)const HOME_SETTLE: Duration = Duration::from_secs(2);/// 按电源键后最多等这么久,等 WDA 报锁屏(iPhone 12 mini 实测约 1 秒)diff --git a/crates/ictl-daemon/src/tools/observe.rs b/crates/ictl-daemon/src/tools/observe.rsindex 4cbc619..a2396cb 100644--- a/crates/ictl-daemon/src/tools/observe.rs+++ b/crates/ictl-daemon/src/tools/observe.rs@@ -52,7 +52,16 @@ impl Daemon {} else {String::new()};- Ok((if lines.is_empty() { no_elements_text(filter, els.len()) } else { lines.join("\n") } + &more, data))+ let limited = self.snapshot_note(g);+ Ok((+ if lines.is_empty() { no_elements_text(filter, els.len()) } else { lines.join("\n") } + &more + &limited,+ data,+ ))+ }++ /// 上一次读的元素树受了快照上限的限制时,接在结果后面的说明(含换行);没有限制时为空+ pub(super) fn snapshot_note(&self, g: &mut Inner) -> String {+ self.wda(g).and_then(|w| w.snapshot_note()).map(|n| format!("\n{n}")).unwrap_or_default()}/// 等界面稳定,最多等 `max`:diff --git a/crates/ictl-device/src/hid.rs b/crates/ictl-device/src/hid.rsindex 27e341f..cbbc6be 100644--- a/crates/ictl-device/src/hid.rs+++ b/crates/ictl-device/src/hid.rs@@ -103,6 +103,9 @@ pub fn ascii_to_usage(c: char) -> Option<(u64, bool)> {}const KEY_LEFT_SHIFT: u64 = 0xE1;+/// 左 Command(HID usage Left GUI)+const KEY_LEFT_GUI: u64 = 0xE3;+const KEY_V: u64 = 0x19;pub struct HidSession {/// 设备竖放时的尺寸:HID 触摸坐标按竖放归一化@@ -220,6 +223,24 @@ impl HidSession {limit(ictl_l10n::tr!("HID 输入", "HID typing"), d, self.send_keys(keys)).await}+ /// 按 Cmd-V(硬件键盘的粘贴):按住 Cmd,按一下 V,松开 Cmd。手机不确认收到,粘没粘上只能看屏幕+ /// (iPhone16,2 / iOS 27.2.1 实测会触发粘贴,见 [`crate::Tunnel::paste_text`])+ pub async fn paste_shortcut(&mut self) -> Result<()> {+ limit(ictl_l10n::tr!("HID 粘贴", "HID paste"), Duration::from_secs(10), async {+ self.indigo.send_keyboard(KEY_LEFT_GUI, ButtonState::Down).await?;+ let r = async {+ self.indigo.send_keyboard(KEY_V, ButtonState::Down).await?;+ self.indigo.send_keyboard(KEY_V, ButtonState::Up).await+ }+ .await;+ // V 没发出去也要松开 Cmd:一直按着的话,后面的按键都会变成快捷键+ let up = self.indigo.send_keyboard(KEY_LEFT_GUI, ButtonState::Up).await;+ r?;+ Ok(up?)+ })+ .await+ }+async fn send_keys(&mut self, keys: Vec<(u64, bool)>) -> Result<()> {for (usage, shift) in keys {if shift {diff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rsindex 231da8a..02ae077 100644--- a/crates/ictl-device/src/lib.rs+++ b/crates/ictl-device/src/lib.rs@@ -6,6 +6,7 @@//! - 开发者镜像:`cryptexd::installed_ddi` / `install_ddi`(个性化 + TSS);DDI 下载见 [`ddi`]//! - HID:universalhidservice(触摸)、indigo(按键、键盘);**必须同时持有显示媒体流**([`hid::HidSession`])//! - 截图:CoreDevice screencaptureservice+//! - 剪贴板:CoreDevice pasteboardservice,HID 粘贴非 ASCII 文字用([`Tunnel::paste_text`])//! - App:installation_proxy(列出时过滤 `SBAppTags` 含 `hidden` 的后台服务,见 [`apps`])、安装 IPA//!//! 不负责:WDA(见 `ictl-wda`)、状态机(见 `ictl-daemon`)。@@ -16,6 +17,7 @@ pub mod hid;mod media;mod models;pub mod oslog;+mod pasteboard;use std::future::Future;use std::path::Path;@@ -556,6 +558,40 @@ impl Device {}}+/// [`Tunnel::restore_pasteboard`] 的结果+#[derive(Debug, Clone, PartialEq)]+pub enum ClipboardRestore {+ /// 原来的内容已经写回+ Restored,+ /// 粘贴后剪贴板被别人改过:不覆盖,留着现在的内容+ ChangedMeanwhile,+ Failed(String),+}++/// [`Tunnel::paste_text`] 存下的原剪贴板,等粘贴弹窗答完再写回([`Tunnel::restore_pasteboard`])+#[derive(Debug, Clone)]+pub struct PendingRestore {+ items: Vec<pasteboard::Item>,+ /// 粘贴用的文字和写进去后的改动计数:剪贴板还是它,才说明期间没人改过+ text: String,+ change_count: Option<i64>,+}++async fn write_back(+ adapter: &mut AdapterHandle,+ handshake: &mut RsdHandshake,+ items: &[pasteboard::Item],+) -> ClipboardRestore {+ match limit(ictl_l10n::tr!("还原剪贴板", "restore the pasteboard"), Duration::from_secs(10), async {+ pasteboard::write(adapter, handshake, items).await+ })+ .await+ {+ Ok(()) => ClipboardRestore::Restored,+ Err(e) => ClipboardRestore::Failed(e.to_string()),+ }+}+/// 一条活着的隧道。HID、截图、cryptexd 都经它访问 RSD 服务;丢掉它隧道就断了。////// HID 会话归隧道所有:它持有屏幕媒体流,必须在隧道断开之前停掉,否则手机端一直挂着这个会话@@ -621,6 +657,86 @@ impl Tunnel {self.hid.as_mut()}+ /// 经剪贴板输入文字(HID 后备路线输入中文等非 ASCII 用),HID 会话要已经开着([`Self::hid`]):+ ///+ /// 1. 存下原来的剪贴板(读不出来、或有不能原样写回的内容时照样粘贴,只是不还原:返回 None)+ /// 2. 写入 `text`,读回核对;对不上就不粘贴,报错+ /// 3. 按 Cmd-V。整段一次粘贴,中文输入法不会把它当成拼音+ ///+ /// iOS 把经 `dtpasteboardd` 写入的内容当成别的 App 的,Cmd-V 也要用户确认:App 弹出「“备忘录”想从“dtpasteboardd”+ /// 粘贴」,点「允许粘贴」才粘进去(iPhone16,2 / iOS 27.2.1 的备忘录,每次都弹)。剪贴板一改,这个弹窗就消失,什么也+ /// 不粘,所以这里不还原:调用方等弹窗答完再用返回的 [`PendingRestore`] 调 [`Self::restore_pasteboard`]。+ /// 手机不确认按键,没有输入框获得焦点时什么也粘不上,结果要看屏幕+ pub async fn paste_text(&mut self, text: &str) -> Result<Option<PendingRestore>> {+ let Tunnel { adapter, handshake, hid } = self;+ let Some(hid) = hid.as_mut() else {+ return Err(DeviceError::InvalidInput(ictl_l10n::tr!("HID 会话没开", "The HID session isn't open").into()));+ };+ if !pasteboard::supported(handshake) {+ return Err(DeviceError::InvalidInput(+ ictl_l10n::tr!(+ "手机没有提供剪贴板服务,HID 不能输入非 ASCII 文字",+ "The phone offers no pasteboard service, so HID can't type non-ASCII text"+ )+ .into(),+ ));+ }+ // 读不出来不影响粘贴;连接卡住时别等太久+ let saved = limit(ictl_l10n::tr!("读剪贴板", "read the pasteboard"), Duration::from_secs(5), async {+ pasteboard::read(adapter, handshake).await+ })+ .await+ .ok()+ .and_then(|c| c.items);+ let ours = pasteboard::text_items(text);+ let written = limit(ictl_l10n::tr!("写剪贴板", "write the pasteboard"), Duration::from_secs(10), async {+ pasteboard::write(adapter, handshake, &ours).await?;+ pasteboard::read(adapter, handshake).await+ })+ .await+ .map_err(|e| {+ DeviceError::Idevice(ictl_l10n::trf!(+ "文字写不进剪贴板,没有粘贴:{e}",+ "The text couldn't be put on the pasteboard; nothing was pasted: {e}"+ ))+ })?;+ if written.text.as_deref() != Some(text) {+ // 还没粘贴,马上写回+ if let Some(items) = &saved {+ write_back(adapter, handshake, items).await;+ }+ return Err(DeviceError::Idevice(+ ictl_l10n::tr!(+ "文字写进剪贴板后读回来对不上,没有粘贴",+ "The text read back from the pasteboard didn't match what was written; nothing was pasted"+ )+ .into(),+ ));+ }+ hid.paste_shortcut().await.map_err(|e| {+ DeviceError::Idevice(ictl_l10n::trf!(+ "按 Cmd-V 失败(可能已经按下,先截图确认):{e}",+ "Pressing Cmd-V failed (it may have gone through; take a screenshot first): {e}"+ ))+ })?;+ Ok(saved.map(|items| PendingRestore { items, text: text.to_owned(), change_count: written.change_count }))+ }++ /// 把 [`Self::paste_text`] 存下的原剪贴板写回去。剪贴板已经不是粘贴的那段文字(期间有人复制了别的)就不动它+ pub async fn restore_pasteboard(&mut self, p: PendingRestore) -> ClipboardRestore {+ let now = limit(ictl_l10n::tr!("读剪贴板", "read the pasteboard"), Duration::from_secs(5), async {+ pasteboard::read(&mut self.adapter, &mut self.handshake).await+ })+ .await;+ match now {+ Ok(now) if now.text.as_deref() != Some(p.text.as_str()) || now.change_count != p.change_count => {+ ClipboardRestore::ChangedMeanwhile+ }+ Ok(_) => write_back(&mut self.adapter, &mut self.handshake, &p.items).await,+ Err(e) => ClipboardRestore::Failed(e.to_string()),+ }+ }+/// 停掉 HID 会话(含屏幕媒体流),隧道保留pub async fn close_hid(&mut self) {if let Some(h) = self.hid.take() {diff --git a/crates/ictl-device/src/pasteboard.rs b/crates/ictl-device/src/pasteboard.rsnew file mode 100644index 0000000..ae90912--- /dev/null+++ b/crates/ictl-device/src/pasteboard.rs@@ -0,0 +1,226 @@+//! 手机的剪贴板:CoreDevice `com.apple.coredevice.pasteboardservice`(RemoteXPC,经隧道,免签名)。+//!+//! HID 后备路线用它输入中文等美式键盘按不出来的文字([`crate::Tunnel::paste_text`]):先存下用户原来的剪贴板,+//! 写入要输入的文字并读回核对,按 Cmd-V 粘贴,再把原来的剪贴板写回去。+//!+//! 读用 idevice 的 [`PasteboardServiceClient`];写原来的内容要原样写回每一项、每一种类型,idevice 只提供写一段文字或一张+//! 图片,所以写由本模块自己发 `SET`(字段和 idevice `pasteboard_service.rs` 相同)。每次读写各开一条连接:上一条连接上+//! 晚到的 `PULL_REPLY` 不会被当成 `SET_REPLY`。剪贴板的内容不写日志。++use std::borrow::Cow;++use idevice::{+ IdeviceError, ReadWrite, RemoteXpcClient, RsdService,+ core_device::{+ DataInclusionPolicy, GENERAL_PASTEBOARD, PasteboardPayload, PasteboardServiceClient, PasteboardSnapshot,+ },+ rsd::RsdHandshake,+ tcp::handle::AdapterHandle,+ xpc::{Dictionary, XPCObject},+};++use crate::Result;++const SERVICE: &str = "com.apple.coredevice.pasteboardservice";++/// 写文字时声明的类型,和 idevice 的 `set_text` 一样+const TEXT_UTIS: [&str; 3] = ["public.utf8-plain-text", "public.plain-text", "public.text"];++/// 剪贴板里的一项:声明的类型(按优先顺序)和每种类型的数据+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct Item {+ pub types: Vec<String>,+ pub data: Vec<(String, Vec<u8>)>,+}++/// 读到的剪贴板+#[derive(Debug, Clone)]+pub(crate) struct Contents {+ /// 每改一次加一。设备没给时为 None+ pub change_count: Option<i64>,+ /// 第一段文字(只看直接带着数据的项)+ pub text: Option<String>,+ /// 能原样写回时的全部内容:每一项的每种类型都直接带着数据。有「承诺」(要另外取的数据)或取数据出错的项时为 None+ pub items: Option<Vec<Item>>,+}++impl Contents {+ fn from_snapshot(s: &PasteboardSnapshot) -> Self {+ Self { change_count: s.change_count, text: s.text(), items: restorable(s) }+ }+}++/// 每一项的每种类型都直接带着数据时,按原来的顺序整理成能写回去的样子+fn restorable(s: &PasteboardSnapshot) -> Option<Vec<Item>> {+ s.items+ .iter()+ .map(|item| {+ let data = item+ .data+ .iter()+ .map(|e| match &e.payload {+ PasteboardPayload::Inline(bytes) => Some((e.uti.clone(), bytes.clone())),+ PasteboardPayload::Promised { .. } | PasteboardPayload::Error(_) => None,+ })+ .collect::<Option<Vec<_>>>()?;+ // 声明了类型却没给数据:写回去就少了,不算能还原+ if item.types.iter().any(|t| !data.iter().any(|(uti, _)| uti == t)) {+ return None;+ }+ Some(Item { types: item.types.clone(), data })+ })+ .collect()+}++/// 只有一段文字的剪贴板内容+pub(crate) fn text_items(text: &str) -> Vec<Item> {+ vec![Item {+ types: TEXT_UTIS.iter().map(|t| (*t).to_owned()).collect(),+ data: TEXT_UTIS.iter().map(|t| ((*t).to_owned(), text.as_bytes().to_vec())).collect(),+ }]+}++/// `SET` 消息:用 `items` 替换整个通用剪贴板+fn set_message(items: &[Item]) -> XPCObject {+ let items = items+ .iter()+ .map(|item| {+ let mut data = Dictionary::new();+ for (uti, bytes) in &item.data {+ let mut payload = Dictionary::new();+ payload.insert("data".into(), XPCObject::Data(bytes.clone()));+ data.insert(uti.clone(), XPCObject::Dictionary(payload));+ }+ let mut d = Dictionary::new();+ d.insert("types".into(), XPCObject::Array(item.types.iter().cloned().map(XPCObject::String).collect()));+ d.insert("data".into(), XPCObject::Dictionary(data));+ XPCObject::Dictionary(d)+ })+ .collect();+ let mut msg = Dictionary::new();+ msg.insert("command".into(), XPCObject::String("SET".into()));+ msg.insert("pasteboardName".into(), XPCObject::String(GENERAL_PASTEBOARD.into()));+ msg.insert("items".into(), XPCObject::Array(items));+ msg.insert("sourceMetadata".into(), XPCObject::Null);+ XPCObject::Dictionary(msg)+}++/// 只用来发 `SET` 的连接+struct Writer(RemoteXpcClient<Box<dyn ReadWrite>>);++impl RsdService for Writer {+ fn rsd_service_name() -> Cow<'static, str> {+ Cow::Borrowed(SERVICE)+ }++ async fn from_stream(stream: Box<dyn ReadWrite>) -> std::result::Result<Self, IdeviceError> {+ let mut inner = RemoteXpcClient::new(stream).await?;+ inner.do_handshake().await?;+ Ok(Self(inner))+ }+}++/// 读通用剪贴板。`matchSource`:数据是不是直接带着由放进去的 App 决定,不让手机现取每一项+/// (`allResolved` 遇到别的 App 承诺的大数据可能要等很久)+pub(crate) async fn read(adapter: &mut AdapterHandle, handshake: &mut RsdHandshake) -> Result<Contents> {+ let mut c: PasteboardServiceClient<Box<dyn ReadWrite>> =+ PasteboardServiceClient::connect_rsd(adapter, handshake).await?;+ let s = c.get_with_policy(GENERAL_PASTEBOARD, DataInclusionPolicy::MatchSource).await?;+ Ok(Contents::from_snapshot(&s))+}++/// 用 `items` 替换通用剪贴板+pub(crate) async fn write(adapter: &mut AdapterHandle, handshake: &mut RsdHandshake, items: &[Item]) -> Result<()> {+ let mut w = Writer::connect_rsd(adapter, handshake).await?;+ w.0.send_object(set_message(items), true).await?;+ // SET_REPLY 不带有用的信息,读掉就行+ w.0.recv().await?;+ Ok(())+}++/// 手机是否提供剪贴板服务+pub(crate) fn supported(handshake: &RsdHandshake) -> bool {+ handshake.services.contains_key(SERVICE)+}++#[cfg(test)]+mod tests {+ use idevice::core_device::{PasteboardEntry, PasteboardItem};++ use super::*;++ fn snapshot(items: Vec<PasteboardItem>) -> PasteboardSnapshot {+ PasteboardSnapshot { pasteboard_name: Some("general".into()), change_count: Some(7), items }+ }++ fn entry(uti: &str, payload: PasteboardPayload) -> PasteboardEntry {+ PasteboardEntry { uti: uti.into(), payload }+ }++ #[test]+ fn inline_items_can_be_written_back_as_they_were() {+ let s = snapshot(vec![+ PasteboardItem {+ index: 0,+ types: vec!["public.utf8-plain-text".into(), "public.html".into()],+ data: vec![+ entry("public.utf8-plain-text", PasteboardPayload::Inline(b"hi".to_vec())),+ entry("public.html", PasteboardPayload::Inline(b"<b>hi</b>".to_vec())),+ ],+ },+ PasteboardItem {+ index: 1,+ types: vec!["public.png".into()],+ data: vec![entry("public.png", PasteboardPayload::Inline(vec![0x89, 0x50]))],+ },+ ]);+ let c = Contents::from_snapshot(&s);+ assert_eq!(c.change_count, Some(7));+ assert_eq!(c.text.as_deref(), Some("hi"));+ let items = c.items.expect("all inline");+ assert_eq!(items.len(), 2);+ assert_eq!(items[0].types, ["public.utf8-plain-text", "public.html"]);+ assert_eq!(items[1].data, [("public.png".to_owned(), vec![0x89, 0x50])]);+ }++ #[test]+ fn an_empty_pasteboard_is_written_back_empty() {+ let c = Contents::from_snapshot(&snapshot(vec![]));+ assert_eq!(c.items, Some(vec![]));+ assert_eq!(c.text, None);+ }++ #[test]+ fn promised_or_failed_data_cannot_be_written_back() {+ for payload in [PasteboardPayload::Promised { size: Some(10) }, PasteboardPayload::Error("x".into())] {+ let s = snapshot(vec![PasteboardItem {+ index: 0,+ types: vec!["public.jpeg".into()],+ data: vec![entry("public.jpeg", payload)],+ }]);+ assert!(Contents::from_snapshot(&s).items.is_none());+ }+ // a declared type with no data at all+ let s = snapshot(vec![PasteboardItem {+ index: 0,+ types: vec!["public.utf8-plain-text".into(), "public.rtf".into()],+ data: vec![entry("public.utf8-plain-text", PasteboardPayload::Inline(b"a".to_vec()))],+ }]);+ assert!(Contents::from_snapshot(&s).items.is_none());+ }++ #[test]+ fn set_message_carries_every_item_and_type() {+ let XPCObject::Dictionary(msg) = set_message(&text_items("你好")) else { panic!("not a dictionary") };+ assert!(matches!(&msg["command"], XPCObject::String(s) if s == "SET"));+ assert!(matches!(&msg["pasteboardName"], XPCObject::String(s) if s == "general"));+ assert!(matches!(msg["sourceMetadata"], XPCObject::Null));+ let XPCObject::Array(items) = &msg["items"] else { panic!("items") };+ let XPCObject::Dictionary(item) = &items[0] else { panic!("item") };+ let XPCObject::Array(types) = &item["types"] else { panic!("types") };+ assert_eq!(types.len(), 3);+ let XPCObject::Dictionary(data) = &item["data"] else { panic!("data") };+ let XPCObject::Dictionary(utf8) = &data["public.utf8-plain-text"] else { panic!("utf8") };+ assert!(matches!(&utf8["data"], XPCObject::Data(b) if b == "你好".as_bytes()));+ }+}diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rsindex d4bc2cf..ab7dfd5 100644--- a/crates/ictl-mcp/src/lib.rs+++ b/crates/ictl-mcp/src/lib.rs@@ -285,7 +285,7 @@ fn standard_tools() -> Vec<Tool> {"iphone_status",ictl_l10n::tr!("查看手机和服务的状态:WDA(WebDriverAgent)是否就绪、是否锁屏、能否自动解锁、当前前台 App 的 Bundle ID、\屏幕尺寸(点)、守护进程状态。\n\n何时用:开始操作前确认手机可用;操作报错、怀疑 WDA 掉线或手机锁屏时排查。\-WDA 不可用时会说明哪些功能受影响(读元素、按名字点击、启动 App、输入中文)。只读,不改变手机状态。", "Show the state of the phone and the service: whether WDA (WebDriverAgent) is ready, whether the phone is locked and can be auto-unlocked, the bundle ID of the foreground app, the screen size (points) and the daemon state.\n\nWhen to use: to check that the phone is usable before starting; to investigate when actions fail or WDA or the lock screen seem to be in the way. If WDA is unavailable it says which features are affected (reading elements, tapping by text, launching apps, typing non-ASCII text). Read-only, doesn't change the phone.")+WDA 不可用时会说明哪些功能受影响(读元素、按名字点击、启动 App)。只读,不改变手机状态。", "Show the state of the phone and the service: whether WDA (WebDriverAgent) is ready, whether the phone is locked and can be auto-unlocked, the bundle ID of the foreground app, the screen size (points) and the daemon state.\n\nWhen to use: to check that the phone is usable before starting; to investigate when actions fail or WDA or the lock screen seem to be in the way. If WDA is unavailable it says which features are affected (reading elements, tapping by text, launching apps). Read-only, doesn't change the phone.").into(),schema(json!({}), &[]),looking(ictl_l10n::tr!("查看状态", "Show status")),@@ -409,7 +409,7 @@ WDA 不可用时改用 CoreDevice HID(iOS 27 起;结果里注明「经 HID」)何时用:搜索框、表单、聊天框等。要先点中输入框让键盘弹出;屏幕上没有键盘时报错,什么都不输。\回车可能会发送消息或提交表单,发送前先向用户确认。\n\n\行为:输完会读回输入框核对,少了结尾几个字会自动补上;对不上就报错,也不按回车。\-WDA 不可用时改用 HID(iOS 27 起),只能输入美式键盘上的英文和符号。", "Type text into the focused text field (any language, including Chinese) at the cursor, without clearing what is already there. With submit=true it presses Return at the end.\n\nWhen to use: search boxes, forms, chat fields. Tap the field first so the keyboard comes up; with no keyboard on screen it fails and types nothing. Return may send a message or submit a form, so ask the user before sending.\n\nBehavior: it reads the field back afterwards; dropped trailing characters are typed again. If it still doesn't match, it reports an error and doesn't press Return. If WDA is unavailable it uses HID instead (iOS 27+), which can only type English letters and symbols of a US keyboard."),+WDA 不可用时改用 HID(iOS 27 起):美式键盘上的英文和符号直接按键;中文等经剪贴板粘贴,手机会弹「允许粘贴」,要截图后点它才粘得进去(剪贴板 45 秒后还原)。", "Type text into the focused text field (any language, including Chinese) at the cursor, without clearing what is already there. With submit=true it presses Return at the end.\n\nWhen to use: search boxes, forms, chat fields. Tap the field first so the keyboard comes up; with no keyboard on screen it fails and types nothing. Return may send a message or submit a form, so ask the user before sending.\n\nBehavior: it reads the field back afterwards; dropped trailing characters are typed again. If it still doesn't match, it reports an error and doesn't press Return. If WDA is unavailable it uses HID instead (iOS 27+): English letters and symbols of a US keyboard are typed as keys, anything else is pasted through the pasteboard, and the phone asks to “Allow Paste”: take a screenshot and tap it to let the text in (the pasteboard is put back after 45 s)."),ictl_l10n::tr!("已输入 4 个字符,并按了回车", "Typed 4 characters and pressed Return"),true,),diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rsindex ee07a11..a328e59 100644--- a/crates/ictl-wda/src/client.rs+++ b/crates/ictl-wda/src/client.rs@@ -80,6 +80,53 @@ impl IdleSettings {pub const NO_COOL_OFF: Self = Self { wait_for_idle_timeout: 1.0, animation_cool_off_timeout: 0.0 };}+/// 读元素树时 WDA 快照的上限:appium settings 的 `snapshotMaxDepth`、`snapshotMaxChildren`,新会话重置成 WDA 的默认+/// (50 层、子元素不限,WDA 16.15.3 `FBConfiguration resetSessionSettings`)。+///+/// 元素很多的界面(信息流、很长的列表)一次快照要很久,WDA 又在主线程上一个一个处理请求,后面的点击、截图都排在它后面。+/// 读得慢([`SLOW_SOURCE`])或超时就收紧一级,读得快([`FAST_SOURCE`])就放宽一级([`next_snapshot_level`])。+/// 先限子元素个数:长列表是宽不是深,只减层数没用;再把层数、子元素数各减一半,最少 12 层、60 个。+/// 级别和数字参考 Poki 的 PokiCore(docs/ios-core.md「A tree that times out is read again shallower」)+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct SnapshotLimits {+ pub depth: u32,+ /// None = 不限(WDA 的 `INT_MAX`)+ pub children: Option<u32>,+}++/// 从不限到最紧,[`WdaClient`] 记的是下标+pub const SNAPSHOT_LEVELS: [SnapshotLimits; 4] = [+ SnapshotLimits { depth: 50, children: None },+ SnapshotLimits { depth: 50, children: Some(150) },+ SnapshotLimits { depth: 25, children: Some(75) },+ SnapshotLimits { depth: 12, children: Some(60) },+];+/// 读一次元素树超过这么久就收紧一级。排除慢属性后平时 0.2~2 秒+pub const SLOW_SOURCE: Duration = Duration::from_secs(8);+/// 收紧过的读得比这快就放宽一级+pub const FAST_SOURCE: Duration = Duration::from_millis(1500);+/// 读元素树的时限:再长就算 WDA 卡住了(见 [`STALL_LIMIT`])+const SOURCE_TIMEOUT: Duration = Duration::from_secs(60);+/// 结束会话([`WdaClient::in_session`] 里动作没有应答时)的时限。WDA 不排队处理它,平时立刻应答+const SESSION_DELETE_TIMEOUT: Duration = Duration::from_secs(3);++/// 读完一次元素树后下次用哪一级上限:`took` 为 None 表示超时+pub fn next_snapshot_level(level: usize, took: Option<Duration>) -> usize {+ let tightest = SNAPSHOT_LEVELS.len() - 1;+ match took {+ None => (level + 1).min(tightest),+ Some(t) if t >= SLOW_SOURCE => (level + 1).min(tightest),+ Some(t) if t < FAST_SOURCE => level.saturating_sub(1),+ Some(_) => level,+ }+}++/// 改变手机状态的请求:没有应答时要结束会话,免得它和排在它后面的请求过一阵才执行(见 [`WdaClient::in_session`])。+/// 读的请求(GET、`POST /elements` 找元素)不算:排在读后面的东西不会动手机,结束会话只会让下一次开会话也排到它后面+fn acts(method: &str, path: &str) -> bool {+ method != "GET" && !path.starts_with("/element")+}+/// Frames a second and size (percent) of WDA's MJPEG stream with [`WdaClient::fast_stream`].////// Full size, so WDA passes on the JPEG that testmanagerd encodes in hardware. Any other size makes WDA decode,@@ -149,6 +196,14 @@ pub struct WdaClient<T> {fast_stream: bool,/// 经 XCTest 的请求(除 `/status` 外都是)连续几次没有应答,有应答就清零。工具调用和守护进程的探测都算unanswered: AtomicU32,+ /// 下次读元素树用的上限,[`SNAPSHOT_LEVELS`] 的下标+ snapshot_level: usize,+ /// WDA 现在用的上限。None = 不知道:这个客户端还没开过会话、也没设过;开会话时 WDA 重置成不限(0)。+ /// 不知道时按不限算,不为读树专门开会话:`ICTL_WDA_DETACHED` 下守护进程重启后接上的 WDA 若留着上一个客户端收紧的值,+ /// 第一次开会话(第一次点击、改设置)就重置了+ snapshot_applied: Option<usize>,+ /// 上一次读到的元素树用的上限([`Self::snapshot_note`])+ snapshot_read: usize,}impl<T: Transport> WdaClient<T> {@@ -164,10 +219,25 @@ impl<T: Transport> WdaClient<T> {idle_current: None,fast_stream: false,unanswered: AtomicU32::new(0),+ snapshot_level: 0,+ snapshot_applied: None,+ snapshot_read: 0,}}async fn call(&self, method: &str, path: &str, body: Option<Value>, timeout: Duration) -> Result<Value> {+ self.call_or_abandon(method, path, body, timeout, None).await+ }++ /// [`Self::call`];`abandon` 是会话号时,请求没有应答就先结束这个会话,再判断 WDA 是不是卡死了(见 [`Self::in_session`])+ async fn call_or_abandon(+ &self,+ method: &str,+ path: &str,+ body: Option<Value>,+ timeout: Duration,+ abandon: Option<&str>,+ ) -> Result<Value> {// `/status` 不经 XCTest:WDA 半死时它照样应答,不能拿它算 WDA 还活着if path == "/status" {return self.send(method, path, body, timeout).await;@@ -183,6 +253,9 @@ impl<T: Transport> WdaClient<T> {let r = self.send(method, path, body, timeout).await;match &r {Err(e) if e.no_answer() => {+ if let Some(sid) = abandon {+ self.delete_session(sid).await;+ }let n = self.unanswered.fetch_add(1, Ordering::Relaxed) + 1;// a long request went unanswered: one quick question tells a stuck WDA from a slow request, instead of// waiting the full time twice more (a tool call took 90 s before the daemon could restart it)@@ -262,6 +335,7 @@ impl<T: Transport> WdaClient<T> {.to_owned();self.session = Some(id.clone());self.idle_current = None;+ self.snapshot_applied = Some(0);if self.fast_stream {// fixOrientation explicitly off: a WDA left running in the background (`ICTL_WDA_DETACHED`) keeps what an// older version set@@ -278,7 +352,12 @@ impl<T: Transport> WdaClient<T> {Ok(id)}- /// 带会话的请求;会话失效时重建一次再试+ /// 带会话的请求;会话失效时重建一次再试。+ ///+ /// 改变手机状态的请求([`acts`])没有应答时,马上结束这个会话(`DELETE /session/:id`,WDA 16.15.3 不排队处理它):+ /// WDA 在主线程上一个一个处理请求,我们不等了它还会接着做。排在慢请求后面的点击、滑动会在报了失败之后很久才落到屏幕上+ /// (Poki 在真机上见过)。结束会话后,这个会话里还在排队的请求 WDA 直接回「会话不存在」,不再执行;正在执行的那个照样做完。+ /// 下一个请求开新会话pub async fn in_session(&mut self,method: &str,@@ -288,14 +367,35 @@ impl<T: Transport> WdaClient<T> {) -> Result<Value> {for attempt in 0..2 {let sid = self.session_id().await?;- match self.call(method, &format!("/session/{sid}{path}"), body.clone(), timeout).await {+ let abandon = acts(method, path).then_some(sid.as_str());+ let r =+ self.call_or_abandon(method, &format!("/session/{sid}{path}"), body.clone(), timeout, abandon).await;+ match r {Err(WdaError::Remote { kind, .. }) if attempt == 0 && kind.contains("session") => self.session = None,+ Err(e) if abandon.is_some() && e.no_answer() => {+ self.forget_session();+ return Err(e);+ }other => return other.map(|mut v| v["value"].take()),}}unreachable!()}+ /// 结束会话,不管结果:结束不了的会话 WDA 下次开会话时也会结束它+ async fn delete_session(&self, sid: &str) {+ // send 而不是 call:WDA 卡死时也要发,也不算进卡死计数+ if let Err(e) = self.send("DELETE", &format!("/session/{sid}"), None, SESSION_DELETE_TIMEOUT).await {+ tracing::debug!("DELETE /session/{sid}: {e}");+ }+ }++ /// 会话已经结束(或要当作结束):下一个请求开新会话,WDA 那时把设置重置成默认+ fn forget_session(&mut self) {+ self.session = None;+ self.idle_current = None;+ }+async fn post(&mut self, path: &str, body: Value) -> Result<Value> {self.in_session("POST", path, Some(body), DEFAULT_TIMEOUT).await}@@ -498,7 +598,7 @@ impl<T: Transport> WdaClient<T> {}/// 前台是 SpringBoard 时看元素树是锁屏、通知中心还是普通界面,并带回元素树;前台是别的 App 就是普通界面- async fn cover_tree(&self) -> Result<(elements::CoverSheet, Option<String>)> {+ async fn cover_tree(&mut self) -> Result<(elements::CoverSheet, Option<String>)> {if self.active_app().await? != SPRINGBOARD {return Ok((elements::CoverSheet::None, None));}@@ -523,13 +623,62 @@ impl<T: Transport> WdaClient<T> {})}- /// 元素树 XML,排除可见性等慢属性(完整树 7~8 秒,排除后约 0.3 秒)- pub async fn source_xml(&self) -> Result<String> {+ /// 元素树 XML,排除可见性等慢属性(完整树 7~8 秒,排除后约 0.3 秒)。读得慢就收紧快照上限([`SnapshotLimits`])+ pub async fn source_xml(&mut self) -> Result<String> {+ let level = self.snapshot_level;+ if self.snapshot_applied.unwrap_or(0) != level {+ let l = SNAPSHOT_LEVELS[level];+ let body = json!({"settings": {+ "snapshotMaxDepth": l.depth,+ "snapshotMaxChildren": l.children.unwrap_or(i32::MAX as u32),+ }});+ // 设不上照样读,下次再设+ match self.post("/appium/settings", body).await {+ Ok(_) => self.snapshot_applied = Some(level),+ Err(e) => tracing::debug!("snapshot limits: {e}"),+ }+ }+ let applied = self.snapshot_applied.unwrap_or(0);let path = format!("/source?format=xml&excluded_attributes={}", elements::SOURCE_EXCLUDED);- let v = self.call("GET", &path, None, Duration::from_secs(60)).await?;+ let t0 = Instant::now();+ let r = self.call("GET", &path, None, SOURCE_TIMEOUT).await;+ let took = match r {+ Ok(_) => Some(t0.elapsed()),+ Err(WdaError::Timeout(_)) => None,+ Err(e) => return Err(e),+ };+ let next = next_snapshot_level(applied, took);+ if next != applied {+ tracing::info!(+ "{}",+ ictl_l10n::log_trf!(+ "读元素树{},快照上限改为 {:?}",+ "Reading the element tree {}; snapshot limits now {:?}",+ took.map_or_else(+ || ictl_l10n::log_tr!("超时", "timed out").to_owned(),+ |t| ictl_l10n::log_trf!("用了 {:.1} 秒", "took {:.1} s", t.as_secs_f64())+ ),+ SNAPSHOT_LEVELS[next]+ )+ );+ }+ self.snapshot_level = next;+ let v = r?;+ self.snapshot_read = applied;Ok(v["value"].as_str().unwrap_or_default().to_owned())}+ /// 上一次读到的元素树受了快照上限([`SnapshotLimits`])的限制时,给人和 agent 看的说明+ pub fn snapshot_note(&self) -> Option<String> {+ let l = SNAPSHOT_LEVELS[self.snapshot_read];+ let children = l.children?;+ Some(ictl_l10n::trf!(+ "(界面元素太多、读得慢,这次只读了 {} 层、每个元素最多 {children} 个子元素:长列表靠后的行、很深的元素可能没列出;读得快了会自动放宽)",+ "(This screen has so many elements that reading them was slow, so this read went {} levels deep with at most {children} children per element: rows far down a long list or deeply nested elements may be missing; the limits loosen again once reads are fast)",+ l.depth+ ))+ }+pub async fn elements(&mut self) -> Result<Vec<elements::Element>> {Ok(self.tree().await?.elements)}@@ -1212,7 +1361,7 @@ mod tests {#[tokio::test]async fn source_request_excludes_slow_attributes() {let m = Mock::with(&[(200, r#"{"value":"<x/>"}"#)]);- let c = WdaClient::new(&m);+ let mut c = WdaClient::new(&m);c.source_xml().await.unwrap();let path = m.seen.lock().unwrap()[0].1.clone();assert!(path.starts_with("/source?format=xml&excluded_attributes=visible,"), "{path}");@@ -1297,4 +1446,155 @@ mod tests {assert!(!c.locked().await.unwrap());assert!(!c.lock_state_trusted);}++ /// 传输层给出的一个结果:状态码和响应体,或者超时之类的错误+ type Reply = std::io::Result<(u16, Vec<u8>)>;++ /// 按顺序给出预设结果(可以是超时),记下每个请求的方法、路径和请求体+ #[derive(Default)]+ struct Script {+ replies: Mutex<VecDeque<Reply>>,+ sent: Mutex<Vec<(String, String, Option<Value>)>>,+ }++ impl Script {+ fn new(replies: Vec<Reply>) -> Self {+ Self { replies: Mutex::new(replies.into()), ..Default::default() }+ }++ fn sent(&self) -> Vec<String> {+ self.sent.lock().unwrap().iter().map(|(m, p, _)| format!("{m} {p}")).collect()+ }++ fn body(&self, i: usize) -> Value {+ self.sent.lock().unwrap()[i].2.clone().expect("a body")+ }+ }++ impl Transport for &Script {+ async fn send(+ &self,+ method: &str,+ path: &str,+ body: Option<Vec<u8>>,+ _: Duration,+ ) -> std::io::Result<(u16, Vec<u8>)> {+ let body = body.map(|b| serde_json::from_slice(&b).unwrap());+ self.sent.lock().unwrap().push((method.into(), path.into(), body));+ self.replies.lock().unwrap().pop_front().expect("unexpected request")+ }+ }++ fn timed_out() -> Reply {+ Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "t"))+ }++ fn ok(body: &str) -> Reply {+ Ok((200, body.as_bytes().to_vec()))+ }++ /// 动作没有应答:先结束会话(WDA 不再执行这个会话里还在排队的请求),再问一次前台 App 判断是不是卡死;+ /// 下一个动作开新会话+ #[tokio::test]+ async fn an_unanswered_action_ends_its_session() {+ let t = Script::new(vec![+ ok(r#"{"sessionId":"A"}"#),+ timed_out(),+ ok(r#"{"value":null}"#),+ ok(r#"{"value":{}}"#),+ ok(r#"{"sessionId":"B"}"#),+ ok(r#"{"value":null}"#),+ ]);+ let mut c = WdaClient::new(&t);+ assert!(matches!(c.press_button("home").await, Err(WdaError::Timeout(_))));+ c.press_button("home").await.unwrap();+ assert_eq!(+ t.sent(),+ [+ "POST /session",+ "POST /session/A/wda/pressButton",+ "DELETE /session/A",+ "GET /wda/activeAppInfo",+ "POST /session",+ "POST /session/B/wda/pressButton",+ ]+ );+ }++ /// 读没有应答不结束会话:排在读后面的不会动手机,结束了只会让下一次开会话也排到它后面+ #[tokio::test]+ async fn an_unanswered_read_keeps_its_session() {+ let t = Script::new(vec![+ ok(r#"{"sessionId":"A"}"#),+ timed_out(),+ ok(r#"{"value":{}}"#),+ timed_out(),+ ok(r#"{"value":{}}"#),+ ok(r#"{"value":null}"#),+ ]);+ let mut c = WdaClient::new(&t);+ assert!(c.alert_text().await.unwrap_err().no_answer());+ assert!(c.keyboard_shown().await.unwrap_err().no_answer());+ c.press_button("home").await.unwrap();+ assert_eq!(+ t.sent(),+ [+ "POST /session",+ "GET /session/A/alert/text",+ "GET /wda/activeAppInfo",+ "POST /session/A/elements",+ "GET /wda/activeAppInfo",+ "POST /session/A/wda/pressButton",+ ]+ );+ }++ #[test]+ fn snapshot_limits_tighten_when_slow_and_loosen_when_fast() {+ let slow = Some(SLOW_SOURCE);+ let fast = Some(Duration::from_millis(300));+ let fair = Some(Duration::from_secs(3));+ assert_eq!(next_snapshot_level(0, slow), 1);+ assert_eq!(next_snapshot_level(1, None), 2);+ assert_eq!(next_snapshot_level(3, None), 3, "never tighter than the last level");+ assert_eq!(next_snapshot_level(2, fair), 2);+ assert_eq!(next_snapshot_level(2, fast), 1);+ assert_eq!(next_snapshot_level(0, fast), 0);+ assert_eq!(next_snapshot_level(0, fair), 0);+ // 先限子元素再减层数,都有下限+ assert_eq!(SNAPSHOT_LEVELS[1], SnapshotLimits { depth: 50, children: Some(150) });+ assert!(SNAPSHOT_LEVELS.windows(2).all(|w| w[1].depth <= w[0].depth));+ assert_eq!(SNAPSHOT_LEVELS[3], SnapshotLimits { depth: 12, children: Some(60) });+ }++ /// 读树超时后下一次先设上限再读,读得快了再放宽;新会话里 WDA 是不限的,不为读树专门设+ #[tokio::test]+ async fn a_timed_out_tree_is_read_again_with_limits() {+ let xml = r#"{"value":"<XCUIElementTypeApplication/>"}"#;+ let t = Script::new(vec![+ timed_out(),+ ok(r#"{"value":{}}"#),+ ok(r#"{"sessionId":"A"}"#),+ ok(r#"{"value":null}"#),+ ok(xml),+ ok(r#"{"value":null}"#),+ ok(xml),+ ok(xml),+ ]);+ let mut c = WdaClient::new(&t);+ assert!(matches!(c.source_xml().await, Err(WdaError::Timeout(_))));+ assert_eq!(c.snapshot_note(), None, "nothing was read with limits yet");+ assert_eq!(c.source_xml().await.unwrap(), "<XCUIElementTypeApplication/>");+ assert!(c.snapshot_note().unwrap().contains("150"));+ c.source_xml().await.unwrap();+ assert_eq!(c.snapshot_note(), None);+ c.source_xml().await.unwrap();+ let sent = t.sent();+ assert!(sent[0].starts_with("GET /source?"));+ assert_eq!(sent[1..4], ["GET /wda/activeAppInfo", "POST /session", "POST /session/A/appium/settings"]);+ assert_eq!(t.body(3)["settings"], json!({"snapshotMaxDepth": 50, "snapshotMaxChildren": 150}));+ assert_eq!(sent[5], "POST /session/A/appium/settings");+ assert_eq!(t.body(5)["settings"]["snapshotMaxChildren"], i32::MAX);+ assert_eq!(sent.len(), 8, "the last read needs no settings: {sent:?}");+ }}diff --git a/docs/architecture.md b/docs/architecture.mdindex 22d257b..3b16f23 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -111,7 +111,7 @@| crate | 职责 | 主要依赖 ||---|---|---|-| `ictl-device` | `Device` 句柄:usbmux 发现与监听、lockdown、配对状态、开发者模式状态、隧道(`Tunnel`,持有 HID 会话和显示媒体流)、开发者镜像(含下载缓存)、截图、App 列表/启动/结束、安装 IPA、卸载、崩溃报告、系统日志流(`oslog`,开发者工具用)、打开 Web Inspector;所有设备调用都有时限 | `idevice`(锁上游 git 提交) |+| `ictl-device` | `Device` 句柄:usbmux 发现与监听、lockdown、配对状态、开发者模式状态、隧道(`Tunnel`,持有 HID 会话和显示媒体流)、开发者镜像(含下载缓存)、截图、剪贴板(HID 粘贴中文等非 ASCII 文字)、App 列表/启动/结束、安装 IPA、卸载、崩溃报告、系统日志流(`oslog`,开发者工具用)、打开 Web Inspector;所有设备调用都有时限 | `idevice`(锁上游 git 提交) || `ictl-wda` | `WdaRunner`(XCUITestService 启动/停止)、`WdaClient`(会话、点击、W3C actions、keys、source、screenshot、appium settings、锁屏核对)、经 usbmuxd 直连设备 8100 端口的 HTTP 传输(区分连不上和请求超时)、元素树解析(纯函数,可单测) | `idevice`(`xctest`)、`quick-xml` || `ictl-webinspector` | Web Inspector 服务(`com.apple.webinspector`,经 lockdown)的客户端:列出可检查的网页和 WebView、在页面里执行 JavaScript(`Target` 域和旧版直接收命令两种都支持,Promise 用 `Runtime.awaitPromise` 等待)。纯协议,消息解析可单测 | `idevice`、`plist` || `ictl-l10n` | 界面文字的语言:取当前语言,`tr!` / `trf!` / `log_tr!` / `log_trf!` 宏(每条文字在代码里原地写成中英一对,见 D12) | 无 |diff --git a/docs/dev/wda-dependency-research.md b/docs/dev/wda-dependency-research.mdindex 5a64d92..0bc9d10 100644--- a/docs/dev/wda-dependency-research.md+++ b/docs/dev/wda-dependency-research.md@@ -48,7 +48,7 @@ WDA 自己只是沙盒里的普通 App,没有任何特权。**真正有权限| 屏幕方向 | WDA 的旋转角 | `springboardservices::get_interface_orientation`(走 lockdown,不需要镜像) | 可行,还能分出 HID 现在分不出的 180° 翻转 || 屏幕点尺寸 | `/wda/screen` | 截图像素除以机型缩放倍数 | 可行 || 读元素树、按名字点、`wait_for`、等界面稳定、看弹窗 | 只走 WDA | remoteAXService(第 5 节) | 能用,但慢、不全 |-| 输入中文 | `/wda/keys` | 没有。HID 只能按键 | 无替代(第 7 节有个可能的办法) |+| 输入中文 | `/wda/keys` | HID 按 Cmd-V 粘贴:先经 CoreDevice `pasteboardservice` 写进剪贴板(`Tunnel::paste_text`) | 已有。App 每次都弹「想从“dtpasteboardd”粘贴」,要点「允许粘贴」;剪贴板一改弹窗就消失,所以 45 秒后才还原(iPhone16,2 / iOS 27.2.1 备忘录实测) || 自动解锁 | 逐位核对密码栏的「已输入 N 位」 | AX 能读锁屏界面,读不读得到密码栏位数没测过 | 要重做 || `open_url` | `/url` | 网页可以用 Web Inspector;跳到其他 App 的链接没有办法 | 部分替代 || 控制台画面 | WDA 9100 端口的 MJPEG | 轮询截图,或 HID 会话的显示媒体流;镜像里还有 `com.apple.coredevice.dtremotedisplayd`,没看过 | 没验证 |