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
Drive iOS 27 and later natively, without WebDriverAgent (#123)
Qinghe Li48c50a30a48a
diff --git a/.gitignore b/.gitignoreindex c94eefc..c24eb17 100644--- a/.gitignore+++ b/.gitignore@@ -1,5 +1,9 @@/target**/*.rs.bk+# 测试进程崩溃(如栈溢出)留下的 core dump,落在各个包的根目录;几十上百 MB,还可能含内存里的数据+/crates/*/core+/apps/*/core+core.[0-9]*# 运行时数据和秘密,永远不进仓库/data//secrets/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e2a3519..d447d6d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ All notable changes to this project are documented here. The format is based on### Added+- Phones on iOS 27 and later are driven without WebDriverAgent by default (native control): no Apple ID, no signing, no WDA; the daemon mounts the developer disk image, connects to the accessibility service (remoteAXService) and is ready, usually within seconds. The screen is read element by element from the accessibility service (types, text, values, ids and frames as WDA has them, so tapping by text, covered elements, system alerts and banners work as before); taps, swipes, long presses, buttons and Home go through HID; text is always pasted: “Allow Paste” is tapped, the field read back, and the pasteboard put back at once. Apps and links launch through CoreDevice, quitting sends SIGKILL, the lock state comes from lockdown, and auto-unlock follows the same rules as through WDA. When Home doesn't reach the home screen, a swipe up from the bottom edge does. `iphone-control setup` skips the Apple ID and signing for such a phone; `status`, `doctor` and the control page say “native”. To go back to WDA, set `ICTL_IOS_BACKEND=wda` in `~/.config/iphone-control/env`. A WDA already installed stays and is still re-signed. iOS 26 and earlier are unchanged. A WDA launched in the background (`ICTL_WDA_DETACHED`) while WDA was in use is ended when the phone is prepared (SIGKILL through CoreDevice AppService; DVT's `kill_app` leaves WDA running).- 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.- An action with `then` says whether the screen changed: the screen after it settles is compared with what was read just before it (an element list, a screenshot, or the tree a tap by text reads before tapping). "The same as before" adds that the action may not have taken effect and to look before trying it again. Nothing is added when the screen wasn't looked at since the action before. On a phone (iPhone 15 Pro Max, iOS 27.2.1, Settings): a tap on an empty spot said "the same", opening General and going back said "changed".diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex ba0aae6..7e1bf1f 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -8,6 +8,7 @@### 新增+- iOS 27 起的手机默认不用 WebDriverAgent(原生控制):不登录 Apple ID、不签名、不装 WDA,守护进程只挂开发者镜像、连上无障碍服务(remoteAXService)就就绪,通常几秒。读界面逐个元素向无障碍服务读(类型、文字、值、id、位置和 WDA 的一致,按名字点击、遮挡判断、系统弹窗、通知横幅照常),点击、滑动、长按、按键和 Home 经 HID,输入文字一律走剪贴板粘贴:自动点「允许粘贴」、读回输入框核对后马上还原剪贴板。启动 App、打开链接经 CoreDevice,结束 App 发 SIGKILL,锁屏状态问 lockdown;自动解锁的规则和经 WDA 时一样。按 Home 没回到主屏幕时改从屏幕底部上滑。`iphone-control setup` 对这样的手机跳过 Apple ID 和签名;`status`、`doctor` 和控制台显示「原生」。要改回 WDA,在 `~/.config/iphone-control/env` 里设 `ICTL_IOS_BACKEND=wda`。已经装着的 WDA 留着,照常自动重签。iOS 26 及以下不变。之前用 WDA 时后台启动(`ICTL_WDA_DETACHED`)的 WDA,在准备手机时会被结束(CoreDevice AppService 发 SIGKILL,DVT 的 `kill_app` 结束不了 WDA)。- WebDriverAgent 不可用时,`iphone_type_text` 也能输入中文等美式键盘按不出来的文字:经 HID 把它写进手机剪贴板(CoreDevice `pasteboardservice`,写完读回核对),再按 Cmd-V,输入法不会把它当成拼音。iOS 把这段文字当成别的 App 的,每次都会问「…想从“dtpasteboardd”粘贴」(iPhone 15 Pro Max、iOS 27.2.1 的备忘录实测);结果里会提示截图后点「允许粘贴」。剪贴板一改这个弹窗就消失,所以原来的内容 45 秒后才写回(下一次这样粘贴前、换设备时也会写回),而且只在剪贴板里还是粘贴的那段文字时才写。带 `submit` 时不按回车:弹窗还在时回车会选中「不允许粘贴」。英文和符号仍然逐键输入,不动剪贴板。- 带 `then` 的操作会说明界面变没变:界面稳定后,和操作前刚读过的界面(元素列表、截图,或按名字点击之前读的元素树)比较。没变时提醒操作可能没生效、先看清再决定要不要重做。上一个操作之后没看过界面就不说。真机(iPhone 15 Pro Max、iOS 27.2.1 的设置):点空白处说「一样」,打开「通用」、点返回都说「有变化」。diff --git a/Cargo.lock b/Cargo.lockindex 20ef422..a8338e8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1933,12 +1933,24 @@ dependencies = ["cc",]+[[package]]+name = "ictl-ax"+version = "0.2.6"+dependencies = [+ "idevice",+ "plist",+ "thiserror 2.0.21",+ "tokio",+ "tracing",+]+[[package]]name = "ictl-daemon"version = "0.2.6"dependencies = ["anyhow","base64 0.23.1",+ "ictl-ax","ictl-device","ictl-l10n","ictl-protocol",@@ -1962,6 +1974,7 @@ dependencies = [name = "ictl-device"version = "0.2.6"dependencies = [+ "ictl-ax","ictl-l10n","ictl-webinspector","idevice",@@ -2273,6 +2286,7 @@ dependencies = ["flate2","http","http-body-util",+ "ictl-ax","ictl-daemon","ictl-device","ictl-l10n",diff --git a/Cargo.toml b/Cargo.tomlindex 203818c..c129555 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,7 @@[workspace]resolver = "3"members = [+ "crates/ictl-ax","crates/ictl-device","crates/ictl-wda","crates/ictl-protocol",@@ -89,6 +90,7 @@ sha2 = "=0.11.1"plume_core = { path = "vendor/plume_core" }plume_store = { path = "vendor/plume_store" }+ictl-ax = { path = "crates/ictl-ax" }ictl-device = { path = "crates/ictl-device" }ictl-wda = { path = "crates/ictl-wda" }ictl-protocol = { path = "crates/ictl-protocol" }diff --git a/apps/iphone-control/Cargo.toml b/apps/iphone-control/Cargo.tomlindex 5414dfc..b10f6d3 100644--- a/apps/iphone-control/Cargo.toml+++ b/apps/iphone-control/Cargo.toml@@ -13,6 +13,7 @@ description = "iphone-control 命令行入口"ictl-l10n.workspace = trueictl-daemon.workspace = trueictl-device.workspace = true+ictl-ax.workspace = trueictl-mcp.workspace = trueictl-sign.workspace = trueictl-wda = { workspace = true, optional = true }diff --git a/apps/iphone-control/src/debug.rs b/apps/iphone-control/src/debug.rsindex d1c164c..4d93833 100644--- a/apps/iphone-control/src/debug.rs+++ b/apps/iphone-control/src/debug.rs@@ -40,8 +40,21 @@ enum Check {#[arg(long, default_value_t = 30)]restore_after: u64,},+ /// 2c. 不经 WDA 读界面(remoteAXService,iOS 27 起):打印用时、元素和 SpringBoard 盖在上面的东西,+ /// 把转成的 WDA 式 XML 存到 `out`(含屏幕文字,用完删)。`watch` 秒内每次推送都再读一次+ AxScreen {+ #[arg(long)]+ out: Option<PathBuf>,+ #[arg(long, default_value_t = 0)]+ watch: u64,+ /// 每秒重新读一次(走一遍树),不等推送+ #[arg(long)]+ dump: bool,+ },/// 3. 截图:screencaptureservice PNGScreenshot { out: PathBuf },+ /// 3a. 截屏服务认哪些格式名(`requestedFormat`):逐个试,打印大小、用时和文件头,或手机的报错+ ShotFormats { formats: Vec<String> },/// 4. 隧道稳定性:同一条隧道持续截图 N 分钟Soak {#[arg(long, default_value_t = 30)]@@ -292,6 +305,97 @@ pub async fn run(udid: Option<&str>, args: DebugArgs) -> anyhow::Result<()> {t.close().await;println!("{}", r?);}+ Check::AxScreen { out, watch, dump } => {+ let mut t = device.open_tunnel().await?;+ let r = async {+ let t0 = Instant::now();+ t.ax().await?;+ println!("connected in {:.2}s", t0.elapsed().as_secs_f64());+ let mut after: Option<Instant> = None;+ let end = Instant::now() + Duration::from_secs(watch);+ loop {+ let s = match after {+ Some(_) if dump => {+ tokio::time::sleep(Duration::from_secs(1)).await;+ let asked = Instant::now();+ let s = t.ax_screen(Duration::from_secs(5), true).await?;+ println!(" read in {:.0} ms", asked.elapsed().as_secs_f64() * 1000.0);+ s+ }+ Some(at) => {+ let left = end.saturating_duration_since(Instant::now()).max(Duration::from_secs(1));+ if t.ax().await?.wait_push(at, left).await.is_none() {+ break;+ }+ t.ax_screen(Duration::from_secs(5), true).await?+ }+ None => t.ax_screen(Duration::from_secs(5), true).await?,+ };+ let xml = ictl_ax::xml::to_xml(+ &s.app,+ &s.overlays,+ args.width,+ args.height,+ &Default::default(),+ s.springboard_front,+ );+ let labelled: Vec<&str> =+ s.app.iter().filter(|e| !e.label.is_empty()).map(|e| e.label.as_str()).take(6).collect();+ println!(+ "{:7.2}s app pid {} with {} elements ({} typed), {} over it: {} | {}",+ t0.elapsed().as_secs_f64(),+ s.app_pid,+ s.app.len(),+ s.app.iter().filter(|e| e.xc_type > 0).count(),+ s.overlays.len(),+ labelled.join(" / "),+ s.overlays+ .iter()+ .filter(|e| !e.label.is_empty())+ .map(|e| e.label.as_str())+ .take(6)+ .collect::<Vec<_>>()+ .join(" / "),+ );+ if let Some(p) = &out {+ std::fs::write(p, &xml)?;+ }+ if Instant::now() >= end {+ break;+ }+ after = Some(s.at);+ }+ Ok::<_, anyhow::Error>(())+ }+ .await;+ t.close().await;+ r?;+ }+ Check::ShotFormats { formats } => {+ let mut t = device.open_tunnel().await?;+ for i in 0..3 {+ let t0 = Instant::now();+ let png = t.screenshot_png().await?;+ println!(+ "png #{i} (kept connection after the first): {} bytes in {:.2}s",+ png.len(),+ t0.elapsed().as_secs_f64()+ );+ }+ for f in formats {+ let t0 = Instant::now();+ match t.screenshot_as(&f).await {+ Ok(b) => println!(+ "{f}: {} bytes in {:.2}s, starts {:02x?}",+ b.len(),+ t0.elapsed().as_secs_f64(),+ &b[..b.len().min(4)]+ ),+ Err(e) => println!("{f}: {}", e.to_string().chars().take(200).collect::<String>()),+ }+ }+ t.close().await;+ }Check::Screenshot { out } => {let mut t = device.open_tunnel().await?;let t0 = Instant::now();diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex 393860d..80a9448 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -1136,6 +1136,13 @@ async fn device_setup(cli: &Cli) -> anyhow::Result<()> {println!("{}", ictl_l10n::tr!(" 已打开", " Turned on"));}+ // iOS 27 起默认原生控制:不用 WDA,也就不用 Apple ID 和签名(ICTL_IOS_BACKEND=wda 时照旧)+ let backend =+ ictl_daemon::config::IosBackend::parse(std::env::var(ictl_daemon::protocol::env::IOS_BACKEND).ok().as_deref());+ if backend.drives_natively(Some(&target)) {+ return native_setup(socket, &device.udid).await;+ }+println!("{}", ictl_l10n::tr!("[4/6] 登录 Apple ID", "[4/6] Apple ID sign-in"));match account_dir(&cli.data_dir).selected_email().await {Ok(e) => println!("{}", ictl_l10n::trf!(" 已登录 {e}", " Signed in as {e}")),@@ -1222,6 +1229,43 @@ async fn device_setup(cli: &Cli) -> anyhow::Result<()> {Ok(())}+/// The last steps of [`device_setup`] for a phone driven natively: no Apple ID, no signing, the daemon only mounts+/// the developer disk image and connects to the accessibility service+async fn native_setup(socket: &Path, udid: &str) -> anyhow::Result<()> {+ println!(+ "{}",+ ictl_l10n::tr!(+ "[4/6] 登录 Apple ID:跳过(iOS 27 起原生控制,不用 WDA,不用签名)\n[5/6] 签名安装 WDA:跳过(要改回 WDA,在 ~/.config/iphone-control/env 里设 ICTL_IOS_BACKEND=wda)",+ "[4/6] Apple ID sign-in: skipped (native control from iOS 27, no WDA, no signing)\n[5/6] Signing and installing WDA: skipped (to go back to WDA, set ICTL_IOS_BACKEND=wda in ~/.config/iphone-control/env)"+ )+ );+ println!(+ "{}",+ ictl_l10n::tr!(+ "[6/6] 等待手机准备好(挂载开发者镜像、连接无障碍服务;手机要保持解锁)",+ "[6/6] Waiting for the phone to get ready (mounting the developer disk image, connecting to the accessibility service; keep the phone unlocked)"+ )+ );+ let ready = wait_until(Duration::from_secs(300), Duration::from_secs(3), || async {+ snapshot(socket).await.is_ok_and(|s| {+ s.state == ictl_daemon::machine::DeviceState::Ready && s.device.as_ref().is_none_or(|d| d.udid == udid)+ })+ })+ .await;+ println!(+ " {}",+ if ready {+ ictl_l10n::tr!("就绪(原生控制)", "Ready (native control)")+ } else {+ ictl_l10n::tr!(+ "5 分钟内没准备好,运行 iphone-control doctor 看看卡在哪",+ "Not ready within 5 minutes; run iphone-control doctor to see where it is stuck"+ )+ }+ );+ Ok(())+}+/// 显式开启:127.0.0.1:port → 手机上的 WDA 8100。只绑本机回环地址。/// 本机的其他用户、浏览器里的网页都能访问到,而 WDA 没有认证。/// 浏览器那条路(DNS rebinding)靠检查 Host 头挡住;本机其他用户挡不住,用完就停。diff --git a/apps/iphone-control/src/video/ffmpeg.rs b/apps/iphone-control/src/video/ffmpeg.rsindex 553ed6f..5ee4752 100644--- a/apps/iphone-control/src/video/ffmpeg.rs+++ b/apps/iphone-control/src/video/ffmpeg.rs@@ -298,6 +298,109 @@ pub fn args(kind: &Kind, w: u32, h: u32, qp: u8, old: bool) -> Vec<String> {a}+/// The ffmpeg command line (without the program) that turns the phone's own HEVC video (Annex-B on stdin, the+/// portrait framebuffer padded to multiples of 16) into H.264 in FLV with `kind`, for a page that can't decode HEVC+/// while WDA's MJPEG isn't there ([`super::transcode`]). `points`: the screen in points, portrait; the padding is cut+/// off by it (1328×2896 → 1290×2796 for 430×932 at ×3). `None` for the native encoder, which takes JPEG only+pub fn hevc_args(kind: &Kind, points: Option<(f64, f64)>, qp: u8, old: bool) -> Option<Vec<String>> {+ let qp_s = qp.to_string();+ // the padding off, to even sizes (4:2:0); the scale is the padded width over the width in points, rounded+ let crop = points.filter(|(w, h)| *w > 1.0 && *h > 1.0).map(|(w, h)| {+ let (pw, ph) = (w.min(h).round(), w.max(h).round());+ format!("crop=w='2*floor(min(iw,{pw}*round(iw/{pw}))/2)':h='2*floor(min(ih,{ph}*round(iw/{pw}))/2)':x=0:y=0,")+ });+ let crop = crop.unwrap_or_default();+ let (input, filter, codec): (Vec<String>, String, Vec<String>) = match kind {+ Kind::Native => return None,+ Kind::Nvenc { .. } => (+ Vec::new(),+ format!("{crop}format=nv12"),+ strings(&[+ "-c:v",+ "h264_nvenc",+ "-preset",+ "p4",+ "-tune",+ "ll",+ "-rc",+ "constqp",+ "-qp",+ &qp_s,+ "-delay",+ "0",+ "-zerolatency",+ "1",+ ]),+ ),+ Kind::Vaapi { node, .. } => {+ let mut codec = strings(&["-c:v", "h264_vaapi", "-rc_mode", "CQP", "-qp", &qp_s]);+ if !old {+ codec.extend(strings(&["-async_depth", "1"]));+ }+ (strings(&["-vaapi_device", &node.to_string_lossy()]), format!("{crop}format=nv12,hwupload"), codec)+ }+ Kind::Qsv => (+ Vec::new(),+ format!("{crop}format=nv12"),+ strings(&["-c:v", "h264_qsv", "-global_quality", &qp_s, "-look_ahead", "0", "-async_depth", "1"]),+ ),+ Kind::V4l2m2m => {+ (Vec::new(), format!("{crop}format=nv12"), strings(&["-c:v", "h264_v4l2m2m", "-b:v", &bitrate(qp)]))+ }+ Kind::VideoToolbox => (+ Vec::new(),+ format!("{crop}format=nv12"),+ strings(&["-c:v", "h264_videotoolbox", "-realtime", "1", "-b:v", &bitrate(qp)]),+ ),+ Kind::X264 => (+ Vec::new(),+ format!("{crop}format=yuv420p"),+ strings(&[+ "-c:v",+ "libx264",+ "-preset",+ "veryfast",+ "-tune",+ "zerolatency",+ "-crf",+ &qp.saturating_sub(1).to_string(),+ ]),+ ),+ };+ let mut a = strings(&[+ "-hide_banner",+ "-loglevel",+ "error",+ "-nostats",+ "-probesize",+ "32",+ "-analyzeduration",+ "0",+ // no `-fflags nobuffer` (as the JPEG input has): with it the HEVC input loses its start, and every frame+ // after it misses its references+ "-flags",+ "low_delay",+ ]);+ a.extend(input);+ a.extend(strings(&["-f", "hevc", "-i", "pipe:0", if old { "-vsync" } else { "-fps_mode" }, "passthrough", "-an"]));+ a.extend(strings(&["-vf", filter.trim_end_matches(',')]));+ a.extend(codec);+ a.extend(strings(&[+ "-bf",+ "0",+ "-g",+ &GOP_FRAMES.to_string(),+ "-f",+ "flv",+ "-flvflags",+ "no_duration_filesize",+ "-flush_packets",+ "1",+ "pipe:1",+ ]));+ Some(a)+}+fn strings(v: &[&str]) -> Vec<String> {v.iter().map(|s| (*s).to_owned()).collect()}@@ -440,6 +543,27 @@ impl Encoders {self.session(&self.list[c.index], (w, h), qp, c.kicks, c.index, None)}+ /// ffmpeg and its command line for transcoding the phone's own HEVC video with the encoder in use+ /// ([`hevc_args`]); the native encoder (JPEG only) is replaced by VideoToolbox through ffmpeg. `Err` without+ /// ffmpeg or a working encoder+ pub fn hevc_command(+ &self,+ points: Option<(f64, f64)>,+ qp: u8,+ ) -> Result<(PathBuf, Vec<String>, &'static str), String> {+ let c = self.current().ok_or_else(|| ictl_l10n::tr!("没有可用的编码器", "no working encoder").to_owned())?;+ let ffmpeg = self.ffmpeg.clone().ok_or_else(|| {+ ictl_l10n::tr!("没有 ffmpeg,转不了手机的 HEVC 画面", "no ffmpeg to transcode the phone's HEVC picture")+ .to_owned()+ })?;+ let kind = match &self.list[c.index] {+ Kind::Native => &Kind::VideoToolbox,+ k => k,+ };+ let args = hevc_args(kind, points, qp, self.old).ok_or("no encoder for HEVC input")?;+ Ok((ffmpeg, args, kind.label()))+ }+/// The quantizer set for the picture (`IPHONE_CONTROL_VIEWER_QP`)pub fn qp(&self) -> u8 {self.qp@@ -794,6 +918,36 @@ impl Process {mod tests {use super::*;+ /// The phone's HEVC in, its padding cut off by the screen's points, H.264 in FLV out; none for the native encoder+ #[test]+ fn hevc_is_transcoded_with_the_padding_cut_off() {+ let a = hevc_args(&Kind::X264, Some((932.0, 430.0)), 20, false).unwrap();+ let at = |flag: &str| a.iter().position(|x| x == flag).map(|i| a[i + 1].as_str());+ assert_eq!(at("-f"), Some("hevc"), "the input");+ assert!(!a.iter().any(|x| x == "nobuffer"), "the HEVC input would lose its start");+ assert_eq!(at("-i"), Some("pipe:0"));+ // turned (landscape points) or not, the crop is portrait: 430 wide at the padded width's scale+ let vf = at("-vf").unwrap();+ assert!(+ vf.starts_with("crop=w='2*floor(min(iw,430*round(iw/430))/2)':h='2*floor(min(ih,932*round(iw/430))/2)'"),+ "{vf}"+ );+ assert!(vf.ends_with("format=yuv420p"), "{vf}");+ assert_eq!(a.last().map(String::as_str), Some("pipe:1"));+ assert!(a.windows(2).any(|w| w == ["-f", "flv"]));+ // without the screen's size: no crop+ let vf = hevc_args(&Kind::Qsv, None, 20, false).unwrap();+ assert!(vf.iter().any(|x| x == "format=nv12"));+ let vaapi =+ hevc_args(&Kind::Vaapi { node: "/dev/dri/renderD128".into(), hw_jpeg: true }, None, 20, false).unwrap();+ assert!(vaapi.windows(2).any(|w| w == ["-vaapi_device", "/dev/dri/renderD128"]));+ assert!(vaapi.iter().any(|x| x == "format=nv12,hwupload"));+ assert!(hevc_args(&Kind::Native, None, 20, false).is_none(), "JPEG in only");+ for k in [Kind::Nvenc { hw_jpeg: false }, Kind::V4l2m2m, Kind::VideoToolbox] {+ assert!(hevc_args(&k, Some((430.0, 932.0)), 20, true).unwrap().iter().any(|x| x == "-vsync"), "old ffmpeg");+ }+ }+#[test]fn versions_before_5_1_are_old() {assert!(is_old("ffmpeg version 4.4.2-0ubuntu0.22.04.1 Copyright (c) 2000-2021 the FFmpeg developers"));diff --git a/apps/iphone-control/src/video/mod.rs b/apps/iphone-control/src/video/mod.rsindex 11d1462..ba39b7b 100644--- a/apps/iphone-control/src/video/mod.rs+++ b/apps/iphone-control/src/video/mod.rs@@ -29,6 +29,7 @@ mod ffmpeg;mod flv;mod mjpeg;mod sps;+pub mod transcode;#[cfg(target_os = "macos")]mod vt;diff --git a/apps/iphone-control/src/video/transcode.rs b/apps/iphone-control/src/video/transcode.rsnew file mode 100644index 0000000..c009a3f--- /dev/null+++ b/apps/iphone-control/src/video/transcode.rs@@ -0,0 +1,301 @@+//! The phone's own HEVC video as H.264 (`GET /video` when WDA's MJPEG isn't there: iOS 27 driven natively, or WDA+//! down), for pages that can't decode HEVC (Firefox, Chrome on most Linux). ffmpeg decodes the stream the daemon+//! hands on ([`super::device`]), cuts the padding off and encodes it with the encoder in use ([`Encoders`]); the+//! page gets the same messages as the H.264 picture of WDA's MJPEG (see the module docs): a portrait picture, turned+//! by the page from the interface's rotation as before.+//!+//! The phone's frames can't be skipped (each needs the ones before since the last keyframe), so falling behind is+//! met by stopping: frames stop going to ffmpeg while the page is behind or its queue is full, and once it caught up+//! the phone is asked for a keyframe and a new ffmpeg starts from it (its first frame is a keyframe too).++use std::collections::VecDeque;+use std::path::PathBuf;+use std::process::Stdio;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use ictl_daemon::protocol::{SCREEN_KEYFRAME, ScreenMsg};+use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};+use tokio::process::{Child, Command};+use tokio::sync::mpsc;++use super::flv::{self, Packet};+use super::{AbortOnDrop, Acks, Encoders, Flow, QUEUE, STREAM_IDLE, config_message, message, send_video};++/// The phone's frames waiting for ffmpeg; more and it can't keep up (a slow software encoder): start over from a+/// keyframe instead of falling further behind+const INPUT_QUEUE: usize = 32;+/// Largest message accepted from the daemon (a keyframe is well under 1 MB)+const MAX_MESSAGE: usize = 16 * 1024 * 1024;+/// ffmpeg failing this many times in a row on one connection: the page is told (it falls back to MJPEG)+const TRIES: usize = 3;+/// Asking for a keyframe again while none came to start ffmpeg at+const ASK_EVERY: Duration = Duration::from_millis(500);++/// One ffmpeg process: HEVC in, H.264 in FLV out+struct Transcoder {+ input: mpsc::Sender<Vec<u8>>,+ out: mpsc::Receiver<Result<Packet, String>>,+ errors: Arc<Mutex<VecDeque<String>>>,+ tasks: Vec<tokio::task::JoinHandle<()>>,+ _child: Child,+}++impl Drop for Transcoder {+ fn drop(&mut self) {+ for t in &self.tasks {+ t.abort();+ }+ }+}++impl Transcoder {+ fn spawn(ffmpeg: &PathBuf, args: &[String]) -> Result<Self, String> {+ let mut child = Command::new(ffmpeg)+ .args(args)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true)+ .spawn()+ .map_err(|e| ictl_l10n::trf!("启动 ffmpeg 失败:{e}", "Starting ffmpeg failed: {e}"))?;+ let (Some(mut stdin), Some(mut stdout), Some(stderr)) =+ (child.stdin.take(), child.stdout.take(), child.stderr.take())+ else {+ return Err("ffmpeg pipes".into());+ };+ let (input, mut rx) = mpsc::channel::<Vec<u8>>(INPUT_QUEUE);+ let writer = tokio::spawn(async move {+ while let Some(f) = rx.recv().await {+ if stdin.write_all(&f).await.is_err() || stdin.flush().await.is_err() {+ return;+ }+ }+ });+ let (tx, out) = mpsc::channel(16);+ let reader = tokio::spawn(async move {+ let mut p = flv::Parser::default();+ let mut buf = vec![0; 256 * 1024];+ loop {+ let n = match stdout.read(&mut buf).await {+ Ok(0) | Err(_) => return,+ Ok(n) => n,+ };+ p.push(&buf[..n]);+ loop {+ match p.next() {+ Ok(Some(pk)) => {+ if tx.send(Ok(pk)).await.is_err() {+ return;+ }+ }+ Ok(None) => break,+ Err(e) => {+ let _ = tx.send(Err(e)).await;+ return;+ }+ }+ }+ }+ });+ let errors = Arc::new(Mutex::new(VecDeque::new()));+ let e = errors.clone();+ let logger = tokio::spawn(async move {+ let mut lines = BufReader::new(stderr).lines();+ while let Ok(Some(l)) = lines.next_line().await {+ tracing::debug!("ffmpeg (HEVC): {l}");+ let mut q = e.lock().unwrap_or_else(|p| p.into_inner());+ if q.len() >= 4 {+ q.pop_front();+ }+ q.push_back(l);+ }+ });+ Ok(Self { input, out, errors, tasks: vec![writer, reader, logger], _child: child })+ }++ /// Why it ended+ fn error(&self) -> String {+ let q = self.errors.lock().unwrap_or_else(|p| p.into_inner());+ if q.is_empty() { "ffmpeg ended".into() } else { q.iter().cloned().collect::<Vec<_>>().join("; ") }+ }+}++/// Asks the phone for a keyframe (through the daemon). False when the stream is gone+async fn ask(w: &mut tokio::net::unix::OwnedWriteHalf, asked: &mut Option<Instant>) -> bool {+ *asked = Some(Instant::now());+ w.write_all(&[SCREEN_KEYFRAME]).await.is_ok()+}++async fn next_packet(t: &mut Option<Transcoder>) -> Option<Result<Packet, String>> {+ match t {+ Some(t) => t.out.recv().await,+ None => std::future::pending().await,+ }+}++/// Sends the phone's video from the daemon's screen stream (`src`, `daemon_w` to ask for keyframes) to `client` as+/// H.264, until either ends. `points`: the screen in points (its padding is cut off by it). The HTTP head is already+/// sent+pub async fn serve(+ enc: Arc<Encoders>,+ qp: u8,+ points: Option<(f64, f64)>,+ acks: Arc<Acks>,+ mut src: tokio::io::BufReader<tokio::net::unix::OwnedReadHalf>,+ mut daemon_w: tokio::net::unix::OwnedWriteHalf,+ client: impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,+) {+ let (ffmpeg, args, label) = match enc.hevc_command(points, qp) {+ Ok(c) => c,+ Err(e) => {+ tracing::debug!("no H.264 of the phone's video: {e}");+ return;+ }+ };+ let (ack_guard, mut acked) = acks.register();+ let mut flow = Flow::default();++ let (msg_tx, mut msgs) = mpsc::channel::<(u8, Vec<u8>)>(8);+ let reader = tokio::spawn(async move {+ loop {+ let mut head = [0u8; 5];+ if src.read_exact(&mut head).await.is_err() {+ return;+ }+ let len = u32::from_be_bytes([head[1], head[2], head[3], head[4]]) as usize;+ if len > MAX_MESSAGE {+ return;+ }+ let mut body = vec![0u8; len];+ if src.read_exact(&mut body).await.is_err() || msg_tx.send((head[0], body)).await.is_err() {+ return;+ }+ }+ });+ let _reader = AbortOnDrop(reader);++ let (out_tx, out_rx) = mpsc::channel(QUEUE);+ let _writer = AbortOnDrop(tokio::spawn(send_video(client, out_rx, STREAM_IDLE)));++ let mut session: Option<Transcoder> = None;+ // frames out of the current ffmpeg; one that fails before any is not the stream's fault+ let mut produced = false;+ let mut failures = 0;+ // stopped: the page is behind or its queue was full; a keyframe and a new ffmpeg once it caught up+ let mut stopped = false;+ // when a keyframe was last asked for; asked again every [`ASK_EVERY`] until ffmpeg runs+ let mut asked: Option<Instant> = None;+ let mut tick = tokio::time::interval(Duration::from_millis(250));+ loop {+ tokio::select! {+ _ = out_tx.closed() => return,+ m = msgs.recv() => {+ let Some((kind, body)) = m else { return };+ let key = match ScreenMsg::from_byte(kind) {+ Some(ScreenMsg::Key) => true,+ Some(ScreenMsg::Delta) => false,+ _ => continue,+ };+ if stopped {+ continue;+ }+ if flow.behind(Instant::now()) {+ stopped = true;+ session = None;+ continue;+ }+ if session.is_none() {+ // a new ffmpeg starts at a keyframe (ffmpeg decodes nothing before one)+ if !key {+ continue;+ }+ match Transcoder::spawn(&ffmpeg, &args) {+ Ok(t) => {+ session = Some(t);+ produced = false;+ }+ Err(e) => {+ tracing::debug!("{e}");+ return;+ }+ }+ }+ let Some(t) = &session else { continue };+ if t.input.try_send(body).is_err() {+ // ffmpeg can't keep up: start over from a keyframe+ session = None;+ if !ask(&mut daemon_w, &mut asked).await {+ return;+ }+ }+ }+ p = next_packet(&mut session) => match p {+ Some(Ok(Packet::Config(avcc))) => {+ let size = points.map_or((0, 0), |(w, h)| (w.min(h) as u32, w.max(h) as u32));+ let Some(m) = config_message(&avcc, size, label, &ack_guard.id) else { continue };+ flow.sent(m.len(), Instant::now());+ if out_tx.send(m).await.is_err() {+ return;+ }+ }+ Some(Ok(Packet::Frame { key, data })) => {+ produced = true;+ failures = 0;+ let m = message(if key { 1 } else { 2 }, &data);+ let len = m.len();+ match out_tx.try_send(m) {+ Ok(()) => flow.sent(len, Instant::now()),+ // the page's queue is full: no more until it drained, then from a keyframe+ Err(mpsc::error::TrySendError::Full(_)) => {+ stopped = true;+ session = None;+ }+ Err(mpsc::error::TrySendError::Closed(_)) => return,+ }+ }+ end => {+ let why = match end {+ Some(Err(e)) => e,+ _ => session.as_ref().map(Transcoder::error).unwrap_or_default(),+ };+ tracing::debug!("HEVC to H.264 ended: {why}");+ session = None;+ failures += 1;+ if !produced && failures >= TRIES {+ return;+ }+ if !ask(&mut daemon_w, &mut asked).await {+ return;+ }+ }+ },+ r = acked.changed() => {+ if r.is_err() {+ return;+ }+ flow.ack(*acked.borrow_and_update(), Instant::now());+ if stopped && !flow.behind(Instant::now()) && out_tx.capacity() == QUEUE {+ stopped = false;+ if !ask(&mut daemon_w, &mut asked).await {+ return;+ }+ }+ }+ _ = tick.tick() => {+ // the queue drained without a report (a page that doesn't report): go on+ if stopped && !flow.behind(Instant::now()) && out_tx.capacity() == QUEUE {+ stopped = false;+ }+ // waiting for a keyframe to start ffmpeg at: ask (again: one asked for may not come)+ if !stopped+ && session.is_none()+ && asked.is_none_or(|t| t.elapsed() >= ASK_EVERY)+ && !ask(&mut daemon_w, &mut asked).await+ {+ return;+ }+ }+ }+ }+}diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.htmlindex 100584d..855364a 100644--- a/apps/iphone-control/src/viewer.html+++ b/apps/iphone-control/src/viewer.html@@ -1133,7 +1133,7 @@ const LANG = (() => {return v === 'en' || v === 'zh' ? v : document.documentElement.dataset.lang === 'en' ? 'en' : 'zh';})();document.documentElement.lang = LANG === 'en' ? 'en' : 'zh-CN';-const EN = {"登录已过期":"Login expired","只读登录":"Read-only login",":能看画面、设备状态和任务,不能操作手机,也不能开始、暂停或确认任务。":": you can watch the picture, the device's state and tasks, but not act on the phone or start, pause or confirm tasks.","只读":"Read-only","只读登录:只能看,不能操作":"Read-only login: you can watch, not act","任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","<div class=\"ph-kb\" data-type=\"Keyboard\">键盘</div>":"<div class=\"ph-kb\" data-type=\"Keyboard\">Keyboard</div>","<li class=\"empty-note\">打开这一页时会读取已安装的 App。</li>":"<li class=\"empty-note\">The installed apps are read when this tab opens.</li>","<li class=\"sr-only\">正在读取 App 列表…</li>":"<li class=\"sr-only\">Reading the app list…</li>","<li class=\"sr-only\">正在读取元素…</li>":"<li class=\"sr-only\">Reading elements…</li>","<option>没有可用的 AI</option>":"<option>No AI available</option>","<p class=\"empty-note\">正在连接 iphone-control 服务…</p>":"<p class=\"empty-note\">Connecting to the iphone-control service…</p>","<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>演示模式</span></span>":"<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>Demo</span></span>","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。":"Run <code>iphone-control sign</code> to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 <code>iphone-control setup --reconfigure</code> 选「手机」,在设备上点「信任」。":"Run <code>iphone-control setup --reconfigure</code>, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress","弱网模式":"Low-bandwidth mode","画面流量减少约一半,帧率不变,适合外网或信号差时用;画面动起来时会略糊。手机自己的画面(HEVC)只有一路,开着时所有在看这台手机的页面都会一起降,切换时画面会断开半秒左右。":"About half the picture's traffic at the same frame rate, for use over the internet or a weak signal; moving content gets a little blurry. The phone's own picture (HEVC) is one stream, so while this is on every page watching this phone gets it too, and switching interrupts the picture for about half a second.","已开启弱网模式,正在重新连接画面…":"Low-bandwidth mode on, reconnecting the picture…","已关闭弱网模式,正在重新连接画面…":"Low-bandwidth mode off, reconnecting the picture…"};+const EN = {"登录已过期":"Login expired","只读登录":"Read-only login",":能看画面、设备状态和任务,不能操作手机,也不能开始、暂停或确认任务。":": you can watch the picture, the device's state and tasks, but not act on the phone or start, pause or confirm tasks.","只读":"Read-only","只读登录:只能看,不能操作":"Read-only login: you can watch, not act","任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","<div class=\"ph-kb\" data-type=\"Keyboard\">键盘</div>":"<div class=\"ph-kb\" data-type=\"Keyboard\">Keyboard</div>","<li class=\"empty-note\">打开这一页时会读取已安装的 App。</li>":"<li class=\"empty-note\">The installed apps are read when this tab opens.</li>","<li class=\"sr-only\">正在读取 App 列表…</li>":"<li class=\"sr-only\">Reading the app list…</li>","<li class=\"sr-only\">正在读取元素…</li>":"<li class=\"sr-only\">Reading elements…</li>","<option>没有可用的 AI</option>":"<option>No AI available</option>","<p class=\"empty-note\">正在连接 iphone-control 服务…</p>":"<p class=\"empty-note\">Connecting to the iphone-control service…</p>","<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>演示模式</span></span>":"<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>Demo</span></span>","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","原生":"Native","正在准备设备(挂载开发者镜像、连接无障碍服务)…":"Preparing the device (mounting the developer disk image, connecting to the accessibility service)…",":准备设备失败,会自动重试":": preparing the device failed, retrying automatically","开发者镜像、无障碍服务":"Developer disk image, accessibility service","正在挂开发者镜像、连接无障碍服务,通常几秒到半分钟。":"Mounting the developer disk image and connecting to the accessibility service, usually a few seconds to half a minute.","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。":"Run <code>iphone-control sign</code> to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 <code>iphone-control setup --reconfigure</code> 选「手机」,在设备上点「信任」。":"Run <code>iphone-control setup --reconfigure</code>, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress","弱网模式":"Low-bandwidth mode","画面流量减少约一半,帧率不变,适合外网或信号差时用;画面动起来时会略糊。手机自己的画面(HEVC)只有一路,开着时所有在看这台手机的页面都会一起降,切换时画面会断开半秒左右。":"About half the picture's traffic at the same frame rate, for use over the internet or a weak signal; moving content gets a little blurry. The phone's own picture (HEVC) is one stream, so while this is on every page watching this phone gets it too, and switching interrupts the picture for about half a second.","已开启弱网模式,正在重新连接画面…":"Low-bandwidth mode on, reconnecting the picture…","已关闭弱网模式,正在重新连接画面…":"Low-bandwidth mode off, reconnecting the picture…"};Object.assign(EN, {'未连接设备':'No device connected', '用数据线连接 iPhone 或 iPad。':'Connect an iPhone or iPad with a USB cable.', '等待设备连接':'Waiting for a device','外观':'Appearance', '界面字号':'Text size', '标准':'Standard', '大':'Large', '特大':'Extra large',@@ -1198,7 +1198,7 @@ language.addEventListener('change', () => {* GET /api/apps?system=1 → { apps: [{ name, bundle_id }] }* GET /api/elements?filter= → { elements: [{ type, label, x, y, width, height }] } // x、y 是左上角,单位点* GET /api/alert → { alert: null | { text, frame?: { x, y, width, height }, buttons: [{ label, x, y, width }] } } // 系统弹窗,单位点:弹窗的框(左上角)、按钮中心和宽;画面是手机自己的视频时页面定时问(2~6 秒,见 alertLoop)- * state 取值:Absent | NeedsTrust | DeveloperModeOff | NeedsSigning | WdaStarting | NeedsUnlock | NeedsAutomationPin | Ready+ * state 取值:Absent | NeedsTrust | DeveloperModeOff | NeedsSigning | WdaStarting | NeedsUnlock | NeedsAutomationPin | Preparing | Ready** AI 任务:交给本机的 Claude Code 或 Codex,它只能用 iphone-control 的 MCP 工具;每一步都经守护进程过一道闸,* 所以暂停、接管、确认在那里生效,和用哪个 agent 无关:@@ -2066,6 +2066,10 @@ function stageNote() {// 启动失败常见的一种是签名证书变了(给另一台设备重签时换了证书),重签这台就好;登录了 Apple ID 就给个按钮if (d.last_error) return `${esc(name)}${esc(tr(':WebDriverAgent 启动失败,会自动重试'))}<br><span class="stage-err">${esc(d.last_error)}</span>${d.signed_in ? `<br>${signButton(tr('重新签名并安装 WDA'))}` : ''}`;return `${esc(tr('正在'))} ${esc(name)} ${esc(tr('上启动 WebDriverAgent,通常 10–60 秒…'))}`;+ case 'Preparing':+ // 原生控制(iOS 27 起不用 WDA):只要挂开发者镜像、连无障碍服务+ if (d.last_error) return `${esc(name)}${esc(tr(':准备设备失败,会自动重试'))}<br><span class="stage-err">${esc(d.last_error)}</span>`;+ return esc(tr('正在准备设备(挂载开发者镜像、连接无障碍服务)…'));case 'NeedsUnlock': return esc(tr('设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。'));case 'NeedsAutomationPin': return esc(tr('设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。'));default: return esc(tr('没有收到设备画面,3 秒后自动重试。'));@@ -2446,7 +2450,7 @@ function renderFeed() {if (frame.hasAttribute('data-absent')) { dot.classList.add('wait'); txt.textContent = tr('等待设备连接'); return; }if (S.stream === 'error') { dot.classList.add('off'); txt.textContent = tr('画面断开 · 自动重试中'); return; }if (!dims()) { dot.classList.add('wait'); txt.textContent = tr('画面已连接 · 等待屏幕尺寸和方向,仅可观看'); return; }- const route = S.dstatus?.route === 'hid' ? tr('HID 后备') : 'WDA';+ const route = S.dstatus?.route === 'hid' ? tr('HID 后备') : S.dstatus?.route === 'native' ? tr('原生') : 'WDA';const codec = V.on ? ` · ${V.codecName || 'H.264'}${V.label ? ` ${V.label}` : ''}${V.rate != null ? ` ${Math.round(V.rate / 1024)} KB/s` : ''}` : ' · MJPEG';const low = V.on && lowBandwidthOn() ? ` · ${tr('弱网模式')}` : '';txt.textContent = `${tr('实时画面')} · ${route}${codec}${low}${S.rtt != null ? ` · ${tr('操作往返')} ${S.rtt} ms` : ''}`;@@ -2462,11 +2466,16 @@ const CHECKS = [{ name: tr('WDA 已签名安装'), fail: ['NeedsSigning'], hint: tr('运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。'), action: 'sign' },{ name: tr('WDA 运行中'), fail: ['WdaStarting', 'NeedsUnlock', 'NeedsAutomationPin'], hint: '' }];+/* 原生控制(iOS 27 起不用 WDA):不签名、不启动 WDA,只挂开发者镜像、连无障碍服务 */+const NATIVE_CHECKS = [...CHECKS.slice(0, 3),+ { name: tr('开发者镜像、无障碍服务'), fail: ['Preparing', 'NeedsUnlock'], hint: '' }+];const STARTING_NO_HID = tr('正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。');const STARTING_HINT = {WdaStarting: tr('正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。'),NeedsUnlock: tr('设备重启后还没解锁过,需要在设备上手动解锁一次。'),- NeedsAutomationPin: tr('设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。')+ NeedsAutomationPin: tr('设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。'),+ Preparing: tr('正在挂开发者镜像、连接无障碍服务,通常几秒到半分钟。')};let statusTimerId = 0, statusSequence = 0;function refreshStatusSoon() { clearTimeout(statusTimerId); statusTimerId = setTimeout(loadDeviceState, 600); }@@ -2579,7 +2588,7 @@ function renderStatusPanel() {const fact = ([k, v], mono = false) => `<div class="fact"><dt class="fact-k">${esc(k)}</dt><dd class="fact-v${mono ? ' mono' : ''}">${esc(v)}</dd></div>`;const facts = [[tr('前台 App'), s?.foreground], [tr('屏幕'), s?.locked != null && (s.locked ? tr('已锁定') : tr('未锁定'))],- [tr('操作通道'), s?.route === 'wda' ? 'WDA' : s?.route === 'hid' ? tr('HID 后备') : null],+ [tr('操作通道'), s?.route === 'wda' ? 'WDA' : s?.route === 'hid' ? tr('HID 后备') : s?.route === 'native' ? tr('原生') : null],[tr('屏幕尺寸'), screen && `${screen.W} × ${screen.H} pt`], [tr('自动解锁'), d && (d.auto_unlock ? tr('已设置密码') : tr('未设置'))]].filter(([,v]) => v);$('#nav-facts').hidden = !selected || !facts.length;@@ -2589,11 +2598,12 @@ function renderStatusPanel() {navigatorHTML('#nav-ids', ids.map(row => fact(row, true)).join(''));const error = S.statusErr || S.devicesErr;- const failAt = CHECKS.findIndex(check => check.fail.includes(d?.state));- const checks = d?.state === 'Ready' ? CHECKS : CHECKS.slice(0, failAt + 1);+ const allChecks = d?.state === 'Preparing' || s?.route === 'native' ? NATIVE_CHECKS : CHECKS;+ const failAt = allChecks.findIndex(check => check.fail.includes(d?.state));+ const checks = d?.state === 'Ready' ? allChecks : allChecks.slice(0, failAt + 1);const rows = checks.map((c,i) => {const issue = i === failAt;- const busy = issue && d.state === 'WdaStarting';+ const busy = issue && (d.state === 'WdaStarting' || d.state === 'Preparing');const hint = issue && (c.hint || (busy && s?.route === 'none' ? STARTING_NO_HID : STARTING_HINT[d.state]));const label = issue ? (busy ? tr('进行中') : tr('需要处理')) : tr('已完成');const sign = issue && c.action === 'sign' && d.signed_in;diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rsindex e324b85..68815be 100644--- a/apps/iphone-control/src/viewer.rs+++ b/apps/iphone-control/src/viewer.rs@@ -697,6 +697,22 @@ async fn picture(mut client: Conn, ctx: &Ctx, req: &Head) -> anyhow::Result<()>let connection = async { ictl_device::Device::find(Some(&udid)).await?.connect_port(MJPEG_PORT).await };let mut remote = match tokio::time::timeout(crate::video::STREAM_IDLE, connection).await {Ok(Ok(r)) => r,+ // no WDA (iOS 27 driven natively, or WDA down): the phone's own HEVC video transcoded to H.264, for a page+ // that can't decode HEVC+ _ if ctx.device_video_allowed && video.is_some() => {+ let Some(enc) = video else { unreachable!("checked") };+ let (src, w) = match crate::video::device::open(&ctx.socket, &udid, low).await {+ Ok(s) => s,+ Err(e) => return reply(&mut client, 502, "text/plain; charset=utf-8", e.as_bytes()).await,+ };+ // the screen in points, to cut the video's padding off by+ let points =+ crate::client::snapshot(&ctx.socket).await.ok().and_then(|s| s.display).map(|d| (d.width, d.height));+ let qp = if low { enc.qp().max(crate::video::LOW_BANDWIDTH_QP) } else { enc.qp() };+ video_head(&mut client).await?;+ crate::video::transcode::serve(enc, qp, points, ctx.acks.clone(), src, w, client).await;+ return Ok(());+ }_ => return reply(&mut client, 502, "text/plain", b"device feed unavailable").await,};tokio::time::timeout(crate::video::STREAM_IDLE, remote.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"))@@ -2102,6 +2118,7 @@ mod tests {foreground: Some("com.apple.Preferences".into()),width: Some(440.0),height: Some(956.0),+ native: false,};let v = status_json(&s, true);assert_eq!(v["wda_ready"], true);@@ -2112,6 +2129,8 @@ mod tests {let down = protocol::StatusData::default();assert_eq!(status_json(&down, true)["route"], "hid", "iOS 27 and later");assert_eq!(status_json(&down, false)["route"], "none", "older: no HID fallback");+ let native = protocol::StatusData { native: true, ..Default::default() };+ assert_eq!(status_json(&native, true)["route"], "native", "iOS 27 driven without WDA");assert!(status_json(&down, true)["locked"].is_null());}diff --git a/apps/iphone-control/src/viewer/api.rs b/apps/iphone-control/src/viewer/api.rsindex 130a6af..8f00021 100644--- a/apps/iphone-control/src/viewer/api.rs+++ b/apps/iphone-control/src/viewer/api.rs@@ -62,6 +62,7 @@ pub(super) fn state_of(s: &DeviceState) -> (&'static str, Option<String>) {DeviceState::NeedsSigning => ("NeedsSigning", None),DeviceState::WdaStarting { last_error } => ("WdaStarting", last_error.clone()),DeviceState::NeedsAutomationPin => ("NeedsAutomationPin", None),+ DeviceState::Preparing { last_error } => ("Preparing", last_error.clone()),DeviceState::Ready => ("Ready", None),}}@@ -132,7 +133,8 @@ pub(super) fn status_json(s: &protocol::StatusData, hid: bool) -> Value {"width": s.width,"height": s.height,// without WDA, screenshots, taps and keys go over CoreDevice HID (iOS 27 and later); otherwise nothing works- "route": if s.wda_ready { "wda" } else if hid { "hid" } else { "none" },+ // driven natively (iOS 27 and later): no WDA at all, by design+ "route": if s.native { "native" } else if s.wda_ready { "wda" } else if hid { "hid" } else { "none" },})}diff --git a/crates/ictl-ax/Cargo.toml b/crates/ictl-ax/Cargo.tomlnew file mode 100644index 0000000..ef9353f--- /dev/null+++ b/crates/ictl-ax/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "ictl-ax"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+license.workspace = true+publish.workspace = true+repository.workspace = true+homepage.workspace = true+description = "remoteAXService client: the phone's accessibility tree without WebDriverAgent (iOS 27+)"++[dependencies]+idevice.workspace = true+plist.workspace = true+tokio.workspace = true+thiserror.workspace = true+tracing.workspace = truediff --git a/crates/ictl-ax/src/archive.rs b/crates/ictl-ax/src/archive.rsnew file mode 100644index 0000000..f6d5845--- /dev/null+++ b/crates/ictl-ax/src/archive.rs@@ -0,0 +1,401 @@+//! NSKeyedArchiver archives: decoding into [`Obj`], with the classes remoteAXService uses kept as objects, and+//! encoding the few values the host sends.+//!+//! `ns-keyed-archive` (which idevice uses) returns instances of custom classes unresolved and turns integer+//! dictionary keys into strings, so this is a small reader and writer of its own.++use std::collections::HashMap;+use std::io::Cursor;++use plist::{Dictionary, Uid, Value};++use crate::{AxError, Result};++/// A decoded archive value+#[derive(Debug, Clone, PartialEq)]+pub enum Obj {+ Null,+ Bool(bool),+ /// Wide enough for both signed values and object IDs above `i64::MAX`+ Int(i128),+ Real(f64),+ Str(String),+ Data(Vec<u8>),+ Array(Vec<Obj>),+ /// Keys keep their decoded type (remoteAXService keys attributes by integer)+ Dict(Vec<(Obj, Obj)>),+ /// `NSValue` holding a CGRect: x, y, width, height+ Rect(f64, f64, f64, f64),+ /// `NSValue` holding a CGPoint+ Point(f64, f64),+ /// An instance of any other class, its fields resolved+ Object {+ class: String,+ fields: Vec<(String, Obj)>,+ },+}++impl Obj {+ pub fn as_str(&self) -> Option<&str> {+ match self {+ Self::Str(s) => Some(s),+ _ => None,+ }+ }++ pub fn as_int(&self) -> Option<i128> {+ match self {+ Self::Int(i) => Some(*i),+ Self::Bool(b) => Some(i128::from(*b)),+ Self::Real(f) if f.fract() == 0.0 => Some(*f as i128),+ _ => None,+ }+ }++ pub fn as_bool(&self) -> Option<bool> {+ match self {+ Self::Bool(b) => Some(*b),+ Self::Int(i) => Some(*i != 0),+ _ => None,+ }+ }++ pub fn as_array(&self) -> Option<&[Obj]> {+ match self {+ Self::Array(a) => Some(a),+ _ => None,+ }+ }++ /// A field of an object, or the value under a string key of a dictionary+ pub fn field(&self, name: &str) -> Option<&Obj> {+ match self {+ Self::Object { fields, .. } => fields.iter().find(|(k, _)| k == name).map(|(_, v)| v),+ Self::Dict(entries) => entries.iter().find(|(k, _)| k.as_str() == Some(name)).map(|(_, v)| v),+ _ => None,+ }+ }++ /// The value under an integer key of a dictionary (attribute numbers)+ pub fn int_key(&self, key: i128) -> Option<&Obj> {+ match self {+ Self::Dict(entries) => entries.iter().find(|(k, _)| k.as_int() == Some(key)).map(|(_, v)| v),+ _ => None,+ }+ }++ pub fn class(&self) -> Option<&str> {+ match self {+ Self::Object { class, .. } => Some(class),+ _ => None,+ }+ }+}++/// Deeper than this is a cycle or garbage: such a value reads as [`Obj::Null`]+const MAX_DEPTH: usize = 200;++/// Decodes one archive+pub fn decode(bytes: &[u8]) -> Result<Obj> {+ let top = Value::from_reader(Cursor::new(bytes)).map_err(|e| AxError::Archive(e.to_string()))?;+ let dict = top.as_dictionary().ok_or_else(|| AxError::Archive("not a dictionary".into()))?;+ let objects =+ dict.get("$objects").and_then(Value::as_array).ok_or_else(|| AxError::Archive("no $objects".into()))?;+ let root = dict+ .get("$top")+ .and_then(Value::as_dictionary)+ .and_then(|t| t.get("root").or_else(|| t.values().next()))+ .ok_or_else(|| AxError::Archive("no $top root".into()))?;+ Ok(Reader { objects }.resolve(root, 0))+}++struct Reader<'a> {+ objects: &'a [Value],+}++impl Reader<'_> {+ fn resolve(&self, v: &Value, depth: usize) -> Obj {+ if depth > MAX_DEPTH {+ return Obj::Null;+ }+ match v {+ Value::Uid(u) => match self.objects.get(u.get() as usize) {+ Some(Value::String(s)) if s == "$null" => Obj::Null,+ Some(o) => self.resolve(o, depth + 1),+ None => Obj::Null,+ },+ Value::Boolean(b) => Obj::Bool(*b),+ Value::Integer(i) => {+ Obj::Int(i.as_signed().map(i128::from).or_else(|| i.as_unsigned().map(i128::from)).unwrap_or(0))+ }+ Value::Real(f) => Obj::Real(*f),+ Value::String(s) => Obj::Str(s.clone()),+ Value::Data(d) => Obj::Data(d.clone()),+ Value::Array(a) => Obj::Array(a.iter().map(|x| self.resolve(x, depth + 1)).collect()),+ Value::Dictionary(d) => self.instance(d, depth),+ _ => Obj::Null,+ }+ }++ fn class_name(&self, d: &Dictionary) -> String {+ d.get("$class")+ .and_then(|c| match c {+ Value::Uid(u) => self.objects.get(u.get() as usize),+ _ => None,+ })+ .and_then(Value::as_dictionary)+ .and_then(|c| c.get("$classname"))+ .and_then(Value::as_string)+ .unwrap_or("")+ .to_owned()+ }++ fn list(&self, d: &Dictionary, key: &str, depth: usize) -> Vec<Obj> {+ d.get(key)+ .and_then(Value::as_array)+ .map(|a| a.iter().map(|x| self.resolve(x, depth + 1)).collect())+ .unwrap_or_default()+ }++ fn instance(&self, d: &Dictionary, depth: usize) -> Obj {+ let class = self.class_name(d);+ match class.as_str() {+ "NSDictionary" | "NSMutableDictionary" => {+ let keys = self.list(d, "NS.keys", depth);+ let values = self.list(d, "NS.objects", depth);+ Obj::Dict(keys.into_iter().zip(values).collect())+ }+ "NSArray" | "NSMutableArray" | "NSSet" | "NSMutableSet" | "NSOrderedSet" | "NSMutableOrderedSet" => {+ Obj::Array(self.list(d, "NS.objects", depth))+ }+ "NSString" | "NSMutableString" => {+ d.get("NS.string").map(|s| self.resolve(s, depth + 1)).unwrap_or(Obj::Str(String::new()))+ }+ "NSAttributedString" | "NSMutableAttributedString" => {+ d.get("NSString").map(|s| self.resolve(s, depth + 1)).unwrap_or(Obj::Str(String::new()))+ }+ "NSData" | "NSMutableData" => d.get("NS.data").map(|s| self.resolve(s, depth + 1)).unwrap_or(Obj::Null),+ "NSValue" => {+ let text =+ |key| d.get(key).map(|v| self.resolve(v, depth + 1)).and_then(|o| o.as_str().map(str::to_owned));+ if let Some(n) = text("NS.rectval").map(|s| numbers(&s)).filter(|n| n.len() == 4) {+ Obj::Rect(n[0], n[1], n[2], n[3])+ } else if let Some(n) = text("NS.pointval").map(|s| numbers(&s)).filter(|n| n.len() == 2) {+ Obj::Point(n[0], n[1])+ } else {+ self.object(class, d, depth)+ }+ }+ _ => self.object(class, d, depth),+ }+ }++ fn object(&self, class: String, d: &Dictionary, depth: usize) -> Obj {+ let fields =+ d.iter().filter(|(k, _)| *k != "$class").map(|(k, v)| (k.clone(), self.resolve(v, depth + 1))).collect();+ Obj::Object { class, fields }+ }+}++/// The numbers in NSStringFromRect's `{{x, y}, {w, h}}` or NSStringFromPoint's `{x, y}`+fn numbers(s: &str) -> Vec<f64> {+ s.split(|c: char| !(c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')))+ .filter_map(|t| t.parse::<f64>().ok())+ .filter(|n| n.is_finite())+ .collect()+}++/// Builds one archive the way NSKeyedArchiver lays it out+struct Writer {+ objects: Vec<Value>,+ classes: HashMap<String, Uid>,+}++impl Writer {+ fn new() -> Self {+ Self { objects: vec![Value::String("$null".into())], classes: HashMap::new() }+ }++ fn add(&mut self, v: Value) -> Uid {+ self.objects.push(v);+ Uid::new(self.objects.len() as u64 - 1)+ }++ fn class(&mut self, name: &str) -> Uid {+ if let Some(u) = self.classes.get(name) {+ return *u;+ }+ let mut d = Dictionary::new();+ d.insert("$classname".into(), Value::String(name.into()));+ d.insert("$classes".into(), Value::Array(vec![Value::String(name.into()), Value::String("NSObject".into())]));+ let u = self.add(Value::Dictionary(d));+ self.classes.insert(name.into(), u);+ u+ }++ fn finish(self, root: Uid) -> Vec<u8> {+ let mut top = Dictionary::new();+ top.insert("root".into(), Value::Uid(root));+ let mut d = Dictionary::new();+ d.insert("$archiver".into(), Value::String("NSKeyedArchiver".into()));+ d.insert("$version".into(), Value::Integer(100_000u64.into()));+ d.insert("$top".into(), Value::Dictionary(top));+ d.insert("$objects".into(), Value::Array(self.objects));+ let mut out = Vec::new();+ // writing a plist into a Vec cannot fail+ plist::to_writer_binary(&mut out, &Value::Dictionary(d)).expect("plist into memory");+ out+ }+}++/// An archived scalar (a bool, an integer, a string) as the root+pub fn encode_scalar(v: Value) -> Vec<u8> {+ let mut w = Writer::new();+ let root = w.add(v);+ w.finish(root)+}++/// Archived bytes: an NSData+pub fn encode_data(bytes: &[u8]) -> Vec<u8> {+ encode_scalar(Value::Data(bytes.to_vec()))+}++/// An archived NSDictionary of string keys and integer values+pub fn encode_int_dict(entries: &[(&str, i64)]) -> Vec<u8> {+ let mut w = Writer::new();+ let keys: Vec<Value> = entries.iter().map(|(k, _)| Value::Uid(w.add(Value::String((*k).into())))).collect();+ let values: Vec<Value> = entries.iter().map(|(_, v)| Value::Uid(w.add(Value::Integer((*v).into())))).collect();+ let class = w.class("NSDictionary");+ let mut d = Dictionary::new();+ d.insert("NS.keys".into(), Value::Array(keys));+ d.insert("NS.objects".into(), Value::Array(values));+ d.insert("$class".into(), Value::Uid(class));+ let root = w.add(Value::Dictionary(d));+ w.finish(root)+}++/// A request parameter+#[derive(Debug, Clone, PartialEq)]+pub enum Param {+ Int(i64),+ Ints(Vec<i64>),+}++/// An element as the phone names it: its process and an ID unique within it+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub struct ObjectRef {+ pub pid: i64,+ pub id: u64,+ pub is_app: bool,+}++/// An archived `AXPTranslatorRequest`, with the keys its `encodeWithCoder:` writes+pub fn encode_request(+ request_type: i64,+ attribute: i64,+ object: Option<ObjectRef>,+ params: &[(&str, Param)],+ client_type: i64,+) -> Vec<u8> {+ let mut w = Writer::new();+ let root = w.add(Value::Boolean(false)); // placeholder, replaced below+ let mut d = Dictionary::new();+ d.insert("requestType".into(), Value::Integer(request_type.into()));+ d.insert("attributeType".into(), Value::Integer(attribute.into()));+ d.insert("actionType".into(), Value::Integer(0.into()));+ d.insert("clientType".into(), Value::Integer(client_type.into()));+ let translation = match object {+ Some(o) => {+ let id = w.add(Value::Integer(o.id.into()));+ let class = w.class("AXPTranslationObject");+ let mut t = Dictionary::new();+ t.insert("$class".into(), Value::Uid(class));+ t.insert("bridgeDelegateToken".into(), Value::Uid(Uid::new(0)));+ t.insert("didPopuldateAppInfo".into(), Value::Boolean(false));+ t.insert("isApplicationElement".into(), Value::Boolean(o.is_app));+ t.insert("objectID".into(), Value::Uid(id));+ t.insert("pid".into(), Value::Integer(o.pid.into()));+ t.insert("rawElementData".into(), Value::Uid(Uid::new(0)));+ w.add(Value::Dictionary(t))+ }+ None => Uid::new(0),+ };+ d.insert("translation".into(), Value::Uid(translation));+ let parameters = if params.is_empty() {+ Uid::new(0)+ } else {+ let keys: Vec<Value> = params.iter().map(|(k, _)| Value::Uid(w.add(Value::String((*k).into())))).collect();+ let values: Vec<Value> = params+ .iter()+ .map(|(_, p)| {+ Value::Uid(match p {+ Param::Int(i) => w.add(Value::Integer((*i).into())),+ Param::Ints(list) => {+ let items: Vec<Value> =+ list.iter().map(|i| Value::Uid(w.add(Value::Integer((*i).into())))).collect();+ let class = w.class("NSArray");+ let mut a = Dictionary::new();+ a.insert("NS.objects".into(), Value::Array(items));+ a.insert("$class".into(), Value::Uid(class));+ w.add(Value::Dictionary(a))+ }+ })+ })+ .collect();+ let class = w.class("NSDictionary");+ let mut p = Dictionary::new();+ p.insert("NS.keys".into(), Value::Array(keys));+ p.insert("NS.objects".into(), Value::Array(values));+ p.insert("$class".into(), Value::Uid(class));+ w.add(Value::Dictionary(p))+ };+ d.insert("parameters".into(), Value::Uid(parameters));+ let class = w.class("AXPTranslatorRequest");+ d.insert("$class".into(), Value::Uid(class));+ w.objects[root.get() as usize] = Value::Dictionary(d);+ w.finish(root)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn scalars_round_trip() {+ assert_eq!(decode(&encode_scalar(Value::Boolean(true))).unwrap(), Obj::Bool(true));+ assert_eq!(decode(&encode_scalar(Value::Integer(7u64.into()))).unwrap(), Obj::Int(7));+ assert_eq!(decode(&encode_data(b"abc")).unwrap(), Obj::Data(b"abc".to_vec()));+ }++ #[test]+ fn dictionaries_keep_their_keys() {+ let d = decode(&encode_int_dict(&[("com.apple.private.DTXConnection", 1)])).unwrap();+ assert_eq!(d.field("com.apple.private.DTXConnection"), Some(&Obj::Int(1)));+ }++ #[test]+ fn a_request_decodes_as_the_object_it_describes() {+ let o = ObjectRef { pid: 39, id: u64::MAX - 5, is_app: true };+ let b = encode_request(5, 0, Some(o), &[("attributes", Param::Ints(vec![8, 21])), ("pid", Param::Int(39))], 2);+ let r = decode(&b).unwrap();+ assert_eq!(r.class(), Some("AXPTranslatorRequest"));+ assert_eq!(r.field("requestType"), Some(&Obj::Int(5)));+ let t = r.field("translation").unwrap();+ assert_eq!(t.class(), Some("AXPTranslationObject"));+ assert_eq!(t.field("objectID"), Some(&Obj::Int(i128::from(u64::MAX - 5))));+ assert_eq!(t.field("bridgeDelegateToken"), Some(&Obj::Null));+ let p = r.field("parameters").unwrap();+ assert_eq!(p.field("attributes"), Some(&Obj::Array(vec![Obj::Int(8), Obj::Int(21)])));+ assert_eq!(p.field("pid"), Some(&Obj::Int(39)));+ // no object, no parameters+ let r = decode(&encode_request(4, 0, None, &[], 2)).unwrap();+ assert_eq!(r.field("translation"), Some(&Obj::Null));+ assert_eq!(r.field("parameters"), Some(&Obj::Null));+ }++ #[test]+ fn ns_values_become_rects_and_points() {+ assert_eq!(numbers("{{20, 116.66666666666667}, {64.5, 40}}"), vec![20.0, 116.666_666_666_666_67, 64.5, 40.0]);+ assert_eq!(numbers("{215, -3e2}"), vec![215.0, -300.0]);+ }+}diff --git a/crates/ictl-ax/src/dtx.rs b/crates/ictl-ax/src/dtx.rsnew file mode 100644index 0000000..2c6d585--- /dev/null+++ b/crates/ictl-ax/src/dtx.rs@@ -0,0 +1,155 @@+//! DTX framing for remoteAXService: reading whole messages, writing method invocations and replies.+//!+//! idevice's `RemoteServerClient` stops its read loop at a message it can't decode, so messages are read here+//! frame by frame. Invocations reuse idevice's message types.++use idevice::dvt::message::{Aux, AuxValue, Message, MessageHeader, PayloadHeader};+use plist::Value;+use tokio::io::{AsyncRead, AsyncReadExt};++use crate::archive::{self, Obj};++/// DTX message types (the first byte of the payload header)+pub const MSG_ACK: u8 = 0;+pub const MSG_INVOCATION: u8 = 2;+pub const MSG_RETURN_VALUE: u8 = 3;++/// One whole message, its fragments joined+#[derive(Debug, Clone)]+pub struct Frame {+ pub identifier: u32,+ pub conversation: u32,+ pub channel: i32,+ pub expects_reply: bool,+ pub msg_type: u8,+ /// The auxiliary arguments that are byte strings (archives), in order+ pub aux: Vec<Vec<u8>>,+ /// The payload proper: the selector of an invocation, the return value of a reply (both archived)+ pub data: Vec<u8>,+}++impl Frame {+ /// The selector of an invocation+ pub fn selector(&self) -> Option<String> {+ if self.msg_type != MSG_INVOCATION || self.data.is_empty() {+ return None;+ }+ archive::decode(&self.data).ok().and_then(|o| o.as_str().map(str::to_owned))+ }++ /// The first auxiliary argument, unarchived (for `processDataFromRemoteDevice:` an NSData holding another+ /// archive)+ pub fn first_arg(&self) -> Option<Obj> {+ self.aux.first().and_then(|b| archive::decode(b).ok())+ }+}++/// Reads the next whole message+pub async fn read_frame<R: AsyncRead + Unpin>(reader: &mut R) -> std::io::Result<Frame> {+ let mut payload = Vec::new();+ loop {+ let mut h = [0u8; 32];+ reader.read_exact(&mut h).await?;+ let word = |i: usize| u32::from_le_bytes([h[i], h[i + 1], h[i + 2], h[i + 3]]);+ if word(0) != 0x1F3D_5B79 {+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "not a DTX message"));+ }+ let fragment = u16::from_le_bytes([h[8], h[9]]);+ let fragments = u16::from_le_bytes([h[10], h[11]]);+ // With several fragments the first one is the header alone+ if fragments > 1 && fragment == 0 {+ continue;+ }+ let len = word(12) as usize;+ if len > 64 << 20 {+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "DTX message too large"));+ }+ let mut part = vec![0u8; len];+ reader.read_exact(&mut part).await?;+ payload.extend(part);+ if fragment + 1 >= fragments {+ return Ok(parse(word(16), word(20), word(24) as i32, word(28) == 1, &payload));+ }+ }+}++fn parse(identifier: u32, conversation: u32, channel: i32, expects_reply: bool, p: &[u8]) -> Frame {+ let mut f =+ Frame { identifier, conversation, channel, expects_reply, msg_type: 0, aux: Vec::new(), data: Vec::new() };+ if p.len() < 16 {+ return f;+ }+ f.msg_type = p[0];+ let aux_len = u32::from_le_bytes([p[4], p[5], p[6], p[7]]) as usize;+ let total = (u32::from_le_bytes([p[8], p[9], p[10], p[11]]) as usize).min(p.len() - 16);+ let aux_len = aux_len.min(total);+ if aux_len > 0+ && let Ok(aux) = Aux::from_bytes(p[16..16 + aux_len].to_vec())+ {+ f.aux = aux+ .values+ .into_iter()+ .filter_map(|v| match v {+ AuxValue::Array(b) => Some(b),+ _ => None,+ })+ .collect();+ }+ f.data = p[16 + aux_len..16 + total].to_vec();+ f+}++/// A method invocation on the global channel; `args` are archives+pub fn invocation(identifier: u32, selector: &str, args: Vec<Vec<u8>>, expects_reply: bool) -> Vec<u8> {+ let aux = (!args.is_empty()).then(|| Aux::from_values(args.into_iter().map(AuxValue::Array).collect()));+ Message::new(+ MessageHeader::new(0, 1, identifier, 0, 0, expects_reply),+ PayloadHeader::method_invocation(),+ aux,+ Some(Value::String(selector.into())),+ )+ .serialize()+}++/// The reply to a message that wants one: an empty acknowledgement, or a return value+pub fn reply(to: &Frame, value: Option<Value>) -> Vec<u8> {+ let with_value = value.is_some();+ let mut b = Message::new(+ MessageHeader::new(0, 1, to.identifier, to.conversation + 1, to.channel, false),+ PayloadHeader::new(),+ None,+ value,+ )+ .serialize();+ if with_value {+ // The payload header follows the 32-byte message header; its first byte is the type, which idevice+ // doesn't let us set+ b[32] = MSG_RETURN_VALUE;+ }+ b+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn an_invocation_reads_back() {+ let args = vec![archive::encode_scalar(Value::Boolean(true))];+ let bytes = invocation(9, "clientNeedsAccessibility:", args, true);+ let f = read_frame(&mut &bytes[..]).await.unwrap();+ assert_eq!((f.identifier, f.conversation, f.expects_reply, f.msg_type), (9, 0, true, MSG_INVOCATION));+ assert_eq!(f.selector().as_deref(), Some("clientNeedsAccessibility:"));+ assert_eq!(f.first_arg(), Some(Obj::Bool(true)));+ }++ #[tokio::test]+ async fn replies_answer_the_conversation() {+ let asked = read_frame(&mut &invocation(4, "hostAPIVersion", vec![], true)[..]).await.unwrap();+ let ack = read_frame(&mut &reply(&asked, None)[..]).await.unwrap();+ assert_eq!((ack.identifier, ack.conversation, ack.expects_reply, ack.msg_type), (4, 1, false, MSG_ACK));+ let answer = read_frame(&mut &reply(&asked, Some(Value::Integer(7u64.into())))[..]).await.unwrap();+ assert_eq!(answer.msg_type, MSG_RETURN_VALUE);+ assert_eq!(archive::decode(&answer.data).unwrap(), Obj::Int(7));+ }+}diff --git a/crates/ictl-ax/src/lib.rs b/crates/ictl-ax/src/lib.rsnew file mode 100644index 0000000..68f038d--- /dev/null+++ b/crates/ictl-ax/src/lib.rs@@ -0,0 +1,40 @@+//! The phone's accessibility tree through `com.apple.accessibility.axAuditDaemon.remoteAXService`, the service+//! Xcode 27's Device Hub uses, without WebDriverAgent (iOS 27 and later).+//!+//! - [`archive`]: NSKeyedArchiver archives (the protocol's payloads)+//! - [`dtx`]: the DTX messages the service speaks+//! - [`session`]: the handshake, the trees the phone pushes after every change, requests+//! - [`tree`]: elements and their attributes+//! - [`xml`]: a tree as WebDriverAgent's `/source` XML, so `ictl_wda::elements` reads it unchanged+//!+//! No device I/O of its own: `ictl-device` opens the connection through its tunnel and hands it to+//! [`session::Session::connect`]. Protocol details: `docs/dev/ios27-native.md`.++pub mod archive;+pub mod dtx;+pub mod session;+pub mod tree;+pub mod xml;++pub use archive::{Obj, ObjectRef};+pub use session::{PushedAt, Response, Session};+pub use tree::{Element, Pushed};++/// The service's name in the phone's RSD list+pub const SERVICE: &str = "com.apple.accessibility.axAuditDaemon.remoteAXService";++#[derive(Debug, thiserror::Error)]+pub enum AxError {+ #[error("remoteAXService: {0}")]+ Io(#[from] std::io::Error),+ #[error("remoteAXService: archive: {0}")]+ Archive(String),+ #[error("remoteAXService: {0}")]+ Protocol(String),+ #[error("remoteAXService: no answer to {0} in time")]+ Timeout(&'static str),+ #[error("remoteAXService: connection closed")]+ Closed,+}++pub type Result<T> = std::result::Result<T, AxError>;diff --git a/crates/ictl-ax/src/session.rs b/crates/ictl-ax/src/session.rsnew file mode 100644index 0000000..9e1b2a3--- /dev/null+++ b/crates/ictl-ax/src/session.rs@@ -0,0 +1,457 @@+//! A remoteAXService session: the handshake Xcode 27's Device Hub does, the trees the phone pushes after every+//! change, and requests (one at a time).+//!+//! The handshake matters: the phone asks the host `hostAPIVersion` and wants every message acknowledged. A host+//! that doesn't answer still gets a first tree but no more pushes once WebDriverAgent isn't running (our rounds 1+//! and 2, `docs/dev/ios27-native.md`). Answering as Xcode does (7), acknowledging, and waiting for+//! `deviceAPIVersion` before `clientNeedsAccessibility:` is what Pinky does (DIYgod/pinky `rax.go`, Apache-2.0).++use std::collections::{HashMap, HashSet, VecDeque};+use std::sync::atomic::{AtomicU32, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use plist::Value;+use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, ReadHalf, WriteHalf};+use tokio::sync::{mpsc, watch};++use crate::archive::{self, Obj, ObjectRef, Param};+use crate::dtx::{self, Frame};+use crate::tree::{self, Element, Pushed, attr};+use crate::{AxError, Result};++/// What Xcode 27's AXAuditRemoteDevice answers when the phone asks `hostAPIVersion`+const HOST_API_VERSION: u64 = 7;+/// The cached-tree client type Xcode uses+const CLIENT_TYPE: i64 = 2;+/// One request's answer takes 5–60 ms over USB+const REQUEST_TIMEOUT: Duration = Duration::from_secs(2);++/// Request types: the cases of `-[AXPTranslator processTranslatorRequest:]`+pub mod request {+ /// An application's element by process (parameter `pid`)+ pub const APP_OBJECT: i64 = 1;+ pub const ATTRIBUTE: i64 = 2;+ pub const FRONTMOST_APP: i64 = 4;+ /// Several attributes (parameter `attributes`)+ pub const ATTRIBUTES: i64 = 5;+ pub const TREE_DUMP: i64 = 11;+}++/// An `AXPTranslatorResponse`+#[derive(Debug, Clone)]+pub struct Response {+ pub request_type: i64,+ pub notification: i64,+ pub error: i64,+ pub object: Option<ObjectRef>,+ pub result: Obj,+}++impl Response {+ fn from_obj(o: &Obj) -> Option<Self> {+ if o.class() != Some("AXPTranslatorResponse") {+ return None;+ }+ let int = |k| o.field(k).and_then(Obj::as_int).unwrap_or(0) as i64;+ Some(Self {+ request_type: int("associatedRequestType"),+ notification: int("notification"),+ error: int("error"),+ object: o.field("associatedTranslationObject").and_then(tree::object_ref),+ result: o.field("resultData").cloned().unwrap_or(Obj::Null),+ })+ }+}++/// A pushed tree and when it came+#[derive(Debug, Clone)]+pub struct PushedAt {+ pub tree: Pushed,+ pub at: Instant,+}++/// Where answers go while requests are out (one caller at a time, [`Session::requests`])+type Waiter = Arc<Mutex<Option<mpsc::UnboundedSender<Response>>>>;+/// Attribute requests sent at once in a walk: answers carry the element they are for, so they need no waiting one by+/// one (a walk of 57 elements took 2.5 s one at a time over USB)+const BATCH: usize = 64;++pub struct Session<S> {+ writer: Arc<tokio::sync::Mutex<WriteHalf<S>>>,+ waiter: Waiter,+ pushes: watch::Receiver<Option<Arc<PushedAt>>>,+ /// When the phone last said the screen is changing (a notification before the next tree)+ changes: watch::Receiver<Option<Instant>>,+ closed: watch::Receiver<bool>,+ requests: tokio::sync::Mutex<()>,+ next_id: AtomicU32,+ reader: tokio::task::JoinHandle<()>,+}++impl<S> Drop for Session<S> {+ fn drop(&mut self) {+ self.reader.abort();+ }+}++async fn send<W: AsyncWrite + Unpin>(w: &mut W, bytes: &[u8]) -> Result<()> {+ w.write_all(bytes).await?;+ w.flush().await?;+ Ok(())+}++/// The reply a message that wants one gets: `hostAPIVersion` is answered, anything else acknowledged+fn answer(frame: &Frame) -> Option<Vec<u8>> {+ if !frame.expects_reply {+ return None;+ }+ let value =+ (frame.selector().as_deref() == Some("hostAPIVersion")).then(|| Value::Integer(HOST_API_VERSION.into()));+ Some(dtx::reply(frame, value))+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send + 'static> Session<S> {+ /// Handshake on a fresh connection to the service, within `wait`+ pub async fn connect(stream: S, wait: Duration) -> Result<Self> {+ let (mut reader, mut writer) = tokio::io::split(stream);+ let capabilities = archive::encode_int_dict(&[+ ("com.apple.private.DTXBlockCompression", 0),+ ("com.apple.private.DTXConnection", 1),+ ]);+ send(&mut writer, &dtx::invocation(1, "_notifyOfPublishedCapabilities:", vec![capabilities], false)).await?;+ send(&mut writer, &dtx::invocation(2, "deviceAPIVersion", Vec::new(), true)).await?;+ tokio::time::timeout(wait, async {+ loop {+ let f = dtx::read_frame(&mut reader).await?;+ if let Some(b) = answer(&f) {+ send(&mut writer, &b).await?;+ }+ if f.identifier == 2 && f.conversation % 2 == 1 {+ return Ok::<_, AxError>(());+ }+ }+ })+ .await+ .map_err(|_| AxError::Timeout("deviceAPIVersion"))??;+ // The translator answers only a client that needs accessibility; it then pushes the screen's tree after+ // every change+ let yes = archive::encode_scalar(Value::Boolean(true));+ send(&mut writer, &dtx::invocation(3, "clientNeedsAccessibility:", vec![yes], false)).await?;++ let writer = Arc::new(tokio::sync::Mutex::new(writer));+ let waiter: Waiter = Arc::default();+ let (push_tx, pushes) = watch::channel(None);+ let (change_tx, changes) = watch::channel(None);+ let (closed_tx, closed) = watch::channel(false);+ let reader = tokio::spawn(read_loop(reader, writer.clone(), waiter.clone(), push_tx, change_tx, closed_tx));+ Ok(Self {+ writer,+ waiter,+ pushes,+ changes,+ closed,+ requests: tokio::sync::Mutex::new(()),+ next_id: AtomicU32::new(4),+ reader,+ })+ }+}++async fn read_loop<S: AsyncRead + AsyncWrite + Unpin + Send>(+ mut reader: ReadHalf<S>,+ writer: Arc<tokio::sync::Mutex<WriteHalf<S>>>,+ waiter: Waiter,+ pushes: watch::Sender<Option<Arc<PushedAt>>>,+ changes: watch::Sender<Option<Instant>>,+ closed: watch::Sender<bool>,+) {+ loop {+ let f = match dtx::read_frame(&mut reader).await {+ Ok(f) => f,+ Err(e) => {+ tracing::debug!("remoteAXService closed: {e}");+ break;+ }+ };+ if let Some(b) = answer(&f)+ && send(&mut *writer.lock().await, &b).await.is_err()+ {+ break;+ }+ if f.selector().as_deref() != Some("processDataFromRemoteDevice:") {+ continue;+ }+ // an NSData holding the archived response+ let Some(Obj::Data(inner)) = f.first_arg() else { continue };+ let Some(r) = archive::decode(&inner).ok().as_ref().and_then(Response::from_obj) else { continue };+ tracing::debug!(+ "remoteAXService: response to request type {}, notification {}, error {}, result {}",+ r.request_type,+ r.notification,+ r.error,+ describe(&r.result)+ );+ if let Some(dump) = r.result.field("treeDump").and_then(Obj::as_array) {+ let kind = r.result.field("treeDumpType").and_then(Obj::as_str).unwrap_or("");+ if let Some(tree) = tree::from_dump(dump, kind) {+ pushes.send_replace(Some(Arc::new(PushedAt { tree, at: Instant::now() })));+ }+ continue;+ }+ if r.notification != 0 || r.request_type == request::TREE_DUMP {+ changes.send_replace(Some(Instant::now()));+ continue;+ }+ if let Some(w) = waiter.lock().unwrap_or_else(|p| p.into_inner()).as_ref() {+ let _ = w.send(r);+ }+ }+ waiter.lock().unwrap_or_else(|p| p.into_inner()).take();+ closed.send_replace(true);+}++/// A result's shape for the debug log: its class and field names (no screen text)+fn describe(o: &Obj) -> String {+ match o {+ Obj::Object { class, fields } => {+ format!("{class}{{{}}}", fields.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>().join(","))+ }+ Obj::Array(a) => format!("[{} items]", a.len()),+ Obj::Dict(d) => format!("{{{} entries}}", d.len()),+ Obj::Null => "null".into(),+ _ => "scalar".into(),+ }+}++impl<S: AsyncRead + AsyncWrite + Unpin + Send + 'static> Session<S> {+ pub fn is_closed(&self) -> bool {+ *self.closed.borrow()+ }++ /// The last tree the phone pushed+ pub fn latest(&self) -> Option<Arc<PushedAt>> {+ self.pushes.borrow().clone()+ }++ /// When the phone last said the screen is changing+ pub fn last_change(&self) -> Option<Instant> {+ *self.changes.borrow()+ }++ /// Waits up to `timeout` for a tree pushed after `since`, preferring a complete one: an initial tree is+ /// returned only when no complete one follows within `timeout`+ pub async fn wait_push(&self, since: Instant, timeout: Duration) -> Option<Arc<PushedAt>> {+ let mut rx = self.pushes.clone();+ let deadline = tokio::time::Instant::now() + timeout;+ loop {+ let cur = rx.borrow_and_update().clone();+ if let Some(p) = &cur+ && p.at > since+ && !p.tree.initial+ {+ return cur;+ }+ match tokio::time::timeout_at(deadline, rx.changed()).await {+ Ok(Ok(())) => continue,+ _ => return cur.filter(|p| p.at > since),+ }+ }+ }++ /// One request, answered within [`REQUEST_TIMEOUT`]. An answer to another request (one that came too late+ /// for it) is passed over+ pub async fn request(+ &self,+ request_type: i64,+ object: Option<ObjectRef>,+ params: &[(&str, Param)],+ ) -> Result<Response> {+ if self.is_closed() {+ return Err(AxError::Closed);+ }+ let _one = self.requests.lock().await;+ let (tx, mut rx) = mpsc::unbounded_channel();+ *self.waiter.lock().unwrap_or_else(|p| p.into_inner()) = Some(tx);+ let r = async {+ let body = archive::encode_data(&archive::encode_request(request_type, 0, object, params, CLIENT_TYPE));+ let id = self.next_id.fetch_add(1, Ordering::Relaxed);+ send(&mut *self.writer.lock().await, &dtx::invocation(id, "processDataFromHost:", vec![body], false))+ .await?;+ let deadline = tokio::time::Instant::now() + REQUEST_TIMEOUT;+ loop {+ let r = match tokio::time::timeout_at(deadline, rx.recv()).await {+ Ok(Some(r)) => r,+ Ok(None) => return Err(AxError::Closed),+ Err(_) => return Err(AxError::Timeout("request")),+ };+ let same_object = object.is_none_or(|o| r.object.is_none_or(|a| (a.pid, a.id) == (o.pid, o.id)));+ if r.request_type == request_type && same_object {+ return Ok(r);+ }+ tracing::debug!("remoteAXService: passed over a late answer to request type {}", r.request_type);+ }+ }+ .await;+ self.waiter.lock().unwrap_or_else(|p| p.into_inner()).take();+ let r = r?;+ if r.error != 0 {+ return Err(AxError::Protocol(format!("request type {request_type} failed: error {}", r.error)));+ }+ Ok(r)+ }++ /// The attributes [`attr::WALK`] of several elements, asked for at once: by element, those answered (an element+ /// that failed, or gone meanwhile, is left out)+ pub async fn attributes_of(&self, objects: &[ObjectRef]) -> Result<HashMap<ObjectRef, Obj>> {+ if self.is_closed() {+ return Err(AxError::Closed);+ }+ let mut out = HashMap::new();+ if objects.is_empty() {+ return Ok(out);+ }+ let _one = self.requests.lock().await;+ let (tx, mut rx) = mpsc::unbounded_channel();+ *self.waiter.lock().unwrap_or_else(|p| p.into_inner()) = Some(tx);+ let r = async {+ let list = Param::Ints(attr::WALK.to_vec());+ {+ let mut w = self.writer.lock().await;+ for o in objects {+ let req = archive::encode_request(+ request::ATTRIBUTES,+ 0,+ Some(*o),+ &[("attributes", list.clone())],+ CLIENT_TYPE,+ );+ let id = self.next_id.fetch_add(1, Ordering::Relaxed);+ let msg = dtx::invocation(id, "processDataFromHost:", vec![archive::encode_data(&req)], false);+ w.write_all(&msg).await?;+ }+ w.flush().await?;+ }+ let mut pending: Vec<ObjectRef> = objects.to_vec();+ let deadline =+ tokio::time::Instant::now() + REQUEST_TIMEOUT + Duration::from_millis(20) * objects.len() as u32;+ while !pending.is_empty() {+ let r = match tokio::time::timeout_at(deadline, rx.recv()).await {+ Ok(Some(r)) => r,+ Ok(None) => return Err(AxError::Closed),+ Err(_) => return Err(AxError::Timeout("attributes")),+ };+ if r.request_type != request::ATTRIBUTES {+ continue;+ }+ // the element it answers for; without one, the oldest still waiting (answers come in order)+ let at = match r.object {+ Some(a) => pending.iter().position(|o| (o.pid, o.id) == (a.pid, a.id)),+ None => Some(0),+ };+ let Some(at) = at else { continue };+ let o = pending.remove(at);+ if r.error == 0 {+ out.insert(o, r.result);+ }+ }+ Ok(())+ }+ .await;+ self.waiter.lock().unwrap_or_else(|p| p.into_inner()).take();+ r.map(|()| out)+ }++ /// The frontmost application's element+ pub async fn frontmost_app(&self) -> Result<ObjectRef> {+ let r = self.request(request::FRONTMOST_APP, None, &[]).await?;+ tree::object_ref(&r.result).ok_or_else(|| AxError::Protocol("no frontmost app".into()))+ }++ /// The application element of process `pid`, in front or not+ pub async fn app_object(&self, pid: i64) -> Result<ObjectRef> {+ let r = self.request(request::APP_OBJECT, None, &[("pid", Param::Int(pid))]).await?;+ tree::object_ref(&r.result).ok_or_else(|| AxError::Protocol(format!("no application element for pid {pid}")))+ }++ /// The attributes [`attr::WALK`] of one element+ pub async fn attributes(&self, object: ObjectRef) -> Result<Obj> {+ let list = Param::Ints(attr::WALK.to_vec());+ Ok(self.request(request::ATTRIBUTES, Some(object), &[("attributes", list)]).await?.result)+ }++ /// `root` and the elements under it, depth first in reading order, each with [`attr::WALK`]: at most `limit` of+ /// them, within `budget`. Each level's elements are asked for at once ([`Self::attributes_of`]). Elements with+ /// any of the traits `prune` are listed, but not walked into. Also says whether the walk got to the end.+ ///+ /// This is how the screen is read: the phone pushes a tree by itself only when the frontmost app changes (and on+ /// connecting), not when an app changes its own screen (iPhone 15 Pro Max, iOS 27.2.1, 2026-11-15; Pinky reads+ /// the same way, DIYgod/pinky `rax.go`). Asking for a tree dump (request type 11) closes the connection+ pub async fn walk(+ &self,+ root: ObjectRef,+ limit: usize,+ budget: Duration,+ prune: u64,+ ) -> Result<(Vec<Element>, bool)> {+ let deadline = Instant::now() + budget;+ let mut attrs: HashMap<ObjectRef, Obj> = HashMap::new();+ let mut seen = HashSet::from([(root.pid, root.id)]);+ let mut frontier: VecDeque<(ObjectRef, usize)> = VecDeque::from([(root, 0)]);+ let mut complete = true;+ while !frontier.is_empty() {+ if attrs.len() >= limit || Instant::now() >= deadline {+ complete = false;+ break;+ }+ let n = frontier.len().min(BATCH).min(limit - attrs.len());+ let chunk: Vec<(ObjectRef, usize)> = frontier.drain(..n).collect();+ let objects: Vec<ObjectRef> = chunk.iter().map(|(o, _)| *o).collect();+ let got = self.attributes_of(&objects).await?;+ for (o, depth) in chunk {+ let Some(a) = got.get(&o) else { continue };+ let (e, kids) = tree::element(Some(o), a, None, depth);+ if (depth > 0 && e.traits & prune != 0) || depth >= 40 {+ continue;+ }+ for k in kids {+ if seen.insert((k.pid, k.id)) {+ frontier.push_back((k, depth + 1));+ }+ }+ }+ attrs.extend(got);+ }+ Ok((tree::assemble(root, &attrs), complete))+ }++ /// The elements under `root` as [`Self::walk`] reads them, without the root: the `parent` indexes point into the+ /// returned list (None for the root's children)+ pub async fn walk_children(+ &self,+ root: ObjectRef,+ limit: usize,+ budget: Duration,+ prune: u64,+ ) -> Result<Vec<Element>> {+ let (mut els, _) = self.walk(root, limit + 1, budget, prune).await?;+ if !els.is_empty() {+ els.remove(0);+ }+ for e in &mut els {+ e.parent = e.parent.and_then(|p| p.checked_sub(1));+ }+ Ok(els)+ }++ /// Tells the phone this client no longer needs accessibility (it then closes the connection)+ pub async fn close(&self) {+ let no = archive::encode_scalar(Value::Boolean(false));+ let id = self.next_id.fetch_add(1, Ordering::Relaxed);+ let msg = dtx::invocation(id, "clientNeedsAccessibility:", vec![no], false);+ let _ =+ tokio::time::timeout(Duration::from_secs(1), async { send(&mut *self.writer.lock().await, &msg).await })+ .await;+ self.reader.abort();+ }+}diff --git a/crates/ictl-ax/src/tree.rs b/crates/ictl-ax/src/tree.rsnew file mode 100644index 0000000..7791100--- /dev/null+++ b/crates/ictl-ax/src/tree.rs@@ -0,0 +1,320 @@+//! Elements as remoteAXService describes them, and the trees the phone pushes.+//!+//! Attribute numbers are AccessibilityPlatformTranslation's, as iOS 27 answers them (not public; the same numbers+//! as Pinky, DIYgod/pinky `internal/driver/ios/rax.go`, Apache-2.0, and our own round of experiments,+//! `docs/dev/ios27-native.md`).++use std::collections::{HashMap, HashSet};++use crate::archive::{Obj, ObjectRef};++pub mod attr {+ pub const ACTIVATION_POINT: i128 = 1;+ pub const ATTRIBUTED_LABEL: i128 = 3;+ pub const CHILDREN: i128 = 8;+ /// Children in VoiceOver's order+ pub const NAVIGATION_ORDER: i128 = 9;+ pub const FRAME: i128 = 21;+ pub const IDENTIFIER: i128 = 25;+ pub const IS_ELEMENT: i128 = 26;+ pub const ENABLED: i128 = 27;+ pub const FOCUSED: i128 = 28;+ pub const SELECTED: i128 = 30;+ pub const VISIBLE: i128 = 32;+ pub const LABEL: i128 = 33;+ pub const PLACEHOLDER: i128 = 42;+ pub const ROLE: i128 = 45;+ pub const VALUE: i128 = 53;+ /// XCUIElementType+ pub const AUTOMATION_TYPE: i128 = 61;+ pub const IS_REMOTE: i128 = 66;+ pub const REMOTE_PID: i128 = 69;+ pub const TRAITS: i128 = 77;++ /// What a walk asks of each element+ pub const WALK: [i64; 16] = [+ CHILDREN as i64,+ NAVIGATION_ORDER as i64,+ ACTIVATION_POINT as i64,+ FRAME as i64,+ IDENTIFIER as i64,+ IS_ELEMENT as i64,+ ENABLED as i64,+ FOCUSED as i64,+ SELECTED as i64,+ VISIBLE as i64,+ LABEL as i64,+ PLACEHOLDER as i64,+ VALUE as i64,+ AUTOMATION_TYPE as i64,+ IS_REMOTE as i64,+ TRAITS as i64,+ ];+}++/// UIAccessibilityTraits bits, private ones included (observed on iOS 27)+pub mod trait_bit {+ pub const BUTTON: u64 = 1;+ pub const LINK: u64 = 1 << 1;+ pub const IMAGE: u64 = 1 << 2;+ pub const KEYBOARD_KEY: u64 = 1 << 5;+ pub const STATIC_TEXT: u64 = 1 << 6;+ pub const SEARCH_FIELD: u64 = 1 << 10;+ pub const ADJUSTABLE: u64 = 1 << 12;+ pub const HEADER: u64 = 1 << 16;+ pub const TEXT_FIELD: u64 = 1 << 18;+ /// SpringBoard's status bar items+ pub const STATUS_BAR: u64 = 1 << 23;+ /// A view showing another process's elements, which come right after it with frames relative to it+ pub const REMOTE_HOST: u64 = 1 << 34;+ pub const SWITCH: u64 = 1 << 53;+}++/// One element+#[derive(Debug, Clone, PartialEq, Default)]+pub struct Element {+ pub object: Option<ObjectRef>,+ /// Index of the parent in the same list; None for the first element (the application)+ pub parent: Option<usize>,+ pub depth: usize,+ pub label: String,+ pub value: String,+ pub placeholder: String,+ pub identifier: String,+ /// x, y, width, height in screen points (for another process's elements: relative to their host, see+ /// [`crate::xml`])+ pub frame: Option<(f64, f64, f64, f64)>,+ pub activation: Option<(f64, f64)>,+ /// XCUIElementType; 0 in the first tree pushed after a change+ pub xc_type: i64,+ pub traits: u64,+ pub is_element: bool,+ pub enabled: bool,+ pub selected: bool,+ pub focused: bool,+ pub visible: bool,+ pub remote: bool,+}++impl Element {+ pub fn pid(&self) -> i64 {+ self.object.map_or(0, |o| o.pid)+ }+}++pub(crate) fn object_ref(o: &Obj) -> Option<ObjectRef> {+ if o.class() != Some("AXPTranslationObject") {+ return None;+ }+ Some(ObjectRef {+ pid: o.field("pid").and_then(Obj::as_int).unwrap_or(0) as i64,+ id: o.field("objectID").and_then(Obj::as_int).unwrap_or(0) as u64,+ is_app: o.field("isApplicationElement").and_then(Obj::as_bool).unwrap_or(false),+ })+}++fn text(o: Option<&Obj>) -> String {+ match o {+ Some(Obj::Str(s)) => s.clone(),+ Some(Obj::Int(i)) => i.to_string(),+ Some(Obj::Real(f)) if f.is_finite() => {+ if f.fract() == 0.0 {+ format!("{f:.0}")+ } else {+ f.to_string()+ }+ }+ Some(Obj::Bool(b)) => u8::from(*b).to_string(),+ _ => String::new(),+ }+}++/// An element from its attributes (a dictionary keyed by attribute number), and its children+pub fn element(+ object: Option<ObjectRef>,+ attrs: &Obj,+ parent: Option<usize>,+ depth: usize,+) -> (Element, Vec<ObjectRef>) {+ let a = |k| attrs.int_key(k);+ let flag = |k, default| a(k).and_then(Obj::as_bool).unwrap_or(default);+ let mut label = text(a(attr::LABEL));+ if label.is_empty() {+ label = text(a(attr::ATTRIBUTED_LABEL));+ }+ let mut value = text(a(attr::VALUE));+ let mut identifier = text(a(attr::IDENTIFIER));+ // Some apps carry the value in the identifier (Calculator's display: "StandardInputView;value:144")+ if let Some((name, v)) = identifier.split_once(";value:")+ && !name.is_empty()+ {+ if value.is_empty() {+ value = v.to_owned();+ }+ identifier = name.to_owned();+ }+ let e = Element {+ object,+ parent,+ depth,+ label,+ value,+ placeholder: text(a(attr::PLACEHOLDER)),+ identifier,+ frame: match a(attr::FRAME) {+ Some(Obj::Rect(x, y, w, h)) => Some((*x, *y, *w, *h)),+ _ => None,+ },+ activation: match a(attr::ACTIVATION_POINT) {+ Some(Obj::Point(x, y)) => Some((*x, *y)),+ _ => None,+ },+ xc_type: a(attr::AUTOMATION_TYPE).and_then(Obj::as_int).unwrap_or(0) as i64,+ traits: a(attr::TRAITS).and_then(Obj::as_int).unwrap_or(0) as u64,+ is_element: flag(attr::IS_ELEMENT, false),+ enabled: flag(attr::ENABLED, true),+ selected: flag(attr::SELECTED, false),+ focused: flag(attr::FOCUSED, false),+ visible: flag(attr::VISIBLE, true),+ remote: flag(attr::IS_REMOTE, false),+ };+ let list = a(attr::NAVIGATION_ORDER).and_then(Obj::as_array).or_else(|| a(attr::CHILDREN).and_then(Obj::as_array));+ let kids = list.map(|l| l.iter().filter_map(object_ref).collect()).unwrap_or_default();+ (e, kids)+}++/// Deeper than this the walk stops (a malformed tree, or a cycle)+const MAX_DEPTH: usize = 60;++/// Elements in reading order from `root`, depth first, each with the attributes `attrs` holds for it. Elements+/// without attributes are left out with their descendants+pub fn assemble(root: ObjectRef, attrs: &HashMap<ObjectRef, Obj>) -> Vec<Element> {+ let mut out = Vec::new();+ let mut seen = HashSet::new();+ let mut stack = vec![(root, None, 0usize)];+ while let Some((o, parent, depth)) = stack.pop() {+ // the same element can be listed under two parents+ let key = (o.pid, o.id);+ let Some(a) = attrs.get(&o) else { continue };+ if depth > MAX_DEPTH || !seen.insert(key) {+ continue;+ }+ let (e, kids) = element(Some(o), a, parent, depth);+ out.push(e);+ let idx = out.len() - 1;+ for k in kids.into_iter().rev() {+ stack.push((k, Some(idx), depth + 1));+ }+ }+ out+}++/// A tree the phone pushed after the screen changed+#[derive(Debug, Clone)]+pub struct Pushed {+ /// The frontmost application's element first+ pub elements: Vec<Element>,+ /// The first tree after a change: it lacks some attributes (the element types); a second, complete one+ /// follows within about half a second+ pub initial: bool,+}++impl Pushed {+ /// The application's process+ pub fn app_pid(&self) -> i64 {+ self.elements.first().map_or(0, Element::pid)+ }+}++/// The tree in a `treeDump` result (the list of responses the phone pushes): the frontmost app's element+/// (request type 4) and every element's attributes (type 5)+pub fn from_dump(list: &[Obj], kind: &str) -> Option<Pushed> {+ let mut app = None;+ let mut attrs = HashMap::new();+ for r in list {+ let request_type = r.field("associatedRequestType").and_then(Obj::as_int);+ let Some(result) = r.field("resultData") else { continue };+ match request_type {+ Some(4) => app = object_ref(result),+ Some(5) => {+ if let Some(o) = r.field("associatedTranslationObject").and_then(object_ref) {+ attrs.insert(o, result.clone());+ }+ }+ _ => {}+ }+ }+ let elements = assemble(app?, &attrs);+ (!elements.is_empty()).then_some(Pushed { elements, initial: kind == "AXPTreeDumpTypeInitialDump" })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn obj(pid: i64, id: u64) -> Obj {+ Obj::Object {+ class: "AXPTranslationObject".into(),+ fields: vec![("pid".into(), Obj::Int(pid.into())), ("objectID".into(), Obj::Int(id.into()))],+ }+ }++ pub(crate) fn attrs(entries: Vec<(i128, Obj)>) -> Obj {+ Obj::Dict(entries.into_iter().map(|(k, v)| (Obj::Int(k), v)).collect())+ }++ fn response(kind: i128, object: Option<Obj>, result: Obj) -> Obj {+ let mut fields = vec![("associatedRequestType".to_owned(), Obj::Int(kind)), ("resultData".to_owned(), result)];+ if let Some(o) = object {+ fields.push(("associatedTranslationObject".into(), o));+ }+ Obj::Object { class: "AXPTranslatorResponse".into(), fields }+ }++ #[test]+ fn a_dump_is_assembled_in_reading_order() {+ let list = vec![+ response(4, None, obj(10, 1)),+ response(+ 5,+ Some(obj(10, 1)),+ attrs(vec![+ (attr::LABEL, Obj::Str("设置".into())),+ (attr::CHILDREN, Obj::Array(vec![obj(10, 2), obj(10, 3)])),+ (attr::FRAME, Obj::Rect(0.0, 0.0, 430.0, 932.0)),+ ]),+ ),+ response(+ 5,+ Some(obj(10, 3)),+ attrs(vec![+ (attr::LABEL, Obj::Str("通用".into())),+ (attr::AUTOMATION_TYPE, Obj::Int(9)),+ (attr::TRAITS, Obj::Int(1)),+ (attr::IDENTIFIER, Obj::Str("com.apple.settings.general".into())),+ ]),+ ),+ response(+ 5,+ Some(obj(10, 2)),+ attrs(vec![(attr::LABEL, Obj::Str("飞行模式".into())), (attr::VALUE, Obj::Int(0))]),+ ),+ ];+ let p = from_dump(&list, "AXPTreeDumpTypeAdditionalData").unwrap();+ assert!(!p.initial);+ assert_eq!(p.app_pid(), 10);+ let labels: Vec<_> = p.elements.iter().map(|e| e.label.as_str()).collect();+ assert_eq!(labels, ["设置", "飞行模式", "通用"]);+ assert_eq!(p.elements[1].parent, Some(0));+ assert_eq!(p.elements[1].value, "0");+ assert_eq!(p.elements[2].xc_type, 9);+ assert_eq!(p.elements[2].identifier, "com.apple.settings.general");+ }++ #[test]+ fn a_value_kept_in_the_identifier_is_split_off() {+ let (e, _) =+ element(None, &attrs(vec![(attr::IDENTIFIER, Obj::Str("StandardInputView;value:144".into()))]), None, 0);+ assert_eq!((e.identifier.as_str(), e.value.as_str()), ("StandardInputView", "144"));+ }+}diff --git a/crates/ictl-ax/src/xml.rs b/crates/ictl-ax/src/xml.rsnew file mode 100644index 0000000..d5634fe--- /dev/null+++ b/crates/ictl-ax/src/xml.rs@@ -0,0 +1,547 @@+//! An accessibility tree as the XML WebDriverAgent's `/source` gives (`XCUIElementType…` tags with `type`,+//! `label`, `name`, `value`, `x`, `y`, `width`, `height`), so `ictl_wda::elements::parse_tree` reads it unchanged:+//! finding by text, what covers what, the keyboard, alerts, the lock screen and the passcode pad.+//!+//! Elements of other processes (a keyboard, an extension, a remote view) come with frames relative to the view+//! hosting them, which carries [`trait_bit::REMOTE_HOST`] and comes right before them; they are moved to screen+//! points by that host. Those without a host (home screen widgets) can't be placed and are left out. A process+//! whose elements are mostly single characters is the on-screen keyboard: it becomes one `Keyboard` element.+//! The same rules as Pinky (DIYgod/pinky `observe_rax.go`, Apache-2.0).++use std::collections::{HashMap, HashSet};+use std::fmt::Write;++use crate::tree::{Element, trait_bit};++/// x, y, width, height in screen points+type Frame = (f64, f64, f64, f64);++/// XCUIElementType names, by the enum's value (Apple's public order)+pub const TYPES: [&str; 83] = [+ "Any",+ "Other",+ "Application",+ "Group",+ "Window",+ "Sheet",+ "Drawer",+ "Alert",+ "Dialog",+ "Button",+ "RadioButton",+ "RadioGroup",+ "CheckBox",+ "DisclosureTriangle",+ "PopUpButton",+ "ComboBox",+ "MenuButton",+ "ToolbarButton",+ "Popover",+ "Keyboard",+ "Key",+ "NavigationBar",+ "TabBar",+ "TabGroup",+ "Toolbar",+ "StatusBar",+ "Table",+ "TableRow",+ "TableColumn",+ "Outline",+ "OutlineRow",+ "Browser",+ "CollectionView",+ "Slider",+ "PageIndicator",+ "ProgressIndicator",+ "ActivityIndicator",+ "SegmentedControl",+ "Picker",+ "PickerWheel",+ "Switch",+ "Toggle",+ "Link",+ "Image",+ "Icon",+ "SearchField",+ "ScrollView",+ "ScrollBar",+ "StaticText",+ "TextField",+ "SecureTextField",+ "DatePicker",+ "TextView",+ "Menu",+ "MenuItem",+ "MenuBar",+ "MenuBarItem",+ "Map",+ "WebView",+ "IncrementArrow",+ "DecrementArrow",+ "Timeline",+ "RatingIndicator",+ "ValueIndicator",+ "SplitGroup",+ "Splitter",+ "RelevanceIndicator",+ "ColorWell",+ "HelpTag",+ "Matte",+ "DockItem",+ "Ruler",+ "RulerMarker",+ "Grid",+ "LevelIndicator",+ "Cell",+ "LayoutArea",+ "LayoutItem",+ "Handle",+ "Stepper",+ "Tab",+ "TouchBar",+ "StatusItem",+];++/// The element's type name: the XCUIElementType, or, in a first pushed tree that lacks it, a guess from the traits+pub fn kind(e: &Element) -> &'static str {+ let k = typed_kind(e);+ // the lock screen's passcode field reads as a plain text field here (typed or not); WDA calls it a secure one,+ // which is what finds it when unlocking (`ictl_wda::elements::passcode_field`, `cover_sheet`)+ if k == "TextField" && passcode_value(&e.value) { "SecureTextField" } else { k }+}++fn typed_kind(e: &Element) -> &'static str {+ if let Some(t) = usize::try_from(e.xc_type).ok().filter(|t| (1..TYPES.len()).contains(t)) {+ return TYPES[t];+ }+ let t = e.traits;+ let has = |bit| t & bit != 0;+ if has(trait_bit::KEYBOARD_KEY) {+ "Key"+ } else if has(trait_bit::SEARCH_FIELD) {+ "SearchField"+ } else if has(trait_bit::TEXT_FIELD) {+ "TextField"+ } else if has(trait_bit::SWITCH) {+ "Switch"+ } else if has(trait_bit::ADJUSTABLE) {+ "Slider"+ } else if has(trait_bit::LINK) {+ "Link"+ } else if has(trait_bit::BUTTON) {+ "Button"+ } else if has(trait_bit::IMAGE) {+ "Image"+ } else if has(trait_bit::STATIC_TEXT) {+ "StaticText"+ } else {+ "Other"+ }+}++/// A passcode field's value: 「共6位数,已输入2位」, "6-digit passcode, 2 entered" (two numbers, and the words for it)+fn passcode_value(v: &str) -> bool {+ let numbers = v.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).count();+ let lower = v.to_lowercase();+ numbers == 2 && (v.contains("位") || lower.contains("passcode") || lower.contains("digit"))+}++/// At least this many one-character elements make a process the keyboard+const KEYBOARD_KEYS: usize = 8;++fn is_key_char(label: &str) -> bool {+ let mut c = label.chars();+ c.next().is_some() && c.next().is_none()+}++/// Where each element goes, in screen points; None = left out+fn place(els: &[Element], keyboard: &HashSet<i64>, web: &HashSet<i64>) -> Vec<Option<Frame>> {+ let app_pid = els.first().map_or(0, Element::pid);+ let mut offset: HashMap<i64, (f64, f64)> = HashMap::new();+ let mut host: Option<Frame> = None;+ let mut out = Vec::with_capacity(els.len());+ for (i, e) in els.iter().enumerate() {+ let parent_out = e.parent.map(|p| out.get(p).copied().flatten().is_some());+ if parent_out == Some(false) {+ // under something left out+ out.push(None);+ continue;+ }+ if e.traits & trait_bit::REMOTE_HOST != 0 && e.frame.is_some() {+ host = e.frame;+ } else if e.pid() == app_pid {+ host = None;+ }+ let Some((x, y, w, h)) = e.frame else {+ out.push(Some((0.0, 0.0, 0.0, 0.0)));+ continue;+ };+ if i == 0 || e.pid() == app_pid {+ out.push(Some((x, y, w, h)));+ continue;+ }+ if let Some(hf) = host+ && !offset.contains_key(&e.pid())+ && w <= hf.2 + 1.0+ && h <= hf.3 + 1.0+ {+ offset.insert(e.pid(), (hf.0, hf.1));+ }+ match offset.get(&e.pid()) {+ Some((dx, dy)) => out.push(Some((x + dx, y + dy, w, h))),+ // the keyboard is kept (it marks the keyboard as shown) even when its keys can't be placed+ None if keyboard.contains(&e.pid()) => out.push(Some((0.0, 0.0, 0.0, 0.0))),+ // a page (WebKit's web content process) is listed without a host, in screen points (Pinky+ // `webcontent.go`)+ None if web.contains(&e.pid()) => out.push(Some((x, y, w, h))),+ None => out.push(None),+ }+ }+ out+}++fn esc(s: &str, out: &mut String) {+ for c in s.chars() {+ match c {+ '&' => out.push_str("&"),+ '<' => out.push_str("<"),+ '>' => out.push_str(">"),+ '"' => out.push_str("""),+ '\n' => out.push_str(" "),+ c if (c as u32) < 0x20 => {}+ c => out.push(c),+ }+ }+}++fn open_tag(out: &mut String, kind: &str, e: &Element, (x, y, w, h): Frame, close: bool) {+ let _ = write!(out, "<XCUIElementType{kind} type=\"XCUIElementType{kind}\"");+ let mut field = |name: &str, v: &str| {+ if !v.is_empty() {+ let _ = write!(out, " {name}=\"");+ esc(v, out);+ out.push('"');+ }+ };+ field("label", &e.label);+ field("name", if e.identifier.is_empty() { &e.label } else { &e.identifier });+ field("value", if e.value.is_empty() { &e.placeholder } else { &e.value });+ field("placeholderValue", &e.placeholder);+ let _ = write!(+ out,+ " enabled=\"{}\" selected=\"{}\" focused=\"{}\" x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"{}>",+ e.enabled,+ e.selected,+ e.focused,+ x.round() as i64,+ y.round() as i64,+ w.round() as i64,+ h.round() as i64,+ if close { "/" } else { "" }+ );+}++/// The XML for `app` (the frontmost application's tree, its element first) with `overlays` (what SpringBoard+/// draws over it: alerts, banners; in screen points) after it, on a `width`×`height` screen. `web`: the processes+/// that are WebKit's web content (a page's elements), placed as they come. `springboard_front`: SpringBoard is the+/// app in front, as when it asks something over an app (see [`looks_like_dialog`])+pub fn to_xml(+ app: &[Element],+ overlays: &[Element],+ width: f64,+ height: f64,+ web: &HashSet<i64>,+ springboard_front: bool,+) -> String {+ let app_pid = app.first().map_or(0, Element::pid);+ let mut keys: HashMap<i64, usize> = HashMap::new();+ // a page's own one-letter links are no keys+ for e in app.iter().filter(|e| e.pid() != app_pid && !web.contains(&e.pid()) && is_key_char(&e.label)) {+ *keys.entry(e.pid()).or_default() += 1;+ }+ let keyboard: HashSet<i64> = keys.into_iter().filter(|(_, n)| *n >= KEYBOARD_KEYS).map(|(p, _)| p).collect();+ let placed = place(app, &keyboard, web);++ let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");+ let root = app.first().cloned().unwrap_or_default();+ open_tag(&mut out, "Application", &root, (0.0, 0.0, width, height), false);+ // the keyboard's keys, gathered under one Keyboard element at the end (drawn over the app)+ let mut kb_keys: Vec<(usize, Frame)> = Vec::new();+ let dialog = springboard_front && looks_like_dialog(app);+ if dialog {+ let title = app+ .iter()+ .skip(1)+ .find(|e| kind(e) == "StaticText" && !e.label.is_empty() && e.traits & trait_bit::STATUS_BAR == 0);+ let a = Element {+ label: title.map(|e| e.label.clone()).unwrap_or_default(),+ enabled: true,+ visible: true,+ ..Default::default()+ };+ let boxes: Vec<(usize, Frame)> =+ placed.iter().enumerate().skip(1).filter_map(|(i, f)| f.map(|f| (i, f))).collect();+ open_tag(&mut out, "Alert", &a, keys_box(&boxes).unwrap_or((0.0, 0.0, width, height)), false);+ }+ write_children(&mut out, app, &placed, Some(0), 0, &keyboard, &mut kb_keys);+ if dialog {+ out.push_str("</XCUIElementTypeAlert>");+ }+ let has_keyboard_type = app.iter().zip(&placed).any(|(e, p)| p.is_some() && kind(e) == "Keyboard");+ if !keyboard.is_empty() && !has_keyboard_type {+ let frame = keys_box(&kb_keys).unwrap_or((0.0, height * 0.6, width, height * 0.4));+ let kb = Element { enabled: true, visible: true, ..Default::default() };+ open_tag(&mut out, "Keyboard", &kb, frame, kb_keys.is_empty());+ if !kb_keys.is_empty() {+ for (i, f) in &kb_keys {+ open_tag(&mut out, "Key", &app[*i], *f, true);+ }+ out.push_str("</XCUIElementTypeKeyboard>");+ }+ }+ // SpringBoard over the app, but not its status bar+ let shown: Vec<Option<Frame>> = overlays+ .iter()+ .map(|e| (e.traits & trait_bit::STATUS_BAR == 0).then_some(e.frame.unwrap_or_default()))+ .collect();+ let shown = inherit_skips(overlays, shown);+ write_children(&mut out, overlays, &shown, None, 0, &HashSet::new(), &mut Vec::new());+ out.push_str("</XCUIElementTypeApplication>");+ out+}++/// SpringBoard in front with a few texts and two buttons or more, and none of the home screen's icons, a+/// keyboard, the passcode field or list cells: a question it asks over an app («“设置”想从“dtpasteboardd”粘贴»,+/// permission requests). Read through WDA it is an Alert; here it comes without one (iPhone 15 Pro Max, iOS 27.2.1)+fn looks_like_dialog(app: &[Element]) -> bool {+ // the status bar's items don't count (with SpringBoard in front they are its own: the lock screen, Face ID's+ // prompt read as an alert titled with the time)+ let shown: Vec<&Element> = app.iter().skip(1).filter(|e| e.traits & trait_bit::STATUS_BAR == 0).collect();+ let kinds: Vec<&str> = shown.iter().map(|e| kind(e)).collect();+ shown.len() <= 12+ && kinds.iter().filter(|k| **k == "Button").count() >= 2+ && kinds.contains(&"StaticText")+ && !kinds.iter().any(|k| matches!(*k, "Icon" | "Key" | "SecureTextField" | "Cell" | "Alert"))+}++/// Elements under a left-out element are left out too+fn inherit_skips(els: &[Element], mut placed: Vec<Option<Frame>>) -> Vec<Option<Frame>> {+ for i in 0..els.len() {+ if let Some(p) = els[i].parent+ && p < i+ && placed[p].is_none()+ {+ placed[i] = None;+ }+ }+ placed+}++fn keys_box(keys: &[(usize, Frame)]) -> Option<Frame> {+ let real: Vec<_> = keys.iter().map(|(_, f)| *f).filter(|f| f.2 > 0.0 && f.3 > 0.0).collect();+ let x1 = real.iter().map(|f| f.0).reduce(f64::min)?;+ let y1 = real.iter().map(|f| f.1).reduce(f64::min)?;+ let x2 = real.iter().map(|f| f.0 + f.2).reduce(f64::max)?;+ let y2 = real.iter().map(|f| f.1 + f.3).reduce(f64::max)?;+ Some((x1, y1, x2 - x1, y2 - y1))+}++/// Writes the elements whose parent is `parent` (None: the roots of a list, as SpringBoard's overlays have), each+/// with its own children+fn write_children(+ out: &mut String,+ els: &[Element],+ placed: &[Option<Frame>],+ parent: Option<usize>,+ depth: usize,+ keyboard: &HashSet<i64>,+ kb_keys: &mut Vec<(usize, Frame)>,+) {+ for (i, e) in els.iter().enumerate() {+ if e.parent != parent || depth > 80 {+ continue;+ }+ let Some(frame) = placed[i] else { continue };+ if keyboard.contains(&e.pid()) {+ if is_key_char(&e.label) && frame.2 > 0.0 && frame.3 > 0.0 {+ kb_keys.push((i, frame));+ }+ write_children(out, els, placed, Some(i), depth + 1, keyboard, kb_keys);+ continue;+ }+ let has_children = els.iter().any(|c| c.parent == Some(i));+ open_tag(out, kind(e), e, frame, !has_children);+ if has_children {+ write_children(out, els, placed, Some(i), depth + 1, keyboard, kb_keys);+ let _ = write!(out, "</XCUIElementType{}>", kind(e));+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::archive::ObjectRef;++ fn el(pid: i64, id: u64, parent: Option<usize>, label: &str, xc: i64, frame: Frame) -> Element {+ Element {+ object: Some(ObjectRef { pid, id, is_app: parent.is_none() }),+ parent,+ label: label.into(),+ xc_type: xc,+ frame: Some(frame),+ enabled: true,+ visible: true,+ ..Default::default()+ }+ }++ #[test]+ fn the_app_and_its_elements_nest_like_wda_source() {+ let els = vec![+ el(10, 1, None, "设置", 2, (0.0, 0.0, 430.0, 932.0)),+ el(10, 2, Some(0), "", 1, (0.0, 0.0, 430.0, 932.0)),+ el(10, 3, Some(1), "通用", 9, (20.0, 745.3, 390.0, 52.3)),+ el(10, 4, Some(0), "a & <b>", 48, (1.0, 2.0, 3.0, 4.0)),+ ];+ let xml = to_xml(&els, &[], 430.0, 932.0, &HashSet::new(), false);+ assert!(xml.contains(r#"<XCUIElementTypeApplication type="XCUIElementTypeApplication" label="设置""#), "{xml}");+ assert!(xml.contains(r#"<XCUIElementTypeOther type="XCUIElementTypeOther" enabled"#), "{xml}");+ assert!(+ xml.contains(r#"label="通用" name="通用" enabled="true" selected="false" focused="false" x="20" y="745" width="390" height="52"/>"#),+ "{xml}"+ );+ assert!(xml.contains("</XCUIElementTypeOther>"));+ assert!(xml.contains("a & <b>"));+ assert!(xml.ends_with("</XCUIElementTypeApplication>"));+ // the button sits inside the Other, which is inside the app+ let (o, b) = (xml.find("XCUIElementTypeOther ").unwrap(), xml.find("通用").unwrap());+ assert!(o < b && b < xml.find("</XCUIElementTypeOther>").unwrap());+ }++ #[test]+ fn another_process_is_placed_by_its_host_or_left_out() {+ let mut host = el(10, 2, Some(0), "", 1, (27.0, 81.0, 179.0, 203.0));+ host.traits = trait_bit::REMOTE_HOST;+ let els = vec![+ el(10, 1, None, "主屏", 2, (0.0, 0.0, 430.0, 932.0)),+ host,+ el(77, 1, Some(1), "上海市", 48, (19.0, 19.0, 52.0, 13.0)),+ el(10, 3, Some(0), "时钟", 44, (228.0, 402.0, 72.0, 95.0)),+ // a widget with no host before it+ el(88, 1, Some(0), "今天无日程", 48, (19.0, 97.0, 85.0, 21.0)),+ ];+ let xml = to_xml(&els, &[], 430.0, 932.0, &HashSet::new(), false);+ assert!(+ xml.contains(+ r#"label="上海市" name="上海市" enabled="true" selected="false" focused="false" x="46" y="100""#+ ),+ "{xml}"+ );+ assert!(!xml.contains("今天无日程"), "{xml}");+ assert!(xml.contains("时钟"));+ }++ #[test]+ fn a_process_of_single_characters_is_the_keyboard() {+ let mut els = vec![el(10, 1, None, "备忘录", 2, (0.0, 0.0, 430.0, 932.0))];+ for (i, c) in "qwertyuiop".chars().enumerate() {+ els.push(el(55, i as u64 + 1, Some(0), &c.to_string(), 0, (i as f64 * 40.0, 600.0, 40.0, 50.0)));+ }+ let xml = to_xml(&els, &[], 430.0, 932.0, &HashSet::new(), false);+ // the keys can't be placed (no host): one Keyboard over the lower part of the screen+ assert!(xml.contains(r#"<XCUIElementTypeKeyboard type="XCUIElementTypeKeyboard" enabled="true" selected="false" focused="false" x="0" y="559" width="430" height="373"/>"#), "{xml}");+ assert!(!xml.contains(r#"label="q""#));+ }++ #[test]+ fn springboard_overlays_go_last_without_the_status_bar() {+ let app = vec![el(10, 1, None, "备忘录", 2, (0.0, 0.0, 430.0, 932.0))];+ let mut time = el(39, 2, None, "14:03", 48, (0.0, 0.0, 80.0, 30.0));+ time.traits = trait_bit::STATUS_BAR;+ let overlays = vec![+ time,+ el(39, 3, None, "“备忘录”想从“dtpasteboardd”粘贴", 7, (55.0, 390.0, 320.0, 175.0)),+ el(39, 4, Some(1), "允许粘贴", 9, (71.0, 501.0, 140.0, 49.0)),+ ];+ let xml = to_xml(&app, &overlays, 430.0, 932.0, &HashSet::new(), false);+ assert!(!xml.contains("14:03"));+ let alert = xml.find("XCUIElementTypeAlert ").unwrap();+ assert!(alert < xml.find("允许粘贴").unwrap());+ assert!(xml.contains("</XCUIElementTypeAlert>"));+ }++ #[test]+ fn a_first_tree_without_types_is_typed_by_traits() {+ let mut e = el(1, 1, Some(0), "x", 0, (0.0, 0.0, 1.0, 1.0));+ e.traits = trait_bit::BUTTON;+ assert_eq!(kind(&e), "Button");+ e.traits = trait_bit::SWITCH | trait_bit::BUTTON;+ assert_eq!(kind(&e), "Switch");+ e.xc_type = 48;+ assert_eq!(kind(&e), "StaticText");+ }++ #[test]+ fn the_lock_screen_passcode_field_reads_as_secure() {+ let field = |value: &str| Element { xc_type: 49, value: value.into(), ..Default::default() };+ assert_eq!(TYPES[49], "TextField");+ assert_eq!(kind(&field("共6位数,已输入0位")), "SecureTextField");+ assert_eq!(kind(&field("6-digit passcode, 2 entered")), "SecureTextField");+ assert_eq!(kind(&field("2 杯咖啡 3 份")), "TextField");+ assert_eq!(kind(&field("hello")), "TextField");+ // untyped, a text field by its traits+ let untyped =+ Element { traits: trait_bit::TEXT_FIELD, value: "共6位数,已输入1位".into(), ..Default::default() };+ assert_eq!(kind(&untyped), "SecureTextField");+ }++ #[test]+ fn a_page_is_placed_as_it_comes_and_a_widget_without_host_is_left_out() {+ let obj = |pid: i64, id: u64| Some(crate::ObjectRef { pid, id, is_app: false });+ let el = |pid, id, parent, label: &str, y| Element {+ object: obj(pid, id),+ parent,+ label: label.into(),+ frame: Some((20.0, y, 200.0, 40.0)),+ xc_type: 48,+ is_element: true,+ enabled: true,+ visible: true,+ ..Default::default()+ };+ let mut app = el(10, 1, None, "Safari", 0.0);+ app.frame = Some((0.0, 0.0, 430.0, 932.0));+ let els = vec![app, el(20, 2, Some(0), "This domain is for use", 300.0), el(30, 3, Some(0), "Widget", 500.0)];+ let web: HashSet<i64> = [20].into();+ let xml = to_xml(&els, &[], 430.0, 932.0, &web, false);+ assert!(xml.contains(r#"label="This domain is for use""#) && xml.contains(r#"y="300""#), "{xml}");+ assert!(!xml.contains("Widget"), "{xml}");+ }++ #[test]+ fn a_question_springboard_asks_reads_as_an_alert() {+ let f = |y| (40.0, y, 350.0, 40.0);+ let els = vec![+ el(39, 1, None, " ", 2, (0.0, 0.0, 430.0, 932.0)),+ el(39, 2, Some(0), "“设置”想从“dtpasteboardd”粘贴", 48, f(380.0)),+ el(39, 3, Some(0), "你允许这样做吗?", 48, f(420.0)),+ el(39, 4, Some(0), "允许粘贴", 9, f(480.0)),+ el(39, 5, Some(0), "不允许粘贴", 9, f(530.0)),+ ];+ let xml = to_xml(&els, &[], 430.0, 932.0, &HashSet::new(), true);+ assert!(+ xml.contains(r#"<XCUIElementTypeAlert type="XCUIElementTypeAlert" label="“设置”想从“dtpasteboardd”粘贴""#),+ "{xml}"+ );+ // the same in an app, or the lock screen's single button: no alert+ assert!(!to_xml(&els, &[], 430.0, 932.0, &HashSet::new(), false).contains("Alert"));+ assert!(!to_xml(&els[..4], &[], 430.0, 932.0, &HashSet::new(), true).contains("Alert"));+ // the status bar's time and buttons alone are no question+ let bar =+ |id, label: &str, xc| Element { traits: trait_bit::STATUS_BAR, ..el(39, id, Some(0), label, xc, f(10.0)) };+ let status_only = vec![els[0].clone(), bar(6, "18:36", 48), bar(7, "Wi-Fi", 9), bar(8, "电池", 9)];+ assert!(!to_xml(&status_only, &[], 430.0, 932.0, &HashSet::new(), true).contains("Alert"));+ }+}diff --git a/crates/ictl-daemon/Cargo.toml b/crates/ictl-daemon/Cargo.tomlindex d9df417..059d612 100644--- a/crates/ictl-daemon/Cargo.toml+++ b/crates/ictl-daemon/Cargo.toml@@ -13,6 +13,7 @@ description = "守护进程:状态机、usbmuxd 看护、重签、通知、控libc.workspace = trueictl-l10n.workspace = trueictl-webinspector.workspace = true+ictl-ax.workspace = trueictl-device.workspace = trueictl-wda.workspace = trueictl-sign.workspace = truediff --git a/crates/ictl-daemon/core b/crates/ictl-daemon/coredeleted file mode 100644index 1fad188..0000000Binary files a/crates/ictl-daemon/core and /dev/null differdiff --git a/crates/ictl-daemon/src/config.rs b/crates/ictl-daemon/src/config.rsindex 450b401..075f3b0 100644--- a/crates/ictl-daemon/src/config.rs+++ b/crates/ictl-daemon/src/config.rs@@ -28,6 +28,33 @@ pub struct Config {pub notify: NotifyConfig,/// 实验(`ICTL_WDA_DETACHED=1`):在后台启动 WDA、不持有 XCTest 会话(见 `docs/dev/wda-dependency-research.md`)pub wda_detached: bool,+ /// iOS 27 及以上怎么控制(`ICTL_IOS_BACKEND`)+ pub ios_backend: IosBackend,+}++/// iOS 27 及以上的手机怎么控制(`ICTL_IOS_BACKEND`)。iOS 26 及以下没有 HID,总是 WDA+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum IosBackend {+ /// 原生(默认)+ #[default]+ Auto,+ Native,+ Wda,+}++impl IosBackend {+ pub fn parse(v: Option<&str>) -> Self {+ match v.map(|s| s.trim().to_ascii_lowercase()).as_deref() {+ Some("wda") => Self::Wda,+ Some("native") => Self::Native,+ _ => Self::Auto,+ }+ }++ /// Whether a phone is driven natively: iOS 27 and later (HID needs `dtuhidd`), unless `ICTL_IOS_BACKEND=wda`+ pub fn drives_natively(self, info: Option<&ictl_device::DeviceInfo>) -> bool {+ self != Self::Wda && info.is_some_and(|i| i.major_version() >= 27)+ }}#[derive(Debug, Clone, Default)]@@ -104,6 +131,7 @@ impl Config {},wda_detached: env(crate::protocol::env::WDA_DETACHED).is_some_and(|v| matches!(v.as_str(), "1" | "true" | "yes")),+ ios_backend: IosBackend::parse(env(crate::protocol::env::IOS_BACKEND).as_deref()),}}diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex 64758cd..62e1f0f 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -371,6 +371,29 @@ pub(crate) struct PerDevice {/// 最近一个操作开始前的界面:操作做完、界面稳定时和它比,告诉调用方界面变没变(`Daemon::settle`)。/// 按名字点击会在点之前读树,用那棵树pub before_action: Option<crate::tools::Seen>,+ /// 最近一个操作开始的时间:原生控制等界面稳定时,从这之后的推送算起+ pub acted_at: Option<Instant>,+ /// 原生控制:进程号 → Bundle ID(前台 App 由无障碍服务给进程号)+ pub bundles: HashMap<i64, String>,+ /// 原生控制:进程号 → 是不是网页内容进程(WebKit WebContent,网页的元素来自它)+ pub web_pids: HashMap<i64, bool>,+}++/// What preparing a phone for native control gives: the developer disk image's version if it was mounted just now,+/// and what became of the WDA launched in the background earlier (if one was recorded for it); failed, whether it was+/// the mount itself+pub(crate) type Prepared = std::result::Result<(Option<String>, Option<StoppedWda>), (DeviceError, bool)>;++/// The WDA launched in the background earlier (by its pid), once it is no longer wanted (driven natively, or the+/// background launch turned off)+#[derive(Debug)]+pub(crate) enum StoppedWda {+ /// It was running and is gone now+ Ended(u64),+ /// It wasn't running (anymore)+ NotRunning(u64),+ /// It may still be running: why+ Failed(u64, String),}pub(crate) struct Inner {@@ -399,6 +422,10 @@ pub(crate) struct Inner {pub offline_target: Option<crate::notify::Target>,/// HID 会话最近一次使用的时间;空闲超过 [`crate::supervise::HID_IDLE`] 就关掉(它持有屏幕媒体流)pub hid_used: Option<Instant>,+ /// 原生控制:无障碍会话最近一次使用的时间;空闲超过 [`crate::supervise::AX_IDLE`] 就关掉+ pub ax_used: Option<Instant>,+ /// 原生控制:后台挂开发者镜像(结果:挂上的版本,已挂载为 None;失败时带上「是不是挂载这一步」)+ pub preparing: Option<JoinHandle<Prepared>>,/// Control pages watching the screen media stream (`screen.rs`): while there are any, the HID session (which owns/// the stream) stays open however long it is idlepub screen_viewers: usize,@@ -464,7 +491,8 @@ pub(crate) async fn close_hid(g: &mut Inner) {pub(crate) async fn drop_tunnel(g: &mut Inner) {g.dev.touch_rotation = None;if let Some(t) = g.tunnel.take() {- t.close().await;+ // boxed: the future holds the whole tunnel, and every tool that may drop it would carry that+ Box::pin(t.close()).await;}}@@ -488,6 +516,14 @@ pub(crate) fn wda_down(state: &DeviceState, info: Option<&DeviceInfo>) -> String).into();}+ // 原生控制(iOS 27 起不用 WDA):只是还没准备好+ if let DeviceState::Preparing { .. } = state {+ return ictl_l10n::trf!(+ "手机还没准备好({}),通常几秒到半分钟;截图、点击、滑动、按键可照常用",+ "The phone isn't ready yet ({}), usually a few seconds to half a minute; screenshots, taps, swipes and buttons still work",+ state.describe()+ );+ }let fallback = if hid_supported(info) {ictl_l10n::tr!("截图/点击/滑动/按键可照常用", "screenshots/taps/swipes/buttons still work")} else {@@ -537,6 +573,8 @@ impl Daemon {offline_since: Some(now),offline_target: None,hid_used: None,+ ax_used: None,+ preparing: None,screen_viewers: 0,low_bandwidth_viewers: 0,elements_cache: None,@@ -693,6 +731,9 @@ impl Daemon {if let Some(h) = g.starting.take() {h.abort();}+ if let Some(h) = g.preparing.take() {+ h.abort();+ }if let Some(r) = g.runner.take() {r.stop();}@@ -711,7 +752,8 @@ impl Daemon {device: &Device,) -> Result<&'a mut Tunnel, DeviceError> {if g.tunnel.is_none() {- g.tunnel = Some(device.open_tunnel().await?);+ // boxed: the tunnel's handshake is a large future (about 35 KB), and nearly every tool may open one+ g.tunnel = Some(Box::pin(device.open_tunnel()).await?);}Ok(g.tunnel.as_mut().expect("刚建好"))}@@ -900,10 +942,16 @@ impl Daemon {"Can't tell which app is in front ({why}); this task is limited to some apps, so nothing was done. Take a screenshot and try again shortly"))};- let Some(w) = self.wda(&mut g) else {- return Err(unknown(ictl_l10n::tr!("WDA 不可用", "WDA unavailable").into()));+ // the lock is let go before the user is asked (below)+ let app = if self.wda(&mut g).is_none() && self.native(&g) {+ Box::pin(self.native_foreground(&mut g)).await.map_err(|e| unknown(e.to_string()))?+ } else {+ let Some(w) = self.wda(&mut g) else {+ return Err(unknown(ictl_l10n::tr!("WDA 不可用", "WDA unavailable").into()));+ };+ w.active_app().await.map_err(|e| unknown(e.to_string()))?};- Target::Foreground(w.active_app().await.map_err(|e| unknown(e.to_string()))?)+ Target::Foreground(app)}};task.check_scope(&target, step, gone).await@@ -1061,6 +1109,8 @@ impl Daemon {if acted {// 这个操作之前读过的界面就是「操作前」;操作期间读的(按名字点击先读树)也是操作前,操作完都不再算g.dev.before_action = g.dev.seen.take_fresh();+ // 原生控制等界面稳定时,从这之后手机推来的树算起+ g.dev.acted_at = Some(Instant::now());}// boxed, like the request in `handle`: two of its large state machine on the stack overflowed a test threadlet r = Box::pin(self.dispatch(g, req, view, ctx.watched)).await;diff --git a/crates/ictl-daemon/src/devtools.rs b/crates/ictl-daemon/src/devtools.rsindex 1f0f672..1fd57e9 100644--- a/crates/ictl-daemon/src/devtools.rs+++ b/crates/ictl-daemon/src/devtools.rs@@ -418,7 +418,13 @@ mod tests {#[test]fn uninstall_needs_an_exact_name() {- let app = |n: &str, b: &str| AppInfo { name: n.into(), bundle_id: b.into(), executable: String::new() };+ let app = |n: &str, b: &str| AppInfo {+ name: n.into(),+ bundle_id: b.into(),+ executable: String::new(),+ path: String::new(),+ schemes: Vec::new(),+ };let apps = [app("Test Flight", "com.apple.TestFlight"),app("MyTest", "com.example.mytest"),diff --git a/crates/ictl-daemon/src/doctor.rs b/crates/ictl-daemon/src/doctor.rsindex 8452b9c..1041c11 100644--- a/crates/ictl-daemon/src/doctor.rs+++ b/crates/ictl-daemon/src/doctor.rs@@ -99,7 +99,18 @@ impl Daemon {out.push(format!(" {l}"));}- out.push(ictl_l10n::tr!("== Apple ID 与签名", "== Apple ID and signing").into());+ // 原生控制(iOS 27 起)不用 WDA:签名的事照样列出来(WDA 暂时还装着、照常重签),但不算问题+ let native = self.native(g);+ let fails_before_signing = fails;+ out.push(if native {+ ictl_l10n::tr!(+ "== Apple ID 与签名(原生控制用不到,仅供参考)",+ "== Apple ID and signing (not needed for native control, for reference)"+ )+ .into()+ } else {+ ictl_l10n::tr!("== Apple ID 与签名", "== Apple ID and signing").into()+ });match self.account().selected_email().await {Ok(_) => out.push(ictl_l10n::tr!("✅ 已登录 Apple ID", "✅ Signed in to an Apple ID").into()),Err(_) => {@@ -221,8 +232,31 @@ impl Daemon {out.push(ictl_l10n::trf!(" 上次重签:{r}", " Last re-sign: {r}"));}- out.push("== WDA".into());+ if native {+ fails = fails_before_signing;+ out.push(ictl_l10n::tr!("== 原生控制", "== Native control").into());+ match Box::pin(self.ax_read(g, crate::tools::AX_WAIT)).await {+ Ok(_) => out.push(+ ictl_l10n::tr!(+ "✅ 无障碍服务可用(读界面、按名字点击不用 WDA;触摸、按键经 HID)",+ "✅ Accessibility service available (reading the screen and tapping by text without WDA; touches and keys through HID)"+ )+ .into(),+ ),+ Err(e) => {+ out.push(ictl_l10n::trf!(+ "❌ 读不了界面:{e}\n → 等守护进程准备好(状态见上);一直不行就设 ICTL_IOS_BACKEND=wda 改回 WDA",+ "❌ Can't read the screen: {e}\n → wait for the daemon to get the phone ready (state above); if it never does, set ICTL_IOS_BACKEND=wda to go back to WDA"+ ));+ fails += 1;+ }+ }+ }+ if !native {+ out.push("== WDA".into());+ }match self.wda(g) {+ _ if native => {}Some(w) if w.ready().await.unwrap_or(false) => out.push(ictl_l10n::tr!("✅ WDA 就绪(经 usbmuxd 直连;守护进程不监听端口,wda-bridge 运行时除外)",diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rsindex d2fdc51..366b7a8 100644--- a/crates/ictl-daemon/src/lib.rs+++ b/crates/ictl-daemon/src/lib.rs@@ -80,13 +80,20 @@ async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::Resultick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);// 每个连接一个任务;请求在任务里等设备锁,主循环本身从不阻塞,停止信号随时能处理let mut conns = JoinSet::new();- let mut ticking: Option<JoinHandle<()>> = None;- // a round asked for (`Daemon::wake`) while one was still running: it starts once that one is done+ // the round running, and whether it was asked for (`Daemon::wake`)+ let mut ticking: Option<(JoinHandle<bool>, bool)> = None;+ // a round asked for while one was still running: it starts once that one is done. One asked for that couldn't+ // run (a request held the device) is asked for again: a phone made ready in the background waited 10 s for the+ // next round when switching back to itlet mut woken = false;loop {- if woken && ticking.as_ref().is_none_or(JoinHandle::is_finished) {+ if let Some((h, asked)) = ticking.take_if(|(h, _)| h.is_finished()) {+ let ran = h.await.unwrap_or(true);+ woken |= asked && !ran;+ }+ if woken && ticking.is_none() {woken = false;- ticking = Some(tokio::task::spawn_local(daemon.clone().tick()));+ ticking = Some((tokio::task::spawn_local(daemon.clone().tick()), true));}tokio::select! {biased;@@ -105,8 +112,8 @@ async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::ResulSome(_) = conns.join_next(), if !conns.is_empty() => {}_ = tick.tick() => {// 上一轮还没跑完(例如在重启 usbmuxd)就不叠加- if ticking.as_ref().is_none_or(JoinHandle::is_finished) {- ticking = Some(tokio::task::spawn_local(daemon.clone().tick()));+ if ticking.as_ref().is_none_or(|(h, _)| h.is_finished()) {+ ticking = Some((tokio::task::spawn_local(daemon.clone().tick()), false));}}() = daemon.wake.notified() => woken = true,@@ -123,7 +130,7 @@ async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::Resul// 自动解锁被打断时停用标记会留着(ictl-unlock),不会因此输错第二次conns.abort_all();while conns.join_next().await.is_some() {}- if let Some(t) = ticking {+ if let Some((t, _)) = ticking {t.abort();let _ = t.await;}diff --git a/crates/ictl-daemon/src/machine.rs b/crates/ictl-daemon/src/machine.rsindex 2b9deb6..d57f998 100644--- a/crates/ictl-daemon/src/machine.rs+++ b/crates/ictl-daemon/src/machine.rs@@ -21,6 +21,10 @@ pub enum DeviceState {},/// 手机重启后首次启用 UI 自动化,等用户在手机上输锁屏密码NeedsAutomationPin,+ /// 原生控制(iOS 27 起不用 WDA):正在挂开发者镜像、连无障碍服务,或失败了在退避+ Preparing {+ last_error: Option<String>,+ },Ready,}@@ -35,6 +39,8 @@ impl DeviceState {Self::WdaStarting { last_error: None } => ictl_l10n::tr!("正在启动 WDA", "Starting WDA").into(),Self::WdaStarting { last_error: Some(e) } => ictl_l10n::trf!("WDA 启动失败,稍后重试:{e}", "WDA failed to start, retrying later: {e}"),Self::NeedsAutomationPin => ictl_l10n::tr!("WDA 卡在手机上的「Enable UI Automation」密码框:请在手机上输入锁屏密码", "WDA is stuck at the “Enable UI Automation” passcode prompt on the phone: enter the passcode on the phone").into(),+ Self::Preparing { last_error: None } => ictl_l10n::tr!("正在准备手机(挂载开发者镜像、连接无障碍服务)", "Preparing the phone (mounting the developer disk image, connecting to the accessibility service)").into(),+ Self::Preparing { last_error: Some(e) } => ictl_l10n::trf!("准备手机失败,稍后重试:{e}", "Preparing the phone failed, retrying later: {e}"),Self::Ready => ictl_l10n::tr!("就绪", "Ready").into(),}}diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rsindex b35f94a..a83093e 100644--- a/crates/ictl-daemon/src/supervise.rs+++ b/crates/ictl-daemon/src/supervise.rs@@ -6,7 +6,7 @@ use std::time::{Duration, Instant, UNIX_EPOCH};use ictl_device::{Device, DeviceError, LogStream, Rotation, ScreenSize, Tunnel, UsbDevice};use ictl_wda::{WdaClient, WdaError, WdaRunner, http::DeviceTransport};-use crate::core::{Daemon, DetachedWda, DeviceProfile, Inner, close_hid};+use crate::core::{Daemon, DetachedWda, DeviceProfile, Inner, StoppedWda, close_hid, drop_tunnel};use crate::machine::DeviceState;use crate::notify::Event;@@ -27,6 +27,8 @@ const PIN_ATTEMPT: Duration = Duration::from_secs(25);/// HID 会话空闲这么久就关掉。它持有屏幕媒体流,开着时 iOS 当作屏幕被远程查看:不会自动锁屏,/// 还会弹「viewed remotely」通知。重开约 0.5 秒pub(crate) const HID_IDLE: Duration = Duration::from_secs(30);+/// 原生控制:无障碍会话空闲这么久就关掉。开着时手机为我们开着无障碍运行时,每次界面变化都推一棵树;重开约 1 秒+pub(crate) const AX_IDLE: Duration = Duration::from_secs(60);/// 连续这么多轮列不出设备才当作离线const LIST_ERRORS_OFFLINE: u32 = 3;/// 开发者镜像连续挂载失败这么多次就清缓存重新下载@@ -91,13 +93,14 @@ async fn then_wake<T>(wake: Arc<tokio::sync::Notify>, work: impl std::future::Fuimpl Daemon {// ------------------------------------------------------------------ 状态机- /// 每 10 秒一次。有请求在用设备就跳过这一轮(巡检不排队,下一轮再来)- pub async fn tick(self: Arc<Self>) {+ /// 每 10 秒一次。有请求在用设备就跳过这一轮(巡检不排队,下一轮再来)。返回这一轮跑了没有(拿不到设备锁时+ /// 没跑:被唤醒的一轮就再来,见 `lib.rs` 的主循环)+ pub async fn tick(self: Arc<Self>) -> bool {let Ok(_lease) = crate::maintenance::shared() else {self.heartbeat.beat();- return;+ return true;};- let Ok(mut g) = self.inner.try_lock() else { return };+ let Ok(mut g) = self.inner.try_lock() else { return false };let g = &mut *g;if g.tunnel.as_ref().is_some_and(Tunnel::hid_open)@@ -113,6 +116,12 @@ impl Daemon {));}+ if g.ax_used.is_none_or(|t| t.elapsed() >= AX_IDLE)+ && let Some(t) = g.tunnel.as_mut().filter(|t| t.ax_open())+ {+ t.close_ax().await;+ tracing::info!("{}", ictl_l10n::log_tr!("无障碍会话空闲,已关闭", "Accessibility session idle, closed it"));+ }self.restore_pasteboard(g, true).await;self.poll_start(g).await;@@ -134,7 +143,7 @@ impl Daemon {);if g.list_errors < LIST_ERRORS_OFFLINE {self.publish(g);- return;+ return true;}Vec::new()}@@ -175,6 +184,7 @@ impl Daemon {self.web_housekeeping(g.device.as_ref().map(|d| d.udid.as_str()));Self::log_housekeeping(g);self.publish(g);+ true}/// Returns the rotation actually observed in this sample and whether the published view changed.@@ -183,9 +193,20 @@ impl Daemon {let device = g.device.clone();// an old size is measured again only while nobody acts: on an iPad mini 5 that takes WDA 0.95 slet refresh = !gesture_start && !self.acting_now(ACTION_QUIET);- let Some(wda) = self.wda(g) else { return (None, self.update_display(g, None).await) };- let (size, rotation) =- wda.display_sample(previous, refresh, async { device?.interface_rotation().await.ok().flatten() }).await;+ let Some(wda) = self.wda(g) else {+ // 原生控制:方向问 SpringBoard(lockdown 服务),尺寸是读界面时记下的(竖放)+ if self.native(g) {+ let rotation = self.native_rotation(g).await;+ let size = g.persisted.screen_for(device.as_ref().map(|d| d.udid.as_str()));+ let changed = self.record_display_sample(g, size, rotation, gesture_start).await;+ return (rotation, changed);+ }+ return (None, self.update_display(g, None).await);+ };+ let (size, rotation) = Box::pin(+ wda.display_sample(previous, refresh, async { device?.interface_rotation().await.ok().flatten() }),+ )+ .await;let changed = self.record_display_sample(g, size, rotation, gesture_start).await;(rotation, changed)}@@ -312,6 +333,10 @@ impl Daemon {if g.state != DeviceState::Ready && !device.developer_mode_enabled().await.unwrap_or(true) {return self.set_state(g, DeviceState::DeveloperModeOff);}+ // iOS 27 起默认原生控制:不签名、不启动 WDA(docs/dev/ios27-native.md)+ if self.native(g) {+ return Box::pin(self.native_online(g, device)).await;+ }let Some(bundle) = g.persisted.wda_bundle.clone() else {return self.set_state(g, DeviceState::NeedsSigning);};@@ -359,6 +384,145 @@ impl Daemon {self.spawn_start(g, device, bundle);}+ /// [`Self::online`] for a phone driven natively: the developer disk image mounted in the background (as before+ /// WDA starts), then the accessibility service's handshake and a first read of the screen+ async fn native_online(&self, g: &mut Inner, device: Device) {+ if g.preparing.as_ref().is_some_and(|h| h.is_finished()) {+ let h = g.preparing.take().expect("刚检查过");+ let r = h.await.unwrap_or_else(|e| {+ Err((DeviceError::Idevice(ictl_l10n::trf!("准备任务异常:{e}", "Preparing task failed: {e}")), false))+ });+ match r {+ Ok((mounted, stopped)) => {+ g.dev.ddi_failures = 0;+ if let Some(s) = stopped {+ self.detached_stopped(g, s);+ }+ if let Some(v) = mounted {+ self.log.log(&ictl_l10n::log_trf!("开发者镜像已挂载 {v}", "Developer disk image mounted {v}"));+ // a tunnel opened before the image was mounted doesn't list the accessibility service+ drop_tunnel(g).await;+ }+ match Box::pin(self.native_check(g, &device)).await {+ Ok(()) => {+ self.log.log(ictl_l10n::log_tr!(+ "原生控制就绪(无障碍服务、HID,不用 WDA)",+ "Native control ready (accessibility service and HID, no WDA)"+ ));+ g.backoff.reset();+ self.set_state(g, DeviceState::Ready);+ self.sample_display(g, false).await;+ }+ Err(e) => {+ self.log.log(&ictl_l10n::log_trf!("准备手机失败:{e}", "Preparing the phone failed: {e}"));+ g.backoff.failed(Instant::now());+ self.set_state(g, DeviceState::Preparing { last_error: Some(e) });+ }+ }+ }+ Err((DeviceError::PasswordProtected, _)) => {+ g.backoff.retry_after(Instant::now(), crate::machine::UNLOCK_RETRY);+ self.set_state(g, DeviceState::NeedsUnlock);+ }+ Err((e, mount_failed)) => {+ self.ddi_failed(g, mount_failed);+ g.backoff.failed(Instant::now());+ let e = ictl_l10n::trf!("开发者镜像:{e}", "Developer disk image: {e}");+ self.log.log(&ictl_l10n::log_trf!("准备手机失败:{e}", "Preparing the phone failed: {e}"));+ self.set_state(g, DeviceState::Preparing { last_error: Some(e) });+ }+ }+ return;+ }+ if g.state == DeviceState::Ready {+ self.sample_display(g, false).await;+ return;+ }+ if g.preparing.is_some() || !g.backoff.ready(Instant::now()) {+ return;+ }+ // retrying: the last error stays up until this round's outcome+ if !matches!(g.state, DeviceState::Preparing { .. }) {+ self.set_state(g, DeviceState::Preparing { last_error: None });+ }+ let (cache, url, user_dir) = (self.cfg.ddi_cache(), self.cfg.ddi_url.clone(), self.cfg.ddi_dir.clone());+ // a WDA launched in the background before (WDA control earlier): not wanted now, ended once the image is up+ // (AppService needs it)+ let known = g.persisted.detached_wda.as_ref().filter(|d| d.udid == device.udid).map(|d| d.pid);+ let Ok(lease) = crate::maintenance::shared() else { return };+ let wake = self.wake.clone();+ g.preparing = Some(tokio::task::spawn_local(then_wake(wake, async move {+ let _lease = lease;+ let mut t = device.open_tunnel().await.map_err(|e| (e, false))?;+ let r = ensure_ddi(&mut t, &cache, &url, user_dir.as_deref()).await;+ let stopped = match (&r, known) {+ (Ok(_), Some(pid)) => Some(stop_detached(&mut t, pid).await),+ _ => None,+ };+ t.close().await;+ r.map(|m| (m, stopped))+ })));+ }++ /// What became of the WDA launched in the background earlier, on a phone driven natively: forgotten once it is+ /// gone; one that may still run stays recorded (tried again the next time the phone is prepared)+ fn detached_stopped(&self, g: &mut Inner, s: StoppedWda) {+ let pid = match s {+ StoppedWda::Ended(pid) => {+ self.log.log(&ictl_l10n::log_trf!(+ "已结束之前后台启动的 WDA(进程 {pid}):原生控制不用它",+ "Stopped the WDA launched in the background earlier (pid {pid}): native control doesn't use it"+ ));+ pid+ }+ StoppedWda::NotRunning(pid) => pid,+ StoppedWda::Failed(pid, e) => {+ self.log.log(&ictl_l10n::log_trf!(+ "结束之前后台启动的 WDA(进程 {pid})失败:{e}",+ "Stopping the WDA launched in the background earlier (pid {pid}) failed: {e}"+ ));+ return;+ }+ };+ if g.persisted.detached_wda.as_ref().is_some_and(|d| d.pid == pid) {+ g.persisted.detached_wda = None;+ g.persisted.save(&self.cfg.state_file());+ }+ }++ /// The accessibility service answers and the screen can be read (which records its size)+ async fn native_check(&self, g: &mut Inner, device: &Device) -> Result<(), String> {+ for attempt in 0..2 {+ let t = self.ensure_tunnel(g, device).await.map_err(|e| e.to_string())?;+ if t.ax_supported() {+ break;+ }+ // the tunnel lists the services as they were when it was opened+ drop_tunnel(g).await;+ if attempt == 1 {+ return Err(ictl_l10n::tr!(+ "手机没有提供无障碍服务(remoteAXService):开发者镜像可能没挂上",+ "The phone offers no accessibility service (remoteAXService): the developer disk image may not be mounted"+ )+ .into());+ }+ }+ Box::pin(self.ax_read(g, crate::tools::AX_WAIT)).await.map(|_| ()).map_err(|e| e.to_string())+ }++ /// A mount that failed may be a broken cache: after a few in a row it is downloaded again (`ICTL_DDI_DIR` is the+ /// user's own and never deleted)+ fn ddi_failed(&self, g: &mut Inner, mount_failed: bool) {+ if mount_failed && self.cfg.ddi_dir.is_none() {+ g.dev.ddi_failures += 1;+ if g.dev.ddi_failures >= DDI_FAILURES_INVALIDATE {+ self.log.log(&ictl_l10n::log_trf!("开发者镜像连续 {} 次挂载失败,清掉缓存,下次重新下载", "Mounting the developer disk image failed {} times in a row, clearing the cache to download it again", g.dev.ddi_failures));+ ictl_device::ddi::invalidate(&self.cfg.ddi_cache());+ g.dev.ddi_failures = 0;+ }+ }+ }+/// WDA 卡死了没有:经 XCTest 的请求连续 [`ictl_wda::client::STALL_LIMIT`] 次没有应答([`WdaClient::stalled`])。/// 还没到就再探测一次([`WdaClient::xctest_responsive`]),算进同一个计数。WDA 回了错误、或者应答了,都算活着async fn xctest_stalled(&self, g: &mut Inner) -> bool {@@ -440,18 +604,7 @@ impl Daemon {type Ready = (Option<String>, Result<Option<Detached>, DeviceError>, Option<LogStream>);let ddi: Result<Ready, (DeviceError, bool)> = async {let mut t = device.open_tunnel().await.map_err(|e| (e, false))?;- let r = async {- if t.ddi_mounted().await.map_err(|e| (e, false))?.is_some() {- return Ok(None);- }- let dir = match &user_dir {- Some(d) => ictl_device::ddi::require_complete(d),- None => ictl_device::ddi::ensure_cache(&cache, &url).await,- }- .map_err(|e| (e, false))?;- Ok(Some(t.mount_ddi(&dir).await.map_err(|e| (e, true))?))- }- .await;+ let r = ensure_ddi(&mut t, &cache, &url, user_dir.as_deref()).await;let r = match r {Ok(m) => {// 后台启动前先开系统日志流:认「Enable UI Automation」密码框靠它(见 WdaRunner::attach)@@ -545,14 +698,7 @@ impl Daemon {}StartOutcome::Ddi { error: e, mount_failed } => {// 只有挂载失败才可能是缓存坏了;ICTL_DDI_DIR 是用户自己的文件,从不删- if mount_failed && self.cfg.ddi_dir.is_none() {- g.dev.ddi_failures += 1;- if g.dev.ddi_failures >= DDI_FAILURES_INVALIDATE {- self.log.log(&ictl_l10n::log_trf!("开发者镜像连续 {} 次挂载失败,清掉缓存,下次重新下载", "Mounting the developer disk image failed {} times in a row, clearing the cache to download it again", g.dev.ddi_failures));- ictl_device::ddi::invalidate(&self.cfg.ddi_cache());- g.dev.ddi_failures = 0;- }- }+ self.ddi_failed(g, mount_failed);g.backoff.failed(Instant::now());self.set_state(g,@@ -899,6 +1045,25 @@ fn now_secs() -> u64 {std::time::SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()}+/// 手机重启后开发者镜像可能掉了:没挂就挂上(返回挂上的版本),已挂载时只是一次查询。+/// 错误带上「是不是挂载这一步」(才可能是缓存坏了)+async fn ensure_ddi(+ t: &mut Tunnel,+ cache: &std::path::Path,+ url: &str,+ user_dir: Option<&std::path::Path>,+) -> Result<Option<String>, (DeviceError, bool)> {+ if t.ddi_mounted().await.map_err(|e| (e, false))?.is_some() {+ return Ok(None);+ }+ let dir = match user_dir {+ Some(d) => ictl_device::ddi::require_complete(d),+ None => ictl_device::ddi::ensure_cache(cache, url).await,+ }+ .map_err(|e| (e, false))?;+ Ok(Some(t.mount_ddi(&dir).await.map_err(|e| (e, true))?))+}+/// 实验开关(`ICTL_WDA_DETACHED`)的那一步,在挂镜像的隧道上做:/// - 开着:`known` 那个进程还是 WDA 就直接接上;否则在后台启动一个(会先结束已在运行的 WDA,包括 XCTest 会话启动的)/// - 关着:结束之前后台启动、还在运行的那个。它不随守护进程退出,留着就一直占着 8100 端口@@ -908,25 +1073,20 @@ async fn prepare_detached(known: Option<u64>,bundle: &str,) -> Result<Option<Detached>, DeviceError> {- fn is_wda(procs: &[(u64, String)], pid: u64) -> bool {- procs.iter().any(|(p, path)| *p == pid && path.contains("WebDriverAgentRunner"))- }match (detached, known) {(true, Some(pid)) if is_wda(&t.processes().await?, pid) => Ok(Some(Detached::Adopted(pid))),(true, _) => Ok(Some(Detached::Launched(t.launch_in_background(bundle).await?))),(false, Some(pid)) => {- if is_wda(&t.processes().await.unwrap_or_default(), pid) {- tracing::info!(+ match stop_detached(t, pid).await {+ StoppedWda::Ended(_) => tracing::info!("{}",ictl_l10n::log_trf!(- "结束之前后台启动的 WDA(进程 {pid})",- "Stopping the WDA launched in the background earlier (pid {pid})"+ "已结束之前后台启动的 WDA(进程 {pid})",+ "Stopped the WDA launched in the background earlier (pid {pid})")- );- if let Err(e) = t.kill(pid).await {- tracing::warn!("kill {pid}: {e}");- }- tokio::time::sleep(Duration::from_secs(1)).await;+ ),+ StoppedWda::NotRunning(_) => {}+ StoppedWda::Failed(_, e) => tracing::warn!("stopping the background WDA (pid {pid}): {e}"),}Ok(None)}@@ -934,6 +1094,37 @@ async fn prepare_detached(}}+/// Whether process `pid` in the phone's process list is WDA+fn is_wda(procs: &[(u64, String)], pid: u64) -> bool {+ procs.iter().any(|(p, path)| *p == pid && path.contains("WebDriverAgentRunner"))+}++/// Ends the WDA launched in the background earlier (`pid`) if it still runs: SIGKILL through AppService (DVT's+/// `kill_app` leaves WDA running), then waits up to 2 s for it to leave the process list+async fn stop_detached(t: &mut Tunnel, pid: u64) -> StoppedWda {+ match t.processes().await {+ Ok(p) if !is_wda(&p, pid) => return StoppedWda::NotRunning(pid),+ Ok(_) => {}+ Err(e) => return StoppedWda::Failed(pid, e.to_string()),+ }+ if let Err(e) = t.signal(pid, 9).await {+ return StoppedWda::Failed(pid, e.to_string());+ }+ let deadline = Instant::now() + Duration::from_secs(2);+ loop {+ tokio::time::sleep(Duration::from_millis(200)).await;+ if t.processes().await.is_ok_and(|p| !is_wda(&p, pid)) {+ return StoppedWda::Ended(pid);+ }+ if Instant::now() >= deadline {+ return StoppedWda::Failed(+ pid,+ ictl_l10n::tr!("发了 SIGKILL,2 秒后还在运行", "still running 2 s after SIGKILL").to_string(),+ );+ }+ }+}+/// 打开手机系统日志流;打不开只记一笔(后台启动照样进行,只是认不出密码框)async fn open_log(device: &Device) -> Option<LogStream> {match device.log_stream().await {diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rsindex 4d87580..64eb36b 100644--- a/crates/ictl-daemon/src/tools/input.rs+++ b/crates/ictl-daemon/src/tools/input.rs@@ -48,6 +48,11 @@ impl Daemon {Err(e) => return Err(e.into()),}}+ // natively HID is the way, not a fallback: the page's view was checked above as through WDA+ if self.native(g) {+ Box::pin(self.native_tap(g, x, y)).await?;+ return Ok(ictl_l10n::trf!("已点击 {pos}", "Tapped {pos}"));+ }if view.is_some() {return Err(wda_down(&g.state, g.info.as_ref()).into());}@@ -133,7 +138,7 @@ impl Daemon {},};h.rotation = rot;- let result = h.touch(contact, x, y).await;+ let result = Box::pin(h.touch(contact, x, y)).await;g.hid_used = Some(Instant::now());if let Err(e) = result {// A failed write may still have reached the phone.@@ -205,7 +210,7 @@ impl Daemon {));}};- self.require_wda(g)?.tap(x, y).await?;+ self.tap_at(g, x, y).await?;let note = if matches.len() > 1 {ictl_l10n::trf!("(共匹配 {} 个,点的是第 {index} 个)", " ({} matches, tapped number {index})", matches.len())} else {@@ -223,7 +228,12 @@ impl Daemon {view: Option<&str>,) -> crate::error::Result<String> {self.prepare_coordinates(g, view, true).await?;- self.require_wda(g)?.touch_and_hold(x, y, seconds).await?;+ let native = self.native(g);+ match self.wda(g) {+ Some(w) => w.touch_and_hold(x, y, seconds).await?,+ None if native => Box::pin(self.native_long_press(g, x, y, seconds)).await?,+ None => self.require_wda(g)?.touch_and_hold(x, y, seconds).await?,+ }Ok(ictl_l10n::trf!("已长按 ({},{}) {} 秒", "Long-pressed ({},{}) for {} s", fmt_g(x), fmt_g(y), fmt_g(seconds)))}@@ -258,7 +268,8 @@ impl Daemon {Err(e) => return Err(e.into()),}}- if view.is_some() {+ let native = self.native(g);+ if view.is_some() && !native {return Err(wda_down(&g.state, g.info.as_ref()).into());}let rot = self.hid_touch_rotation(g).await?;@@ -269,7 +280,18 @@ impl Daemon {})}).await?;- Ok(ictl_l10n::trf!("已滑动 {desc}(经 HID)", "Swiped {desc} (via HID)"))+ if !native {+ return Ok(ictl_l10n::trf!("已滑动 {desc}(经 HID)", "Swiped {desc} (via HID)"));+ }+ // as through WDA: a list still scrolling only stops at the next tap; someone watching sees when it stops+ g.swiped_tree = None;+ let note = if watched {+ String::new()+ } else {+ let vertical = (to.1 - from.1).abs() >= (to.0 - from.0).abs();+ Box::pin(self.native_scrolled(g, vertical)).await+ };+ Ok(ictl_l10n::trf!("已滑动 {desc}{note}", "Swiped {desc}{note}"))}pub(crate) async fn type_text(&self, g: &mut Inner, text: &str, submit: bool) -> crate::error::Result<String> {@@ -323,6 +345,9 @@ impl Daemon {Err(e) => return Err(e.into()),}}+ if self.native(g) {+ return Box::pin(self.native_type(g, text, submit)).await;+ }let payload = if submit { format!("{text}\n") } else { text.to_owned() };// 美式键盘按得出来的直接按键,不动剪贴板if payload.chars().all(|c| ascii_to_usage(c).is_some()) {@@ -341,7 +366,7 @@ impl Daemon {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;+ let r = Box::pin(g.tunnel.as_mut().expect("hid() 刚建好隧道").paste_text(text)).await;g.hid_used = Some(Instant::now());let pending = match r {Ok(p) => p,@@ -390,7 +415,7 @@ impl Daemon {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,+ Ok(t) => Box::pin(t.restore_pasteboard(p)).await,Err(e) => ClipboardRestore::Failed(e.to_string()),};match r {diff --git a/crates/ictl-daemon/src/tools/keys.rs b/crates/ictl-daemon/src/tools/keys.rsindex 54b127d..c3e8798 100644--- a/crates/ictl-daemon/src/tools/keys.rs+++ b/crates/ictl-daemon/src/tools/keys.rs@@ -67,6 +67,9 @@ impl Daemon {Err(e) => return Err(e.into()),}}+ if hid_button == Button::Home && self.native(g) {+ return Box::pin(self.native_home(g, watched)).await;+ }self.hid_do(g, |h| Box::pin(h.press(hid_button))).await?;Ok(ictl_l10n::trf!("已按 {button}", "Pressed {button}"))}@@ -97,7 +100,13 @@ impl Daemon {}worked.ok_or(failed)}- None => Err(Vec::new()),+ None => {+ // 已经锁着就不按(同上)+ if self.native(g) && self.native_locked(g).await.unwrap_or(false) {+ return self.locked_now(g);+ }+ Err(Vec::new())+ }};let way = match outcome {Ok(way) => Some(way),diff --git a/crates/ictl-daemon/src/tools/launch.rs b/crates/ictl-daemon/src/tools/launch.rsindex 84180ba..0aa8d28 100644--- a/crates/ictl-daemon/src/tools/launch.rs+++ b/crates/ictl-daemon/src/tools/launch.rs@@ -44,8 +44,12 @@ impl Daemon {pub(crate) async fn launch_app(&self, g: &mut Inner, app: &str) -> crate::error::Result<(String, bool)> {let bid = self.resolve_app(g, app).await?;self.ensure_unlocked(g).await?;- let w = self.require_wda(g)?;- let r = w.launch_app(&bid).await?;+ let native = self.native(g);+ let r = match self.wda(g) {+ Some(w) => w.launch_app(&bid).await?,+ None if native => Box::pin(self.native_launch(g, &bid, None)).await?,+ None => self.require_wda(g)?.launch_app(&bid).await?,+ };let blocked = matches!(r, Launch::Blocked(_));let text = match r {Launch::Foreground => ictl_l10n::trf!("已启动 {bid}", "Launched {bid}"),@@ -67,13 +71,30 @@ impl Daemon {pub(crate) async fn terminate_app(&self, g: &mut Inner, app: &str) -> crate::error::Result<String> {let bid = self.resolve_app(g, app).await?;self.ensure_unlocked(g).await?;+ if self.wda(g).is_none() && self.native(g) {+ if !Box::pin(self.native_terminate(g, &bid)).await? {+ return Ok(ictl_l10n::trf!("{bid} 没在运行", "{bid} wasn't running"));+ }+ return Ok(ictl_l10n::trf!("已结束 {bid}", "Terminated {bid}"));+ }self.require_wda(g)?.terminate_app(&bid).await?;Ok(ictl_l10n::trf!("已结束 {bid}", "Terminated {bid}"))}pub(crate) async fn open_url(&self, g: &mut Inner, url: &str) -> crate::error::Result<(String, bool)> {self.ensure_unlocked(g).await?;- let (r, app) = self.require_wda(g)?.open_url(url).await?;+ let (r, app) = if self.wda(g).is_none() && self.native(g) {+ // the app the link is for, launched with it+ let bid = Box::pin(self.native_app_for_url(g, url)).await?;+ let r = Box::pin(self.native_launch(g, &bid, Some(url))).await?;+ let app = match r {+ Launch::Slow => Box::pin(self.native_foreground(g)).await.unwrap_or_default(),+ _ => bid,+ };+ (r, app)+ } else {+ self.require_wda(g)?.open_url(url).await?+ };let blocked = matches!(r, Launch::Blocked(_));let text = match r {Launch::Foreground => ictl_l10n::trf!("已打开 {url}(前台 {app})", "Opened {url} (foreground {app})"),diff --git a/crates/ictl-daemon/src/tools/mod.rs b/crates/ictl-daemon/src/tools/mod.rsindex 97e0bf6..b1bdaea 100644--- a/crates/ictl-daemon/src/tools/mod.rs+++ b/crates/ictl-daemon/src/tools/mod.rs@@ -3,6 +3,7 @@mod input;mod keys;mod launch;+mod native;mod observe;use std::time::{Duration, Instant};@@ -22,6 +23,7 @@ use crate::imaging::{self, fmt_g};use crate::notify::Event;use crate::protocol::{ALERT_BLOCKING, Response, TAP_MISSED, TouchPhase};use crate::protocol::{ElementData, StatusData};+pub(crate) use native::AX_WAIT;pub(crate) use observe::Seen;use observe::*;@@ -58,8 +60,13 @@ impl Daemon {if let Some(left) = g.dev.last_lock.and_then(|t| LOCK_SETTLE.checked_sub(t.elapsed())) {tokio::time::sleep(left).await;}- let Some(wda) = self.wda(g) else { return Ok(()) };- match ictl_unlock::ensure_unlocked(wda, &cfg).await {+ let native = self.native(g);+ let r = match self.wda(g) {+ Some(wda) => ictl_unlock::ensure_unlocked(wda, &cfg).await,+ None if native => Box::pin(self.native_unlock(g, &cfg)).await,+ None => return Ok(()),+ };+ match r {Ok(_) => Ok(()),Err(e @ (UnlockError::WrongPasscode | UnlockError::Uncertain(_))) => {self.notify(g, Event::UnlockDisabled);@@ -74,12 +81,19 @@ impl Daemon {}}- async fn screen(&self, g: &mut Inner) -> crate::error::Result<ScreenSize> {+ pub(crate) async fn screen(&self, g: &mut Inner) -> crate::error::Result<ScreenSize> {if let Some(w) = self.wda(g)&& let Ok(s) = w.screen_size().await{return Ok(s);}+ // 原生控制每次读界面都记下尺寸([`Self::ax_read`]):按现在的方向给+ if self.native(g)+ && let Some(s) = g.persisted.screen_for(g.device.as_ref().map(|d| d.udid.as_str()))+ {+ let landscape = g.dev.last_rotation.is_some_and(|(_, r)| r.is_landscape());+ return Ok(if landscape { ScreenSize { width: s.height, height: s.width } } else { s });+ }// 这台设备记下的尺寸(别的设备的不用;旧版本没记是哪台,照用)g.persisted.screen_for(g.device.as_ref().map(|d| d.udid.as_str()))@@ -95,6 +109,13 @@ impl Daemon {if !hid_supported(g.info.as_ref()) {return Err(wda_down(&g.state, g.info.as_ref()).into());}+ // 原生控制:SpringBoard 直接给出四个方向(lockdown 服务,不用截图)+ if self.native(g)+ && let Some(r) = self.native_rotation(g).await+ {+ g.dev.last_rotation = Some((Instant::now(), r));+ return Ok(r);+ }self.sample_display(g, false).await;let png = self.hid_screenshot(g).await.map_err(|e| {ictl_l10n::trf!(@@ -108,11 +129,35 @@ impl Daemon {Ok(hid_rotation(w, h, known)?)}+ /// A screenshot as PNG for comparing pictures: through WDA, or natively through the tunnel; otherwise WDA's+ /// "unavailable"+ async fn raw_png(&self, g: &mut Inner) -> crate::error::Result<Vec<u8>> {+ if let Some(w) = self.wda(g) {+ return Ok(w.screenshot_png().await?);+ }+ if self.native(g) {+ return self.hid_screenshot(g).await;+ }+ Ok(self.require_wda(g)?.screenshot_png().await?)+ }++ /// A tap at a point: through WDA, or natively through HID+ async fn tap_at(&self, g: &mut Inner, x: f64, y: f64) -> crate::error::Result<()> {+ if let Some(w) = self.wda(g) {+ return Ok(w.tap(x, y).await?);+ }+ if self.native(g) {+ return Box::pin(self.native_tap(g, x, y)).await;+ }+ Ok(self.require_wda(g)?.tap(x, y).await?)+ }+/// 经隧道截图(WDA 不可用时)。失败就丢掉隧道,下次重建async fn hid_screenshot(&self, g: &mut Inner) -> crate::error::Result<Vec<u8>> {let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;let t = self.ensure_tunnel(g, &device).await?;- match t.screenshot_png().await {+ // boxed: the screenshot service's future is large (tens of KB), and every tool that may take one carries it+ match Box::pin(t.screenshot_png()).await {Ok(p) => Ok(p),Err(e) => {drop_tunnel(g).await;@@ -145,12 +190,13 @@ impl Daemon {.ensure_tunnel(g, &device).await.map_err(|e| ictl_l10n::trf!("HID 后备路线不可用:{e}", "HID fallback unavailable: {e}"))?;- if let Err(e) = t.hid(screen, max_bitrate).await {+ // boxed, as the screenshot above: opening the session is a large future+ if let Err(e) = Box::pin(t.hid(screen, max_bitrate)).await {drop_tunnel(g).await;return Err(ictl_l10n::trf!("HID 后备路线不可用:{e}", "HID fallback unavailable: {e}").into());}// 第二次调用直接返回已开好的会话(这样写是为了绕开借用检查对条件返回的限制)- Ok(g.tunnel.as_mut().expect("刚建好").hid(screen, max_bitrate).await?)+ Ok(Box::pin(g.tunnel.as_mut().expect("刚建好").hid(screen, max_bitrate)).await?)}async fn hid_do<F>(&self, g: &mut Inner, f: F) -> crate::error::Result<()>@@ -229,6 +275,14 @@ impl Daemon {}let unlock = self.unlock_cfg(g.device.as_ref().map(|d| d.udid.as_str()));let Some(w) = self.wda(g) else {+ if self.native(g) {+ if g.state == crate::machine::DeviceState::Ready {+ let (text, data) = Box::pin(self.native_status(g, &unlock)).await;+ return (format!("{text}\n{daemon_line}"), data);+ }+ let text = format!("{}\n{daemon_line}", wda_down(&g.state, g.info.as_ref()));+ return (text, StatusData { native: true, ..Default::default() });+ }let text = format!("{}\n{}\n{daemon_line}", wda_down(&g.state, g.info.as_ref()), needs_wda());return (text, StatusData::default());};@@ -238,20 +292,7 @@ impl Daemon {let s = w.screen_size().await?;let check = w.check_lock(None, false).await?;let locked = check.locked;- let mut lock = if check.uncertain {- ictl_l10n::tr!("可能已锁屏(屏幕上是锁屏样式的界面,WDA 说没锁;配置了自动解锁时操作前会先尝试解锁)", "possibly locked (the screen looks like the lock screen though WDA says unlocked; with auto-unlock configured, actions try to unlock first)").to_owned()- } else if !locked {- ictl_l10n::tr!("未锁屏", "unlocked").to_owned()- } else if unlock.disabled_by_failure() {- ictl_l10n::tr!("已锁屏(自动解锁之前失败过已停用,需要人工解锁,核对密码后运行 iphone-control unlock-reset)", "locked (auto-unlock was disabled after an earlier failure; unlock by hand, check the passcode, then run iphone-control unlock-reset)").to_owned()- } else if unlock.enabled() {- ictl_l10n::tr!("已锁屏(操作时会自动解锁)", "locked (actions unlock automatically)").to_owned()- } else {- ictl_l10n::tr!("已锁屏(未配置自动解锁,需要人工解锁)", "locked (no auto-unlock configured; unlock by hand)").to_owned()- };- if !locked && unlock.disabled_by_failure() {- lock += ictl_l10n::tr!(";自动解锁已停用", "; auto-unlock disabled");- }+ let lock = lock_text(locked, check.uncertain, &unlock);let data = StatusData {wda_ready: ready,locked: Some(locked || check.uncertain),@@ -259,9 +300,12 @@ impl Daemon {foreground: Some(app.clone()).filter(|a| !a.is_empty()),width: Some(s.width),height: Some(s.height),+ native: false,};let ready = if ready { "True" } else { "False" };- let text = ictl_l10n::trf!("WDA 就绪: {ready}\n锁屏: {lock}\n前台 App: {app}\n屏幕: {}x{} 点", "WDA ready: {ready}\nLocked: {lock}\nForeground app: {app}\nScreen: {}x{} points",+ let text = ictl_l10n::trf!(+ "WDA 就绪: {ready}\n锁屏: {lock}\n前台 App: {app}\n屏幕: {}x{} 点",+ "WDA ready: {ready}\nLocked: {lock}\nForeground app: {app}\nScreen: {}x{} points",fmt_g(s.width),fmt_g(s.height));@@ -280,6 +324,7 @@ impl Daemon {region: Option<(f64, f64, f64, f64)>,) -> crate::error::Result<Response> {self.ensure_unlocked(g).await?;+ let fetched = Instant::now();let wda_png = match self.wda(g) {Some(w) => w.screenshot_png().await.ok(),None => None,@@ -306,11 +351,17 @@ impl Daemon {// 解码、缩放、JPEG 编码是 CPU 活(1290×2796),放到阻塞线程,不卡住主循环// 说明文字在阻塞线程里生成:带上这个请求的语言let lang = ictl_l10n::lang();+ let (png_len, processed) = (png.len(), Instant::now());+ let fetch_ms = processed.duration_since(fetched).as_millis();let (jpeg, caption, thumb) = tokio::task::spawn_blocking(move || {ictl_l10n::with_lang(lang, || imaging::answer(&png, screen, region, via))}).await.map_err(|e| ictl_l10n::trf!("图像处理任务异常:{e}", "Image processing task failed: {e}"))??;+ tracing::debug!(+ "screenshot via {via}: {png_len} bytes of PNG in {fetch_ms} ms, processed in {} ms",+ processed.elapsed().as_millis()+ );// 区域放大也记整屏:下一个操作做完后比的是整个画面g.dev.seen.saw_thumb(thumb);Ok(Response::Image { jpeg_base64: base64::engine::general_purpose::STANDARD.encode(jpeg), caption })@@ -349,6 +400,26 @@ async fn thumbnail(png: Vec<u8>) -> crate::error::Result<Vec<u8>> {.map_err(Into::into)}+/// The status's lock line+pub(super) fn lock_text(locked: bool, uncertain: bool, unlock: &ictl_unlock::UnlockConfig) -> String {+ let mut lock = if uncertain {+ ictl_l10n::tr!("可能已锁屏(屏幕上是锁屏样式的界面,WDA 说没锁;配置了自动解锁时操作前会先尝试解锁)", "possibly locked (the screen looks like the lock screen though WDA says unlocked; with auto-unlock configured, actions try to unlock first)").to_owned()+ } else if !locked {+ ictl_l10n::tr!("未锁屏", "unlocked").to_owned()+ } else if unlock.disabled_by_failure() {+ ictl_l10n::tr!("已锁屏(自动解锁之前失败过已停用,需要人工解锁,核对密码后运行 iphone-control unlock-reset)", "locked (auto-unlock was disabled after an earlier failure; unlock by hand, check the passcode, then run iphone-control unlock-reset)").to_owned()+ } else if unlock.enabled() {+ ictl_l10n::tr!("已锁屏(操作时会自动解锁)", "locked (actions unlock automatically)").to_owned()+ } else {+ ictl_l10n::tr!("已锁屏(未配置自动解锁,需要人工解锁)", "locked (no auto-unlock configured; unlock by hand)")+ .to_owned()+ };+ if !locked && unlock.disabled_by_failure() {+ lock += ictl_l10n::tr!(";自动解锁已停用", "; auto-unlock disabled");+ }+ lock+}+fn needs_wda() -> &'static str {if ictl_l10n::is_en() { NEEDS_WDA_EN } else { NEEDS_WDA }}diff --git a/crates/ictl-daemon/src/tools/native.rs b/crates/ictl-daemon/src/tools/native.rsnew file mode 100644index 0000000..5b31771--- /dev/null+++ b/crates/ictl-daemon/src/tools/native.rs@@ -0,0 +1,837 @@+//! Native control of iOS 27 and later, without WebDriverAgent (`ICTL_IOS_BACKEND`, docs/dev/ios27-native.md):+//! the screen through remoteAXService (`ictl_ax`, turned into WDA's XML so `ictl_wda::elements` reads it), touches,+//! keys and Home through HID, text through the pasteboard, apps and links through CoreDevice AppService, the lock+//! state through lockdown.+//!+//! The tools keep their WDA code; where WDA isn't there they come here when [`Daemon::native`] says so.++use ictl_device::{ClipboardRestore, DeviceInfo};+use ictl_unlock::Screen;+use ictl_wda::client::LockCheck;+use ictl_wda::elements::View;++use super::*;+use crate::config::IosBackend;++/// A read of the screen waits at most this long for a tree (the first one of a session comes in about a second)+pub(crate) const AX_WAIT: Duration = Duration::from_secs(5);+/// After an action, the screen is first read this long after it started: an app reacts to a tap within about+/// 0.1 s, a page slides in within about 0.35 s (the second read, which confirms, comes about 0.2 s later)+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);+/// 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+const TERMINATE_WAIT: Duration = Duration::from_secs(2);+/// Home is answered no sooner than this after it was pressed: what it closes on the home screen animates meanwhile+const HOME_ANIMATION: Duration = Duration::from_millis(600);+/// After Home, how long the screen takes to wake before the swipe up (WDA's 1 s covers its slow queries)+const NATIVE_WAKE_SETTLE: Duration = Duration::from_millis(500);+/// After unlocking, the lock screen slides away for about half a second+const UNLOCK_SETTLE: Duration = Duration::from_millis(700);+/// The app's zoom-in takes about half a second; a tap during it is lost (the same as WDA's `LAUNCH_MIN`)+const LAUNCH_SETTLE: Duration = Duration::from_millis(800);++/// See [`IosBackend::drives_natively`]+fn native_for(backend: IosBackend, info: Option<&DeviceInfo>) -> bool {+ backend.drives_natively(info)+}++/// 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 {+ tree.elements.iter().any(|e| e.kind == "Keyboard") || tree.elements.iter().filter(|e| e.kind == "Key").count() >= 8+}++/// The paste prompt's "Allow Paste" button ("“Notes” would like to paste from “dtpasteboardd”"), when it is up+fn paste_allow(tree: &Tree) -> Option<(f64, f64)> {+ tree.alert().filter(|a| a.label.contains("dtpasteboardd"))?;+ tree.elements+ .iter()+ .find(|e| e.kind == "Button" && matches!(e.label.as_str(), "允许粘贴" | "Allow Paste" | "允許貼上"))+ .map(|e| (e.center.0 as f64, e.center.1 as f64))+}++impl Daemon {+ /// The current phone is driven natively (no WDA): see [`native_for`]+ pub(crate) fn native(&self, g: &Inner) -> bool {+ native_for(self.cfg.ios_backend, g.info.as_ref())+ }++ /// One read of the screen through remoteAXService, as WDA-style XML: the frontmost app's tree as it is now and+ /// SpringBoard's elements over the app. Returns the XML, the screen (as turned now) and the frontmost app's+ /// process+ pub(crate) async fn ax_read(+ &self,+ g: &mut Inner,+ wait: Duration,+ ) -> crate::error::Result<(String, ScreenSize, i64)> {+ self.ax_read_with(g, wait, true).await+ }++ /// [`Self::ax_read`], SpringBoard's elements over the app left out unless `overlays` (they don't tell whether a+ /// list has stopped, and reading them takes as long again)+ async fn ax_read_with(+ &self,+ g: &mut Inner,+ wait: Duration,+ overlays: bool,+ ) -> crate::error::Result<(String, ScreenSize, i64)> {+ let s = self.ax_snapshot(g, wait, overlays).await?;+ self.ax_render(g, &s).await+ }++ /// One read of the screen as the phone gives it ([`Self::ax_read_with`] before it becomes XML)+ async fn ax_snapshot(+ &self,+ g: &mut Inner,+ wait: Duration,+ overlays: bool,+ ) -> crate::error::Result<ictl_device::ax::AxScreen> {+ let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;+ let t = self+ .ensure_tunnel(g, &device)+ .await+ .map_err(|e| ictl_l10n::trf!("读界面失败(建隧道):{e}", "Reading the screen failed (tunnel): {e}"))?;+ let r = t.ax_screen(wait, overlays).await;+ if r.is_err() {+ t.close_ax().await;+ }+ g.ax_used = Some(Instant::now());+ Ok(r.map_err(|e| ictl_l10n::trf!("读界面失败:{e}", "Reading the screen failed: {e}"))?)+ }++ /// A read as WDA-style XML, the screen (as turned now) and the frontmost app's process+ async fn ax_render(+ &self,+ g: &mut Inner,+ s: &ictl_device::ax::AxScreen,+ ) -> crate::error::Result<(String, ScreenSize, i64)> {+ // the application element covers the screen: its frame is the screen in points, as turned now+ let root = s.app.first().and_then(|e| e.frame).map(|f| ScreenSize { width: f.2, height: f.3 });+ let size = match root.filter(|r| r.width > 1.0 && r.height > 1.0) {+ Some(r) => {+ if let Some(udid) = g.device.as_ref().map(|d| d.udid.clone())+ && g.persisted.record_screen(&udid, r.portrait())+ {+ g.persisted.save(&self.cfg.state_file());+ }+ r+ }+ None => self.screen(g).await?,+ };+ tracing::debug!(+ "native read: app pid {} with {} elements, {} over it, app frame {:?}, screen {}x{}",+ s.app_pid,+ s.app.len(),+ s.overlays.len(),+ s.app.first().and_then(|e| e.frame),+ size.width,+ size.height+ );+ let web = self.web_processes(g, &s.app).await;+ Ok((+ ictl_ax::xml::to_xml(&s.app, &s.overlays, size.width, size.height, &web, s.springboard_front),+ size,+ s.app_pid,+ ))+ }++ /// Which of the processes in a read are WebKit's web content (a page's elements, listed without a host): from+ /// the process list, read again only for a process not seen yet+ async fn web_processes(&self, g: &mut Inner, app: &[ictl_ax::Element]) -> std::collections::HashSet<i64> {+ let app_pid = app.first().map_or(0, ictl_ax::Element::pid);+ let mut pids: Vec<i64> = app.iter().map(ictl_ax::Element::pid).filter(|p| *p != app_pid).collect();+ pids.sort_unstable();+ pids.dedup();+ if pids.iter().any(|p| !g.dev.web_pids.contains_key(p))+ && let Some(device) = g.device.clone()+ && let Ok(t) = self.ensure_tunnel(g, &device).await+ && let Ok(procs) = t.processes().await+ {+ if g.dev.web_pids.len() > 200 {+ g.dev.web_pids.clear();+ }+ for p in &pids {+ let exe = procs.iter().find(|(q, _)| *q as i64 == *p).map(|(_, e)| e.as_str()).unwrap_or("");+ let name = exe.rsplit('/').next().unwrap_or("");+ g.dev.web_pids.insert(*p, name.starts_with("com.apple.WebKit.WebContent"));+ }+ }+ pids.into_iter().filter(|p| g.dev.web_pids.get(p) == Some(&true)).collect()+ }++ /// The screen's elements through remoteAXService (see [`Self::ax_read`])+ pub(crate) async fn ax_tree(&self, g: &mut Inner, wait: Duration) -> crate::error::Result<Tree> {+ let (xml, size, _) = self.ax_read(g, wait).await?;+ Ok(elements::parse_tree(&xml, size))+ }++ /// The frontmost app's bundle ID (one request, no walk)+ pub(crate) async fn native_foreground(&self, g: &mut Inner) -> crate::error::Result<String> {+ let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;+ let t = self.ensure_tunnel(g, &device).await?;+ let r = t.ax_frontmost_pid(AX_WAIT).await;+ if r.is_err() {+ t.close_ax().await;+ }+ g.ax_used = Some(Instant::now());+ let pid = r.map_err(|e| ictl_l10n::trf!("读前台 App 失败:{e}", "Reading the foreground app failed: {e}"))?;+ self.bundle_of_pid(g, pid).await+ }++ async fn bundle_of_pid(&self, g: &mut Inner, pid: i64) -> crate::error::Result<String> {+ if let Some(b) = g.dev.bundles.get(&pid) {+ return Ok(b.clone());+ }+ let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;+ let procs = self.ensure_tunnel(g, &device).await?.processes().await?;+ let exe = procs+ .into_iter()+ .find(|(p, _)| *p as i64 == pid)+ .map(|(_, e)| e)+ .ok_or_else(|| ictl_l10n::trf!("前台进程 {pid} 已经不在了", "The foreground process {pid} is gone"))?;+ for attempt in 0..2 {+ // the user's apps first: a system app never shares their paths, but this keeps the order of resolve+ let mut apps = self.list_apps(g, false).await?;+ apps.extend(self.list_apps(g, true).await?);+ if let Some(b) = apps::bundle_of_process(&exe, &apps) {+ if g.dev.bundles.len() > 200 {+ g.dev.bundles.clear();+ }+ g.dev.bundles.insert(pid, b.clone());+ return Ok(b);+ }+ // installed since the list was read+ if attempt == 0 {+ g.dev.apps.clear();+ }+ }+ Err(ictl_l10n::trf!("看不出进程 {pid}({exe})是哪个 App", "Can't tell which app process {pid} ({exe}) is")+ .into())+ }++ /// [`Self::status`] for a phone driven natively+ pub(crate) async fn native_status(+ &self,+ g: &mut Inner,+ unlock: &ictl_unlock::UnlockConfig,+ ) -> (String, StatusData) {+ let mut data = StatusData { native: true, ..Default::default() };+ let mut lines = vec![ictl_l10n::tr!(+ "控制方式: 原生(iOS 27 起不用 WDA:读界面经无障碍服务,触摸和按键经 HID)",+ "Control: native (no WDA from iOS 27: the screen through the accessibility service, touches and keys through HID)"+ )+ .to_owned()];+ match self.native_locked(g).await {+ Ok(locked) => {+ data.locked = Some(locked);+ lines.push(ictl_l10n::trf!("锁屏: {}", "Locked: {}", lock_text(locked, false, unlock)));+ }+ Err(e) => lines.push(ictl_l10n::trf!("锁屏: 查不到({e})", "Locked: unknown ({e})")),+ }+ match self.native_foreground(g).await {+ Ok(app) => {+ lines.push(ictl_l10n::trf!("前台 App: {app}", "Foreground app: {app}"));+ data.foreground = Some(app);+ }+ Err(e) => lines.push(ictl_l10n::trf!("前台 App: 查不到({e})", "Foreground app: unknown ({e})")),+ }+ if let Ok(s) = self.screen(g).await {+ lines.push(ictl_l10n::trf!("屏幕: {}x{} 点", "Screen: {}x{} points", fmt_g(s.width), fmt_g(s.height)));+ (data.width, data.height) = (Some(s.width), Some(s.height));+ }+ (lines.join("\n"), data)+ }++ /// Whether the phone is locked (lockdown's `PasswordProtected`)+ pub(crate) async fn native_locked(&self, g: &mut Inner) -> crate::error::Result<bool> {+ let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;+ Ok(device.passcode_locked().await?)+ }++ /// The interface's rotation, from SpringBoard (a lockdown service: no tunnel, no screenshot)+ pub(crate) async fn native_rotation(&self, g: &Inner) -> Option<Rotation> {+ Box::pin(g.device.as_ref()?.interface_rotation()).await.ok().flatten()+ }++ /// Waits for the screen to settle after an action, as through WDA: the tree read again until two reads in a+ /// row are alike and nothing is loading, at most `max`. The first read waits a moment after the action (the+ /// app's reaction, a page's slide in), or two reads of the old screen would count as settled. The reads meanwhile+ /// are of the app alone; what SpringBoard shows over it is read once, for the tree returned+ pub(crate) async fn native_settle(&self, g: &mut Inner, max: Duration) -> crate::error::Result<(String, Tree)> {+ let t0 = Instant::now();+ if let Some(left) = g.dev.acted_at.and_then(|t| REACT.checked_sub(t.elapsed())) {+ tokio::time::sleep(left).await;+ }+ let mut snap = self.ax_snapshot(g, AX_WAIT, false).await?;+ let mut prev = self.snapshot_tree(g, &snap).await?;+ if prev.elements.len() < VISUAL_SETTLE_BELOW {+ // between two pages (a slide in or back) the tree can be nearly empty for a moment: once more. Few+ // elements twice, and the same: a screen whose changes the tree doesn't show (a game, a map), the caller+ // looks at the picture. Otherwise the tree goes on telling (Settings → General has 12 or 13 elements,+ // fewer while it slides in)+ tokio::time::sleep(Duration::from_millis(300)).await;+ let again = self.ax_snapshot(g, AX_WAIT, false).await?;+ let cur = self.snapshot_tree(g, &again).await?;+ let sparse = cur.elements.len() < VISUAL_SETTLE_BELOW && cur.close_to(&prev, STILL_TOLERANCE);+ (snap, prev) = (again, cur);+ if sparse {+ return Ok((String::new(), self.with_overlays(g, snap).await?));+ }+ }+ loop {+ if t0.elapsed() >= max {+ let msg = if prev.loading {+ ictl_l10n::trf!(+ "{:.1} 秒内页面一直在加载(有加载圈),按最后的状态返回;要等结果出来用 iphone_wait_for",+ "The page kept loading for {:.1} s (spinner shown), returning the last state; to wait for the result use iphone_wait_for",+ max.as_secs_f64()+ )+ } else {+ ictl_l10n::trf!(+ "{:.1} 秒内界面一直在变(可能有动画),按最后的状态返回",+ "The screen kept changing for {:.1} s (perhaps an animation), returning the last state",+ max.as_secs_f64()+ )+ };+ return Ok((msg, self.with_overlays(g, snap).await?));+ }+ snap = self.ax_snapshot(g, AX_WAIT, false).await?;+ let cur = self.snapshot_tree(g, &snap).await?;+ let same = cur.close_to(&prev, STILL_TOLERANCE);+ prev = cur;+ if same && !prev.loading {+ let tree = self.with_overlays(g, snap).await?;+ let msg =+ ictl_l10n::trf!("界面已稳定({:.1} 秒)", "Screen settled ({:.1} s)", t0.elapsed().as_secs_f64());+ return Ok((msg, tree));+ }+ }+ }++ async fn snapshot_tree(&self, g: &mut Inner, s: &ictl_device::ax::AxScreen) -> crate::error::Result<Tree> {+ let (xml, size, _) = self.ax_render(g, s).await?;+ Ok(elements::parse_tree(&xml, size))+ }++ /// `s`, a read of the app alone, with what SpringBoard shows over it, as a tree+ async fn with_overlays(&self, g: &mut Inner, mut s: ictl_device::ax::AxScreen) -> crate::error::Result<Tree> {+ if let Some(t) = g.tunnel.as_mut() {+ s.overlays = t.ax_overlays(s.app_pid).await;+ }+ self.snapshot_tree(g, &s).await+ }++ /// The frontmost app's elements alone ([`Self::ax_read_with`])+ async fn ax_tree_app(&self, g: &mut Inner) -> crate::error::Result<Tree> {+ let (xml, size, _) = self.ax_read_with(g, AX_WAIT, false).await?;+ Ok(elements::parse_tree(&xml, size))+ }++ /// After a swipe, waits for the list to stop (at most [`SCROLL_SETTLE`]): two reads in a row with the elements+ /// in the same place along the swipe. Says when it was still moving; a screen with few elements isn't waited for+ pub(crate) async fn native_scrolled(&self, g: &mut Inner, vertical: bool) -> String {+ let t0 = Instant::now();++ let Ok(mut prev) = self.ax_tree_app(g).await else { return String::new() };+ if prev.elements.len() < VISUAL_SETTLE_BELOW {+ return String::new();+ }+ while t0.elapsed() < SCROLL_SETTLE {+ let Ok(cur) = self.ax_tree_app(g).await else { return String::new() };+ let still = cur.still_along_common(&prev, vertical, STILL_TOLERANCE);+ tracing::debug!(+ "scroll wait at {:.2} s: {} then {} elements, still: {still}",+ t0.elapsed().as_secs_f64(),+ prev.elements.len(),+ cur.elements.len()+ );+ if still {+ return String::new();+ }+ prev = cur;+ }+ ictl_l10n::trf!(+ "({:.1} 秒后列表还在动,可能还在滚动)",+ " (the list was still moving after {:.1} s, it may still be scrolling)",+ SCROLL_SETTLE.as_secs_f64()+ )+ }++ /// Text appearing on screen, natively: the tree read again every 0.3 s+ pub(crate) async fn native_wait_for(+ &self,+ g: &mut Inner,+ text: &str,+ timeout: Duration,+ ) -> crate::error::Result<String> {+ let t0 = Instant::now();+ loop {+ let tree = self.ax_tree(g, AX_WAIT).await?;+ // 不算输入框里的字:刚输入的搜索词不能算「结果出来了」+ if let Some(e) = elements::find_shown(&tree.elements, text).first() {+ return Ok(ictl_l10n::trf!(+ "已出现 {}({:.1} 秒)",+ "Appeared: {} ({:.1} s)",+ e.describe(),+ t0.elapsed().as_secs_f64()+ ));+ }+ if t0.elapsed() >= timeout {+ return Err(ictl_l10n::trf!(+ "{:.0} 秒内没出现包含 \"{text}\" 的元素,截图看看屏幕",+ "No element containing \"{text}\" appeared within {:.0} s; take a screenshot to look at the screen",+ timeout.as_secs_f64()+ )+ .into());+ }+ tokio::time::sleep(Duration::from_millis(300)).await;+ }+ }++ /// A system alert over the screen, natively: SpringBoard's elements are part of every read+ pub(crate) async fn native_alert(&self, g: &mut Inner) -> crate::error::Result<(String, Option<String>)> {+ let tree = self.ax_tree(g, AX_WAIT).await?;+ Ok(match tree.alert().map(|a| a.label.clone()).filter(|l| !l.is_empty()) {+ Some(text) => (alert_msg(&text), Some(text)),+ None => (String::new(), None),+ })+ }++ /// Home, natively: not pressed under a system alert (it would do nothing), and confirmed by the home screen+ /// coming to the front; when the key does nothing, a swipe up from the bottom edge does it+ pub(crate) async fn native_home(&self, g: &mut Inner, watched: bool) -> crate::error::Result<String> {+ if !watched && let (_, Some(text)) = self.native_alert(g).await? {+ return Ok(ictl_l10n::trf!(+ "{},按 Home 不会生效,没有按;{TAP_ALERT}",+ "{}, pressing Home would have no effect, not pressed; {TAP_ALERT_EN}",+ blocking(&text)+ ));+ }+ let pressed = Instant::now();+ self.hid_do(g, |h| Box::pin(h.press(Button::Home))).await?;+ if self.native_reached_home(g).await {+ // already on the home screen (Home closed a menu, a folder): what it closes is still animating, and an+ // app launched meanwhile was sent back to the home screen once it ended (3 times in 3)+ if let Some(left) = HOME_ANIMATION.checked_sub(pressed.elapsed()) {+ tokio::time::sleep(left).await;+ }+ return Ok(ictl_l10n::tr!("已按 home", "Pressed home").into());+ }+ let s = self.screen(g).await?;+ let rot = self.hid_touch_rotation(g).await?;+ let (from, to) = ((s.width / 2.0, s.height - 2.0), (s.width / 2.0, s.height * 0.55));+ self.hid_do(g, move |h| {+ Box::pin(async move {+ h.rotation = rot;+ h.drag(from, to, 0.25).await+ })+ })+ .await?;+ if self.native_reached_home(g).await {+ return Ok(ictl_l10n::tr!(+ "已按 home(Home 键没反应,改为从屏幕底部上滑)",+ "Pressed home (the key did nothing, swiped up from the bottom edge instead)"+ )+ .into());+ }+ if let (_, Some(text)) = self.native_alert(g).await? {+ return Ok(ictl_l10n::trf!(+ "{},按 Home 没有生效,先点弹窗上的按钮",+ "{}, pressing Home had no effect; first tap a button on the alert",+ blocking(&text)+ ));+ }+ let app = self.native_foreground(g).await.unwrap_or_default();+ Ok(ictl_l10n::trf!(+ "已按 home,但前台还是 {app},先截图看看",+ "Pressed home, but the foreground is still {app}; take a screenshot"+ ))+ }++ /// Whether the home screen comes to the front within [`HOME_SETTLE`]+ async fn native_reached_home(&self, g: &mut Inner) -> bool {+ let deadline = Instant::now() + HOME_SETTLE;+ loop {+ if self.native_foreground(g).await.is_ok_and(|b| b == SPRINGBOARD) {+ return true;+ }+ if Instant::now() >= deadline {+ return false;+ }+ tokio::time::sleep(Duration::from_millis(150)).await;+ }+ }++ /// A tap at a point through HID, the interface's rotation read first+ pub(crate) async fn native_tap(&self, g: &mut Inner, x: f64, y: f64) -> crate::error::Result<()> {+ let rot = self.hid_touch_rotation(g).await?;+ self.hid_do(g, move |h| {+ Box::pin(async move {+ h.rotation = rot;+ h.tap(x, y).await+ })+ })+ .await+ }++ pub(crate) async fn native_long_press(+ &self,+ g: &mut Inner,+ x: f64,+ y: f64,+ seconds: f64,+ ) -> crate::error::Result<()> {+ let rot = self.hid_touch_rotation(g).await?;+ self.hid_do(g, move |h| {+ Box::pin(async move {+ h.rotation = rot;+ h.long_press(x, y, seconds).await+ })+ })+ .await+ }++ /// Typing, natively: all text is pasted, the paste prompt answered, and the field read back before the+ /// pasteboard is put back and Return pressed. Not as keys: HID keys go through the hardware keyboard's input+ /// source, which composed them as pinyin with the on-screen keyboard showing English («wifi» became marked+ /// pinyin «w i f i»), and the "next keyboard" button names the keyboard it switches to, not the one shown+ pub(crate) async fn native_type(&self, g: &mut Inner, text: &str, submit: bool) -> crate::error::Result<String> {+ let n = text.chars().count();+ let before = self.ax_tree_app(g).await?;+ if !keyboard_up(&before) {+ return Err(ictl_l10n::tr!(+ "屏幕上没有键盘(没有输入框获得焦点),什么都没输;先点一下输入框,截图确认键盘出来了再输入",+ "No keyboard on screen (no text field has focus), nothing typed; tap a text field first and check with a screenshot that the keyboard is up"+ )+ .into());+ }+ let old = elements::field_values(&before.elements);+ let mut note = String::new();+ if !text.is_empty() {+ let (typed, prompt) = self.native_paste(g, text, old.as_deref()).await?;+ if prompt {+ note += ictl_l10n::tr!("(已替你点了「允许粘贴」)", " (“Allow Paste” was tapped for you)");+ }+ match typed {+ Some(true) => {}+ // a password field: its value can't be read+ None => {+ note += ictl_l10n::tr!(+ "(这是密码框,读不出内容,截图确认输进去了)",+ " (a password field: its contents can't be read back, check with a screenshot)"+ )+ }+ Some(false) => {+ 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",+ PASTE_WAIT.as_secs(),+ if submit { ictl_l10n::tr!(",没有按回车", ", Return not pressed") } else { "" }+ )+ .into());+ }+ }+ }+ if submit {+ self.hid_do(g, |h| Box::pin(async move { h.type_ascii("\n").await })).await.map_err(|e| {+ ictl_l10n::trf!("文字已输入{note},按回车失败:{e}", "Text typed{note}, pressing Return failed: {e}")+ })?;+ }+ Ok(ictl_l10n::trf!(+ "已输入 {n} 个字符{note}{}",+ "Typed {n} characters{note}{}",+ if submit { ictl_l10n::tr!(",并按了回车", " and pressed Return") } else { "" }+ ))+ }++ /// 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+ async fn native_paste(+ &self,+ g: &mut Inner,+ text: &str,+ old: Option<&[String]>,+ ) -> crate::error::Result<(Option<bool>, 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?;+ let r = Box::pin(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!("粘贴失败:{e}", "Paste failed: {e}").into());+ }+ };+ let deadline = Instant::now() + PASTE_WAIT;+ let mut prompt = false;+ let wanted = text.trim();+ let typed = loop {+ // a whole read: the prompt brings SpringBoard to the front, but it may also come over the app (a read+ // of the app alone missed it once in a regression run, and the paste never went in)+ let tree = self.ax_tree(g, AX_WAIT).await?;+ if let Some((x, y)) = paste_allow(&tree) {+ self.native_tap(g, x, y).await?;+ prompt = true;+ 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),+ _ => {}+ }+ tokio::time::sleep(Duration::from_millis(250)).await;+ };+ if let Some(p) = pending {+ let restored = match g.tunnel.as_mut() {+ Some(t) => Box::pin(t.restore_pasteboard(p)).await,+ None => ClipboardRestore::Failed("no tunnel".into()),+ };+ if let ClipboardRestore::Failed(e) = restored {+ tracing::warn!(+ "{}",+ ictl_l10n::log_trf!(+ "粘贴后还原剪贴板失败:{e}",+ "Restoring the pasteboard after the paste failed: {e}"+ )+ );+ }+ }+ Ok((typed, prompt))+ }++ /// Launches `bundle_id` in front (with `url`, the link for it to open) and waits for it to be there+ pub(crate) async fn native_launch(+ &self,+ g: &mut Inner,+ bundle_id: &str,+ url: Option<&str>,+ ) -> crate::error::Result<ictl_wda::Launch> {+ let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;+ let t0 = Instant::now();+ self.ensure_tunnel(g, &device).await?.launch_foreground(bundle_id, url).await?;+ loop {+ tokio::time::sleep(Duration::from_millis(300)).await;+ let (xml, size, pid) = self.ax_read(g, AX_WAIT).await?;+ let tree = elements::parse_tree(&xml, size);+ if let Some(a) = tree.alert().filter(|a| !a.label.is_empty()) {+ return Ok(ictl_wda::Launch::Blocked(a.label.clone()));+ }+ if self.bundle_of_pid(g, pid).await.is_ok_and(|b| b == bundle_id) {+ if let Some(left) = LAUNCH_SETTLE.checked_sub(t0.elapsed()) {+ tokio::time::sleep(left).await;+ }+ return Ok(ictl_wda::Launch::Foreground);+ }+ if t0.elapsed() >= LAUNCH_WAIT {+ return Ok(ictl_wda::Launch::Slow);+ }+ }+ }++ /// Ends `bundle_id`'s process (SIGKILL through CoreDevice); Ok(false) when it wasn't running+ pub(crate) async fn native_terminate(&self, g: &mut Inner, bundle_id: &str) -> crate::error::Result<bool> {+ let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;+ let procs = self.ensure_tunnel(g, &device).await?.processes().await?;+ let mut apps = self.list_apps(g, false).await?;+ apps.extend(self.list_apps(g, true).await?);+ let pids: Vec<u64> = procs+ .iter()+ .filter(|(_, exe)| apps::bundle_of_process(exe, &apps).as_deref() == Some(bundle_id))+ .map(|(p, _)| *p)+ .collect();+ for pid in &pids {+ self.ensure_tunnel(g, &device).await?.signal(*pid, 9).await?;+ }+ // gone before this says so: a launch right after one killed failed with «The process identifier of the+ // launched application could not be determined. It may have already terminated.»+ let deadline = Instant::now() + TERMINATE_WAIT;+ while !pids.is_empty() && Instant::now() < deadline {+ let procs = self.ensure_tunnel(g, &device).await?.processes().await?;+ if !procs.iter().any(|(p, _)| pids.contains(p)) {+ break;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ Ok(!pids.is_empty())+ }++ /// The app that opens `url`+ pub(crate) async fn native_app_for_url(&self, g: &mut Inner, url: &str) -> crate::error::Result<String> {+ let mut apps = self.list_apps(g, false).await?;+ apps.extend(self.list_apps(g, true).await?);+ apps::app_for_url(url, &apps)+ .ok_or_else(|| ictl_l10n::trf!("手机上没有 App 能打开 {url}", "No app on the phone opens {url}").into())+ }++ /// Unlocks natively, with the same rules and guards as through WDA (`ictl_unlock`)+ pub(crate) async fn native_unlock(+ &self,+ g: &mut Inner,+ cfg: &ictl_unlock::UnlockConfig,+ ) -> ictl_unlock::Result<ictl_unlock::Outcome> {+ // Home wakes a dark screen within about 0.3 s; the keypad is looked for as it comes (`reads_cheaply`)+ let cfg = ictl_unlock::UnlockConfig {+ passcode_file: cfg.passcode_file.clone(),+ disabled_flag: cfg.disabled_flag.clone(),+ timing: ictl_unlock::Timing { wake_settle: NATIVE_WAKE_SETTLE, ..cfg.timing },+ };+ let mut screen = NativeScreen { d: self, g };+ let r = Box::pin(ictl_unlock::ensure_unlocked(&mut screen, &cfg)).await;+ if matches!(r, Ok(ictl_unlock::Outcome::Unlocked)) {+ // the lock screen is still sliding away: a tap now is lost (a tap by text right after unlocking did+ // nothing on the phone)+ tokio::time::sleep(UNLOCK_SETTLE).await;+ }+ r+ }+}++/// The phone as [`ictl_unlock`] sees it, driven natively+struct NativeScreen<'a> {+ d: &'a Daemon,+ g: &'a mut Inner,+}++/// Reads the lock screen: with the HID session's screen stream open, the phone hides the lock screen and its+/// passcode keypad from accessibility (one element, the app's, for every session; iPhone 15 Pro Max, iOS 27.2.1), so+/// the session is closed first, and the elements come back a moment after. The next tap opens it again (about 0.5 s)+async fn read_lock_screen(d: &Daemon, g: &mut Inner) -> crate::error::Result<(String, ScreenSize, i64)> {+ let was_open = g.tunnel.as_ref().is_some_and(ictl_device::Tunnel::hid_open);+ crate::core::close_hid(g).await;+ let t0 = Instant::now();+ loop {+ let read = Box::pin(d.ax_read(g, Duration::from_secs(3))).await?;+ let shown = read.0.matches("<XCUIElementType").count() > 1;+ if shown || !was_open || t0.elapsed() >= LOCK_SCREEN_BACK {+ tracing::debug!(+ "lock screen read {:.0} ms after closing HID, elements shown: {shown}",+ t0.elapsed().as_secs_f64() * 1000.0+ );+ return Ok(read);+ }+ tokio::time::sleep(Duration::from_millis(150)).await;+ }+}++/// How long after the HID session closes the lock screen's elements may take to come back+const LOCK_SCREEN_BACK: Duration = Duration::from_secs(3);++/// A step that failed: unlocking tries another round+fn step(e: impl std::fmt::Display) -> WdaError {+ WdaError::Remote { kind: "native".into(), message: e.to_string() }+}++impl Screen for NativeScreen<'_> {+ async fn reports_locked(&mut self) -> std::result::Result<bool, WdaError> {+ self.d.native_locked(self.g).await.map_err(|e| WdaError::Unavailable(e.to_string()))+ }++ fn lock_state_trusted(&self) -> bool {+ // lockdown knows: no lock-screen-looking notification center to tell apart+ true+ }++ async fn check_lock(&mut self, _reported: Option<bool>, _strict: bool) -> std::result::Result<LockCheck, WdaError> {+ let locked = self.d.native_locked(self.g).await.map_err(|e| WdaError::Unavailable(e.to_string()))?;+ let tree = if locked { read_lock_screen(self.d, self.g).await.ok().map(|(x, _, _)| x) } else { None };+ Ok(LockCheck { locked, uncertain: false, tree })+ }++ async fn quick_waits(&mut self) -> std::result::Result<Option<ictl_wda::IdleSettings>, WdaError> {+ Ok(None)+ }++ async fn restore_waits(&mut self, _: ictl_wda::IdleSettings) -> std::result::Result<(), WdaError> {+ Ok(())+ }++ async fn press_home(&mut self, _round: u32) -> std::result::Result<(), WdaError> {+ self.d.hid_do(self.g, |h| Box::pin(h.press(Button::Home))).await.map_err(step)+ }++ async fn view(&mut self) -> std::result::Result<View, WdaError> {+ self.d.screen(self.g).await.map(View::from).map_err(|e| WdaError::Unavailable(e.to_string()))+ }++ async fn swipe(&mut self, from: (f64, f64), to: (f64, f64), ms: u64) -> std::result::Result<(), WdaError> {+ let rot = self.d.hid_touch_rotation(self.g).await.map_err(step)?;+ let seconds = ms as f64 / 1000.0;+ self.d+ .hid_do(self.g, move |h| {+ Box::pin(async move {+ h.rotation = rot;+ h.drag(from, to, seconds).await+ })+ })+ .await+ .map_err(step)+ }++ async fn tap(&mut self, x: f64, y: f64, _press_ms: u64) -> std::result::Result<(), WdaError> {+ self.d.native_tap(self.g, x, y).await.map_err(step)+ }++ async fn elements(&mut self) -> std::result::Result<Vec<elements::Element>, WdaError> {+ let (xml, size, _) = read_lock_screen(self.d, self.g).await.map_err(step)?;+ Ok(elements::parse(&xml, size))+ }++ async fn passcode_field(&mut self) -> std::result::Result<Option<(u32, u32)>, WdaError> {+ Ok(elements::passcode_field(&self.elements().await?))+ }++ fn reads_cheaply(&self) -> bool {+ // a read of the lock screen takes about 0.1 s+ true+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn info(version: &str) -> DeviceInfo {+ DeviceInfo {+ udid: "u".into(),+ name: "n".into(),+ product_type: "iPhone16,2".into(),+ product_version: version.into(),+ }+ }++ #[test]+ fn ios_27_and_later_are_native_unless_wda_is_asked_for() {+ assert!(native_for(IosBackend::Auto, Some(&info("27.2.1"))));+ assert!(native_for(IosBackend::Native, Some(&info("28.0"))));+ assert!(!native_for(IosBackend::Wda, Some(&info("27.2.1"))));+ // no HID below 27+ assert!(!native_for(IosBackend::Native, Some(&info("26.7.3"))));+ assert!(!native_for(IosBackend::Auto, None));+ }++ #[test]+ fn the_paste_prompt_is_answered_only_for_our_paste() {+ let xml = |alert: &str| {+ format!(+ r#"<XCUIElementTypeApplication type="XCUIElementTypeApplication" label="备忘录" x="0" y="0" width="430" height="932"><XCUIElementTypeAlert type="XCUIElementTypeAlert" label="{alert}" x="55" y="390" width="320" height="175"><XCUIElementTypeButton type="XCUIElementTypeButton" label="允许粘贴" x="71" y="501" width="140" height="49"/><XCUIElementTypeButton type="XCUIElementTypeButton" label="不允许粘贴" x="219" y="501" width="140" height="49"/></XCUIElementTypeAlert></XCUIElementTypeApplication>"#+ )+ };+ let screen = ScreenSize { width: 430.0, height: 932.0 };+ let ours = elements::parse_tree(&xml("“备忘录”想从“dtpasteboardd”粘贴"), screen);+ assert_eq!(paste_allow(&ours), Some((141.0, 526.0)));+ let other = elements::parse_tree(&xml("“备忘录”想从“微信”粘贴"), screen);+ assert_eq!(paste_allow(&other), None);+ }+}diff --git a/crates/ictl-daemon/src/tools/observe.rs b/crates/ictl-daemon/src/tools/observe.rsindex c37e196..3eac074 100644--- a/crates/ictl-daemon/src/tools/observe.rs+++ b/crates/ictl-daemon/src/tools/observe.rs@@ -13,7 +13,12 @@ impl Daemon {g.dev.seen.saw_tree(&tree);return Ok(tree);}- let tree = self.require_wda(g)?.tree().await?;+ let native = self.native(g);+ let tree = match self.wda(g) {+ Some(w) => w.tree().await?,+ None if native => Box::pin(self.ax_tree(g, super::native::AX_WAIT)).await?,+ None => self.require_wda(g)?.tree().await?,+ };g.elements_cache = Some((Instant::now(), tree.clone()));g.dev.seen.saw_tree(&tree);Ok(tree)@@ -29,9 +34,13 @@ impl Daemon {) -> crate::error::Result<(String, Vec<ElementData>)> {if keep_locked {// only looking (a read-only viewer): the passcode isn't typed for it- if let Some(w) = self.wda(g)- && w.locked().await?- {+ let native = self.native(g);+ let locked = match self.wda(g) {+ Some(w) => w.locked().await?,+ None if native => self.native_locked(g).await?,+ None => false,+ };+ if locked {return Err(ictl_l10n::tr!("手机锁着:只看不操作时不会替你解锁","The phone is locked: it isn't unlocked for someone who only watches"@@ -78,6 +87,9 @@ impl Daemon {let t0 = Instant::now();// 刚滑完读到的树:只作比较的起点,是不是真稳定还要看下一次读到的let seed = g.swiped_tree.take().filter(|(at, _)| at.elapsed() < SWIPED_TREE_FRESH).map(|(_, t)| t);+ if self.wda(g).is_none() && self.native(g) {+ return Box::pin(self.settle_native(g, t0, max)).await;+ }let Some(w) = self.wda(g) else {tokio::time::sleep(max.min(Duration::from_millis(500))).await;return Ok(ictl_l10n::tr!("WDA 不可用,等了 0.5 秒", "WDA unavailable, waited 0.5 s").into());@@ -107,6 +119,24 @@ impl Daemon {Ok(msg + &change + ¬e)}+ /// [`Self::settle`] without WDA: the trees the phone pushes say when the screen has settled; a screen with few+ /// elements (a game, a map) is judged by its picture, as through WDA+ async fn settle_native(&self, g: &mut Inner, t0: Instant, max: Duration) -> crate::error::Result<String> {+ let (msg, tree) = Box::pin(self.native_settle(g, max)).await?;+ let note = alert_note(&tree);+ // no word from it: a screen with few elements that stay the same (a game, a map), judged by the picture+ if msg.is_empty() {+ let left = max.saturating_sub(t0.elapsed()).max(Duration::from_millis(600));+ let msg = self.settle_visually(g, Instant::now(), left).await?;+ let change = self.change_note(g, None).await;+ return Ok(msg + &change + ¬e);+ }+ let change = self.change_note(g, Some(&tree)).await;+ g.dev.seen.saw_tree(&tree);+ g.elements_cache = Some((Instant::now(), tree));+ Ok(msg + &change + ¬e)+ }+/// 操作做完、界面稳定后,和操作前([`PerDevice::before_action`](crate::core::PerDevice))比有没有变化,/// 接在 settle 结果后面的说明。`tree`:稳定时读到的元素树(看画面判断稳定时为 None,用记下的画面指纹)。/// 操作前只截过图、没读过元素树时,补截一张图来比(约 0.3 秒);操作前什么都没看过就不说@@ -116,8 +146,7 @@ impl Daemon {if before.tree.as_ref().zip(tree).is_none()&& before.thumb.is_some()&& thumb.is_none()- && let Some(w) = self.wda(g)- && let Ok(png) = w.screenshot_png().await+ && let Ok(png) = self.raw_png(g).await&& let Ok(t) = thumbnail(png).await{g.dev.seen.saw_thumb(t.clone());@@ -135,7 +164,7 @@ impl Daemon {let deadline = t0 + max;let mut prev: Option<Vec<u8>> = None;loop {- let png = self.require_wda(g)?.screenshot_png().await?;+ let png = self.raw_png(g).await?;let cur = thumbnail(png).await?;// 最后一帧就是操作后的画面:和操作前比([`Self::change_note`]),也是下一个操作的「操作前」g.dev.seen.saw_thumb(cur.clone());@@ -172,13 +201,12 @@ impl Daemon {/// 隔一下截两张图,画面还在动就返回提醒,否则返回空串pub(super) async fn motion_note(&self, g: &mut Inner) -> String {- let Some(w) = self.wda(g) else { return String::new() };let mut thumbs = Vec::new();for i in 0..2 {if i > 0 {tokio::time::sleep(Duration::from_millis(150)).await;}- let Ok(png) = w.screenshot_png().await else { return String::new() };+ let Ok(png) = self.raw_png(g).await else { return String::new() };let Ok(t) = thumbnail(png).await else { return String::new() };thumbs.push(t);}@@ -195,6 +223,9 @@ impl Daemon {/// 前台是 App 时只多一次约 0.13 秒的查询;在主屏上再多约 0.4 秒/// A system alert in front: the note for the agent, and the alert's own textpub(crate) async fn alert_check(&self, g: &mut Inner) -> crate::error::Result<(String, Option<String>)> {+ if self.wda(g).is_none() && self.native(g) {+ return Box::pin(self.native_alert(g)).await;+ }let Some(w) = self.wda(g) else { return Ok((String::new(), None)) };if w.active_app().await? != SPRINGBOARD {return Ok((String::new(), None));@@ -209,6 +240,9 @@ impl Daemon {pub(crate) async fn wait_for(&self, g: &mut Inner, text: &str, timeout: Duration) -> crate::error::Result<String> {self.ensure_unlocked(g).await?;let t0 = Instant::now();+ if self.wda(g).is_none() && self.native(g) {+ return Box::pin(self.native_wait_for(g, text, timeout)).await;+ }let w = self.require_wda(g)?;// 轮询时不等界面空闲:页面还在加载、播放动画时每次读树也只要约 0.2 秒w.begin_polling().await?;diff --git a/crates/ictl-device/Cargo.toml b/crates/ictl-device/Cargo.tomlindex 7d7bb38..bb1ef0c 100644--- a/crates/ictl-device/Cargo.toml+++ b/crates/ictl-device/Cargo.toml@@ -10,6 +10,7 @@ homepage.workspace = truedescription = "设备层:发现、配对、隧道、开发者镜像、HID、截图、App"[dependencies]+ictl-ax.workspace = trueictl-l10n.workspace = trueictl-webinspector.workspace = trueidevice.workspace = truediff --git a/crates/ictl-device/src/apps.rs b/crates/ictl-device/src/apps.rsindex 0bbb748..ad70b09 100644--- a/crates/ictl-device/src/apps.rs+++ b/crates/ictl-device/src/apps.rs@@ -8,6 +8,11 @@ pub struct AppInfo {pub bundle_id: String,/// CFBundleExecutable: the process name the app runs as (for filtering its logs)pub executable: String,+ /// Where the app is installed (`Path`, e.g. `/Applications/Preferences.app`): a running process's executable is+ /// inside it, which tells which app a process is (see [`bundle_of_process`])+ pub path: String,+ /// The link schemes it opens (`CFBundleURLTypes`), lowercase+ pub schemes: Vec<String>,}/// 解析 installation_proxy `Lookup` 的结果,按名字排序。@@ -32,13 +37,56 @@ pub fn parse_apps(lookup: HashMap<String, plist::Value>) -> Vec<AppInfo> {.to_owned();let bundle_id = d.get("CFBundleIdentifier").and_then(|v| v.as_string()).unwrap_or(&bid).to_owned();let executable = d.get("CFBundleExecutable").and_then(|v| v.as_string()).unwrap_or_default().to_owned();- Some(AppInfo { name, bundle_id, executable })+ let path = d.get("Path").and_then(|v| v.as_string()).unwrap_or_default().to_owned();+ let schemes = d+ .get("CFBundleURLTypes")+ .and_then(|v| v.as_array())+ .into_iter()+ .flatten()+ .filter_map(|t| t.as_dictionary()?.get("CFBundleURLSchemes")?.as_array())+ .flatten()+ .filter_map(|s| s.as_string().map(str::to_ascii_lowercase))+ .collect();+ Some(AppInfo { name, bundle_id, executable, path, schemes })}).collect();out.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.bundle_id.cmp(&b.bundle_id)));out}+/// SpringBoard's executable (the home screen, the lock screen); not in the installed apps+pub const SPRINGBOARD_EXECUTABLE: &str = "/System/Library/CoreServices/SpringBoard.app/SpringBoard";++/// The bundle ID of the app whose process runs `executable` (a process's executable URL or path, as CoreDevice's+/// process list gives it), from where the apps are installed. SpringBoard is `com.apple.springboard`+pub fn bundle_of_process<'a>(executable: &str, apps: impl IntoIterator<Item = &'a AppInfo>) -> Option<String> {+ // /var is a link to /private/var: compare without it+ fn norm(p: &str) -> &str {+ p.strip_prefix("/private").unwrap_or(p)+ }+ let exe = executable.strip_prefix("file://").unwrap_or(executable);+ if norm(exe) == norm(SPRINGBOARD_EXECUTABLE) {+ return Some("com.apple.springboard".into());+ }+ apps.into_iter()+ .filter(|a| !a.path.is_empty())+ .find(|a| norm(exe).strip_prefix(norm(a.path.trim_end_matches('/'))).is_some_and(|rest| rest.starts_with('/')))+ .map(|a| a.bundle_id.clone())+}++/// The app that opens `url`: Safari for web pages, otherwise the first of `apps` (pass the user's apps first) that+/// declares its scheme. None for a link no app opens, or one without a scheme+pub fn app_for_url<'a>(url: &str, apps: impl IntoIterator<Item = &'a AppInfo>) -> Option<String> {+ let scheme = url.split_once(':')?.0.to_ascii_lowercase();+ if scheme.is_empty() || !scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) {+ return None;+ }+ if scheme == "http" || scheme == "https" {+ return Some("com.apple.mobilesafari".into());+ }+ apps.into_iter().find(|a| a.schemes.contains(&scheme)).map(|a| a.bundle_id.clone())+}+/// 看起来就是 Bundle ID(带点、不带空格),不用查列表pub fn looks_like_bundle_id(app: &str) -> bool {app.contains('.') && !app.contains(' ')@@ -98,7 +146,9 @@ mod tests {assert!(s.contains(&AppInfo {name: "设置".into(),bundle_id: "com.apple.Preferences".into(),- executable: String::new()+ executable: String::new(),+ path: String::new(),+ schemes: Vec::new(),}));assert!(s.iter().all(|a| a.bundle_id != "com.apple.NewDeviceSetupUIService"));assert_eq!(s.iter().filter(|a| a.name == "设置").count(), 1);@@ -140,4 +190,48 @@ mod tests {let (u, s) = (user(), system());assert_eq!(resolve("不存在的 App", [&u[..], &s[..]]), None);}++ #[test]+ fn a_process_is_named_by_the_app_it_runs_in() {+ let app = |b: &str, p: &str| AppInfo {+ name: String::new(),+ bundle_id: b.into(),+ executable: String::new(),+ path: p.into(),+ schemes: Vec::new(),+ };+ let apps = [+ app("com.apple.Preferences", "/Applications/Preferences.app"),+ app("com.tencent.xin", "/private/var/containers/Bundle/Application/AB-12/WeChat.app"),+ app("com.example.pref", "/Applications/Preferences.appx"),+ ];+ let of = |exe: &str| bundle_of_process(exe, &apps);+ assert_eq!(of("file:///Applications/Preferences.app/Preferences").as_deref(), Some("com.apple.Preferences"));+ assert_eq!(+ of("file:///var/containers/Bundle/Application/AB-12/WeChat.app/WeChat").as_deref(),+ Some("com.tencent.xin")+ );+ assert_eq!(+ of("file:///System/Library/CoreServices/SpringBoard.app/SpringBoard").as_deref(),+ Some("com.apple.springboard")+ );+ assert_eq!(of("file:///usr/libexec/backboardd"), None);+ }++ #[test]+ fn a_link_opens_in_the_app_of_its_scheme() {+ let app = |b: &str, schemes: &[&str]| AppInfo {+ name: String::new(),+ bundle_id: b.into(),+ executable: String::new(),+ path: String::new(),+ schemes: schemes.iter().map(|s| s.to_string()).collect(),+ };+ let apps = [app("com.tencent.xin", &["weixin", "wechat"]), app("com.apple.Maps", &["maps"])];+ assert_eq!(app_for_url("https://example.com", &apps).as_deref(), Some("com.apple.mobilesafari"));+ assert_eq!(app_for_url("WeiXin://dl/chat", &apps).as_deref(), Some("com.tencent.xin"));+ assert_eq!(app_for_url("maps:?q=x", &apps).as_deref(), Some("com.apple.Maps"));+ assert_eq!(app_for_url("nothing://x", &apps), None);+ assert_eq!(app_for_url("no scheme", &apps), None);+ }}diff --git a/crates/ictl-device/src/ax.rs b/crates/ictl-device/src/ax.rsnew file mode 100644index 0000000..e6d4e27--- /dev/null+++ b/crates/ictl-device/src/ax.rs@@ -0,0 +1,184 @@+//! The screen's elements through remoteAXService ([`ictl_ax`]), without WebDriverAgent: the session lives on the+//! tunnel like the HID session, and is opened again when the phone closed it.++use std::time::{Duration, Instant};++use ictl_ax::{Element, ObjectRef};+use idevice::ReadWrite;++use crate::{DeviceError, Result, Tunnel, limit};++pub type AxSession = ictl_ax::Session<Box<dyn ReadWrite>>;++/// The handshake answers in tens of milliseconds over USB+const CONNECT_WAIT: Duration = Duration::from_secs(8);+/// A walk of the app reads at most this many elements, within this long (Pinky's bounds over USB)+const WALK_LIMIT: usize = 400;+const WALK_BUDGET: Duration = Duration::from_secs(4);+/// At most this many of SpringBoard's elements are read over the app (the status bar and what covers the app)+const OVERLAY_LIMIT: usize = 80;+const OVERLAY_BUDGET: Duration = Duration::from_secs(2);++impl From<ictl_ax::AxError> for DeviceError {+ fn from(e: ictl_ax::AxError) -> Self {+ match e {+ ictl_ax::AxError::Timeout(what) => Self::Timeout(format!("remoteAXService: {what}")),+ other => Self::Idevice(other.to_string()),+ }+ }+}++/// One read of the screen+#[derive(Debug, Clone)]+pub struct AxScreen {+ /// The frontmost application's tree, its element first+ pub app: Vec<Element>,+ /// What SpringBoard shows over the app (alerts, banners, its status bar); empty when SpringBoard is the app+ pub overlays: Vec<Element>,+ pub app_pid: i64,+ /// SpringBoard is the app in front (the home screen, the lock screen, or a question it asks over an app)+ pub springboard_front: bool,+ /// When the screen was read+ pub at: Instant,+}++impl Tunnel {+ /// Whether the phone offers remoteAXService (iOS 27 with the developer disk image)+ pub fn ax_supported(&self) -> bool {+ self.handshake.services.contains_key(ictl_ax::SERVICE)+ }++ pub fn ax_open(&self) -> bool {+ self.ax.as_ref().is_some_and(|s| !s.is_closed())+ }++ /// The session, opened (again) if needed+ pub async fn ax(&mut self) -> Result<&AxSession> {+ if !self.ax_open() {+ self.ax = None;+ self.springboard_app = None;+ let port = self+ .handshake+ .services+ .get(ictl_ax::SERVICE)+ .map(|s| s.port)+ .ok_or_else(|| DeviceError::Idevice(format!("the phone offers no {}", ictl_ax::SERVICE)))?;+ let stream: Box<dyn ReadWrite> = Box::new(self.adapter.connect(port).await?);+ let s =+ limit(ictl_l10n::tr!("连接无障碍服务", "connect to the accessibility service"), CONNECT_WAIT, async {+ Ok(AxSession::connect(stream, CONNECT_WAIT).await?)+ })+ .await?;+ self.ax = Some(s);+ }+ Ok(self.ax.as_ref().expect("just opened"))+ }++ /// Closes the session (the phone turns its accessibility runtime off for us)+ pub async fn close_ax(&mut self) {+ self.springboard_app = None;+ if let Some(s) = self.ax.take() {+ s.close().await;+ }+ }++ /// The screen's elements as they are now: a walk of the frontmost app's tree, and (with `overlays`)+ /// SpringBoard's elements over the app. `wait` bounds a session's opening and the first request (an app that just came up builds its+ /// accessibility tree first)+ pub async fn ax_screen(&mut self, wait: Duration, overlays: bool) -> Result<AxScreen> {+ let sb = self.springboard_pid().await;+ let (mut app, (mut elements, mut complete)) = {+ let s = self.ax().await?;+ let app = frontmost(s, wait).await?;+ (app, s.walk(app, WALK_LIMIT, WALK_BUDGET, 0).await?)+ };+ // A session that lived through the phone locking reads the app's element alone from then on (the passcode+ // keypad up, a new session read 15 elements): read again on a new one+ if elements.len() <= 1 {+ tracing::debug!("remoteAXService: app {} reads empty, reconnecting", app.pid);+ self.close_ax().await;+ let s = self.ax().await?;+ app = frontmost(s, wait).await?;+ (elements, complete) = s.walk(app, WALK_LIMIT, WALK_BUDGET, 0).await?;+ }+ if !complete {+ tracing::debug!("remoteAXService: walk cut at {} elements", elements.len());+ }+ if elements.is_empty() {+ return Err(DeviceError::Timeout(ictl_l10n::tr!("没有读到界面元素", "no screen elements read").into()));+ }+ let overlays = if overlays { self.ax_overlays(app.pid).await } else { Vec::new() };+ Ok(AxScreen {+ app: elements,+ overlays,+ app_pid: app.pid,+ springboard_front: sb == Some(app.pid),+ at: Instant::now(),+ })+ }++ /// What SpringBoard shows over the app of process `app_pid` (alerts, banners, its status bar); empty when+ /// SpringBoard is that app, or can't be read+ pub async fn ax_overlays(&mut self, app_pid: i64) -> Vec<Element> {+ let Some(sb) = self.springboard_pid().await.filter(|sb| *sb != app_pid) else { return Vec::new() };+ let r = async {+ let root = match self.springboard_app {+ Some(o) => o,+ None => {+ let o = self.ax().await?.app_object(sb).await?;+ self.springboard_app = Some(o);+ o+ }+ };+ let s = self.ax().await?;+ Ok::<_, DeviceError>(+ s.walk_children(root, OVERLAY_LIMIT, OVERLAY_BUDGET, ictl_ax::tree::trait_bit::STATUS_BAR).await?,+ )+ }+ .await;+ r.unwrap_or_else(|e| {+ tracing::debug!("SpringBoard's elements: {e}");+ self.springboard_app = None;+ Vec::new()+ })+ }++ /// The frontmost app's process (one request, no walk)+ pub async fn ax_frontmost_pid(&mut self, wait: Duration) -> Result<i64> {+ let s = self.ax().await?;+ Ok(frontmost(s, wait).await?.pid)+ }++ /// SpringBoard's process, found once per tunnel+ async fn springboard_pid(&mut self) -> Option<i64> {+ if self.springboard.is_none() {+ let found = self+ .processes()+ .await+ .ok()?+ .into_iter()+ .find(|(_, exe)| exe.ends_with("/SpringBoard.app/SpringBoard"))+ .map(|(pid, _)| pid as i64);+ self.springboard = found;+ }+ self.springboard+ }+}++// SpringBoard's application element answers whichever app is in front: its children are the status bar's items+// and whatever it draws over the app (Pinky, DIYgod/pinky `springboard.go`); see `Tunnel::ax_overlays`++/// The frontmost app's element, asked again for up to `wait` while the phone has none (between two apps)+async fn frontmost(s: &AxSession, wait: Duration) -> Result<ObjectRef> {+ let deadline = Instant::now() + wait;+ loop {+ match s.frontmost_app().await {+ Ok(app) => return Ok(app),+ Err(ictl_ax::AxError::Protocol(e)) if Instant::now() < deadline => {+ tracing::debug!("remoteAXService: no frontmost app yet: {e}");+ tokio::time::sleep(Duration::from_millis(200)).await;+ }+ Err(e) => return Err(e.into()),+ }+ }+}diff --git a/crates/ictl-device/src/coredevice.rs b/crates/ictl-device/src/coredevice.rsnew file mode 100644index 0000000..b9b7d44--- /dev/null+++ b/crates/ictl-device/src/coredevice.rs@@ -0,0 +1,123 @@+//! CoreDevice requests the native path (iOS 27, no WebDriverAgent) needs: launching an app in front, optionally+//! with a link for it to open; sending a process a signal; whether the phone is locked.++use std::time::Duration;++use idevice::core_device::{AppServiceClient, CoreDeviceServiceClient};+use idevice::lockdown::LockdownClient;+use idevice::{IdeviceError, IdeviceService, ReadWrite, RsdService};+use plist::{Dictionary, Value};++use crate::{Device, DeviceError, Result, Tunnel, limit};++/// AppService through the generic CoreDevice client: idevice's `launch_application` has no payload URL+struct AppService(CoreDeviceServiceClient<Box<dyn ReadWrite>>);++impl RsdService for AppService {+ fn rsd_service_name() -> std::borrow::Cow<'static, str> {+ "com.apple.coredevice.appservice".into()+ }++ async fn from_stream(stream: Box<dyn ReadWrite>) -> std::result::Result<Self, IdeviceError> {+ Ok(Self(CoreDeviceServiceClient::new(stream).await?))+ }+}++/// The launch request (`com.apple.coredevice.feature.launchapplication`), with `url` as the payload URL when given+/// (as `devicectl device process launch --payload-url`; the same fields as Pinky's `launchInput`)+pub(crate) fn launch_request(bundle_id: &str, url: Option<&str>) -> Dictionary {+ let mut platform = Vec::new();+ // an empty dictionary into memory: cannot fail+ plist::to_writer_binary(&mut platform, &Value::Dictionary(Dictionary::new())).expect("plist into memory");+ let mut user = Dictionary::new();+ user.insert("active".into(), true.into());+ let mut options = Dictionary::new();+ options.insert("arguments".into(), Value::Array(Vec::new()));+ options.insert("environmentVariables".into(), Value::Dictionary(Dictionary::new()));+ options.insert("platformSpecificOptions".into(), Value::Data(platform));+ options.insert("standardIOUsesPseudoterminals".into(), true.into());+ options.insert("startStopped".into(), false.into());+ options.insert("terminateExisting".into(), false.into());+ options.insert("user".into(), Value::Dictionary(user));+ if let Some(u) = url {+ let mut payload = Dictionary::new();+ payload.insert("relative".into(), u.into());+ options.insert("payloadURL".into(), Value::Dictionary(payload));+ }+ let mut id = Dictionary::new();+ id.insert("_0".into(), bundle_id.into());+ let mut spec = Dictionary::new();+ spec.insert("bundleIdentifier".into(), Value::Dictionary(id));+ let mut req = Dictionary::new();+ req.insert("applicationSpecifier".into(), Value::Dictionary(spec));+ req.insert("options".into(), Value::Dictionary(options));+ req.insert("standardIOIdentifiers".into(), Value::Dictionary(Dictionary::new()));+ req+}++impl Tunnel {+ /// Launches an app in front (a running one comes to the front without restarting), with `url` for it to open;+ /// returns its process. SpringBoard refuses while the phone is locked+ pub async fn launch_foreground(&mut self, bundle_id: &str, url: Option<&str>) -> Result<u64> {+ limit(ictl_l10n::tr!("启动 App", "launch the app"), Duration::from_secs(30), async {+ let mut c = AppService::connect_rsd(&mut self.adapter, &mut self.handshake).await?;+ let res =+ c.0.invoke_with_plist("com.apple.coredevice.feature.launchapplication", launch_request(bundle_id, url))+ .await?;+ res.as_dictionary()+ .and_then(|d| d.get("processToken"))+ .and_then(Value::as_dictionary)+ .and_then(|t| t.get("processIdentifier"))+ .and_then(Value::as_signed_integer)+ .map(|p| p as u64)+ .ok_or_else(|| DeviceError::Idevice(format!("launching {bundle_id}: no process in the answer")))+ })+ .await+ }++ /// Sends `pid` a signal (9 ends it) through CoreDevice AppService+ pub async fn signal(&mut self, pid: u64, signal: u32) -> Result<()> {+ limit(ictl_l10n::tr!("结束进程", "end a process"), Duration::from_secs(20), async {+ let mut c = AppServiceClient::connect_rsd(&mut self.adapter, &mut self.handshake).await?;+ c.send_signal(pid as u32, signal).await?;+ Ok(())+ })+ .await+ }+}++impl Device {+ /// Whether the phone is locked: lockdown's `PasswordProtected`, true while it needs its passcode (iOS 27's+ /// developer disk image doesn't implement CoreDevice's lock state). A phone without a passcode never reads as+ /// locked+ pub async fn passcode_locked(&self) -> Result<bool> {+ limit(ictl_l10n::tr!("查锁屏状态", "check the lock state"), Duration::from_secs(5), async {+ let mut lockdown = LockdownClient::connect(&*self.provider).await?;+ // asked without a session, lockdown answers "this request was prohibited"+ let pairing = idevice::provider::IdeviceProvider::get_pairing_file(&*self.provider).await?;+ lockdown.start_session(&pairing).await?;+ let v = lockdown.get_value(Some("PasswordProtected"), None).await?;+ v.as_boolean().ok_or_else(|| DeviceError::Idevice(format!("PasswordProtected: {v:?}")))+ })+ .await+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_link_rides_in_the_launch_request() {+ let r = launch_request("com.apple.mobilesafari", Some("https://example.com/a?b=1"));+ let opts = r["options"].as_dictionary().unwrap();+ assert_eq!(+ opts["payloadURL"].as_dictionary().unwrap()["relative"].as_string(),+ Some("https://example.com/a?b=1")+ );+ assert_eq!(opts["terminateExisting"].as_boolean(), Some(false));+ let spec = r["applicationSpecifier"].as_dictionary().unwrap()["bundleIdentifier"].as_dictionary().unwrap();+ assert_eq!(spec["_0"].as_string(), Some("com.apple.mobilesafari"));+ assert!(!launch_request("x", None)["options"].as_dictionary().unwrap().contains_key("payloadURL"));+ }+}diff --git a/crates/ictl-device/src/hid.rs b/crates/ictl-device/src/hid.rsindex cbbc6be..4e93751 100644--- a/crates/ictl-device/src/hid.rs+++ b/crates/ictl-device/src/hid.rs@@ -196,6 +196,26 @@ impl HidSession {.await}+ /// 长按:按下,按住 `seconds` 秒,抬起。按住时每 100 毫秒重报一次位置:只报一次的话,有的 App(微信)+ /// 会当成轻点(iCTRL 的做法)+ pub async fn long_press(&mut self, x: f64, y: f64, seconds: f64) -> Result<()> {+ let (hx, hy) = self.hid_point((x, y));+ let held = Duration::from_secs_f64(seconds.clamp(0.0, 60.0));+ limit(ictl_l10n::tr!("HID 长按", "HID long press"), held + Duration::from_secs(10), async {+ let end = tokio::time::Instant::now() + held;+ self.touch.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, hx, hy, None).await?;+ self.contact = Some((hx, hy));+ while tokio::time::Instant::now() < end {+ tokio::time::sleep(Duration::from_millis(100).min(end - tokio::time::Instant::now())).await;+ self.touch.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, hx, hy, None).await?;+ }+ self.touch.send_touchscreen(TOUCHSCREEN_STATE_RELEASE, hx, hy, None).await?;+ self.contact = None;+ Ok(())+ })+ .await+ }+pub async fn press(&mut self, button: Button) -> Result<()> {let (page, code, hold) = button.usage();limit(ictl_l10n::tr!("HID 按键", "HID key press"), Duration::from_secs(10), async {diff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rsindex 02ae077..6058fe3 100644--- a/crates/ictl-device/src/lib.rs+++ b/crates/ictl-device/src/lib.rs@@ -12,6 +12,8 @@//! 不负责:WDA(见 `ictl-wda`)、状态机(见 `ictl-daemon`)。pub mod apps;+pub mod ax;+mod coredevice;pub mod ddi;pub mod hid;mod media;@@ -146,11 +148,32 @@ impl From<IdeviceError> for DeviceError {IdeviceError::PairingDialogResponsePending => Self::PairingPending,IdeviceError::UserDeniedPairing => Self::PairingDenied,IdeviceError::DeveloperModeNotEnabled => Self::DeveloperModeOff,- other => Self::Idevice(other.to_string()),+ other => {+ let s = other.to_string();+ Self::Idevice(device_error_text(&s).unwrap_or(s))+ }}}}+/// What a CoreDevice error says, out of the archive it comes in: idevice gives the error dictionary as text, with+/// `userInfoWithNSSecureCoding` as the bytes of an NSKeyedArchive holding `NSLocalizedDescription` («The process+/// identifier of the launched application could not be determined. It may have already terminated.»). None when+/// there is none+fn device_error_text(s: &str) -> Option<String> {+ let start = s.find("userInfoWithNSSecureCoding")?;+ let rest = &s[start..];+ let open = rest.find("Data([")? + "Data([".len();+ let close = rest[open..].find("])")? + open;+ let bytes: Vec<u8> =+ rest[open..close].split(',').map(|n| n.trim().parse::<u8>()).collect::<std::result::Result<_, _>>().ok()?;+ let v = plist::Value::from_reader(std::io::Cursor::new(bytes)).ok()?;+ let objects = v.as_dictionary()?.get("$objects")?.as_array()?;+ // the archive's strings: keys and class names have no spaces, a sentence does+ let text: Vec<&str> = objects.iter().filter_map(|o| o.as_string()).filter(|t| t.contains(' ')).collect();+ (!text.is_empty()).then(|| text.join(" "))+}+pub type Result<T> = std::result::Result<T, DeviceError>;/// 屏幕逻辑尺寸(点)@@ -459,10 +482,19 @@ impl Device {limit(ictl_l10n::tr!("建隧道", "open the tunnel"), Duration::from_secs(30), async {let proxy = CoreDeviceProxy::connect(&*self.provider).await?;let rsd_port = proxy.tunnel_info().server_rsd_port;+ tracing::debug!("CoreDeviceProxy tunnel: MTU {}", proxy.tunnel_info().mtu);let mut adapter = proxy.create_software_tunnel()?.to_async_handle();let stream = adapter.connect(rsd_port).await?;let handshake = RsdHandshake::new(stream).await?;- Ok(Tunnel { adapter, handshake, hid: None })+ Ok(Tunnel {+ adapter,+ handshake,+ hid: None,+ ax: None,+ springboard: None,+ springboard_app: None,+ screenshots: None,+ })}).await}@@ -601,6 +633,14 @@ pub struct Tunnel {adapter: AdapterHandle,handshake: RsdHandshake,hid: Option<HidSession>,+ /// remoteAXService([`ax`]),用时才开+ ax: Option<ax::AxSession>,+ /// SpringBoard 的进程号([`ax`] 读盖在 App 上的弹窗用),每条隧道查一次+ springboard: Option<i64>,+ /// SpringBoard 的应用元素,每个无障碍会话问一次(每次读界面省一个请求)+ springboard_app: Option<ictl_ax::ObjectRef>,+ /// 截屏服务的连接,留着复用([`Tunnel::screenshot_png`])+ screenshots: Option<ScreenCaptureServiceClient<Box<dyn idevice::ReadWrite>>>,}impl Tunnel {@@ -627,10 +667,53 @@ impl Tunnel {.await}+ /// The screen in the format the phone calls `format` (`requestedFormat`; idevice's "jpeg" is refused: «Cannot+ /// initialize ScreenshotImageFormat from invalid String value jpeg»)+ pub async fn screenshot_as(&mut self, format: &str) -> Result<Vec<u8>> {+ limit(ictl_l10n::tr!("截图", "screenshot"), Duration::from_secs(30), async {+ let port = self+ .handshake+ .services+ .get("com.apple.coredevice.screencaptureservice")+ .map(|s| s.port)+ .ok_or_else(|| DeviceError::Idevice("the phone offers no screencaptureservice".into()))?;+ let stream: Box<dyn idevice::ReadWrite> = Box::new(self.adapter.connect(port).await?);+ let mut c = idevice::core_device::CoreDeviceServiceClient::new(stream).await?;+ let mut req = plist::Dictionary::new();+ req.insert("requestedFormat".into(), format.into());+ let res = c+ .invoke_with_plist_action(+ "com.apple.coredevice.feature.capturescreenshot",+ req,+ "com.apple.coredevice.action.capturescreenshot",+ )+ .await?;+ match res.as_dictionary().and_then(|d| d.get("image")) {+ Some(plist::Value::Data(image)) => Ok(image.clone()),+ _ => Err(DeviceError::Idevice("the screenshot came without an image".into())),+ }+ })+ .await+ }++ /// The screen as PNG, on the screen capture service's connection kept from the last time: the first request on+ /// a new one does the service's handshake too (0.82 s against 0.30 s for the next ones on a simple screen). A+ /// connection that fails is dropped and one new one triedpub async fn screenshot_png(&mut self) -> Result<Vec<u8>> {limit(ictl_l10n::tr!("截图", "screenshot"), Duration::from_secs(30), async {- let mut client = ScreenCaptureServiceClient::connect_rsd(&mut self.adapter, &mut self.handshake).await?;- Ok(client.take_screenshot(None, ImageFormat::Png).await?)+ if let Some(c) = self.screenshots.as_mut() {+ match c.take_screenshot(None, ImageFormat::Png).await {+ Ok(png) => return Ok(png),+ Err(e) => {+ tracing::debug!("screenshot on the kept connection failed, connecting again: {e}");+ self.screenshots = None;+ }+ }+ }+ let mut c = ScreenCaptureServiceClient::connect_rsd(&mut self.adapter, &mut self.handshake).await?;+ let png = c.take_screenshot(None, ImageFormat::Png).await?;+ self.screenshots = Some(c);+ Ok(png)}).await}@@ -668,7 +751,7 @@ impl Tunnel {/// 不粘,所以这里不还原:调用方等弹窗答完再用返回的 [`PendingRestore`] 调 [`Self::restore_pasteboard`]。/// 手机不确认按键,没有输入框获得焦点时什么也粘不上,结果要看屏幕pub async fn paste_text(&mut self, text: &str) -> Result<Option<PendingRestore>> {- let Tunnel { adapter, handshake, hid } = self;+ 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()));};@@ -740,7 +823,8 @@ impl Tunnel {/// 停掉 HID 会话(含屏幕媒体流),隧道保留pub async fn close_hid(&mut self) {if let Some(h) = self.hid.take() {- let _ = tokio::time::timeout(Duration::from_secs(3), h.close()).await;+ // boxed: the future holds the whole session, and callers that may close it would carry that+ let _ = tokio::time::timeout(Duration::from_secs(3), Box::pin(h.close())).await;}}@@ -800,20 +884,9 @@ impl Tunnel {.await}- /// 结束一个进程(DVT processcontrol `killPid:`,不等确认)- pub async fn kill(&mut self, pid: u64) -> Result<()> {- use idevice::dvt::{process_control::ProcessControlClient, remote_server::RemoteServerClient};- limit(ictl_l10n::tr!("结束进程", "kill a process"), Duration::from_secs(20), async {- let mut dvt: RemoteServerClient<Box<dyn idevice::ReadWrite>> =- RemoteServerClient::connect_rsd(&mut self.adapter, &mut self.handshake).await?;- ProcessControlClient::new(&mut dvt).await?.kill_app(pid).await?;- Ok(())- })- .await- }-/// 关掉隧道:先停 HID 的屏幕媒体流pub async fn close(mut self) {+ self.close_ax().await;self.close_hid().await;}}@@ -896,4 +969,29 @@ mod tests {| +-o Magic Keyboard@00100000 <class IOUSBHostDevice>";assert!(!ioreg_has_ios_device(without));}++ #[test]+ fn a_coredevice_error_says_what_it_says() {+ let mut d = plist::Dictionary::new();+ d.insert("$version".into(), 100000u64.into());+ d.insert("$archiver".into(), "NSKeyedArchiver".into());+ d.insert(+ "$objects".into(),+ plist::Value::Array(vec![+ "$null".into(),+ "NSLocalizedDescription".into(),+ "The process identifier of the launched application could not be determined.".into(),+ ]),+ );+ let mut bytes = Vec::new();+ plist::Value::Dictionary(d).to_writer_binary(&mut bytes).unwrap();+ let s = format!(+ "device returned an error: Dictionary({{\"userInfoWithNSSecureCoding\": Data({bytes:?}), \"code\": Integer(1)}})"+ );+ assert_eq!(+ device_error_text(&s).as_deref(),+ Some("The process identifier of the launched application could not be determined.")+ );+ assert_eq!(device_error_text("socket closed"), None);+ }}diff --git a/crates/ictl-protocol/src/env.rs b/crates/ictl-protocol/src/env.rsindex 28621e0..69ffa1e 100644--- a/crates/ictl-protocol/src/env.rs+++ b/crates/ictl-protocol/src/env.rs@@ -51,6 +51,8 @@ pub const DDI_DIR: &str = "ICTL_DDI_DIR";pub const FFMPEG: &str = "ICTL_FFMPEG";pub const WDA_UNSIGNED: &str = "ICTL_WDA_UNSIGNED";pub const WDA_DETACHED: &str = "ICTL_WDA_DETACHED";+/// How iOS 27 and later are driven: `auto` (the default: natively, without WDA), `native`, `wda`+pub const IOS_BACKEND: &str = "ICTL_IOS_BACKEND";/// Read by `ictl_l10n` (below this crate), so its name is kept therepub const LANG: &str = ictl_l10n::ENV;pub const DEV_TOOLS: &str = "IPHONE_CONTROL_DEV_TOOLS";@@ -107,6 +109,7 @@ pub const ALL: &[Var] = &[var(FFMPEG, Kind::Setting, false),var(WDA_UNSIGNED, Kind::Setting, true),var(WDA_DETACHED, Kind::Experiment, true),+ var(IOS_BACKEND, Kind::Setting, true),var(LANG, Kind::Setting, true),var(DEV_TOOLS, Kind::Setting, true),var(TG_BOT_TOKEN, Kind::Notify, true),diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rsindex 768b20f..b9fe2e6 100644--- a/crates/ictl-protocol/src/lib.rs+++ b/crates/ictl-protocol/src/lib.rs@@ -370,6 +370,9 @@ pub struct StatusData {/// The screen in points, as it is turned nowpub width: Option<f64>,pub height: Option<f64>,+ /// Driven natively (iOS 27 and later without WDA: remoteAXService, HID, CoreDevice)+ #[serde(default)]+ pub native: bool,}/// An element on screen: its type, the text it shows, and its box in points (top left, size)diff --git a/crates/ictl-unlock/src/lib.rs b/crates/ictl-unlock/src/lib.rsindex 43dec73..83bf6c3 100644--- a/crates/ictl-unlock/src/lib.rs+++ b/crates/ictl-unlock/src/lib.rs@@ -17,8 +17,80 @@use std::path::PathBuf;use std::time::Duration;+use ictl_wda::client::LockCheck;use ictl_wda::{IdleSettings, WdaClient, WdaError, elements, http::Transport, swipe_steps, tap_steps};+/// What unlocking needs of the phone. WebDriverAgent implements it below; the daemon's native path (iOS 27 without+/// WDA: HID, remoteAXService, lockdown) implements it too. Errors are WDA's: the native path maps its own onto them+/// (`Unavailable` when it can't reach the phone, `Remote` for a step that failed and can be tried again)+#[allow(async_fn_in_trait)]+pub trait Screen {+ /// Whether the phone says it is locked, cheaply ([`WdaClient::wda_reports_locked`])+ async fn reports_locked(&mut self) -> std::result::Result<bool, WdaError>;+ /// Whether a "not locked" from [`Self::reports_locked`] can be believed without a look at the screen+ fn lock_state_trusted(&self) -> bool;+ /// The lock state checked against the screen, with the element tree it read ([`WdaClient::check_lock`])+ async fn check_lock(&mut self, reported: Option<bool>, strict: bool) -> std::result::Result<LockCheck, WdaError>;+ /// Shorter waits for the duration of unlocking; returns what to restore+ async fn quick_waits(&mut self) -> std::result::Result<Option<IdleSettings>, WdaError>;+ async fn restore_waits(&mut self, to: IdleSettings) -> std::result::Result<(), WdaError>;+ /// Home, to wake the screen. `round` counts the attempts: WDA alternates two ways of pressing it+ async fn press_home(&mut self, round: u32) -> std::result::Result<(), WdaError>;+ async fn view(&mut self) -> std::result::Result<elements::View, WdaError>;+ async fn swipe(&mut self, from: (f64, f64), to: (f64, f64), ms: u64) -> std::result::Result<(), WdaError>;+ async fn tap(&mut self, x: f64, y: f64, press_ms: u64) -> std::result::Result<(), WdaError>;+ async fn elements(&mut self) -> std::result::Result<Vec<elements::Element>, WdaError>;+ /// The passcode field's (total, entered) digits ([`WdaClient::passcode_field`])+ async fn passcode_field(&mut self) -> std::result::Result<Option<(u32, u32)>, WdaError>;+ /// Reading the screen is cheap even while it animates: after the swipe up the keypad is looked for every 0.2 s+ /// instead of waiting [`Timing::swipe_settle`] out. Not through WDA, whose queries wait for the animations (#3)+ fn reads_cheaply(&self) -> bool {+ false+ }+}++impl<T: Transport> Screen for WdaClient<T> {+ async fn reports_locked(&mut self) -> std::result::Result<bool, WdaError> {+ self.wda_reports_locked().await+ }+ fn lock_state_trusted(&self) -> bool {+ WdaClient::lock_state_trusted(self)+ }+ async fn check_lock(&mut self, reported: Option<bool>, strict: bool) -> std::result::Result<LockCheck, WdaError> {+ WdaClient::check_lock(self, reported, strict).await+ }+ async fn quick_waits(&mut self) -> std::result::Result<Option<IdleSettings>, WdaError> {+ // 解锁期间等待上限调小(不能是 0:唤醒会失败),做完恢复成平时的值。+ // 上次异常退出没恢复的话读到的是调小的值,baseline 会按 WDA 默认值算+ let restore = self.baseline().await?;+ self.set_idle_settings(IdleSettings::QUICK).await?;+ Ok(Some(restore))+ }+ async fn restore_waits(&mut self, to: IdleSettings) -> std::result::Result<(), WdaError> {+ self.set_idle_settings(to).await+ }+ async fn press_home(&mut self, round: u32) -> std::result::Result<(), WdaError> {+ // XCTest 的 home 和 IOHID 的 Home 轮流用:iPhone 12 mini(iOS 26.4.1)上 XCTest 的 home 点不亮熄灭的屏幕,+ // IOHID 的能;iOS 27 上一直用的是 XCTest 的,第一轮还是它+ if round.is_multiple_of(2) { self.press_button("home").await } else { self.press_home_hid().await }+ }+ async fn view(&mut self) -> std::result::Result<elements::View, WdaError> {+ WdaClient::view(self).await+ }+ async fn swipe(&mut self, from: (f64, f64), to: (f64, f64), ms: u64) -> std::result::Result<(), WdaError> {+ self.actions(&swipe_steps(from, to, ms)).await+ }+ async fn tap(&mut self, x: f64, y: f64, press_ms: u64) -> std::result::Result<(), WdaError> {+ self.actions(&tap_steps(x, y, press_ms)).await+ }+ async fn elements(&mut self) -> std::result::Result<Vec<elements::Element>, WdaError> {+ WdaClient::elements(self).await+ }+ async fn passcode_field(&mut self) -> std::result::Result<Option<(u32, u32)>, WdaError> {+ WdaClient::passcode_field(self).await+ }+}+#[derive(Debug, thiserror::Error)]pub enum UnlockError {#[error("{}", ictl_l10n::tr!("手机已锁屏,且没有配置锁屏密码,需要人工解锁", "The phone is locked and no passcode is configured; unlock it by hand"))]@@ -100,9 +172,9 @@ impl UnlockConfig {}/// 未锁屏直接返回;否则按规则解锁-pub async fn ensure_unlocked<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig) -> Result<Outcome> {+pub async fn ensure_unlocked<D: Screen>(wda: &mut D, cfg: &UnlockConfig) -> Result<Outcome> {// 先只问 WDA:确定没锁就直接返回,日常操作不多发请求- let reported = match wda.wda_reports_locked().await {+ let reported = match wda.reports_locked().await {Ok(v) => v,Err(WdaError::Unavailable(_)) => return Ok(Outcome::NotLocked),Err(e) => return Err(e.into()),@@ -124,12 +196,11 @@ pub async fn ensure_unlocked<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockC}}let code = code?;- // 解锁期间等待上限调小(不能是 0:唤醒会失败),做完恢复成平时的值。- // 上次异常退出没恢复的话读到的是调小的值,baseline 会按 WDA 默认值算- let restore = wda.baseline().await?;- wda.set_idle_settings(IdleSettings::QUICK).await?;+ let restore = wda.quick_waits().await?;let r = unlock(wda, cfg, code.as_bytes()).await;- if let Err(e) = wda.set_idle_settings(restore).await {+ if let Some(restore) = restore+ && let Err(e) = wda.restore_waits(restore).await+ {tracing::warn!("{}",ictl_l10n::log_trf!("恢复 WDA 等待设置失败:{e}", "Restoring the WDA wait settings failed: {e}")@@ -150,17 +221,12 @@ fn passcode(cfg: &UnlockConfig) -> Result<String> {Ok(code)}-async fn press<T: Transport>(wda: &mut WdaClient<T>, at: (i64, i64), t: &Timing) -> Result<()> {- Ok(wda.actions(&tap_steps(at.0 as f64, at.1 as f64, t.key_press_ms)).await?)+async fn press<D: Screen>(wda: &mut D, at: (i64, i64), t: &Timing) -> Result<()> {+ Ok(wda.tap(at.0 as f64, at.1 as f64, t.key_press_ms).await?)}/// 用删除键把 `entered` 位残留删到 0;找不到删除键或某次没删掉返回 false(这轮作废,一位没输)-async fn clear_residual<T: Transport>(- wda: &mut WdaClient<T>,- delete: Option<(i64, i64)>,- entered: u32,- t: &Timing,-) -> Result<bool> {+async fn clear_residual<D: Screen>(wda: &mut D, delete: Option<(i64, i64)>, entered: u32, t: &Timing) -> Result<bool> {let Some(del) = delete else { return Ok(false) };for left in (0..entered).rev() {if tap_key(wda, del, left as i64 + 1, t).await? != left as i64 {@@ -172,7 +238,7 @@ async fn clear_residual<T: Transport>(/// 按一下键(数字或删除),等密码栏已输入位数离开 `before`;返回最后读到的位数(读不到密码栏为 -1)。/// 只认「变了」不认方向:删除键是变少,数字键是变多,按键被记成两下时会多变一位-async fn tap_key<T: Transport>(wda: &mut WdaClient<T>, at: (i64, i64), before: i64, t: &Timing) -> Result<i64> {+async fn tap_key<D: Screen>(wda: &mut D, at: (i64, i64), before: i64, t: &Timing) -> Result<i64> {press(wda, at, t).await?;let deadline = tokio::time::Instant::now() + t.key_confirm;loop {@@ -199,7 +265,7 @@ fn write_flag(cfg: &UnlockConfig, why: &str) -> std::io::Result<()> {std::fs::write(&cfg.disabled_flag, format!("{now} {why}\n"))}-async fn unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, code: &[u8]) -> Result<Outcome> {+async fn unlock<D: Screen>(wda: &mut D, cfg: &UnlockConfig, code: &[u8]) -> Result<Outcome> {let t = &cfg.timing;let digit = |i: usize| (code[i] - b'0') as usize;let len = code.len() as u32;@@ -208,19 +274,13 @@ async fn unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, code:for round in 0..FIRST_DIGIT_ROUNDS {// Home 唤醒(键盘已打开时 iOS 27 只是把键收起,半截输入还在,下面用删除键处理)// 熄屏锁屏刚唤醒时上滑偶尔卡十几秒后报 `point.x != INFINITY`(WDA 还拿不到界面尺寸):一位没输,算这轮落空重来。- // XCTest 的 home 和 IOHID 的 Home 轮流用:iPhone 12 mini(iOS 26.4.1)上 XCTest 的 home 点不亮熄灭的屏幕,- // IOHID 的能;iOS 27 上一直用的是 XCTest 的,第一轮还是它。// 唤醒后才问方向(iPad 横竖屏的上滑位置、键位换算都靠它):熄屏时的第一个无障碍查询要等约 8 秒let woke = async {- if round % 2 == 0 {- wda.press_button("home").await?;- } else {- wda.press_home_hid().await?;- }+ wda.press_home(round).await?;tokio::time::sleep(t.wake_settle).await;let view = wda.view().await?;let (cx, h) = (view.screen.width / 2.0, view.screen.height);- wda.actions(&swipe_steps((cx, h - 8.0), (cx, h * 0.45), 250)).await?;+ wda.swipe((cx, h - 8.0), (cx, h * 0.45), 250).await?;Ok::<_, WdaError>(view)}.await;@@ -238,12 +298,26 @@ async fn unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, code:}Err(other) => return Err(other.into()),};- tokio::time::sleep(t.swipe_settle).await;+ if wda.reads_cheaply() {+ let deadline = tokio::time::Instant::now() + t.swipe_settle;+ loop {+ tokio::time::sleep(t.poll.min(Duration::from_millis(200))).await;+ let els = wda.elements().await?;+ if (elements::keypad(&els).is_some() && elements::passcode_field(&els).is_some())+ || tokio::time::Instant::now() >= deadline+ {+ break;+ }+ }+ } else {+ tokio::time::sleep(t.swipe_settle).await;+ }let check = wda.check_lock(None, false).await?;// 按过 Home、上滑之后还是认不出的锁屏样式界面:不算解开,接着找键盘(找不到就重来一轮)if !check.locked && !check.uncertain {return Ok(Outcome::Unlocked);}+ tracing::debug!("unlock round {round}: locked, tree read with the check: {}", check.tree.is_some());// 核对时已取到元素树就直接用,密码栏也从树里读。那棵树是上滑后马上取的,键盘有时还没进树:// 缺键盘或密码栏时再取一次(真机上这样省掉一整轮,约 4.5 秒)let mut els = match &check.tree {@@ -266,6 +340,11 @@ async fn unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, code:None => wda.passcode_field().await?,};let (Some(pad), Some((total, entered))) = (elements::keypad(&els), field) else {+ tracing::debug!(+ "unlock round {round}: keypad {}, passcode field {field:?} among {} elements",+ if elements::keypad(&els).is_some() { "found" } else { "not found" },+ els.len()+ );continue;};if total != len {@@ -282,7 +361,10 @@ async fn unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, code:break;}n if n > 1 => return Err(UnlockError::Incomplete(1)),- _ => continue,+ n => {+ tracing::debug!("unlock round {round}: the first digit didn't register (field reads {n})");+ continue;+ }}}let pad = keys.ok_or(UnlockError::NoKeypad)?;@@ -336,8 +418,8 @@ async fn unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, code:}/// 输第 2 位到最后一位并确认结果。出错直接返回(调用方保留停用标记)-async fn enter_rest<T: Transport>(- wda: &mut WdaClient<T>,+async fn enter_rest<D: Screen>(+ wda: &mut D,cfg: &UnlockConfig,pad: &[(i64, i64); 10],code: &[u8],@@ -414,6 +496,57 @@ mod tests {(UnlockConfig { passcode_file: dir.join("passcode"), disabled_flag: dir.join("UNLOCK-DISABLED"), timing }, dir)}+ #[tokio::test]+ async fn a_screen_read_cheaply_finds_the_keypad_without_waiting_it_out() {+ /// The fake WDA, read as cheaply as natively (`reads_cheaply`)+ struct Cheap<'a, T: Transport>(&'a mut WdaClient<T>);+ impl<T: Transport> Screen for Cheap<'_, T> {+ async fn reports_locked(&mut self) -> std::result::Result<bool, WdaError> {+ Screen::reports_locked(self.0).await+ }+ fn lock_state_trusted(&self) -> bool {+ Screen::lock_state_trusted(self.0)+ }+ async fn check_lock(&mut self, r: Option<bool>, s: bool) -> std::result::Result<LockCheck, WdaError> {+ Screen::check_lock(self.0, r, s).await+ }+ async fn quick_waits(&mut self) -> std::result::Result<Option<IdleSettings>, WdaError> {+ Screen::quick_waits(self.0).await+ }+ async fn restore_waits(&mut self, to: IdleSettings) -> std::result::Result<(), WdaError> {+ Screen::restore_waits(self.0, to).await+ }+ async fn press_home(&mut self, round: u32) -> std::result::Result<(), WdaError> {+ Screen::press_home(self.0, round).await+ }+ async fn view(&mut self) -> std::result::Result<elements::View, WdaError> {+ Screen::view(self.0).await+ }+ async fn swipe(&mut self, f: (f64, f64), t: (f64, f64), ms: u64) -> std::result::Result<(), WdaError> {+ Screen::swipe(self.0, f, t, ms).await+ }+ async fn tap(&mut self, x: f64, y: f64, ms: u64) -> std::result::Result<(), WdaError> {+ Screen::tap(self.0, x, y, ms).await+ }+ async fn elements(&mut self) -> std::result::Result<Vec<elements::Element>, WdaError> {+ Screen::elements(self.0).await+ }+ async fn passcode_field(&mut self) -> std::result::Result<Option<(u32, u32)>, WdaError> {+ Screen::passcode_field(self.0).await+ }+ fn reads_cheaply(&self) -> bool {+ true+ }+ }+ let fake = FakeLockScreen::new("123456");+ let (cfg, dir) = cfg(Some("123456\n"));+ let mut wda = WdaClient::new(&fake);+ assert_eq!(ensure_unlocked(&mut Cheap(&mut wda), &cfg).await.unwrap(), Outcome::Unlocked);+ assert!(!fake.state().locked);+ assert!(!cfg.disabled_flag.exists());+ std::fs::remove_dir_all(dir).unwrap();+ }+#[tokio::test]async fn correct_passcode_unlocks_and_restores_idle_settings() {let fake = FakeLockScreen::new("123456");diff --git a/crates/ictl-wda/src/elements.rs b/crates/ictl-wda/src/elements.rsindex bd4604f..a7b8be6 100644--- a/crates/ictl-wda/src/elements.rs+++ b/crates/ictl-wda/src/elements.rs@@ -257,6 +257,31 @@ impl Tree {})}+ /// [`Self::still_along`], judged on the elements both reads have: a list that scrolls moves cells in and out at its+ /// edges, so the two lists differ while it moves and right after it stops. Matched by type, label and name, in+ /// order of appearance; at least half of the smaller read (and 3) must match, and all of them stand still+ pub fn still_along_common(&self, o: &Tree, vertical: bool, tol: i64) -> bool {+ fn key(e: &Element) -> (&str, &str, &str) {+ (e.kind.as_str(), e.label.as_str(), e.name.as_str())+ }+ let mut theirs: std::collections::HashMap<(&str, &str, &str), std::collections::VecDeque<&Element>> =+ std::collections::HashMap::new();+ for e in &o.elements {+ theirs.entry(key(e)).or_default().push_back(e);+ }+ let mut matched = 0usize;+ for a in &self.elements {+ let Some(b) = theirs.get_mut(&key(a)).and_then(|q| q.pop_front()) else { continue };+ let (pa, pb) = if vertical { (a.center.1, b.center.1) } else { (a.center.0, b.center.0) };+ if (pa - pb).abs() > tol {+ return false;+ }+ matched += 1;+ }+ let smaller = self.elements.len().min(o.elements.len());+ matched >= 3 && matched * 2 >= smaller+ }+/// 弹窗(系统权限弹窗、App 自己的提示框)pub fn alert(&self) -> Option<&Element> {self.elements.iter().find(|e| e.kind == "Alert")@@ -1363,4 +1388,32 @@ mod tests {assert_eq!(use_passcode_button(&parse(IPAD_TOUCHID_LEFT, o)), Some((512, 430)));assert_eq!(cover_sheet(IPAD_PIN_LEFT), CoverSheet::Locked);}++ #[test]+ fn a_list_that_stopped_is_still_though_cells_came_and_went() {+ let tree = |rows: &[(&str, i64)]| {+ let cells: String = rows+ .iter()+ .map(|(l, y)| format!(r#"<XCUIElementTypeButton type="XCUIElementTypeButton" label="{l}" x="20" y="{y}" width="390" height="44"/>"#))+ .collect();+ parse_tree(+ &format!(+ r#"<XCUIElementTypeApplication type="XCUIElementTypeApplication" label="A" x="0" y="0" width="430" height="932">{cells}</XCUIElementTypeApplication>"#+ ),+ View { screen: ScreenSize { width: 430.0, height: 932.0 }, orientation: None },+ )+ };+ let a = tree(&[("通用", 100), ("辅助功能", 150), ("墙纸", 200), ("相机", 250), ("搜索", 300)]);+ // one cell more at the bottom edge, the rest where they were: stopped+ let b =+ tree(&[("通用", 100), ("辅助功能", 150), ("墙纸", 200), ("相机", 250), ("搜索", 300), ("待机显示", 850)]);+ assert!(b.still_along_common(&a, true, 3));+ assert!(!b.still_along(&a, true, 3), "the strict check waits for the same list");+ // still moving+ let c = tree(&[("辅助功能", 120), ("墙纸", 170), ("相机", 220), ("搜索", 270), ("待机显示", 320)]);+ assert!(!c.still_along_common(&a, true, 3));+ // too little in common to tell+ let d = tree(&[("墙纸", 200), ("x", 400), ("y", 450), ("z", 500), ("w", 550), ("v", 600)]);+ assert!(!d.still_along_common(&a, true, 3));+ }}diff --git a/docs/architecture.md b/docs/architecture.mdindex 3b16f23..406595c 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -84,6 +84,8 @@│ 是开发者模式已开? ──────────── 否 ─▶ DeveloperModeOff(只在未就绪时检查)│ 是+ iOS 27 起且没设 ICTL_IOS_BACKEND=wda? ── 是 ─▶ 原生控制(见下)+ │ 否WDA 签名安装过? ──────────── 否 ─▶ NeedsSigning(iphone-control sign)│ 是本进程 runner 存活且 /status ready? ── 是 ─▶ Ready@@ -97,6 +99,19 @@└─ 镜像或 WDA 其它失败 ─────────────────▶ WdaStarting { last_error },按退避重试```+原生控制(iOS 27 起默认,`tools/native.rs`,方案见 [ios27-native.md](dev/ios27-native.md))不签名、不启动 WDA:++```+ Preparing:后台任务 开隧道 → 查/挂开发者镜像 → 关隧道(结果由下一轮巡检收)+ ├─ 成功 → 镜像是刚挂上的就丢掉旧隧道(建隧道时手机列出的服务里还没有无障碍服务)+ │ → 连 remoteAXService、读一次界面 ── 成功 ─▶ Ready+ │ └ 失败 ─▶ Preparing { last_error },按退避重试+ ├─ 隧道报 PasswordProtected ──────────▶ NeedsUnlock+ └─ 镜像失败 ───────────────────────────▶ Preparing { last_error },按退避重试+```++各工具在 WDA 不在、设备走原生时改走 `native.rs`:读界面每次都向 remoteAXService 走一遍前台 App 的树(类型 4,再按层一次发出这一层每个元素的类型 5 请求、按答复里的元素对象配对,最多 400 个、4 秒),网页内容进程(WebKit WebContent)的元素原样放置,再读 SpringBoard 盖在上面的元素,转成 WDA `/source` 风格的 XML 交给 `ictl_wda::elements::parse_tree`,按名字找、遮挡、弹窗、密码栏的逻辑都复用。手机只在前台 App 变化时主动推送树,App 内换页不推,所以不靠推送。等稳定和 WDA 一样轮询(连续两次一样),操作后先等 0.4 秒。触摸、按键经 HID;输入一律粘贴;启动 App、打开链接经 CoreDevice AppService;锁屏状态问 lockdown(`PasswordProtected`,要建会话);自动解锁经 `ictl_unlock::Screen` 用同一套规则,每次读锁屏前先关 HID 会话(媒体流开着时锁屏对无障碍是空的)。无障碍会话归 `Tunnel`,空闲 60 秒关闭。+要点(每一条都来自 toolkit 实际踩过的坑):- **热插拔**:交给系统的 usbmuxd(Linux 上由 udev 通知)。守护进程每 10 秒向 usbmuxd 列一次设备;列设备连续 3 轮出错才当作离线,usbmuxd 抖一下不拆会话。`doctor` 另数 sysfs `/sys/bus/usb/devices/`(Linux)或 IORegistry(macOS)里的 iPhone/iPad/iPod(厂商号 `05ac` 且产品名匹配,键盘等配件不算),区分「USB 上没有手机」和「usbmuxd 看不到」。(以前的 Docker 镜像里没有 udev,守护进程自己看护 usbmuxd,台数对不上就重启它;去掉 Docker 后这部分删了,见 D5、D14。)diff --git a/docs/dev/ios27-native.md b/docs/dev/ios27-native.mdnew file mode 100644index 0000000..5f9c812--- /dev/null+++ b/docs/dev/ios27-native.md@@ -0,0 +1,113 @@+# 方案:iOS 27 上不用 WDA(草案)++2026-11-15。状态:已在分支 `feat/ios27-native` 实现(默认原生),真机验证中。相关:[wda-dependency-research.md](wda-dependency-research.md)(WDA 依赖调研)、分支 `spike/ax-service-2` 的 `docs/dev/ax-spike-results.md`(remoteAXService 三轮实验)。++## 1. 为什么现在提++- 实验第三轮(iPhone 15 Pro Max,iOS 27.2.1):主机按 Xcode 的方式回答 remoteAXService 的握手后,没有 WDA 也能读到完整的元素树。前两轮「没有 WDA 读不到」是探针没回答握手造成的。+ - **更正(实现后真机复测)**:手机只在**前台 App 变化时**(以及刚连上时)主动推送整棵树;App 自己换页(设置里点进「关于本机」再返回)不推。所以读界面一律自己「走一遍」:请求类型 4 拿前台 App,再逐个元素请求类型 5 的属性(和 Pinky 一样,最多 400 个、4 秒)。主动请求整棵树(类型 11,不带参数)会让手机直接断开连接。+- 点击、按键、Home 早已经能走 HID(iOS 27 的 `dtuhidd`),截图能走 screencaptureservice,输入中文能走剪贴板粘贴(#118、#122)。读界面是最后一块。+- [Pinky](https://github.com/DIYgod/pinky)(Apache-2.0)在 iOS 27 上已经这样做:手机上什么都不装,README 写「除了双指缩放都能用」(iPhone 13 mini,iOS 27.0.1)。下文标「Pinky」的做法都出自它的代码和 `docs/notes/ios.md`。++不用 WDA 能省掉的:Apple ID 登录、免费描述文件和 7 天重签、证书被吊销、「UI 自动化」开关和重启后输密码(`NeedsAutomationPin`)、WDA 启动慢(10~60 秒)、卡死和重启、`ictl-sign`/`plume_core`/omnisette 这一串依赖(对只有 iOS 27 手机的用户)。还要的:配对、开发者模式、开发者镜像。++## 2. 目标和不做的++- 目标:iOS 27 及以上的手机,**全部工具**在不装 WDA 的情况下可用,结果和措辞对 Agent 尽量不变;可以按设备切回 WDA。+- 不做:iOS 26 及以下(没有 HID,仍然只能 WDA);双指缩放(我们本来就没有这个工具);把 WDA 代码删掉(低版本还要用)。++## 3. 每项能力怎么实现++「已验证」= 我们在真机上测过;「Pinky」= Pinky 已在真机上做到、我们没测;「待测」= 都没验证。++| 能力 | 现在(WDA) | 不用 WDA 时 | 状态 |+|---|---|---|---|+| 截图 | `/screenshot` 约 0.4 秒 | CoreDevice screencaptureservice(已是后备),约 0.5 秒 | 已验证 |+| 读元素(`list_elements`、`then=elements`) | `/source` XML | remoteAXService 逐个元素读(走树),字段和推送的树一样:类型(属性 61,和 WDA 类型名一致)、文字 33/3、值 53、id 25、位置 21、点击点 1、traits 77、可用 27、子元素 8 | 已实现;字段对照已验证(设置、主屏) |+| 跨进程元素(小组件等) | WDA 原始坐标也是相对的,`parse_tree` 已换算 | traits 第 34 位标出宿主视图,加上宿主的位置(Pinky `observe_rax.go`) | Pinky |+| 系统弹窗、通知横幅、权限请求 | `/alert/text`、SpringBoard 的树 | 另读 SpringBoard 应用元素(请求类型 1,带它的 pid):子元素里除了状态栏(有专门的 trait 位)就是盖在 App 上的东西(Pinky `springboard.go`) | Pinky |+| 点击、长按、滑动 | W3C actions | HID(已有后备)。按名字点用 AX 的点击点 | 已验证 |+| 等界面稳定、界面变没变 | 轮询 `/source` | 和 WDA 一样轮询:连续两次读到的树一样、没有加载圈就算稳定;操作后先等 0.4 秒再读第一次(推送靠不住,见第 1 节的更正) | 已实现 |+| 输入文字 | `/wda/keys` | 全部走剪贴板粘贴(拼音键盘下按 ASCII 键会变成拼音输入,已见过);读回输入框(AX 的值)核对 | 粘贴已验证 |+| 「允许粘贴」弹窗 | 不会出现 | 用 AX 在 SpringBoard 的元素里找到弹窗,点「允许粘贴」,等输入框的值变了再还原剪贴板(不再需要 Agent 去点、等 45 秒) | 弹窗出现已验证(备忘录);自动点待做。Pinky 在设置的搜索框里没遇到弹窗 |+| 键盘在不在、哪个输入框有焦点 | 找 `XCUIElementTypeKeyboard` | 树里的 Keyboard 类型元素;应用的焦点元素(属性 19)、`isFocused`(28) | Pinky |+| Home、电源、音量 | XCTest 按键 / IOHID | HID(已有) | 已验证 |+| 启动 App、等到前台 | `/wda/apps/launch` | CoreDevice AppService `launch_application`;前台 App 用请求类型 4(frontmost app) | 启动已有;前台判断待做 |+| 结束 App | `/wda/apps/terminate` | AppService 发信号(已在实验里用过 SIGKILL) | 已验证 |+| 打开链接(`open_url`) | `/url` | AppService 启动目标 App 时带 `payloadURL`(同 `devicectl --payload-url`),先查清这个链接由哪个 App 打开 | Pinky |+| 锁屏状态 | `/wda/locked` + 树核对 | lockdown 的 `PasswordProtected`(Pinky:iOS 27 的镜像没实现 CoreDevice getlockstate);屏幕亮不亮看 CoreDevice 显示信息里的背光状态 | Pinky |+| 自动解锁 | WDA 读密码栏、逐位点击核对(`ictl-unlock`) | 上滑叫出密码键盘,AX 确认键盘在(实验里读到过「密码栏」和数字键),用虚拟 HID 键盘逐位敲,每位之前确认还锁着,最后看 lockdown(Pinky `power.go`)。保留现在的停用标记和「从第 2 位起先写停用标记」 | Pinky;我们要重写 |+| 屏幕尺寸、方向 | `/wda/screen`、`/rotation` | 截图像素 ÷ 机型倍数;方向用 springboardservices(已有 `interface_rotation`)或 AX 属性 129 | 已有部分 |+| 控制台画面 | WDA MJPEG(低版本) | 手机自己的 HEVC(iOS 27 已默认用它) | 已在用 |+| 开发者工具(日志、崩溃、安装、网页) | 本来就不经 WDA | 不变 | — |++## 4. 架构++### 4.1 新 crate:`ictl-ax`++- **会话**:DTX 连接 `com.apple.accessibility.axAuditDaemon.remoteAXService`;握手 `_notifyOfPublishedCapabilities:` → `deviceAPIVersion`(等答复)→ `clientNeedsAccessibility: true`;回答 `hostAPIVersion = 7`;手机每条要回执的消息都回空回执。idevice 的 `RemoteServerClient` 遇到解不开的消息会退出,探针是自己读帧,正式代码沿用这个做法或给 idevice 提补丁(idevice 的 AI.md 要求 PR 描述由作者亲手写)。+- **解码**:两层 NSKeyedArchive → `AXPTranslatorResponse`。引入 `ns-keyed-archive` crate(idevice 已经依赖它)。只解我们用的字段,未知字段忽略;解码是纯函数,用脱敏后的真机数据做测试夹具。+- **请求**:类型 1(某进程的应用元素,读 SpringBoard 用)、2/5(属性)、4(前台 App)。一次只发一个请求。类型 11(整棵树)不带参数会让手机断开连接,不用。+- **转换**:输出现在的 `ictl_wda::elements::Tree`/`Element`(类型名、文字、值、中心点、大小),这样 `find`、遮挡判断、`describe`、`close_to` 都能复用。为此把 `Tree`/`Element` 和与 WDA 无关的逻辑从 `ictl-wda` 挪到一个两边都依赖的地方(`ictl-protocol` 或新的 `ictl-ui`)。+- **会话归属**:和 HID 会话一样归 `Tunnel` 所有、常驻复用(空闲 60 秒关掉)。每次读界面都走一遍树,不用推送的树(推送只在前台 App 变化时才来)。连接断了就重建,不重放操作。++### 4.2 守护进程:按设备选「后端」++现在工具代码里大约 56 处直接用 `WdaClient`(`tools/`、`core.rs`、`supervise.rs`),`ictl-unlock` 有 52 处。做法:++- 定义一组守护进程内部的操作(读树、截图、点、滑、按键、输入、启动、结束、开链接、锁屏状态、解锁、前台 App),WDA 和「原生」(AX + HID + CoreDevice)各实现一份;工具代码只调这组操作。现有的 HID 后备逻辑并进原生那一份。+- 选择:iOS 27 及以上默认原生,低于 27 用 WDA;`ICTL_IOS_BACKEND=wda|native|auto`(按设备也可以设)随时切回。+- `ictl-unlock` 拆成「判断/输入密码的流程」和「读界面、按键」两层,流程不变,下层各有 WDA、原生两种。++### 4.3 状态机和引导++- 原生设备的「就绪」= 已配对 + 开发者模式 + 镜像已挂载 + 隧道 + AX 会话握手成功。不再有 `NeedsSigning`、`WdaStarting`、`NeedsAutomationPin`。+- 重签、Apple ID 会话检查只对还在用 WDA 的设备做;全部设备都是原生时,`setup` 跳过 Apple ID 和签名两步。+- `status`、`doctor` 说明这台用的是哪种后端。++## 5. 对 Agent 可见的差别++- 元素粒度不同:AX 把一行合成一个元素(「Wi-Fi、Derrors-5G」),WDA 还列出里面的文字和箭头。按包含文字查找都找得到;`list_elements` 的输出会变短。+- 屏幕外的行 AX 不列:长列表要先滑到才找得到(WDA 会列出但点不到,影响不大)。+- 时间:推送的树在变化后约 0.3 秒先来通知、1~2 秒内来完整的树(WDA 在时测的;没有 WDA 时要用常驻 HID 会话重测)。 **更正**:没有 WDA 时 App 内换页不推送,见第 1 节。+- 粘贴弹窗由守护进程自己点掉,`type_text` 的结果不再要求 Agent 去点。++## 6. 风险++| 风险 | 对策 |+|---|---|+| 协议和属性编号没公开,iOS 更新可能变 | 握手失败或解码不出必需字段时,这台设备自动退回 WDA(装了的话)或报清楚原因;每个 iOS 大版本发布后跑一遍回归 |+| 推送漏了、来晚了 | 不靠推送:每次读界面都走树(类型 4 + 类型 5),有 400 个元素、4 秒的上限 |+| 无障碍运行时打开后影响手机(耗电、App 行为) | 只在有人用设备时保持会话,空闲关掉(和 HID 会话一样 30 秒) |+| 系统弹窗读不全 | SpringBoard 那一读失败时回到截图;先在常见弹窗(权限、粘贴、提醒事项到期)上验证 |+| 解锁失败把密码输错 | 沿用现有的停用标记;每一位之前确认还锁着;只试一次 |+| 和 WDA 并存,代码变复杂 | 后端接口一处定义;低版本路径不动,只把工具代码改成调接口 |+| 借用 Pinky 的做法 | Apache-2.0,可以参考和移植,移植的代码保留出处并记进 THIRD_PARTY.md |++## 7. 分阶段++每一步都能单独合并,原来的 WDA 路线一直可用。++1. **`ictl-ax` 和读元素后备**(约 1~1.5 周):会话、握手、解码、转成 `Tree`、跨进程坐标、SpringBoard 弹窗。先只在 **WDA 不可用时**用:`list_elements`、`tap_element`、`wait_for`、`then` 等稳定、HID 粘贴的弹窗自动点。验收:设置、主屏(小组件)、备忘录、微信等 5 个界面和 WDA 对照,按名字点一致;粘贴不再需要 Agent 点弹窗。+2. **后端接口和原生实现**(约 1.5~2 周):把工具代码改成调接口;原生实现启动/前台、开链接、锁屏状态、解锁;状态机加原生设备。开关默认关(`ICTL_IOS_BACKEND=auto` 仍按 WDA)。验收:现有回归用例(`docs/dev/regression-cases.md`)在原生后端上全部过;`ictl-soak` 长测 8 小时(含锁屏、重启守护进程、拔插)。+3. **默认切换**(约 0.5 周):iOS 27 设备默认原生;`setup` 在只有原生设备时跳过 Apple ID 和签名;文档、网站、更新日志。验收:一台没装过 WDA 的 iOS 27 手机从 `setup` 到 Agent 完成任务。++阶段 1 本身就有用(WDA 掉线时也能读界面),做完再决定要不要进阶段 2。++## 8. 需要你决定的++1. 方向:按第 7 节分阶段做,还是只做阶段 1 当后备。+2. iOS 27 设备默认切到原生的时机:阶段 3 一完成就切,还是先作为可选项跑一个版本。+3. 已经签好 WDA 的 iOS 27 手机:切到原生后 WDA 留着当备用(重签继续),还是不再管它。+4. 解码和协议部分是参考 Pinky 自己写,还是直接移植它的 Go 代码改写成 Rust(后者快一些,要保留 Apache-2.0 的出处说明)。++## 附:实现后真机验证发现的(2026-11-15,iPhone 15 Pro Max,iOS 27.2.1)++- **推送只在前台 App 变化时来**:App 内换页不推送,所以每次读界面都自己走树。主动请求整棵树(类型 11,不带参数)会让手机断开连接。+- **走树要流水线**:一个元素一次请求、一来一回约 40 毫秒,57 个元素要 2.5 秒。答复里带着元素对象(`associatedTranslationObject`),所以一层的属性请求一次发出去、按对象收答复,再用 `tree::assemble` 按阅读顺序拼起来:同一屏 0.45~1.2 秒。+- **HID 的屏幕媒体流开着时,锁屏对无障碍是空的**:任何会话读到的都只有应用元素自己。原生解锁每次读锁屏前先关 HID 会话,元素 0.1~0.7 秒后回来;下一次点击再重开(约 0.5 秒)。解锁后等 0.7 秒再操作,否则锁屏滑开的动画会吞掉点击。+- **锁屏的密码栏是 `TextField`**(值「共6位数,已输入0位」),转 XML 时改标成 `SecureTextField`,解锁逻辑照旧认得。+- **SpringBoard 问的问题没有 Alert 元素**:「“设置”想从“dtpasteboardd”粘贴」出来时前台变成 SpringBoard,只有两段文字和两个按钮。前台是 SpringBoard、元素不多、至少两个按钮、没有图标/键盘/密码栏/单元格时,转 XML 时包一层 `Alert`,弹窗提醒和自动点「允许粘贴」都靠它。+- **网页在 WebContent 进程里**:它的元素没有宿主视图、坐标就是屏幕坐标。按进程列表认出 `com.apple.WebKit.WebContent*`,原样放置(Pinky `webcontent.go` 的做法)。+- **键盘的键有时算 App 自己的元素**,合成不出 `Keyboard`;输入前判断键盘时,有 8 个以上 `Key` 也算。+- 锁屏状态读 lockdown 的 `PasswordProtected` 要先建会话,否则报 `this request was prohibited`。diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.mdindex 8255bc9..b7bc8f9 100644--- a/docs/dev/regression-cases.md+++ b/docs/dev/regression-cases.md@@ -128,3 +128,19 @@| 122 | 升级时运行新程序的 `--version` 偶尔失败:`Text file busy`(同一进程的其他线程 fork 时,新程序还以写方式打开) | 遇到 `ETXTBSY` 等 50 毫秒重试,最多 20 次 | 单测 `the_candidate_runs_once_it_is_no_longer_open_for_writing`(修复前稳定复现) || 123 | iPad(iPadOS 26)重启后要输入密码启用 UI 自动化时,通知写的是「iPhone 需要输入锁屏密码」;所有通知标题都写死「iPhone」,多台设备时看不出是哪一台 | 标题用设备名(没有名字时用型号类别),密码提示按设备类别写系统弹窗的说法;离线通知用离线前记下的名字 | 单测 `a_notification_names_its_device`;真机 `notify-test pin`(控制 iPad,经本地假 Bark 截到标题) || 124 | 切到另一台设备再切回 iPhone(iOS 27)后,WDA 卡在「Enable UI Automation」密码框期间,HID 后备路线的截图、按键都报「WDA 不可用,也不知道屏幕尺寸」:state.json 只记最后一台的尺寸 | 每台设备的尺寸按 UDID 记下(`screens`),`screen`/`screen_udid` 照旧写给旧版本 | 单测 `every_device_keeps_its_screen_size`;真机:iPhone 和 iPad 来回切换后,iPhone 的 WDA 还没起来时截图、按 Home |+| 125 | 原生控制(iOS 27 不用 WDA):手机只在切换 App 时推送元素树,App 内换页(设置 → 通用)读到的还是点击前的页面 | 每次读界面都自己走树(类型 4 + 每层一次发出类型 5) | 真机(`then=elements` 里有新页面的元素,「界面有变化」) |+| 126 | 原生:HID 的屏幕媒体流开着时,锁屏键盘和系统密码框对无障碍是空的(任何会话都只读到应用元素),自动解锁报「调不出键盘」 | 读锁屏前先关 HID 会话,元素 0.1~0.7 秒后回来 | 真机(锁屏后任一操作) |+| 127 | 原生:解锁后马上点击,被锁屏滑开的动画吞掉,界面不变 | 解锁后等 0.7 秒再操作 | 真机(锁屏后 `tap_element`,3/3) |+| 128 | 原生:走树一个元素一次请求、一来一回约 40 毫秒,57 个元素 2.5 秒;滑动后等列表停下时还连带读 SpringBoard,读太慢,每次都报「还在滚动」 | 一层的请求一次发出、按答复里的元素对象配对;等列表停下只读 App | 真机计时(列元素约 0.2 秒;向上滑不再报还在动) |+| 129 | 原生:SpringBoard 的提问(「…想从“dtpasteboardd”粘贴」、权限请求)没有 Alert 元素:按 Home 不拦、「允许粘贴」不点、输入中文失败 | 前台是 SpringBoard、元素不多、两个以上按钮、没有图标/键盘/密码栏/单元格时包一层 Alert | 单测 `a_question_springboard_asks_reads_as_an_alert` + 真机 |+| 130 | 原生:按 Home 关掉主屏的长按菜单后马上启动 App,菜单动画结束时 App 又被送回主屏(3/3) | Home 按下后至少 0.6 秒才返回 | 真机(3/3 留在前台) |+| 131 | 原生:结束 App 后马上打开链接,手机报「无法确定启动的应用的进程标识符」,报错是一串归档的字节 | 结束 App 等进程真的退出(最多 2 秒);CoreDevice 的报错取出里面的说明文字 | 单测 `a_coredevice_error_says_what_it_says` + 真机 |+| 132 | 原生:解锁沿用 WDA 的固定等待(唤醒 1 秒、上滑 1.5 秒),一次解锁约 8 秒 | 原生读锁屏只要约 0.1 秒:上滑后每 0.2 秒找键盘,唤醒等 0.5 秒;每位照旧读回核对(#4) | 单测 `a_screen_read_cheaply_finds_the_keypad_without_waiting_it_out` + 真机计时 |+| 133 | 原生:网页(Safari)的文字读不到:网页元素在 WebKit WebContent 进程里,没有宿主视图 | 按进程列表认出 WebContent,元素原样放置 | 单测 + 真机(`wait_for` 网页文字 0.2~0.8 秒) |+| 134 | 原生:每次截图都重新连截屏服务,新连接上第一个请求要多做一次握手(0.82 秒,同一连接上之后 0.30 秒)。截屏服务只认 `png`(idevice 的 `jpeg` 和其他十几个格式名都被拒),在隧道的 SYN 里通告 MSS 也没让 8 MB 的 PNG 变快 | 截屏服务的连接留在隧道上复用,失效就重连一次 | 真机计时(截图中位数 0.91 → 0.43 秒);`debug shot-formats` |+| 135 | 原生:按键盘「下一个键盘」按钮的值判断是英文键盘就直接按键:那个值是点了要切到的键盘,不是当前的;HID 按键走硬件键盘的输入法,屏幕上是英文键盘也照样组成拼音(「wifi」成了带下划线的「w i f i」),去掉空格的读回核对没拦住 | 一律粘贴 | 真机 |+| 136 | 原生:SpringBoard 在前台时(锁屏、面容 ID 框)状态栏的按钮被算进「SpringBoard 的提问」,报出一个标题是时间的弹窗 | 判断提问、取标题都不算状态栏元素 | 单测 `a_question_springboard_asks_reads_as_an_alert` |+| 137 | 后台准备好手机后唤醒的那轮巡检,正赶上请求占着设备锁就跳过了,切回 iPhone 要等下一轮(10 秒)才就绪 | 唤醒的一轮没跑成就隔 200 毫秒再来 | 真机(切到 iPad 再切回) |+| 138 | 控制台页面脚本里同一函数重复声明变量(`list`),整页脚本跑不起来,停在「正在连接」;页面测试只抽单个函数,没发现 | 测试编译整页脚本 | 单测 `tests/viewer/syntax.test.mjs` |+| 139 | 原生控制(没有 WDA)时,解不了 HEVC 的浏览器(Firefox、多数 Linux 上的 Chrome)没有画面:H.264 和 MJPEG 两路的源头都是 WDA 的 MJPEG,都 502。手机的视频转码时带 `-fflags nobuffer` 会丢掉开头,之后每帧都找不到参考帧 | `/video` 连不上 WDA 时把手机的 HEVC 交给 ffmpeg 转成 H.264(按点数尺寸裁掉补齐的边),HEVC 输入不带 `nobuffer` | 单测 `hevc_is_transcoded_with_the_padding_cut_off` + 无头 Chromium(不支持 HEVC)看到画面 |+| 140 | 开着后台启动(`ICTL_WDA_DETACHED=1`)用过 WDA、再切回原生控制:之前后台启动的 WDA 一直在手机上运行,state.json 里也一直记着它。原来结束它用的 DVT `kill_app` 对 WDA 无效(WDA 模式下关掉开关时,随后用 XCTest 会话启动的 WDA 会顶替它,所以那条路看不出问题) | 原生准备手机时(开发者镜像好了之后)结束记下的那个 WDA;结束一律走 AppService 的 SIGKILL,等它从进程列表消失(最多 2 秒)再忘掉;结束不了就留着记录,下次准备时再试 | 真机(切 WDA 让后台 WDA 起来,再切回原生,看日志和 state.json) |diff --git a/packaging/env.example b/packaging/env.exampleindex fb02df9..7edc124 100644--- a/packaging/env.example+++ b/packaging/env.example@@ -75,6 +75,8 @@ ICTL_DDI_URL=ICTL_DDI_DIR=# 未签名 WDA 的路径。默认是数据目录的 wda/WDA-unsigned.ipa,首次签名前下载# ICTL_WDA_UNSIGNED=/path/to/WDA-unsigned.ipa+# iOS 27 及以上怎么控制:auto(默认,原生:不用 WDA,经 HID、无障碍服务和 CoreDevice)、native、wda(仍用 WDA)+# ICTL_IOS_BACKEND=auto# 实验:在后台启动 WDA、不持有 XCTest 会话(锁屏时也能启动,守护进程重启时 WDA 不跟着断)。# 手机重启后的「UI 自动化」密码框靠手机系统日志识别。见 docs/dev/wda-dependency-research.md# ICTL_WDA_DETACHED=1diff --git a/tests/viewer/syntax.test.mjs b/tests/viewer/syntax.test.mjsnew file mode 100644index 0000000..9b157cb--- /dev/null+++ b/tests/viewer/syntax.test.mjs@@ -0,0 +1,16 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { test } from 'node:test';+import { Script } from 'node:vm';++const html = readFileSync(new URL('../../apps/iphone-control/src/viewer.html', import.meta.url), 'utf8');++// The other tests take single functions out of the page; a mistake elsewhere in its script (a name declared twice+// in one function) stopped the whole page at "connecting" while they all passed+test("the page's script compiles", () => {+ const scripts = [...html.matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/g)].map(m => m[1]);+ assert.ok(scripts.length > 0, 'the page has an inline script');+ for (const s of scripts) {+ assert.doesNotThrow(() => new Script(s, { filename: 'viewer.html' }));+ }+});diff --git a/website/en/guide/configuration.md b/website/en/guide/configuration.mdindex 1196dbf..1b1d465 100644--- a/website/en/guide/configuration.md+++ b/website/en/guide/configuration.md@@ -54,6 +54,7 @@ Notification variables: see [Notifications](./notifications).| `ICTL_ANISETTE_URL` | Your own anisette server (the default is a public third-party one; see [Security](./security)) || `ICTL_DDI_URL` | Developer Disk Image download URL; the default is a community-maintained mirror || `ICTL_DDI_DIR` | A Developer Disk Image directory you extracted from Xcode. The daemon doesn't download anything or delete its files, and the error names any missing file. When unset, the `ddi/` cache in the data directory is used, and it is deleted and downloaded again after 3 failed mounts in a row |+| `ICTL_IOS_BACKEND` | How phones on iOS 27 and later are driven. `auto` (the default) and `native`: natively, without WDA: HID for touches, the accessibility service to read the screen, the pasteboard to type. `wda`: still through WDA. iOS 26 and earlier always use WDA || `ICTL_WDA_UNSIGNED` | Path of the unsigned WDA. Default: `wda/WDA-unsigned.ipa` in the data directory, downloaded before the first signing. A path you set yourself is not downloaded || `SCREEN_W` / `SCREEN_H` | Screen size in points for the HID fallback, used only while WDA is down and there is no record of this device's size: WDA has never connected, or you switched to a device without one. It applies to every device, so take care with several || `ICTL_LOG` | Log filter, e.g. `info,ictl_wda::http=debug` logs every WDA request with its duration |diff --git a/website/guide/configuration.md b/website/guide/configuration.mdindex 8a0a9c8..093877c 100644--- a/website/guide/configuration.md+++ b/website/guide/configuration.md@@ -54,6 +54,7 @@ MCP 服务由 AI 客户端拉起,注册时写进去的环境变量优先于设| `ICTL_ANISETTE_URL` | 自建 anisette 服务地址(默认用公共的第三方服务,见[安全与隐私](./security)) || `ICTL_DDI_URL` | 开发者镜像的下载地址,默认社区维护的镜像仓库 || `ICTL_DDI_DIR` | 自己从 Xcode 提取的开发者镜像目录。设了就不下载,也不会删里面的文件;缺文件时报错说明缺哪个。不设时用数据目录下的 `ddi/` 缓存,连续 3 次挂载失败后清掉重新下载 |+| `ICTL_IOS_BACKEND` | iOS 27 及以上的手机怎么控制。`auto`(默认)和 `native`:原生,不用 WDA,经 HID 点按、无障碍服务读界面、剪贴板输入;`wda`:仍用 WDA。iOS 26 及以下总是用 WDA || `ICTL_WDA_UNSIGNED` | 未签名 WDA 的路径。默认是数据目录的 `wda/WDA-unsigned.ipa`,第一次签名前下载。自己指定的路径不会下载 || `SCREEN_W` / `SCREEN_H` | HID 后备路线换算坐标用的屏幕尺寸(点):WDA 不可用、又没有这台设备的尺寸记录时才用,比如 WDA 从没连上过,或切到记录里没有尺寸的设备。不分设备,接多台时要小心 || `ICTL_LOG` | 日志级别,例如 `info,ictl_wda::http=debug` 记录每个 WDA 请求的耗时 |