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
fix(daemon): a background WDA per phone; `service stop` ends them (#124)
Qinghe Lidac7dbe55704
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d447d6d..fcd0a15 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ All notable changes to this project are documented here. The format is based on### Fixed+- With WDA launched in the background (`ICTL_WDA_DETACHED`): `iphone-control service stop` and `service uninstall` now end the background WDA on the connected phones once the service is stopped, instead of leaving it running (`service restart` and updates still don't interrupt it). Each phone keeps its own background WDA across device switches, so switching back attaches to it instead of launching a new one.- An arrow key in the setup guide's menus (`iphone-control setup`) could come out as a letter on a busy machine: when the program was descheduled for more than 250 ms in the middle of reading the key, the rest of its bytes, though already there, were dropped and the last one taken as typed (↓ as "B"). Bytes already received are now always read.- A tap or swipe a minute or more after the last one no longer waits for the screen size to be measured again first: that takes WDA 0.95 s on an iPad mini 5 (iPadOS 26.7.3), where the first tap after a pause took 1.7 s instead of 0.9. The size is now measured again in the background while nobody acts (only Display Zoom changes it), and on rotation as before.- A control page whose H.264 or the phone's own video didn't show a first frame within 9 s (the viewer or daemon restarting, the encoder starting up) used MJPEG until it was reloaded; it now tries again after 30 s, 1 min and 2 min. A picture the viewer said isn't available still isn't tried again.diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex 7e1bf1f..2c48828 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -20,6 +20,7 @@### 修复+- 开着后台启动 WDA(`ICTL_WDA_DETACHED`)时:`iphone-control service stop`、`service uninstall` 停掉服务后,会结束接着的手机上后台启动的 WDA,不再让它一直留在手机上(`service restart` 和升级照旧不打断它);切换设备时每台手机的后台 WDA 各记一条,切回去直接接上,不再重新启动。- 引导(`iphone-control setup`)菜单里的方向键在机器很忙时可能变成字母:读按键读到一半,程序被挂起超过 250 毫秒,后面已经到了的字节会被丢掉,最后一个当成输入的字符(↓ 变成「B」)。现在已经收到的字节一定会读。- 隔了一分钟以上的点按、滑动不再先等重新读屏幕尺寸:iPad mini 5(iPadOS 26.7.3)上 WDA 读一次要 0.95 秒,停一会儿后的第一次点按要 1.7 秒,平时 0.9 秒。尺寸现在在没人操作时于后台重读(只有「显示缩放」会改变它),转屏时照旧马上重读。- 控制台页面的 H.264 或手机自己的视频 9 秒内没出第一帧时(控制台服务或守护进程正在重启、编码器正在启动),原来一直用 MJPEG 直到刷新页面;现在 30 秒、1 分钟、2 分钟后各再试一次。控制台服务明确说不可用的画面仍然不再试。diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex 80a9448..7b67341 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -185,9 +185,10 @@ enum UpdateAction {enum ServiceAction {#[command(about = ictl_l10n::tr!("装成登录后自动启动的后台服务并启动(已有就直接启动)", "Set up the service that starts at login and start it (just start it if it exists)"))]Install,- #[command(about = ictl_l10n::tr!("停止并移除本程序装的后台服务(数据保留)", "Stop and remove the service this program set up (data is kept)"))]+ #[command(about = ictl_l10n::tr!("停止并移除本程序装的后台服务(数据保留),后台启动的 WDA 也一并结束", "Stop and remove the service this program set up (data is kept), and the WDA launched in the background with it"))]Uninstall,Start,+ #[command(about = ictl_l10n::tr!("停止后台服务;后台启动的 WDA(ICTL_WDA_DETACHED)也一并结束(restart 和升级不会)", "Stop the service, and the WDA launched in the background (ICTL_WDA_DETACHED) with it (restart and updates leave it running)"))]Stop,#[command(about = ictl_l10n::tr!("重启,改过 ~/.config/iphone-control/env 后用", "Restart, after editing ~/.config/iphone-control/env"))]Restart,@@ -479,6 +480,36 @@ fn mcp_config(socket: &Path) -> anyhow::Result<String> {Ok(mcp_command(&service::stable_exe()?, socket))}+/// After `service stop` / `uninstall`: a WDA launched in the background (`ICTL_WDA_DETACHED`) doesn't end with the+/// daemon, so restarts and updates don't interrupt it; stopping the service on purpose ends it too. Not while a+/// daemon still answers (one run by hand): it keeps using its WDA+async fn end_background_wda(socket: &Path, data_dir: &Path) {+ use ictl_daemon::detached::StoppedWda;+ if tokio::net::UnixStream::connect(socket).await.is_ok() {+ return;+ }+ let cfg = ictl_daemon::Config::from_env(data_dir);+ for (udid, s) in ictl_daemon::detached::end_recorded(&cfg).await {+ match s {+ StoppedWda::Ended(pid) => println!(+ "{}",+ ictl_l10n::trf!(+ "已结束 {udid} 上后台启动的 WDA(进程 {pid})",+ "Stopped the WDA launched in the background on {udid} (pid {pid})"+ )+ ),+ StoppedWda::NotRunning(_) => {}+ StoppedWda::Failed(pid, e) => println!(+ "{}",+ ictl_l10n::trf!(+ "没能结束 {udid} 上后台启动的 WDA(进程 {pid}):{e}。守护进程下次准备这台手机时会再处理",+ "Couldn't stop the WDA launched in the background on {udid} (pid {pid}): {e}. The daemon deals with it the next time it prepares this phone"+ )+ ),+ }+ }+}+async fn service_cmd(socket: &Path, data_dir: &Path, action: ServiceAction) -> anyhow::Result<()> {let none = || {anyhow::anyhow!(@@ -494,9 +525,15 @@ async fn service_cmd(socket: &Path, data_dir: &Path, action: ServiceAction) -> alet s = service::install()?;println!("{}", ictl_l10n::trf!("已安装并启动:{}", "Installed and started: {}", s.describe()));}- ServiceAction::Uninstall => service::uninstall()?,+ ServiceAction::Uninstall => {+ service::uninstall()?;+ end_background_wda(socket, data_dir).await;+ }ServiceAction::Start => service::start(&service::find().ok_or_else(none)?)?,- ServiceAction::Stop => service::stop(&service::find().ok_or_else(none)?)?,+ ServiceAction::Stop => {+ service::stop(&service::find().ok_or_else(none)?)?;+ end_background_wda(socket, data_dir).await;+ }ServiceAction::Restart => service::restart(&service::find().ok_or_else(none)?)?,ServiceAction::Viewer { action } => viewer_service_cmd(action)?,ServiceAction::Status => {diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex 62e1f0f..eeb04b9 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -62,10 +62,15 @@ pub struct Persisted {/// 运行中选定要控制的设备(`iphone-control select`、`iphone_select_device`);None 是自动选。/// 设了 `IPHONE_UDID` 时以它为准,这个不起作用pub selected_udid: Option<String>,- /// 实验(`ICTL_WDA_DETACHED`):后台启动的 WDA 是哪台设备上的哪个进程。守护进程重启后据此直接接上它,- /// 不重新启动;关掉实验开关后据此结束它(不然它一直占着 8100 端口,新 runner 的 HTTP 服务起不来)+ /// 实验(`ICTL_WDA_DETACHED`):最近记下的那个后台启动的 WDA(哪台设备上的哪个进程)。只留给旧版本读+ /// (降级后它据此接上或结束这一个);新版本看 [`Self::detached_wdas`],经 [`Self::detached_for`] 等读写#[serde(default, skip_serializing_if = "Option::is_none")]pub detached_wda: Option<DetachedWda>,+ /// 实验(`ICTL_WDA_DETACHED`):每台设备上后台启动的 WDA 的进程号,按 UDID。守护进程重启、切换设备再切回来时+ /// 据此直接接上,不重新启动;关掉实验开关、改走原生控制、`service stop`/`uninstall` 时据此结束它(不然它一直+ /// 占着 8100 端口,新 runner 的 HTTP 服务起不来)。见 [`crate::detached`]+ #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]+ pub detached_wdas: std::collections::BTreeMap<String, u64>,/// Which way Home and locking work on each device, by UDID ([`Self::ways_for`]). Kept here, not only in memory:/// after a restart or switching devices the first Home on an iPad mini 5 tried the way that doesn't work there,/// waited 2 s for the home screen, then pressed again (4.4 s instead of 0.8)@@ -154,6 +159,63 @@ impl Persisted {true}+ /// The WDA launched in the background on `udid`, if one is recorded (by an older version: only the last one)+ pub fn detached_for(&self, udid: &str) -> Option<u64> {+ self.detached_wdas+ .iter()+ .find(|(k, _)| k.eq_ignore_ascii_case(udid))+ .map(|(_, p)| *p)+ .or_else(|| self.detached_wda.as_ref().filter(|d| d.udid.eq_ignore_ascii_case(udid)).map(|d| d.pid))+ }++ /// Every recorded background WDA: (UDID, pid)+ pub fn detached_all(&self) -> Vec<(String, u64)> {+ let mut all: Vec<_> = self.detached_wdas.iter().map(|(u, p)| (u.clone(), *p)).collect();+ if let Some(d) = &self.detached_wda+ && !all.iter().any(|(u, _)| u.eq_ignore_ascii_case(&d.udid))+ {+ all.push((d.udid.clone(), d.pid));+ }+ all+ }++ /// Records the WDA launched in the background on `udid` (the other devices' stay); whether anything changed+ /// (then save)+ pub fn record_detached(&mut self, udid: &str, pid: u64) -> bool {+ // an older version's only record is overwritten below: keep it among the devices' records first+ if let Some(d) = self.detached_wda.clone()+ && !self.detached_wdas.keys().any(|k| k.eq_ignore_ascii_case(&d.udid))+ {+ self.detached_wdas.insert(d.udid, d.pid);+ }+ let key = self+ .detached_wdas+ .keys()+ .find(|k| k.eq_ignore_ascii_case(udid))+ .cloned()+ .unwrap_or_else(|| udid.to_owned());+ let last = Some(DetachedWda { udid: key.clone(), pid });+ let changed = self.detached_wdas.get(&key) != Some(&pid) || self.detached_wda != last;+ self.detached_wdas.insert(key, pid);+ self.detached_wda = last;+ changed+ }++ /// Forgets the background WDA recorded for `udid` (only if it is `pid`, when given); whether anything changed+ /// (then save)+ pub fn forget_detached(&mut self, udid: &str, pid: Option<u64>) -> bool {+ let before = (self.detached_wdas.len(), self.detached_wda.is_some());+ self.detached_wdas.retain(|k, p| !(k.eq_ignore_ascii_case(udid) && pid.is_none_or(|x| x == *p)));+ if self+ .detached_wda+ .as_ref()+ .is_some_and(|d| d.udid.eq_ignore_ascii_case(udid) && pid.is_none_or(|x| x == d.pid))+ {+ self.detached_wda = None;+ }+ before != (self.detached_wdas.len(), self.detached_wda.is_some())+ }+/// 记下这次重签的结果:新字段,加上旧版本认的中文整句pub fn record_resign(&mut self, at: u64, error: Option<String>) {let when = crate::eventlog::format_utc(at);@@ -382,19 +444,8 @@ pub(crate) struct PerDevice {/// 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) type Prepared =+ std::result::Result<(Option<String>, Option<(String, crate::detached::StoppedWda)>), (DeviceError, bool)>;pub(crate) struct Inner {pub persisted: Persisted,@@ -1437,6 +1488,50 @@ fn check_request(req: &Request) -> Result<(), String> {pub(crate) mod tests {use super::*;+ /// Each device keeps its own background WDA: switching to another device and back attaches to it again, and+ /// `service stop` sees all of them. The last one is still written the old way for older versions+ #[test]+ fn each_device_keeps_its_background_wda() {+ let mut p = Persisted::default();+ assert!(p.record_detached("IPHONE", 10));+ assert!(p.record_detached("IPAD", 20));+ assert!(!p.record_detached("ipad", 20), "the same again changes nothing");+ assert_eq!(p.detached_for("IPHONE"), Some(10), "switching to the iPad kept the iPhone's");+ assert_eq!(p.detached_for("iPad"), Some(20));+ assert_eq!(+ p.detached_wda,+ Some(DetachedWda { udid: "IPAD".into(), pid: 20 }),+ "the last one, for old versions"+ );+ assert_eq!(p.detached_all(), vec![("IPAD".into(), 20), ("IPHONE".into(), 10)]);++ assert!(!p.forget_detached("IPHONE", Some(11)), "another pid: a newer one, kept");+ assert!(p.forget_detached("IPHONE", Some(10)));+ assert_eq!(p.detached_for("IPHONE"), None);+ assert!(p.forget_detached("ipad", None));+ assert_eq!((p.detached_all(), p.detached_wda), (vec![], None));+ }++ /// A state.json from an older version has only the one record: it is still found, attached to and forgotten+ #[test]+ fn an_older_versions_background_wda_is_still_known() {+ let p: Persisted = serde_json::from_str(r#"{"detached_wda":{"udid":"IPHONE","pid":7}}"#).unwrap();+ assert_eq!(p.detached_for("iphone"), Some(7));+ assert_eq!(p.detached_for("IPAD"), None);+ assert_eq!(p.detached_all(), vec![("IPHONE".into(), 7)]);++ let mut q = p.clone();+ assert!(q.forget_detached("IPHONE", Some(7)));+ assert_eq!(q.detached_all(), vec![]);++ let mut r = p;+ assert!(r.record_detached("IPAD", 8));+ assert_eq!(r.detached_all(), vec![("IPAD".into(), 8), ("IPHONE".into(), 7)], "the old record is kept");+ let json = serde_json::to_value(&r).unwrap();+ assert_eq!(json["detached_wdas"], serde_json::json!({"IPAD": 8, "IPHONE": 7}));+ assert_eq!(json["detached_wda"], serde_json::json!({"udid": "IPAD", "pid": 8}));+ }+/// 重签结果存成时间和成败,按看的人的语言显示;旧字段照旧写中文整句,旧版本的 state.json 照样读#[test]fn resign_result_is_shown_in_the_reader_language() {diff --git a/crates/ictl-daemon/src/detached.rs b/crates/ictl-daemon/src/detached.rsnew file mode 100644index 0000000..ff75e79--- /dev/null+++ b/crates/ictl-daemon/src/detached.rs@@ -0,0 +1,126 @@+//! The WDA launched in the background (`ICTL_WDA_DETACHED`), once it isn't used. It doesn't end with the daemon (that+//! is the point: a restart or an update attaches to it again), so it is ended where it is no longer wanted: preparing+//! a phone for native control, starting WDA with the switch turned off, and `iphone-control service stop` /+//! `uninstall` ([`end_recorded`], with the daemon stopped). Each phone keeps its own (`Persisted::detached_wdas`):+//! switching to another device and back attaches to it again.++use std::time::{Duration, Instant};++use ictl_device::Tunnel;++use crate::Config;+use crate::core::Persisted;++/// What became of a WDA launched in the background earlier (by its pid)+#[derive(Debug, Clone, PartialEq, Eq)]+pub 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),+}++impl StoppedWda {+ /// Whether it is gone, so its record can be forgotten+ pub fn gone(&self) -> bool {+ !matches!(self, Self::Failed(..))+ }+}++/// Whether process `pid` in the phone's process list is WDA+pub(crate) 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+pub(crate) async fn stop(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(),+ );+ }+ }+}++/// For `service stop` and `uninstall`, with the daemon stopped: ends every recorded background WDA on the phones that+/// are connected and forgets the ones that are gone. A phone that isn't connected, or one that couldn't be stopped,+/// stays recorded; the daemon deals with it the next time it prepares that phone. By UDID+pub async fn end_recorded(cfg: &Config) -> Vec<(String, StoppedWda)> {+ let path = cfg.state_file();+ let recorded = Persisted::load(&path).detached_all();+ if recorded.is_empty() {+ return Vec::new();+ }+ let connected = ictl_device::list_devices().await.unwrap_or_default();+ // an update or a re-sign holding the phones: leave them to the daemon+ let _lease = match crate::maintenance::shared() {+ Ok(l) => l,+ Err(e) => {+ let why =+ ictl_l10n::trf!("别的维护操作正占着手机:{e}", "another maintenance operation holds the phones: {e}");+ return recorded.into_iter().map(|(u, pid)| (u, StoppedWda::Failed(pid, why.clone()))).collect();+ }+ };+ let mut out = Vec::new();+ for (udid, pid) in recorded {+ let Some(usb) = connected.iter().find(|d| d.udid.eq_ignore_ascii_case(&udid)) else {+ out.push((udid, StoppedWda::Failed(pid, ictl_l10n::tr!("没接着", "not connected").to_string())));+ continue;+ };+ let s = match ictl_device::Device::from_usb(usb).open_tunnel().await {+ Ok(mut t) => {+ let s = stop(&mut t, pid).await;+ t.close().await;+ s+ }+ Err(e) => StoppedWda::Failed(pid, e.to_string()),+ };+ out.push((udid, s));+ }+ // read again: only what was dealt with here changes+ let mut p = Persisted::load(&path);+ let mut changed = false;+ for (udid, s) in &out {+ if let StoppedWda::Ended(pid) | StoppedWda::NotRunning(pid) = s {+ changed |= p.forget_detached(udid, Some(*pid));+ }+ }+ if changed {+ p.save(&path);+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn only_the_wda_runner_with_that_pid_is_wda() {+ let procs = vec![+ (10, "/private/var/containers/Bundle/Application/X/WebDriverAgentRunner-Runner.app/WebDriverAgentRunner-Runner".into()),+ (11, "/Applications/MobileSafari.app/MobileSafari".into()),+ ];+ assert!(is_wda(&procs, 10));+ assert!(!is_wda(&procs, 11), "another app");+ assert!(!is_wda(&procs, 12), "gone");+ }+}diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rsindex 366b7a8..a1c66f2 100644--- a/crates/ictl-daemon/src/lib.rs+++ b/crates/ictl-daemon/src/lib.rs@@ -8,6 +8,7 @@pub mod config;pub mod core;+pub mod detached;pub mod devices;mod devtools;mod doctor;diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rsindex a83093e..128fd49 100644--- a/crates/ictl-daemon/src/supervise.rs+++ b/crates/ictl-daemon/src/supervise.rs@@ -6,7 +6,8 @@ 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, StoppedWda, close_hid, drop_tunnel};+use crate::core::{Daemon, DeviceProfile, Inner, close_hid, drop_tunnel};+use crate::detached::{self, StoppedWda};use crate::machine::DeviceState;use crate::notify::Event;@@ -395,8 +396,8 @@ impl Daemon {match r {Ok((mounted, stopped)) => {g.dev.ddi_failures = 0;- if let Some(s) = stopped {- self.detached_stopped(g, s);+ if let Some((udid, s)) = stopped {+ self.detached_stopped(g, &udid, s);}if let Some(v) = mounted {self.log.log(&ictl_l10n::log_trf!("开发者镜像已挂载 {v}", "Developer disk image mounted {v}"));@@ -448,7 +449,7 @@ impl Daemon {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 known = g.persisted.detached_for(&device.udid);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 {@@ -456,7 +457,7 @@ impl Daemon {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),+ (Ok(_), Some(pid)) => Some((device.udid.clone(), detached::stop(&mut t, pid).await)),_ => None,};t.close().await;@@ -464,9 +465,9 @@ impl Daemon {})));}- /// 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) {+ /// What became of the WDA launched in the background earlier on `udid`, 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, udid: &str, s: StoppedWda) {let pid = match s {StoppedWda::Ended(pid) => {self.log.log(&ictl_l10n::log_trf!(@@ -484,8 +485,7 @@ impl Daemon {return;}};- if g.persisted.detached_wda.as_ref().is_some_and(|d| d.pid == pid) {- g.persisted.detached_wda = None;+ if g.persisted.forget_detached(udid, Some(pid)) {g.persisted.save(&self.cfg.state_file());}}@@ -551,9 +551,7 @@ impl Daemon {ictl_wda::client::STALL_LIMIT));// 后台启动的那个不能再接上:忘掉它,重新后台启动时会先结束它- if g.persisted.detached_wda.take().is_some() {- g.persisted.save(&self.cfg.state_file());- }+ self.forget_detached_here(g);self.update_display(g, None).await;self.drop_session(g).await;let (Some(device), Some(bundle)) = (g.device.clone(), g.persisted.wda_bundle.clone()) else { return };@@ -562,6 +560,16 @@ impl Daemon {}}+ /// Forgets the background WDA recorded for the device in use (it didn't answer): the next background launch+ /// replaces it+ fn forget_detached_here(&self, g: &mut Inner) {+ if let Some(udid) = g.device.as_ref().map(|d| d.udid.clone())+ && g.persisted.forget_detached(&udid, None)+ {+ g.persisted.save(&self.cfg.state_file());+ }+ }+/// Keep an active view and finger through the same transient status misses as the runner.pub(crate) async fn confirm_wda_loss(&self, g: &mut Inner, runner_alive: bool) -> bool {if runner_alive && !g.wda_misses.hit() {@@ -592,7 +600,7 @@ impl Daemon {ictl_l10n::log_tr!("启动 WDA", "Starting WDA")});}- let known = g.persisted.detached_wda.as_ref().filter(|d| d.udid == device.udid).map(|d| d.pid);+ let known = g.persisted.detached_for(&device.udid);let (cache, url, user_dir) = (self.cfg.ddi_cache(), self.cfg.ddi_url.clone(), self.cfg.ddi_dir.clone());let Ok(lease) = crate::maintenance::shared() else { return };let wake = self.wake.clone();@@ -677,12 +685,16 @@ impl Daemon {)),None => {}}- let record = detached- .zip(g.device.as_ref())- .map(|(d, dev)| DetachedWda { udid: dev.udid.clone(), pid: d.pid() });- if g.persisted.detached_wda != record {- g.persisted.detached_wda = record;- g.persisted.save(&self.cfg.state_file());+ // this device's record only: the other devices' background WDAs keep running and are attached to+ // again when switched back to+ if let Some(udid) = g.device.as_ref().map(|d| d.udid.clone()) {+ let changed = match detached {+ Some(d) => g.persisted.record_detached(&udid, d.pid()),+ None => g.persisted.forget_detached(&udid, None),+ };+ if changed {+ g.persisted.save(&self.cfg.state_file());+ }}g.dev.ddi_failures = 0;g.runner = Some(runner);@@ -721,8 +733,8 @@ impl Daemon {};g.backoff.failed(Instant::now());// 接上的后台 WDA 没应答:忘掉它,下一次重新后台启动(会先结束它)- if self.cfg.wda_detached && g.persisted.detached_wda.take().is_some() {- g.persisted.save(&self.cfg.state_file());+ if self.cfg.wda_detached {+ self.forget_detached_here(g);}// StartFailed 自己就以「WDA 启动失败:」开头,日志和状态里再加一遍就重复了let e = match e {@@ -1074,10 +1086,10 @@ async fn prepare_detached(bundle: &str,) -> Result<Option<Detached>, DeviceError> {match (detached, known) {- (true, Some(pid)) if is_wda(&t.processes().await?, pid) => Ok(Some(Detached::Adopted(pid))),+ (true, Some(pid)) if detached::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)) => {- match stop_detached(t, pid).await {+ match detached::stop(t, pid).await {StoppedWda::Ended(_) => tracing::info!("{}",ictl_l10n::log_trf!(@@ -1094,37 +1106,6 @@ 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/docs/architecture.md b/docs/architecture.mdindex 406595c..e58a443 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -118,7 +118,7 @@- **隧道**:CoreDeviceProxy + jktcp 用户态 TCP 栈(idevice `tunnel_tcp_stack`),不需要 root,不创建 TUN 网卡。锁屏且从未解锁过(BFU)时报 `PasswordProtected`,进入 `NeedsUnlock`,只能人工解锁。HID 和截图用的隧道按需建立、常驻复用;WDA 掉线或 usbmuxd 重启时连隧道一起丢。- **HID 会话**:归 `Tunnel` 所有(`Tunnel::hid` / `close_hid` / `close`),持有屏幕媒体流。关闭时必须先停媒体流再断隧道,否则手机一直挂着「配对的电脑」会话(灵动岛图标常驻、不自动锁屏)。空闲 30 秒关闭,重开约 0.5 秒。- **开发者镜像**:每次启动 WDA 前都先 `installed_ddi()` 查询(toolkit 实测已挂载时约 1 秒),未挂载才走 `install_ddi()`(个性化 + TSS)。手机重启后镜像可能会掉,所以这一步不能省。默认缓存(`ddi/`)连续 3 次**挂载**失败才清掉重新下载,隧道建不起来不计入。设了 `ICTL_DDI_DIR` 时不下载、也不删里面的文件,缺文件时报错说明缺哪个。-- **WDA 就绪判定**:必须同时满足"本进程持有的 XCTest 会话存活"和 `/status` 返回 ready。toolkit 踩过:host 侧 runner 退出后,手机上残留的 WDA 还会响应几十秒再自杀,单看 `/status` 会误判。实验开关 `ICTL_WDA_DETACHED=1` 下 WDA 在后台启动、本进程不持有 XCTest 会话,就绪只看 `/status`,守护进程重启后接上原来的进程(`state.json` 的 `detached_wda`),见 [WDA 依赖调研](dev/wda-dependency-research.md#8-不挂-xctest-会话启动-wda)。+- **WDA 就绪判定**:必须同时满足"本进程持有的 XCTest 会话存活"和 `/status` 返回 ready。toolkit 踩过:host 侧 runner 退出后,手机上残留的 WDA 还会响应几十秒再自杀,单看 `/status` 会误判。实验开关 `ICTL_WDA_DETACHED=1` 下 WDA 在后台启动、本进程不持有 XCTest 会话,就绪只看 `/status`,守护进程重启、切换设备再切回来时接上原来的进程(`state.json` 的 `detached_wdas`,每台设备一条);`service stop`/`uninstall` 时结束它,见 [WDA 依赖调研](dev/wda-dependency-research.md#8-不挂-xctest-会话启动-wda)。- **自动化密码框**:手机重启后首次启用 UI 自动化会弹「为 XCTest 输入 iPhone 密码」,没人输就报 `Timed out while enabling automation mode`。识别到这个错误:进入 `NeedsAutomationPin`、只推送一次通知;之后每次启动只等 25 秒,没弹出密码框就 5 秒后再启动一次(密码框只在启动时出现、每次约 45 秒,且不是每次启动都出现;弹出来的那次会一直等到密码框消失),这样手机上大部分时间都有框可输。恢复后再推送一次。- **退避**:其它 WDA 启动失败按 60s → 120s → 240s → 300s 退避,上限 5 分钟;手机重新连上、WDA 就绪、重签完成时重置。diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.mdindex b7bc8f9..cf95628 100644--- a/docs/dev/regression-cases.md+++ b/docs/dev/regression-cases.md@@ -144,3 +144,5 @@| 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) |+| 141 | 开着后台启动(`ICTL_WDA_DETACHED=1`)时 `iphone-control service stop`、`service uninstall` 之后,后台启动的 WDA 还在手机上运行(它本来就不随守护进程退出,好让重启、升级不打断它),一直占着 8100 端口 | `service stop`/`uninstall` 停掉服务后(还有守护进程应答时不动),对接着的手机逐个结束记下的后台 WDA(AppService SIGKILL,等它从进程列表消失),忘掉结束了的;没接着、结束不了的留着记录,守护进程下次准备这台手机时处理。`service restart`、升级照旧不结束 | 单测 `only_the_wda_runner_with_that_pid_is_wda` + 真机(`service stop` 后进程列表里没有 WDA、记录清空;`restart` 后接上原进程) |+| 142 | 开着后台启动时切换设备:`state.json` 只记一条后台 WDA,切到另一台就被覆盖,原来那台手机上的 WDA 没人记着、继续运行,切回去时只能重新后台启动 | 每台设备各记一条(`detached_wdas`,按 UDID),切回去直接接上;最近一条照旧写进 `detached_wda` 给旧版本;旧版本留下的那一条在记下别的设备之前先迁进新表 | 单测 `each_device_keeps_its_background_wda`、`an_older_versions_background_wda_is_still_known` + 真机(iPhone ↔ iPad 来回切,日志是「接上…没有重新启动」) |diff --git a/docs/dev/wda-dependency-research.md b/docs/dev/wda-dependency-research.mdindex 0bc9d10..f6a293e 100644--- a/docs/dev/wda-dependency-research.md+++ b/docs/dev/wda-dependency-research.md@@ -146,10 +146,10 @@ iPad 上那次失败和启动方式无关:手机端 amfid 报 `AppleMobileFile开关在 `~/.config/iphone-control/env` 里设,重启服务后生效。代码:-- `ictl-device`:`Tunnel::launch_in_background`(processcontrol,选项 `StartSuspendedKey: false`、`ActivateSuspended: true`、`KillExisting: true`,不带环境变量和参数)、`Tunnel::processes`(appservice `list_processes`)、`Tunnel::kill`(processcontrol `killPid:`)。+- `ictl-device`:`Tunnel::launch_in_background`(processcontrol,选项 `StartSuspendedKey: false`、`ActivateSuspended: true`、`KillExisting: true`,不带环境变量和参数)、`Tunnel::processes`(appservice `list_processes`)。结束它用 `Tunnel::signal`(AppService 发 SIGKILL);原来的 `Tunnel::kill`(processcontrol `killPid:`)结束不了 WDA,已删掉。- `ictl-wda`:`WdaRunner::attach` 只等 `/status` ready。这样得到的 runner 没有任务,`alive()` 总是 true,`detached()` 是 true;丢掉它不会结束手机上的 WDA。- `ictl-daemon`:`spawn_start` 挂好开发者镜像后,在同一条隧道上调 `prepare_detached`:- - 开关开着:`state.json` 里的 `detached_wda`(UDID + 进程号)对应的进程还在、可执行文件是 WebDriverAgentRunner,就**直接接上**(`/status` 等 15 秒);否则在后台启动一个(会先结束已在运行的 WDA,包括 XCTest 会话启动的),等最多 120 秒。就绪后记下进程号;接上的那个不应答就忘掉它,下一次重新启动。+ - 开关开着:`state.json` 里这台设备的记录(`detached_wdas`,按 UDID 记进程号;旧版本只认最近一条 `detached_wda`,照旧也写)对应的进程还在、可执行文件是 WebDriverAgentRunner,就**直接接上**(`/status` 等 15 秒);否则在后台启动一个(会先结束已在运行的 WDA,包括 XCTest 会话启动的),等最多 120 秒。就绪后记下进程号;接上的那个不应答就忘掉它,下一次重新启动。- 开关关着:记录里的那个还在就先结束它,再照原来的方式启动。不然它一直占着 8100,新 runner 的 HTTP 服务起不来。- 健康检查不变:每 10 秒 `/status`,连续 3 次不应答就丢掉,重新启动。@@ -168,11 +168,11 @@ iPad 上那次失败和启动方式无关:手机端 amfid 报 `AppleMobileFile- **「UI 自动化」密码框靠手机系统日志识别**,等待和输入后恢复已在手机重启后验证;一直不输、等满 60 秒的那条路还没亲眼看到(见 8.6 节)。- 证书被吊销时,手机没重启前签名校验有缓存,WDA 照样能起来;**重启后才起不来**。这对两种启动方式都一样。-- 守护进程停了 WDA 还在跑(这正是想要的效果),所以 `service stop` 不会停掉 WDA。+- 守护进程重启、升级时 WDA 照样跑(这正是想要的效果)。`iphone-control service stop`、`service uninstall` 停掉服务后会结束接着的手机上记下的后台 WDA(`detached::end_recorded`);绕过它们停服务(`systemctl --user stop`、`brew services stop`)或者手机没接着时不会,记录留着,守护进程下次准备这台手机时处理(开关开着就接上,关着或走原生控制就结束)。- 只测了几分钟。还要做长时间运行、反复锁屏和熄屏、手机重启、拔插 USB 的测试。- 只在一台 iPhone、iOS 27.0.1 上验证过;iOS 17~26 和 iPad 都没测。- 接上旧进程时只按「进程号 + 可执行文件名」判断。手机重启后进程号恰好撞上另一个 WDA 进程的可能性很小;就算撞上了,`/status` 等不到也会重新启动。-- 切换设备时,旧设备上的后台 WDA 继续跑,记录只留一台。+- 切换设备时,旧设备上的后台 WDA 继续跑,每台设备各记一条:切回去直接接上,不重新启动。- 控制台画面(9100 MJPEG)和 `fast_stream`、`keep_stream_upright` 这些 appium settings 在接上旧进程时的表现没有专门测过。### 8.6 识别「UI 自动化」密码框(2026-11-12)