Skip to content

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

阶段 3/4:守护进程 ictl-daemon

Derrors1b1558ca42d9
diff --git a/Cargo.lock b/Cargo.lock
index 57d28cd..ddb6c53 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1472,7 +1472,7 @@ dependencies = [
"atomic",
"pear",
"serde",
- "toml 0.8.23",
+ "toml",
"uncased",
"version_check",
]
@@ -1987,16 +1987,17 @@ name = "ictl-daemon"
version = "0.1.0"
dependencies = [
"anyhow",
+ "base64 0.23.1",
"ictl-device",
"ictl-sign",
"ictl-unlock",
"ictl-wda",
+ "image",
"reqwest 0.13.5",
"serde",
"serde_json",
"thiserror 2.0.21",
"tokio",
- "toml 1.1.8+spec-1.1.0",
"tracing",
]
@@ -3801,6 +3802,7 @@ dependencies = [
"rustls-platform-verifier",
"serde",
"serde_json",
+ "serde_urlencoded",
"sync_wrapper",
"tokio",
"tokio-native-tls",
@@ -4263,15 +4265,6 @@ dependencies = [
"serde",
]
-[[package]]
-name = "serde_spanned"
-version = "1.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c"
-dependencies = [
- "serde_core",
-]
-
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
@@ -4827,26 +4820,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
dependencies = [
"serde",
- "serde_spanned 0.6.9",
- "toml_datetime 0.6.11",
+ "serde_spanned",
+ "toml_datetime",
"toml_edit",
]
-[[package]]
-name = "toml"
-version = "1.1.8+spec-1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d"
-dependencies = [
- "indexmap",
- "serde_core",
- "serde_spanned 1.1.2",
- "toml_datetime 1.1.2+spec-1.1.0",
- "toml_parser",
- "toml_writer",
- "winnow 1.0.4",
-]
-
[[package]]
name = "toml_datetime"
version = "0.6.11"
@@ -4856,15 +4834,6 @@ dependencies = [
"serde",
]
-[[package]]
-name = "toml_datetime"
-version = "1.1.2+spec-1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053"
-dependencies = [
- "serde_core",
-]
-
[[package]]
name = "toml_edit"
version = "0.22.27"
@@ -4873,19 +4842,10 @@ checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [
"indexmap",
"serde",
- "serde_spanned 0.6.9",
- "toml_datetime 0.6.11",
+ "serde_spanned",
+ "toml_datetime",
"toml_write",
- "winnow 0.7.15",
-]
-
-[[package]]
-name = "toml_parser"
-version = "1.1.5+spec-1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
-dependencies = [
- "winnow 1.0.4",
+ "winnow",
]
[[package]]
@@ -4894,12 +4854,6 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
-[[package]]
-name = "toml_writer"
-version = "1.1.3+spec-1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"
-
[[package]]
name = "tower"
version = "0.5.3"
@@ -5630,12 +5584,6 @@ dependencies = [
"memchr",
]
-[[package]]
-name = "winnow"
-version = "1.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
-
[[package]]
name = "wit-bindgen"
version = "0.57.1"
diff --git a/Cargo.toml b/Cargo.toml
index a84e9c1..350e86b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -44,7 +44,7 @@ idevice = { version = "=0.1.68", default-features = false, features = [
] }
rmcp = { version = "=3.8.0", features = ["server", "transport-io"] }
tokio = { version = "=1.54.1", features = ["full"] }
-reqwest = { version = "=0.13.5", default-features = false, features = ["json", "rustls"] }
+reqwest = { version = "=0.13.5", default-features = false, features = ["json", "form", "rustls"] }
quick-xml = "=0.42.0"
image = { version = "=0.25.10", default-features = false, features = ["png", "jpeg"] }
clap = { version = "=4.6.7", features = ["derive", "env"] }
diff --git a/crates/ictl-daemon/Cargo.toml b/crates/ictl-daemon/Cargo.toml
index e49bcca..e8c5348 100644
--- a/crates/ictl-daemon/Cargo.toml
+++ b/crates/ictl-daemon/Cargo.toml
@@ -16,7 +16,8 @@ tokio.workspace = true
reqwest.workspace = true
serde.workspace = true
serde_json.workspace = true
-toml.workspace = true
thiserror.workspace = true
tracing.workspace = true
anyhow.workspace = true
+image.workspace = true
+base64.workspace = true
diff --git a/crates/ictl-daemon/src/config.rs b/crates/ictl-daemon/src/config.rs
new file mode 100644
index 0000000..a2d2d54
--- /dev/null
+++ b/crates/ictl-daemon/src/config.rs
@@ -0,0 +1,123 @@
+//! 守护进程配置:全部来自环境变量(容器里由 .env 注入),都有默认值。秘密只放文件,不放环境变量以外的地方。
+
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use ictl_device::ScreenSize;
+
+#[derive(Debug, Clone)]
+pub struct Config {
+ pub data_dir: PathBuf,
+ pub socket: PathBuf,
+ /// 指定要控制的手机;None 用第一台
+ pub udid: Option<String>,
+ /// 由守护进程拉起并看护 usbmuxd(容器里为 true;宿主机已有 usbmuxd 服务时设 false)
+ pub manage_usbmuxd: bool,
+ pub usbmuxd_bin: String,
+ /// 未签名的 WDA(镜像里自带)
+ pub wda_unsigned: PathBuf,
+ pub ddi_url: String,
+ /// 自己从 Xcode 提取的 DDI Restore 目录;设了就不下载
+ pub ddi_dir: Option<PathBuf>,
+ pub anisette_url: Option<String>,
+ /// WDA 从没连上过时,HID 换算坐标用的屏幕尺寸
+ pub screen_fallback: Option<ScreenSize>,
+ pub resign_min: Duration,
+ pub resign_check: Duration,
+ pub session_check: Duration,
+ /// 0 表示不提醒
+ pub offline_alert: Duration,
+ pub notify: NotifyConfig,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct NotifyConfig {
+ pub tg_bot_token: Option<String>,
+ pub tg_chat_id: Option<String>,
+ pub bark_server: String,
+ pub bark_key: Option<String>,
+}
+
+impl NotifyConfig {
+ pub fn any(&self) -> bool {
+ (self.tg_bot_token.is_some() && self.tg_chat_id.is_some()) || self.bark_key.is_some()
+ }
+}
+
+fn env(k: &str) -> Option<String> {
+ std::env::var(k).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty())
+}
+
+fn env_num<T: std::str::FromStr>(k: &str, default: T) -> T {
+ env(k).and_then(|v| v.parse().ok()).unwrap_or(default)
+}
+
+impl Config {
+ pub fn from_env(data_dir: &Path) -> Self {
+ let screen_fallback = match (env("SCREEN_W").and_then(|v| v.parse().ok()), env("SCREEN_H").and_then(|v| v.parse().ok())) {
+ (Some(width), Some(height)) => Some(ScreenSize { width, height }),
+ _ => None,
+ };
+ Self {
+ data_dir: data_dir.to_owned(),
+ socket: env("ICTL_SOCKET").map(PathBuf::from).unwrap_or_else(|| crate::protocol::DEFAULT_SOCKET.into()),
+ udid: env("IPHONE_UDID"),
+ manage_usbmuxd: env("ICTL_MANAGE_USBMUXD").is_none_or(|v| v != "0" && v != "false"),
+ usbmuxd_bin: env("ICTL_USBMUXD_BIN").unwrap_or_else(|| "usbmuxd".into()),
+ wda_unsigned: env("ICTL_WDA_UNSIGNED")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| "/usr/share/iphone-control/WDA-unsigned.ipa".into()),
+ ddi_url: env("ICTL_DDI_URL").unwrap_or_else(|| ictl_device::ddi::DEFAULT_BASE_URL.into()),
+ ddi_dir: env("ICTL_DDI_DIR").map(PathBuf::from),
+ anisette_url: env("ICTL_ANISETTE_URL"),
+ screen_fallback,
+ resign_min: Duration::from_secs(env_num("RESIGN_MIN_DAYS", 2u64) * 86400),
+ resign_check: Duration::from_secs(env_num("RESIGN_CHECK_HOURS", 6u64) * 3600),
+ session_check: Duration::from_secs(24 * 3600),
+ offline_alert: Duration::from_secs(env_num("OFFLINE_ALERT_MIN", 10u64) * 60),
+ notify: NotifyConfig {
+ tg_bot_token: env("TG_BOT_TOKEN"),
+ tg_chat_id: env("TG_CHAT_ID"),
+ bark_server: env("BARK_SERVER").unwrap_or_else(|| "https://api.day.app".into()),
+ bark_key: env("BARK_KEY"),
+ },
+ }
+ }
+
+ pub fn logs(&self) -> PathBuf {
+ self.data_dir.join("logs")
+ }
+ pub fn account_dir(&self) -> PathBuf {
+ self.data_dir.join("account")
+ }
+ pub fn wda_dir(&self) -> PathBuf {
+ self.data_dir.join("wda")
+ }
+ pub fn wda_signed(&self) -> PathBuf {
+ self.wda_dir().join("WDA-signed.ipa")
+ }
+ pub fn ddi_cache(&self) -> PathBuf {
+ self.ddi_dir.clone().unwrap_or_else(|| self.data_dir.join("ddi"))
+ }
+ pub fn passcode_file(&self) -> PathBuf {
+ self.data_dir.join("secrets/passcode")
+ }
+ pub fn unlock_disabled_flag(&self) -> PathBuf {
+ self.logs().join("UNLOCK-DISABLED")
+ }
+ pub fn state_file(&self) -> PathBuf {
+ self.data_dir.join("state.json")
+ }
+
+ /// 建好数据目录并收紧权限:配对记录、账号私钥、锁屏密码都在里面
+ pub fn prepare_dirs(&self) -> std::io::Result<()> {
+ use std::os::unix::fs::PermissionsExt;
+ for d in ["lockdown", "account", "wda", "ddi", "secrets", "logs"] {
+ std::fs::create_dir_all(self.data_dir.join(d))?;
+ }
+ for d in ["", "lockdown", "account", "secrets"] {
+ std::fs::set_permissions(self.data_dir.join(d), std::fs::Permissions::from_mode(0o700))?;
+ }
+ Ok(())
+ }
+}
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
new file mode 100644
index 0000000..97588ca
--- /dev/null
+++ b/crates/ictl-daemon/src/core.rs
@@ -0,0 +1,885 @@
+//! 守护进程核心:唯一持有设备的进程。每 10 秒跑一次状态机,同时处理控制接口的请求。
+//!
+//! 所有设备操作都在同一把锁下串行执行:HID 会话、WDA 会话只能有一个持有者;
+//! 也因此不会出现 toolkit 那种「长请求期间被巡检误判 WDA 挂了」的问题。
+
+use std::collections::HashMap;
+use std::path::Path;
+use std::sync::Arc;
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+use base64::Engine;
+use ictl_device::{AppInfo, Button, Device, DeviceError, DeviceInfo, HidSession, ScreenSize, Tunnel, apps};
+use ictl_unlock::{UnlockConfig, UnlockError};
+use ictl_wda::{WdaClient, WdaError, WdaRunner, elements, http::DeviceTransport, swipe_steps};
+use serde::{Deserialize, Serialize};
+use tokio::sync::Mutex;
+
+use crate::config::Config;
+use crate::eventlog::EventLog;
+use crate::imaging::{self, fmt_g};
+use crate::machine::{Backoff, DeviceState, Misses, MuxWatch};
+use crate::notify::{self, Dedup, Event};
+use crate::protocol::{Request, Response};
+
+pub const TICK: Duration = Duration::from_secs(10);
+const WDA_START_TIMEOUT: Duration = Duration::from_secs(60);
+const SYSFS_USB: &str = "/sys/bus/usb/devices";
+
+/// 持久化到 `state.json` 的状态(不含秘密)
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct Persisted {
+ pub team_id: Option<String>,
+ pub wda_bundle: Option<String>,
+ /// 描述文件到期时间(Unix 秒)
+ pub profile_expires: Option<u64>,
+ pub screen: Option<ScreenSize>,
+ pub last_resign: Option<String>,
+}
+
+impl Persisted {
+ pub fn load(path: &Path) -> Self {
+ std::fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
+ }
+
+ fn save(&self, path: &Path) {
+ let tmp = path.with_extension("json.tmp");
+ let r = std::fs::write(&tmp, serde_json::to_vec_pretty(self).unwrap_or_default()).and_then(|_| std::fs::rename(&tmp, path));
+ if let Err(e) = r {
+ tracing::warn!("保存 state.json 失败:{e}");
+ }
+ }
+
+ /// 描述文件还剩多久;不知道返回 None
+ pub fn profile_left(&self) -> Option<Duration> {
+ let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
+ self.profile_expires.map(|e| Duration::from_secs(e.saturating_sub(now)))
+ }
+}
+
+/// 快照:`iphone-control status` 显示
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Snapshot {
+ pub state: DeviceState,
+ pub device: Option<DeviceInfo>,
+ pub persisted: Persisted,
+ pub auto_unlock: bool,
+ pub unlock_disabled: bool,
+ pub notify_configured: bool,
+ pub log_tail: Vec<String>,
+}
+
+struct Inner {
+ persisted: Persisted,
+ state: DeviceState,
+ device: Option<Device>,
+ info: Option<DeviceInfo>,
+ tunnel: Option<Tunnel>,
+ hid: Option<HidSession>,
+ runner: Option<WdaRunner>,
+ wda: Option<WdaClient<DeviceTransport>>,
+ wda_misses: Misses,
+ backoff: Backoff,
+ mux: MuxWatch,
+ usbmuxd: Option<tokio::process::Child>,
+ offline_since: Option<Instant>,
+ dedup: Dedup,
+ next_resign: Instant,
+ next_session_check: Instant,
+ apps: HashMap<bool, Vec<AppInfo>>,
+}
+
+pub struct Daemon {
+ pub cfg: Config,
+ pub log: EventLog,
+ inner: Mutex<Inner>,
+}
+
+fn wda_down(state: &DeviceState) -> String {
+ format!("WDA 不可用({}),守护进程一般 1~2 分钟内会拉起;截图/点击/滑动/按键可照常用", state.describe())
+}
+
+impl Daemon {
+ pub fn new(cfg: Config) -> Arc<Self> {
+ let log = EventLog::new(&cfg.logs());
+ let persisted = Persisted::load(&cfg.state_file());
+ let now = Instant::now();
+ let inner = Inner {
+ persisted,
+ state: DeviceState::Absent,
+ device: None,
+ info: None,
+ tunnel: None,
+ hid: None,
+ runner: None,
+ wda: None,
+ wda_misses: Misses::default(),
+ backoff: Backoff::default(),
+ mux: MuxWatch::default(),
+ usbmuxd: None,
+ offline_since: Some(now),
+ dedup: Dedup::default(),
+ // 启动一分钟后再做第一次重签检查和会话验证,先让设备就绪
+ next_resign: now + Duration::from_secs(60),
+ next_session_check: now + Duration::from_secs(90),
+ apps: HashMap::new(),
+ };
+ Arc::new(Self { cfg, log, inner: Mutex::new(inner) })
+ }
+
+ fn unlock_cfg(&self) -> UnlockConfig {
+ UnlockConfig {
+ passcode_file: self.cfg.passcode_file(),
+ disabled_flag: self.cfg.unlock_disabled_flag(),
+ timing: Default::default(),
+ }
+ }
+
+ fn notify(&self, g: &mut Inner, e: Event) {
+ if !g.dedup.should_send(&e, Instant::now()) {
+ return;
+ }
+ let (title, body) = e.title_body();
+ self.log.log(&format!("通知:{title}"));
+ let cfg = self.cfg.notify.clone();
+ if cfg.any() {
+ tokio::spawn(async move {
+ notify::send(&cfg, &title, &body).await;
+ });
+ }
+ }
+
+ // ------------------------------------------------------------------ usbmuxd
+
+ async fn ensure_usbmuxd(&self, g: &mut Inner, restart: bool) {
+ if !self.cfg.manage_usbmuxd {
+ return;
+ }
+ let alive = g.usbmuxd.as_mut().is_some_and(|c| matches!(c.try_wait(), Ok(None)));
+ if alive && !restart {
+ return;
+ }
+ if let Some(mut c) = g.usbmuxd.take() {
+ let _ = c.kill().await;
+ }
+ let log = std::fs::OpenOptions::new().create(true).append(true).open(self.cfg.logs().join("usbmuxd.log"));
+ let mut cmd = tokio::process::Command::new(&self.cfg.usbmuxd_bin);
+ cmd.args(["-U", "root", "-f"]).kill_on_drop(true);
+ if let Ok(f) = log {
+ if let Ok(f2) = f.try_clone() {
+ cmd.stdout(f).stderr(f2);
+ }
+ }
+ match cmd.spawn() {
+ Ok(c) => {
+ g.usbmuxd = Some(c);
+ self.log.log("usbmuxd 已(重新)启动");
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ }
+ Err(e) => self.log.log(&format!("启动 usbmuxd 失败:{e}")),
+ }
+ }
+
+ // ------------------------------------------------------------------ 状态机
+
+ fn drop_session(&self, g: &mut Inner) {
+ if let Some(r) = g.runner.take() {
+ r.stop();
+ }
+ g.wda = None;
+ g.hid = None;
+ g.tunnel = None;
+ g.wda_misses.reset();
+ }
+
+ fn set_state(&self, g: &mut Inner, s: DeviceState) {
+ if g.state != s {
+ self.log.log(&format!("状态:{}", s.describe()));
+ g.state = s;
+ }
+ }
+
+ pub async fn tick(&self) {
+ let mut g = self.inner.lock().await;
+ let g = &mut *g;
+ self.ensure_usbmuxd(g, false).await;
+
+ let devices = ictl_device::list_devices().await.unwrap_or_default();
+ let target = match &self.cfg.udid {
+ Some(u) => devices.into_iter().find(|d| &d.udid == u),
+ None => devices.into_iter().next(),
+ };
+ let usb_present = ictl_device::apple_usb_present(Path::new(SYSFS_USB));
+ if g.mux.observe(usb_present, target.is_some()) {
+ self.log.log("USB 上有 Apple 设备但 usbmuxd 看不到,重启 usbmuxd");
+ self.ensure_usbmuxd(g, true).await;
+ }
+
+ match target {
+ None => self.offline(g),
+ Some(d) => self.online(g, &d.udid).await,
+ }
+
+ let now = Instant::now();
+ if now >= g.next_resign {
+ g.next_resign = now + self.cfg.resign_check;
+ if g.device.is_some() && g.persisted.wda_bundle.is_some() {
+ if let Err(e) = self.resign(g, false).await {
+ self.notify(g, Event::ResignFailed(e));
+ }
+ }
+ }
+ if now >= g.next_session_check {
+ g.next_session_check = now + self.cfg.session_check;
+ self.check_session(g).await;
+ }
+ }
+
+ fn offline(&self, g: &mut Inner) {
+ let now = Instant::now();
+ if g.device.take().is_some() {
+ self.log.log("手机离线");
+ self.drop_session(g);
+ g.offline_since = Some(now);
+ g.apps.clear();
+ }
+ self.set_state(g, DeviceState::Absent);
+ let since = *g.offline_since.get_or_insert(now);
+ let alert = self.cfg.offline_alert;
+ if !alert.is_zero() && now.duration_since(since) >= alert {
+ self.notify(g, Event::DeviceOffline { minutes: alert.as_secs() / 60 });
+ }
+ }
+
+ async fn online(&self, g: &mut Inner, udid: &str) {
+ if g.device.as_ref().map(|d| d.udid.as_str()) != Some(udid) {
+ self.drop_session(g);
+ match Device::find(Some(udid)).await {
+ Ok(d) => {
+ g.info = d.info().await.ok();
+ let model = g.info.as_ref().map(|i| format!(" {} iOS {}", i.product_type, i.product_version)).unwrap_or_default();
+ self.log.log(&format!("手机在线{model}"));
+ g.device = Some(d);
+ }
+ Err(e) => {
+ self.log.log(&format!("打开设备失败:{e}"));
+ return;
+ }
+ }
+ g.backoff.reset();
+ if let Some(since) = g.offline_since.take()
+ && g.dedup.was_sent("offline")
+ {
+ g.dedup.clear("offline");
+ self.notify(g, Event::DeviceOnline { minutes: since.elapsed().as_secs() / 60 });
+ }
+ }
+ let device = g.device.clone().expect("刚设置过");
+
+ if !device.paired().await.unwrap_or(false) {
+ return self.set_state(g, DeviceState::NeedsTrust);
+ }
+ if g.state != DeviceState::Ready && !device.developer_mode_enabled().await.unwrap_or(true) {
+ return self.set_state(g, DeviceState::DeveloperModeOff);
+ }
+ let Some(bundle) = g.persisted.wda_bundle.clone() else {
+ return self.set_state(g, DeviceState::NeedsSigning);
+ };
+
+ // WDA 健康:本进程的 runner 还活着,且 /status ready
+ let runner_alive = g.runner.as_ref().is_some_and(|r| r.alive());
+ let ready = match (&g.wda, runner_alive) {
+ (Some(w), true) => w.ready().await.unwrap_or(false),
+ _ => false,
+ };
+ if ready {
+ g.wda_misses.reset();
+ if g.state != DeviceState::Ready {
+ if g.state == DeviceState::NeedsAutomationPin || g.dedup.was_sent("pin") {
+ g.dedup.clear("pin");
+ self.notify(g, Event::WdaRecovered);
+ }
+ self.set_state(g, DeviceState::Ready);
+ g.backoff.reset();
+ if let Some(w) = g.wda.as_mut()
+ && let Ok(s) = w.screen_size().await
+ {
+ g.persisted.screen = Some(s);
+ g.persisted.save(&self.cfg.state_file());
+ }
+ }
+ return;
+ }
+ if runner_alive && !g.wda_misses.hit() {
+ return;
+ }
+ if g.runner.is_some() {
+ self.log.log("WDA 不可用");
+ if let Some(r) = g.runner.take() {
+ r.stop();
+ }
+ g.wda = None;
+ }
+ g.wda_misses.reset();
+ if !g.backoff.ready(Instant::now()) {
+ return;
+ }
+ self.start_wda(g, &device, &bundle).await;
+ }
+
+ async fn ensure_tunnel<'a>(&self, g: &'a mut Inner, device: &Device) -> Result<&'a mut Tunnel, DeviceError> {
+ if g.tunnel.is_none() {
+ g.tunnel = Some(device.open_tunnel().await?);
+ }
+ Ok(g.tunnel.as_mut().expect("刚建好"))
+ }
+
+ async fn start_wda(&self, g: &mut Inner, device: &Device, bundle: &str) {
+ self.set_state(g, DeviceState::WdaStarting { last_error: None });
+ // 手机重启后开发者镜像会掉;已挂载时只是一次查询
+ let ddi_cache = self.cfg.ddi_cache();
+ let ddi_url = self.cfg.ddi_url.clone();
+ let ddi: Result<Option<String>, DeviceError> = async {
+ let t = self.ensure_tunnel(g, device).await?;
+ if t.ddi_mounted().await?.is_some() {
+ return Ok(None);
+ }
+ let dir = ictl_device::ddi::ensure_cache(&ddi_cache, &ddi_url).await?;
+ Ok(Some(t.mount_ddi(&dir).await?))
+ }
+ .await;
+ match ddi {
+ Ok(Some(v)) => self.log.log(&format!("开发者镜像已挂载 {v}")),
+ Ok(None) => {}
+ Err(DeviceError::PasswordProtected) => {
+ g.tunnel = None;
+ return self.set_state(g, DeviceState::NeedsUnlock);
+ }
+ Err(e) => {
+ g.tunnel = None;
+ g.backoff.failed(Instant::now());
+ return self.set_state(g, DeviceState::WdaStarting { last_error: Some(format!("开发者镜像:{e}")) });
+ }
+ }
+
+ self.log.log("启动 WDA");
+ match WdaRunner::start(device.provider(), bundle, WDA_START_TIMEOUT).await {
+ Ok((runner, client)) => {
+ g.runner = Some(runner);
+ g.wda = Some(client);
+ }
+ Err(WdaError::NeedsAutomationPin) => {
+ g.backoff.waiting_for_pin(Instant::now());
+ self.set_state(g, DeviceState::NeedsAutomationPin);
+ self.notify(g, Event::NeedsAutomationPin);
+ }
+ Err(e) => {
+ g.backoff.failed(Instant::now());
+ self.log.log(&format!("WDA 启动失败:{e}"));
+ self.set_state(g, DeviceState::WdaStarting { last_error: Some(e.to_string()) });
+ }
+ }
+ }
+
+ // ------------------------------------------------------------------ 重签与会话
+
+ fn account(&self) -> ictl_sign::AccountDir {
+ ictl_sign::AccountDir { dir: self.cfg.account_dir(), anisette_url: self.cfg.anisette_url.clone() }
+ }
+
+ async fn check_session(&self, g: &mut Inner) {
+ match self.account().session().await {
+ Ok(_) => g.dedup.clear("session"),
+ Err(ictl_sign::SignError::NotLoggedIn) => {}
+ Err(e) => {
+ self.log.log(&format!("Apple ID 会话检查失败:{e}"));
+ self.notify(g, Event::SessionExpired(e.to_string()));
+ }
+ }
+ }
+
+ async fn resign(&self, g: &mut Inner, force: bool) -> Result<String, String> {
+ if !force
+ && g.persisted.wda_bundle.is_some()
+ && let Some(left) = g.persisted.profile_left()
+ && left > self.cfg.resign_min
+ {
+ return Ok(format!("描述文件还剩 {} 小时,无需重签", left.as_secs() / 3600));
+ }
+ let device = g.device.clone().ok_or("手机未连接")?;
+ self.log.log("开始重签");
+ let account = self.account();
+ let name = g.info.as_ref().map(|i| i.name.clone()).filter(|n| !n.is_empty()).unwrap_or_else(|| "iphone-control".into());
+ let (wda_dir, unsigned, signed_path) = (self.cfg.wda_dir(), self.cfg.wda_unsigned.clone(), self.cfg.wda_signed());
+ // plume_core 的签名 future 不是 Send(持有 &mut dyn FnMut 和非 Send 的私钥),放到阻塞线程里 block_on
+ let r: Result<ictl_sign::Signed, String> = tokio::task::spawn_blocking(move || {
+ tokio::runtime::Handle::current().block_on(async move {
+ let session = account.session().await.map_err(|e| e.to_string())?;
+ session.ensure_device(&device.udid, &name).await.map_err(|e| e.to_string())?;
+ std::fs::create_dir_all(&wda_dir).map_err(|e| e.to_string())?;
+ let tmp = wda_dir.join("WDA-signing.ipa");
+ let signed = session.sign_ipa(&unsigned, &tmp, &device.udid).await.map_err(|e| e.to_string())?;
+ device.install(&tmp).await.map_err(|e| format!("安装到手机失败(手机锁屏?):{e}"))?;
+ std::fs::rename(&tmp, &signed_path).map_err(|e| e.to_string())?;
+ Ok(signed)
+ })
+ })
+ .await
+ .unwrap_or_else(|e| Err(format!("签名任务异常退出:{e}")));
+ match r {
+ Ok(s) => {
+ let exp = s.profile.expires.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
+ g.persisted.team_id = Some(s.team_id);
+ g.persisted.wda_bundle = Some(s.bundle_id);
+ g.persisted.profile_expires = Some(exp);
+ g.persisted.last_resign = Some(format!("{} 成功", crate::eventlog::timestamp()));
+ g.persisted.save(&self.cfg.state_file());
+ // 新包装上后旧的 runner 会失效,下一轮巡检重新拉起
+ self.drop_session(g);
+ g.backoff.reset();
+ g.dedup.clear("resign");
+ let msg = format!("重签完成,新描述文件到期 {} UTC", crate::eventlog::format_utc(exp));
+ self.log.log(&msg);
+ Ok(msg)
+ }
+ Err(e) => {
+ g.persisted.last_resign = Some(format!("{} 失败:{e}", crate::eventlog::timestamp()));
+ g.persisted.save(&self.cfg.state_file());
+ self.log.log(&format!("重签失败:{e}"));
+ Err(e)
+ }
+ }
+ }
+
+ // ------------------------------------------------------------------ 请求处理
+
+ pub async fn handle(&self, req: Request) -> Response {
+ let mut g = self.inner.lock().await;
+ let g = &mut *g;
+ let r = match req {
+ Request::Status => Ok(self.status_text(g).await),
+ Request::Screenshot { region } => return self.screenshot(g, region).await.unwrap_or_else(Response::error),
+ Request::ListElements { filter, limit } => self.list_elements(g, &filter, limit).await,
+ Request::Tap { x, y } => self.tap(g, x, y).await,
+ Request::TapElement { text, index } => self.tap_element(g, &text, index).await,
+ Request::LongPress { x, y, seconds } => self.long_press(g, x, y, seconds).await,
+ Request::Swipe { from, to, seconds } => self.swipe(g, from, to, seconds).await,
+ Request::TypeText { text, submit } => self.type_text(g, &text, submit).await,
+ Request::PressButton { button } => self.press_button(g, &button).await,
+ Request::ListApps { include_system } => self.list_apps(g, include_system).await.map(|a| {
+ a.iter().map(|a| format!("{}\t{}", a.name, a.bundle_id)).collect::<Vec<_>>().join("\n")
+ }),
+ Request::LaunchApp { app } => self.launch_app(g, &app).await,
+ Request::TerminateApp { app } => self.terminate_app(g, &app).await,
+ Request::OpenUrl { url } => self.open_url(g, &url).await,
+ Request::Daemon => Ok(serde_json::to_string_pretty(&self.snapshot(g)).unwrap_or_default()),
+ Request::Doctor => Ok(self.doctor(g).await),
+ Request::Resign { force } => self.resign(g, force).await,
+ Request::UnlockReset => {
+ let _ = std::fs::remove_file(self.cfg.unlock_disabled_flag());
+ g.dedup.clear("unlock");
+ Ok("已恢复自动解锁".into())
+ }
+ };
+ r.map(Response::text).unwrap_or_else(Response::error)
+ }
+
+ fn snapshot(&self, g: &Inner) -> Snapshot {
+ let unlock = self.unlock_cfg();
+ Snapshot {
+ state: g.state.clone(),
+ device: g.info.clone(),
+ persisted: g.persisted.clone(),
+ auto_unlock: unlock.enabled(),
+ unlock_disabled: unlock.disabled_by_failure(),
+ notify_configured: self.cfg.notify.any(),
+ log_tail: self.log.tail(15),
+ }
+ }
+
+ /// WDA 可用就返回客户端(本进程 runner 存活)
+ fn wda<'a>(&self, g: &'a mut Inner) -> Option<&'a mut WdaClient<DeviceTransport>> {
+ if g.runner.as_ref().is_some_and(|r| r.alive()) { g.wda.as_mut() } else { None }
+ }
+
+ fn require_wda<'a>(&self, g: &'a mut Inner) -> Result<&'a mut WdaClient<DeviceTransport>, String> {
+ let msg = wda_down(&g.state);
+ self.wda(g).ok_or(msg)
+ }
+
+ /// 配置了密码就在锁屏时自动解锁;没配置而手机锁着则报错(与 toolkit 一致)
+ async fn ensure_unlocked(&self, g: &mut Inner) -> Result<(), String> {
+ let cfg = self.unlock_cfg();
+ let Some(wda) = self.wda(g) else { return Ok(()) };
+ match ictl_unlock::ensure_unlocked(wda, &cfg).await {
+ Ok(_) => Ok(()),
+ Err(UnlockError::WrongPasscode) => {
+ self.notify(g, Event::UnlockDisabled);
+ Err(format!("{},已推送通知", UnlockError::WrongPasscode))
+ }
+ Err(e) => Err(e.to_string()),
+ }
+ }
+
+ async fn screen(&self, g: &mut Inner) -> Result<ScreenSize, String> {
+ if let Some(w) = self.wda(g)
+ && let Ok(s) = w.screen_size().await
+ {
+ return Ok(s);
+ }
+ g.persisted
+ .screen
+ .or(self.cfg.screen_fallback)
+ .ok_or_else(|| "WDA 不可用,也不知道屏幕尺寸;等 WDA 起来一次,或在 .env 里设 SCREEN_W/SCREEN_H".into())
+ }
+
+ /// HID 会话(WDA 不可用时的后备路线)。出错时丢掉会话和隧道,下次重建
+ async fn hid<'a>(&self, g: &'a mut Inner) -> Result<&'a mut HidSession, String> {
+ if g.hid.is_none() {
+ let screen = self.screen(g).await?;
+ let device = g.device.clone().ok_or("手机未连接")?;
+ let t = self.ensure_tunnel(g, &device).await.map_err(|e| format!("HID 后备路线不可用:{e}"))?;
+ match t.hid(screen).await {
+ Ok(h) => g.hid = Some(h),
+ Err(e) => {
+ g.tunnel = None;
+ return Err(format!("HID 后备路线不可用:{e}"));
+ }
+ }
+ }
+ Ok(g.hid.as_mut().expect("刚建好"))
+ }
+
+ async fn hid_do<F>(&self, g: &mut Inner, f: F) -> Result<(), String>
+ where
+ F: for<'h> FnOnce(&'h mut HidSession) -> std::pin::Pin<Box<dyn std::future::Future<Output = ictl_device::Result<()>> + Send + 'h>>,
+ {
+ let r = f(self.hid(g).await?).await;
+ if let Err(e) = r {
+ g.hid = None;
+ g.tunnel = None;
+ return Err(format!("HID 命令失败: {e}"));
+ }
+ Ok(())
+ }
+
+ async fn status_text(&self, g: &mut Inner) -> String {
+ let daemon_line = format!("守护进程: {}", g.state.describe());
+ let unlock = self.unlock_cfg();
+ let Some(w) = self.wda(g) else {
+ return format!("{}\n读界面元素、按名字点击、启动 App、输入中文要等 WDA 恢复\n{daemon_line}", wda_down(&g.state));
+ };
+ let r: Result<String, WdaError> = async {
+ let ready = w.ready().await?;
+ let app = w.active_app().await?;
+ let s = w.screen_size().await?;
+ let mut lock = if !w.locked().await? {
+ "未锁屏".to_owned()
+ } else if unlock.enabled() {
+ "已锁屏(操作时会自动解锁)".to_owned()
+ } else {
+ "已锁屏(未配置自动解锁,需要人工解锁)".to_owned()
+ };
+ if unlock.disabled_by_failure() {
+ lock += ";自动解锁已停用";
+ }
+ let ready = if ready { "True" } else { "False" };
+ Ok(format!("WDA 就绪: {ready}\n锁屏: {lock}\n前台 App: {app}\n屏幕: {}x{} 点", fmt_g(s.width), fmt_g(s.height)))
+ }
+ .await;
+ match r {
+ Ok(t) => format!("{t}\n{daemon_line}"),
+ Err(e) => format!("{e}\n读界面元素、按名字点击、启动 App、输入中文要等 WDA 恢复\n{daemon_line}"),
+ }
+ }
+
+ async fn screenshot(&self, g: &mut Inner, region: Option<(f64, f64, f64, f64)>) -> Result<Response, String> {
+ self.ensure_unlocked(g).await?;
+ let wda_png = match self.wda(g) {
+ Some(w) => w.screenshot_png().await.ok(),
+ None => None,
+ };
+ let (png, via) = match wda_png {
+ Some(p) => (p, "WDA"),
+ None => {
+ let device = g.device.clone().ok_or("手机未连接")?;
+ let t = self.ensure_tunnel(g, &device).await.map_err(|e| format!("HID 命令失败: {e}"))?;
+ match t.screenshot_png().await {
+ Ok(p) => (p, "HID"),
+ Err(e) => {
+ g.tunnel = None;
+ g.hid = None;
+ return Err(format!("HID 命令失败: {e}"));
+ }
+ }
+ }
+ };
+ let screen = self.screen(g).await?;
+ let (jpeg, caption) = match region {
+ None => imaging::full_screen(&png, screen, via)?,
+ Some(r) => imaging::region(&png, screen, r, via)?,
+ };
+ Ok(Response::Image { jpeg_base64: base64::engine::general_purpose::STANDARD.encode(jpeg), caption })
+ }
+
+ async fn list_elements(&self, g: &mut Inner, filter: &str, limit: usize) -> Result<String, String> {
+ self.ensure_unlocked(g).await?;
+ let els = self.require_wda(g)?.elements().await.map_err(|e| e.to_string())?;
+ let shown: Vec<&elements::Element> = if filter.is_empty() { els.iter().collect() } else { elements::filter(&els, filter) };
+ let lines: Vec<_> = shown.iter().take(limit).map(|e| e.describe()).collect();
+ let more = if shown.len() > limit {
+ format!("\n……另有 {} 个未列出,可用 filter 缩小范围", shown.len() - limit)
+ } else {
+ String::new()
+ };
+ Ok(if lines.is_empty() { "没有找到带文字的元素".into() } else { lines.join("\n") } + &more)
+ }
+
+ async fn tap(&self, g: &mut Inner, x: f64, y: f64) -> Result<String, String> {
+ self.ensure_unlocked(g).await?;
+ let pos = format!("({},{})", fmt_g(x), fmt_g(y));
+ if let Some(w) = self.wda(g) {
+ match w.tap(x, y).await {
+ Ok(()) => return Ok(format!("已点击 {pos}")),
+ Err(WdaError::Unavailable(_)) => {}
+ Err(e) => return Err(e.to_string()),
+ }
+ }
+ self.hid_do(g, |h| Box::pin(h.tap(x, y))).await?;
+ Ok(format!("已点击 {pos}(经 HID)"))
+ }
+
+ async fn tap_element(&self, g: &mut Inner, text: &str, index: usize) -> Result<String, String> {
+ self.ensure_unlocked(g).await?;
+ let w = self.require_wda(g)?;
+ let els = w.elements().await.map_err(|e| e.to_string())?;
+ let matches = elements::find(&els, text);
+ if matches.is_empty() {
+ return Ok(format!("没找到包含 \"{text}\" 的元素,先用 iphone_list_elements 或截图看看屏幕"));
+ }
+ if index >= matches.len() {
+ let list: Vec<_> = matches.iter().map(|e| e.describe()).collect();
+ return Ok(format!("只匹配到 {} 个:\n{}", matches.len(), list.join("\n")));
+ }
+ let e = matches[index];
+ w.tap(e.center.0 as f64, e.center.1 as f64).await.map_err(|e| e.to_string())?;
+ let note = if matches.len() > 1 { format!("(共匹配 {} 个,点的是第 {index} 个)", matches.len()) } else { String::new() };
+ Ok(format!("已点击 {}{note}", e.describe()))
+ }
+
+ async fn long_press(&self, g: &mut Inner, x: f64, y: f64, seconds: f64) -> Result<String, String> {
+ self.ensure_unlocked(g).await?;
+ self.require_wda(g)?.touch_and_hold(x, y, seconds).await.map_err(|e| e.to_string())?;
+ Ok(format!("已长按 ({},{}) {} 秒", fmt_g(x), fmt_g(y), fmt_g(seconds)))
+ }
+
+ async fn swipe(&self, g: &mut Inner, from: (f64, f64), to: (f64, f64), seconds: f64) -> Result<String, String> {
+ self.ensure_unlocked(g).await?;
+ let desc = format!("({},{}) → ({},{})", fmt_g(from.0), fmt_g(from.1), fmt_g(to.0), fmt_g(to.1));
+ if let Some(w) = self.wda(g) {
+ match w.actions(&swipe_steps(from, to, (seconds * 1000.0) as u64)).await {
+ Ok(()) => return Ok(format!("已滑动 {desc}")),
+ Err(WdaError::Unavailable(_)) => {}
+ Err(e) => return Err(e.to_string()),
+ }
+ }
+ self.hid_do(g, |h| Box::pin(h.drag(from, to, seconds))).await?;
+ Ok(format!("已滑动 {desc}(经 HID)"))
+ }
+
+ async fn type_text(&self, g: &mut Inner, text: &str, submit: bool) -> Result<String, String> {
+ self.ensure_unlocked(g).await?;
+ let payload = if submit { format!("{text}\n") } else { text.to_owned() };
+ let n = text.chars().count();
+ if let Some(w) = self.wda(g) {
+ match w.keys(&payload).await {
+ Ok(()) => return Ok(format!("已输入 {n} 个字符{}", if submit { ",并按了回车" } else { "" })),
+ Err(WdaError::Unavailable(_)) => {}
+ Err(e) => return Err(e.to_string()),
+ }
+ }
+ if !payload.is_ascii() {
+ return Err("WDA 不可用,HID 只能输入英文和符号".into());
+ }
+ let p = payload.clone();
+ self.hid_do(g, move |h| Box::pin(async move { h.type_ascii(&p).await })).await?;
+ Ok(format!("已输入 {n} 个字符(经 HID)"))
+ }
+
+ async fn press_button(&self, g: &mut Inner, button: &str) -> Result<String, String> {
+ if button == "lock" {
+ if let Some(w) = self.wda(g)
+ && w.lock().await.is_ok()
+ {
+ return Ok("已锁屏".into());
+ }
+ self.hid_do(g, |h| Box::pin(h.press(Button::Lock))).await?;
+ return Ok("已锁屏".into());
+ }
+ let (wda_name, hid_button) = match button {
+ "home" => ("home", Button::Home),
+ "volume_up" => ("volumeUp", Button::VolumeUp),
+ "volume_down" => ("volumeDown", Button::VolumeDown),
+ _ => return Err("button 只能是 home / volume_up / volume_down / lock".into()),
+ };
+ self.ensure_unlocked(g).await?;
+ if let Some(w) = self.wda(g) {
+ match w.press_button(wda_name).await {
+ Ok(()) => return Ok(format!("已按 {button}")),
+ Err(WdaError::Unavailable(_)) => {}
+ Err(e) => return Err(e.to_string()),
+ }
+ }
+ self.hid_do(g, |h| Box::pin(h.press(hid_button))).await?;
+ Ok(format!("已按 {button}"))
+ }
+
+ async fn list_apps(&self, g: &mut Inner, include_system: bool) -> Result<Vec<AppInfo>, String> {
+ if let Some(a) = g.apps.get(&include_system) {
+ return Ok(a.clone());
+ }
+ let device = g.device.clone().ok_or("手机未连接")?;
+ let a = device.list_apps(include_system).await.map_err(|e| e.to_string())?;
+ g.apps.insert(include_system, a.clone());
+ Ok(a)
+ }
+
+ async fn resolve_app(&self, g: &mut Inner, app: &str) -> Result<String, String> {
+ if apps::looks_like_bundle_id(app) {
+ return Ok(app.to_owned());
+ }
+ // 先只查用户 App;列系统 App 要好几秒,只在找不到时才去取
+ let user = self.list_apps(g, false).await?;
+ if let Some(b) = user.iter().find(|a| a.name == app) {
+ return Ok(b.bundle_id.clone());
+ }
+ let system = self.list_apps(g, true).await?;
+ apps::resolve(app, [&user[..], &system[..]]).ok_or_else(|| format!("找不到名为 \"{app}\" 的 App,用 iphone_list_apps 查看"))
+ }
+
+ async fn launch_app(&self, g: &mut Inner, app: &str) -> Result<String, String> {
+ let bid = self.resolve_app(g, app).await?;
+ self.ensure_unlocked(g).await?;
+ self.require_wda(g)?.launch_app(&bid).await.map_err(|e| e.to_string())?;
+ Ok(format!("已启动 {bid}"))
+ }
+
+ async fn terminate_app(&self, g: &mut Inner, app: &str) -> Result<String, String> {
+ let bid = self.resolve_app(g, app).await?;
+ self.ensure_unlocked(g).await?;
+ self.require_wda(g)?.terminate_app(&bid).await.map_err(|e| e.to_string())?;
+ Ok(format!("已结束 {bid}"))
+ }
+
+ async fn open_url(&self, g: &mut Inner, url: &str) -> Result<String, String> {
+ self.ensure_unlocked(g).await?;
+ self.require_wda(g)?.open_url(url).await.map_err(|e| e.to_string())?;
+ Ok(format!("已打开 {url}"))
+ }
+
+ // ------------------------------------------------------------------ 诊断
+
+ async fn doctor(&self, g: &mut Inner) -> String {
+ let mut out: Vec<String> = Vec::new();
+ let mut fails = 0;
+
+ out.push("== 设备连接".into());
+ match ictl_device::list_devices().await {
+ Ok(_) => out.push("✅ usbmuxd 在运行".into()),
+ Err(e) => {
+ out.push(format!("❌ 连不上 usbmuxd:{e}\n → 容器里由守护进程自动拉起;宿主机部署请启动 usbmuxd 服务"));
+ fails += 1;
+ }
+ }
+ let usb = ictl_device::apple_usb_present(Path::new(SYSFS_USB));
+ if usb {
+ out.push("✅ USB 上有 Apple 设备".into());
+ } else {
+ out.push("❌ USB 上没有 Apple 设备\n → 插好数据线;用 USB-C 转接头的话换一根试试".into());
+ fails += 1;
+ }
+ match (&g.device, &g.info) {
+ (Some(d), info) => {
+ let i = info.clone().unwrap_or_default();
+ out.push(format!("✅ 已连接 {} {} iOS {}", d.udid, i.product_type, i.product_version));
+ let major = i.major_version();
+ if major > 0 && major < 17 {
+ out.push("⚠️ iOS 低于 17 未在此版本测试过".into());
+ } else if major > 0 && major < 27 {
+ out.push("⚠️ iOS 低于 27 HID 后备路线(免签名截图/点击)不可用,只能走 WDA".into());
+ }
+ }
+ (None, _) => {
+ out.push("❌ 守护进程看不到手机\n → 等 30 秒,会自动重启 usbmuxd;仍不行就重启容器".into());
+ fails += 1;
+ }
+ }
+ out.push(format!(" 状态:{}", g.state.describe()));
+
+ out.push("== Apple ID 与签名".into());
+ match self.account().selected_email().await {
+ Ok(_) => out.push("✅ 已登录 Apple ID".into()),
+ Err(_) => {
+ out.push("❌ 没有登录 Apple ID\n → iphone-control login".into());
+ fails += 1;
+ }
+ }
+ match (&g.persisted.wda_bundle, g.persisted.profile_left()) {
+ (Some(b), Some(left)) => {
+ out.push(format!("✅ WDA 已签名 {b}"));
+ if left.is_zero() {
+ out.push("❌ 描述文件已过期\n → iphone-control resign --force".into());
+ fails += 1;
+ } else if left < Duration::from_secs(48 * 3600) {
+ out.push(format!("⚠️ 描述文件只剩 {} 小时 守护进程会自动重签", left.as_secs() / 3600));
+ } else {
+ out.push(format!("✅ 描述文件有效 还剩 {} 天", left.as_secs() / 86400));
+ }
+ }
+ _ => {
+ out.push("❌ WDA 还没签名安装\n → iphone-control sign".into());
+ fails += 1;
+ }
+ }
+ if let Some(r) = &g.persisted.last_resign {
+ out.push(format!(" 上次重签:{r}"));
+ }
+
+ out.push("== WDA".into());
+ match self.wda(g) {
+ Some(w) if w.ready().await.unwrap_or(false) => out.push("✅ WDA 就绪(经 usbmuxd 直连,本机不监听端口)".into()),
+ _ => {
+ out.push(format!("❌ WDA 不可用:{}", g.state.describe()));
+ fails += 1;
+ }
+ }
+
+ out.push("== 附加功能".into());
+ if self.cfg.notify.any() {
+ out.push("✅ 通知已配置".into());
+ } else {
+ out.push("⚠️ 没有配置通知 重签失败、手机离线、需要输密码时不会提醒你".into());
+ }
+ let unlock = self.unlock_cfg();
+ if unlock.disabled_by_failure() {
+ out.push("❌ 自动解锁已停用(之前输错过)\n → 核对密码后 iphone-control unlock-reset".into());
+ fails += 1;
+ } else if unlock.enabled() {
+ out.push("✅ 自动解锁已启用".into());
+ } else {
+ out.push("⚠️ 自动解锁未启用 手机锁屏时需要人工解锁(可选:iphone-control passcode set)".into());
+ }
+ out.push(String::new());
+ out.push(if fails == 0 { "全部正常".into() } else { format!("{fails} 项需要处理") });
+ out.join("\n")
+ }
+
+ pub async fn shutdown(&self) {
+ let mut g = self.inner.lock().await;
+ self.log.log("收到停止信号,退出");
+ self.drop_session(&mut g);
+ if let Some(mut c) = g.usbmuxd.take() {
+ let _ = c.kill().await;
+ }
+ }
+}
diff --git a/crates/ictl-daemon/src/eventlog.rs b/crates/ictl-daemon/src/eventlog.rs
new file mode 100644
index 0000000..1ba4d02
--- /dev/null
+++ b/crates/ictl-daemon/src/eventlog.rs
@@ -0,0 +1,99 @@
+//! 守护进程的事件日志(`logs/daemon.log`):一行一条,带时间,超过 5MB 轮转成 `.1`。
+//! 相当于 toolkit 的 supervisor.log,`iphone-control status` 显示它的最后几行。
+
+use std::io::Write;
+use std::path::{Path, PathBuf};
+
+pub const MAX_BYTES: u64 = 5 * 1024 * 1024;
+
+#[derive(Debug, Clone)]
+pub struct EventLog {
+ path: PathBuf,
+ max: u64,
+}
+
+impl EventLog {
+ pub fn new(dir: &Path) -> Self {
+ Self { path: dir.join("daemon.log"), max: MAX_BYTES }
+ }
+
+ #[cfg(test)]
+ fn with_max(dir: &Path, max: u64) -> Self {
+ Self { path: dir.join("daemon.log"), max }
+ }
+
+ pub fn path(&self) -> &Path {
+ &self.path
+ }
+
+ pub fn log(&self, msg: &str) {
+ tracing::info!("{msg}");
+ if let Err(e) = self.append(msg) {
+ tracing::warn!("写事件日志失败:{e}");
+ }
+ }
+
+ fn append(&self, msg: &str) -> std::io::Result<()> {
+ if std::fs::metadata(&self.path).map(|m| m.len() >= self.max).unwrap_or(false) {
+ std::fs::rename(&self.path, self.path.with_extension("log.1"))?;
+ }
+ let mut f = std::fs::OpenOptions::new().create(true).append(true).open(&self.path)?;
+ writeln!(f, "{} {msg}", timestamp())
+ }
+
+ /// 最后 n 行
+ pub fn tail(&self, n: usize) -> Vec<String> {
+ let text = std::fs::read_to_string(&self.path).unwrap_or_default();
+ let lines: Vec<_> = text.lines().map(str::to_owned).collect();
+ lines[lines.len().saturating_sub(n)..].to_vec()
+ }
+}
+
+/// UTC 时间 `YYYY-MM-DD HH:MM:SS`(不引入时间库,按公历自己算)
+pub fn timestamp() -> String {
+ let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs();
+ format_utc(secs)
+}
+
+pub fn format_utc(secs: u64) -> String {
+ let (days, rem) = (secs / 86400, secs % 86400);
+ // civil_from_days(Howard Hinnant)
+ let z = days as i64 + 719468;
+ let era = z.div_euclid(146097);
+ let doe = z - era * 146097;
+ let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let d = doy - (153 * mp + 2) / 5 + 1;
+ let m = if mp < 10 { mp + 3 } else { mp - 9 };
+ let y = yoe + era * 400 + i64::from(m <= 2);
+ format!("{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}", rem / 3600, rem % 3600 / 60, rem % 60)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn utc_formatting() {
+ assert_eq!(format_utc(0), "1970-01-01 00:00:00");
+ assert_eq!(format_utc(1_793_448_000), "2026-10-31 12:00:00");
+ assert_eq!(format_utc(951_782_400), "2000-02-29 00:00:00");
+ }
+
+ #[test]
+ fn rotates_when_too_big_and_tails() {
+ let dir = std::env::temp_dir().join(format!("ictl-log-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let log = EventLog::with_max(&dir, 64);
+ for i in 0..10 {
+ log.log(&format!("第 {i} 行"));
+ }
+ assert!(dir.join("daemon.log.1").exists());
+ let tail = log.tail(5);
+ assert!(!tail.is_empty() && tail.len() <= 3, "轮转后当前文件只留最近几行:{tail:?}");
+ assert!(tail.last().unwrap().ends_with("第 9 行"));
+ assert!(std::fs::metadata(log.path()).unwrap().len() < 64 + 40);
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+}
diff --git a/crates/ictl-daemon/src/imaging.rs b/crates/ictl-daemon/src/imaging.rs
new file mode 100644
index 0000000..95dae77
--- /dev/null
+++ b/crates/ictl-daemon/src/imaging.rs
@@ -0,0 +1,175 @@
+//! 截图缩放到点坐标、区域放大。与 toolkit 的 `imaging.py` 行为和说明文字一致。
+
+use std::io::Cursor;
+
+use ictl_device::ScreenSize;
+use image::{DynamicImage, ImageFormat, codecs::jpeg::JpegEncoder, imageops::FilterType};
+
+pub const ZOOM_MIN_LONG_SIDE: f64 = 600.0;
+pub const ZOOM_MAX_LONG_SIDE: f64 = 1200.0;
+
+/// Python 的 `{:g}`:整数不带小数点,其余用最短表示
+pub fn fmt_g(v: f64) -> String {
+ format!("{v}")
+}
+
+/// Python 的 `{:.3g}`:3 位有效数字、去掉末尾的 0
+pub fn fmt_3g(v: f64) -> String {
+ if v == 0.0 {
+ return "0".into();
+ }
+ let decimals = (2 - v.abs().log10().floor() as i32).max(0) as usize;
+ let s = format!("{v:.decimals$}");
+ if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_owned() } else { s }
+}
+
+/// 截图是横的而屏幕尺寸是竖的(横屏 App),就把宽高互换
+pub fn oriented(img_w: u32, img_h: u32, screen: ScreenSize) -> (u32, u32) {
+ let (w, h) = (screen.width.round() as u32, screen.height.round() as u32);
+ if img_w > img_h && w < h { (h, w) } else { (w, h) }
+}
+
+fn decode(png: &[u8]) -> Result<DynamicImage, String> {
+ image::load_from_memory(png).map_err(|e| format!("截图解码失败:{e}"))
+}
+
+fn jpeg(img: &DynamicImage, quality: u8) -> Result<Vec<u8>, String> {
+ let mut out = Cursor::new(Vec::new());
+ img.to_rgb8()
+ .write_with_encoder(JpegEncoder::new_with_quality(&mut out, quality))
+ .map_err(|e| format!("JPEG 编码失败:{e}"))?;
+ Ok(out.into_inner())
+}
+
+/// 整屏缩放到点尺寸:图像像素即点坐标。返回 (jpeg, 说明文字)
+pub fn full_screen(png: &[u8], screen: ScreenSize, via: &str) -> Result<(Vec<u8>, String), String> {
+ let img = decode(png)?;
+ let (w, h) = oriented(img.width(), img.height(), screen);
+ let out = jpeg(&img.resize_exact(w, h, FilterType::Lanczos3), 80)?;
+ Ok((out, format!("{w}x{h} 点,图像像素即点坐标(经 {via})")))
+}
+
+/// 区域放大的几何计算(纯函数):裁剪框(原图像素)、输出尺寸、放大倍数、裁剪后的点区域
+#[derive(Debug, Clone, PartialEq)]
+pub struct ZoomPlan {
+ pub crop: (u32, u32, u32, u32),
+ pub out: (u32, u32),
+ pub zoom: f64,
+ pub region: (f64, f64, f64, f64),
+}
+
+pub fn plan_zoom(img_w: u32, img_h: u32, screen: ScreenSize, x: f64, y: f64, width: f64, height: f64) -> Result<ZoomPlan, String> {
+ let (w, h) = oriented(img_w, img_h, screen);
+ let (w, h) = (w as f64, h as f64);
+ let (x1, y1) = (x.max(0.0), y.max(0.0));
+ let (x2, y2) = ((x + width).min(w), (y + height).min(h));
+ if x2 - x1 < 1.0 || y2 - y1 < 1.0 {
+ return Err(format!("放大区域不在屏幕内(屏幕 {}x{} 点)", w, h));
+ }
+ let px = img_w as f64 / w; // 每点对应的原图像素,一般是 3
+ let (cx1, cy1) = ((x1 * px).round() as u32, (y1 * px).round() as u32);
+ let (cx2, cy2) = ((x2 * px).round() as u32, (y2 * px).round() as u32);
+ let (cw, ch) = (cx2 - cx1, cy2 - cy1);
+ let long = cw.max(ch) as f64;
+ let k = if long < ZOOM_MIN_LONG_SIDE { ZOOM_MIN_LONG_SIDE / long } else { (ZOOM_MAX_LONG_SIDE / long).min(1.0) };
+ let out = ((cw as f64 * k).round() as u32, (ch as f64 * k).round() as u32);
+ Ok(ZoomPlan { crop: (cx1, cy1, cw, ch), out, zoom: out.0 as f64 / (x2 - x1), region: (x1, y1, x2 - x1, y2 - y1) })
+}
+
+/// 从原始高清截图裁出一块并放大。返回 (jpeg, 说明文字,含坐标换算式)
+pub fn region(png: &[u8], screen: ScreenSize, rect: (f64, f64, f64, f64), via: &str) -> Result<(Vec<u8>, String), String> {
+ let img = decode(png)?;
+ let p = plan_zoom(img.width(), img.height(), screen, rect.0, rect.1, rect.2, rect.3)?;
+ let (cx, cy, cw, ch) = p.crop;
+ let mut crop = img.crop_imm(cx, cy, cw, ch);
+ if p.out != (cw, ch) {
+ crop = crop.resize_exact(p.out.0, p.out.1, FilterType::Lanczos3);
+ }
+ let (x1, y1, rw, rh) = p.region;
+ let (x, y, z) = (fmt_g(x1), fmt_g(y1), fmt_3g(p.zoom));
+ let caption = format!(
+ "区域 ({x},{y}) 起 {}x{} 点,放大 {z} 倍;图中像素 (u,v) 对应屏幕点 ({x}+u/{z}, {y}+v/{z})(经 {via})",
+ fmt_g(rw),
+ fmt_g(rh)
+ );
+ Ok((jpeg(&crop, 90)?, caption))
+}
+
+/// 读取 PNG 尺寸(不解码像素)
+pub fn png_size(png: &[u8]) -> Option<(u32, u32)> {
+ image::ImageReader::with_format(Cursor::new(png), ImageFormat::Png).into_dimensions().ok()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const SCREEN: ScreenSize = ScreenSize { width: 430.0, height: 932.0 };
+
+ fn png(w: u32, h: u32) -> Vec<u8> {
+ let mut out = Cursor::new(Vec::new());
+ image::RgbImage::from_pixel(w, h, image::Rgb([30, 60, 90])).write_to(&mut out, ImageFormat::Png).unwrap();
+ out.into_inner()
+ }
+
+ fn jpeg_size(j: &[u8]) -> (u32, u32) {
+ image::load_from_memory(j).unwrap().to_rgb8().dimensions()
+ }
+
+ #[test]
+ fn full_screen_is_scaled_to_points() {
+ let (j, cap) = full_screen(&png(1290, 2796), SCREEN, "WDA").unwrap();
+ assert_eq!(jpeg_size(&j), (430, 932));
+ assert_eq!(cap, "430x932 点,图像像素即点坐标(经 WDA)");
+ }
+
+ #[test]
+ fn landscape_screenshot_swaps_dimensions() {
+ let (j, _) = full_screen(&png(2796, 1290), SCREEN, "HID").unwrap();
+ assert_eq!(jpeg_size(&j), (932, 430));
+ }
+
+ #[test]
+ fn wide_region_is_capped_at_1200() {
+ let p = plan_zoom(1290, 2796, SCREEN, 0.0, 55.0, 430.0, 40.0).unwrap();
+ assert_eq!(p.region, (0.0, 55.0, 430.0, 40.0));
+ assert_eq!(p.out.0, 1200);
+ assert!((p.zoom - 1200.0 / 430.0).abs() < 1e-9);
+ }
+
+ #[test]
+ fn small_region_is_upscaled_to_600() {
+ let p = plan_zoom(1290, 2796, SCREEN, 115.0, 108.0, 50.0, 20.0).unwrap();
+ assert_eq!(p.out.0, 600);
+ assert!((p.zoom - 12.0).abs() < 1e-9);
+ }
+
+ #[test]
+ fn region_is_clamped_to_screen() {
+ assert_eq!(plan_zoom(1290, 2796, SCREEN, -10.0, 900.0, 100.0, 100.0).unwrap().region, (0.0, 900.0, 90.0, 32.0));
+ }
+
+ #[test]
+ fn region_outside_screen_errors() {
+ assert_eq!(plan_zoom(1290, 2796, SCREEN, 500.0, 10.0, 50.0, 50.0).unwrap_err(), "放大区域不在屏幕内(屏幕 430x932 点)");
+ }
+
+ /// 回归用例 #16:倍数保留 3 位有效数字(2 位会让右边缘差约 1.4 点)
+ #[test]
+ fn zoom_caption_uses_three_significant_digits() {
+ let (j, cap) = region(&png(1290, 2796), SCREEN, (0.0, 55.0, 430.0, 40.0), "WDA").unwrap();
+ assert_eq!(jpeg_size(&j).0, 1200);
+ assert_eq!(cap, "区域 (0,55) 起 430x40 点,放大 2.79 倍;图中像素 (u,v) 对应屏幕点 (0+u/2.79, 55+v/2.79)(经 WDA)");
+ }
+
+ #[test]
+ fn python_like_number_formatting() {
+ assert_eq!((fmt_g(215.0), fmt_g(0.3), fmt_g(10.5)), ("215".into(), "0.3".into(), "10.5".into()));
+ assert_eq!((fmt_3g(2.790697), fmt_3g(12.0), fmt_3g(3.0), fmt_3g(0.5)), ("2.79".into(), "12".into(), "3".into(), "0.5".into()));
+ }
+
+ #[test]
+ fn png_size_reads_header() {
+ assert_eq!(png_size(&png(12, 34)), Some((12, 34)));
+ }
+}
diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs
index 8e88362..0a6fd0b 100644
--- a/crates/ictl-daemon/src/lib.rs
+++ b/crates/ictl-daemon/src/lib.rs
@@ -1,64 +1,91 @@
-//! 守护进程:唯一持有设备的进程。替代 toolkit 的 supervisor.sh + resign 定时器 + notify.sh。
+//! 守护进程:唯一持有设备的进程。替代 toolkit 的 supervisor.sh + 重签定时器 + notify.sh。
//!
-//! 设备状态机(docs/architecture.md §3):
-//! Absent → Attached → Paired → Tunneling → DdiCheck → WdaStarting → Ready
-//! 以及 NeedsTrust / NeedsUnlock(BFU)/ NeedsAutomationPin 三个等人的状态。
+//! - 状态机([`machine::DeviceState`],docs/architecture.md §3)每 10 秒推进一次
+//! - usbmuxd 作为子进程看护;容器无 udev,靠 sysfs 发现漏掉的设备并重启它
+//! - 控制接口:Unix socket,每行一个 JSON([`protocol`]),MCP 和 CLI 都通过它访问设备
+pub mod config;
+pub mod core;
+pub mod eventlog;
+pub mod imaging;
+pub mod machine;
+pub mod notify;
pub mod protocol;
-use std::path::PathBuf;
-use std::time::Duration;
+use tokio::sync::oneshot;
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
-pub enum DeviceState {
- Absent,
- Attached,
- NeedsTrust,
- Paired,
- Tunneling,
- NeedsUnlock,
- DdiCheck,
- WdaStarting,
- NeedsAutomationPin,
- Ready { locked: bool },
-}
+pub use config::Config;
+pub use core::{Daemon, Snapshot};
-/// usbmuxd 看护:sysfs 有 Apple 设备但 usbmuxd 看不到,连续这么多次就重启 usbmuxd
-pub const USBMUXD_MISS_LIMIT: u32 = 3;
-pub const POLL_INTERVAL: Duration = Duration::from_secs(10);
-/// WDA 启动失败退避:60s 起翻倍,上限 300s;等自动化密码时固定 60s
-pub const WDA_BACKOFF_START: Duration = Duration::from_secs(60);
-pub const WDA_BACKOFF_MAX: Duration = Duration::from_secs(300);
-pub const AUTOMATION_PIN_RETRY: Duration = Duration::from_secs(60);
-/// 描述文件剩余少于这个就重签
-pub const RESIGN_THRESHOLD: Duration = Duration::from_secs(2 * 24 * 3600);
+/// 运行守护进程直到收到 SIGTERM / SIGINT
+pub async fn run(cfg: Config) -> anyhow::Result<()> {
+ cfg.prepare_dirs()?;
+ let socket = cfg.socket.clone();
+ if let Some(dir) = socket.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
+ let _ = std::fs::remove_file(&socket);
+ let listener = tokio::net::UnixListener::bind(&socket)?;
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))?;
+ }
-pub struct Config {
- pub data_dir: PathBuf,
- pub udid: Option<String>,
- pub wda_bundle_id: Option<String>,
- pub auto_unlock: bool,
-}
+ let daemon = Daemon::new(cfg);
+ daemon.log.log("守护进程启动");
-/// 需要推送的事件;同一事件去重,恢复时推送一次
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum Event {
- ResignFailed(String),
- SessionExpired,
- NeedsAutomationPin,
- WdaRecovered,
- UnlockDisabled,
- DeviceOffline,
- DeviceOnline,
-}
+ // 连接任务只负责收发,请求经通道交给主循环串行处理:设备只能有一个持有者,
+ // 而且处理设备的 future 不必是 Send(plume_core / 泛型 async 的 Send 推断有限制)
+ let (tx, mut rx) = tokio::sync::mpsc::channel::<(protocol::Request, oneshot::Sender<protocol::Response>)>(16);
+ let server = tokio::spawn(async move {
+ loop {
+ match listener.accept().await {
+ Ok((stream, _)) => {
+ tokio::spawn(serve_conn(tx.clone(), stream));
+ }
+ Err(e) => tracing::warn!("控制接口 accept 失败:{e}"),
+ }
+ }
+ });
-pub trait Notifier: Send + Sync {
- fn notify(&self, event: &Event) -> impl std::future::Future<Output = ()> + Send;
+ let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
+ let mut tick = tokio::time::interval(core::TICK);
+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ loop {
+ tokio::select! {
+ Some((req, reply)) = rx.recv() => {
+ let _ = reply.send(daemon.handle(req).await);
+ }
+ _ = tick.tick() => daemon.tick().await,
+ _ = term.recv() => break,
+ _ = tokio::signal::ctrl_c() => break,
+ }
+ }
+ server.abort();
+ daemon.shutdown().await;
+ let _ = std::fs::remove_file(&socket);
+ Ok(())
}
-/// 运行守护进程直到收到停止信号
-pub async fn run(config: Config) -> anyhow::Result<()> {
- let _ = config;
- todo!("状态机循环、usbmuxd 子进程、控制接口、重签调度")
+async fn serve_conn(tx: tokio::sync::mpsc::Sender<(protocol::Request, oneshot::Sender<protocol::Response>)>, stream: tokio::net::UnixStream) {
+ let (r, mut w) = stream.into_split();
+ let mut lines = BufReader::new(r).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ let resp = match serde_json::from_str::<protocol::Request>(&line) {
+ Ok(req) => {
+ let (otx, orx) = oneshot::channel();
+ if tx.send((req, otx)).await.is_err() {
+ break;
+ }
+ orx.await.unwrap_or_else(|_| protocol::Response::error("守护进程正在退出"))
+ }
+ Err(e) => protocol::Response::error(format!("请求格式错误:{e}")),
+ };
+ let mut out = serde_json::to_string(&resp).unwrap_or_default();
+ out.push('\n');
+ if w.write_all(out.as_bytes()).await.is_err() {
+ break;
+ }
+ }
}
-
diff --git a/crates/ictl-daemon/src/machine.rs b/crates/ictl-daemon/src/machine.rs
new file mode 100644
index 0000000..9f904f8
--- /dev/null
+++ b/crates/ictl-daemon/src/machine.rs
@@ -0,0 +1,185 @@
+//! 状态机的纯逻辑部分:设备状态、WDA 启动退避、usbmuxd 漏设备判定。可单测,不碰设备。
+
+use std::time::{Duration, Instant};
+
+/// 设备状态(docs/architecture.md §3)
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(tag = "state", rename_all = "snake_case")]
+pub enum DeviceState {
+ /// usbmuxd 看不到手机
+ Absent,
+ /// 没有配对记录,需要在手机上点「信任」(iphone-control setup)
+ NeedsTrust,
+ DeveloperModeOff,
+ /// 锁屏时建不了隧道(BFU 只能人工解锁)
+ NeedsUnlock,
+ /// 还没签名安装 WDA(iphone-control sign)
+ NeedsSigning,
+ /// 正在建隧道、挂镜像、启动 WDA,或启动失败在退避
+ WdaStarting { last_error: Option<String> },
+ /// 手机重启后首次启用 UI 自动化,等用户在手机上输锁屏密码
+ NeedsAutomationPin,
+ Ready,
+}
+
+impl DeviceState {
+ pub fn describe(&self) -> String {
+ match self {
+ Self::Absent => "手机未连接".into(),
+ Self::NeedsTrust => "未配对:运行 iphone-control setup,在手机上点「信任」".into(),
+ Self::DeveloperModeOff => "开发者模式未打开:运行 iphone-control setup".into(),
+ Self::NeedsUnlock => "手机锁屏,隧道建不起来:请解锁手机".into(),
+ Self::NeedsSigning => "WDA 还没签名安装:运行 iphone-control sign".into(),
+ Self::WdaStarting { last_error: None } => "正在启动 WDA".into(),
+ Self::WdaStarting { last_error: Some(e) } => format!("WDA 启动失败,稍后重试:{e}"),
+ Self::NeedsAutomationPin => "WDA 卡在手机上的「Enable UI Automation」密码框:请在手机上输入锁屏密码".into(),
+ Self::Ready => "就绪".into(),
+ }
+ }
+}
+
+/// WDA 启动失败退避:60s 起翻倍,上限 300s;等自动化密码时固定 60s;手机重新连上时重置
+#[derive(Debug, Clone)]
+pub struct Backoff {
+ next_at: Option<Instant>,
+ delay: Duration,
+}
+
+pub const BACKOFF_START: Duration = Duration::from_secs(60);
+pub const BACKOFF_MAX: Duration = Duration::from_secs(300);
+pub const PIN_RETRY: Duration = Duration::from_secs(60);
+
+impl Default for Backoff {
+ fn default() -> Self {
+ Self { next_at: None, delay: BACKOFF_START }
+ }
+}
+
+impl Backoff {
+ pub fn ready(&self, now: Instant) -> bool {
+ self.next_at.is_none_or(|t| now >= t)
+ }
+
+ pub fn failed(&mut self, now: Instant) {
+ self.next_at = Some(now + self.delay);
+ self.delay = (self.delay * 2).min(BACKOFF_MAX);
+ }
+
+ pub fn waiting_for_pin(&mut self, now: Instant) {
+ self.next_at = Some(now + PIN_RETRY);
+ self.delay = BACKOFF_START;
+ }
+
+ pub fn reset(&mut self) {
+ *self = Self::default();
+ }
+
+ pub fn current_delay(&self) -> Duration {
+ self.delay
+ }
+}
+
+/// 容器里没有 udev,usbmuxd 收不到热插拔:sysfs 上有 Apple 设备但 usbmuxd 看不到,连续 3 次就该重启它
+#[derive(Debug, Default)]
+pub struct MuxWatch {
+ misses: u32,
+}
+
+pub const USBMUXD_MISS_LIMIT: u32 = 3;
+
+impl MuxWatch {
+ /// 返回 true 表示该重启 usbmuxd 了
+ pub fn observe(&mut self, usb_present: bool, mux_sees_device: bool) -> bool {
+ if mux_sees_device || !usb_present {
+ self.misses = 0;
+ return false;
+ }
+ self.misses += 1;
+ if self.misses >= USBMUXD_MISS_LIMIT {
+ self.misses = 0;
+ return true;
+ }
+ false
+ }
+}
+
+/// WDA 连续几次探测不通才算挂(避免一次慢请求就重启它)
+#[derive(Debug, Default)]
+pub struct Misses(u32);
+
+impl Misses {
+ pub const LIMIT: u32 = 3;
+
+ pub fn hit(&mut self) -> bool {
+ self.0 += 1;
+ self.0 >= Self::LIMIT
+ }
+
+ pub fn reset(&mut self) {
+ self.0 = 0;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn backoff_doubles_to_cap_and_resets() {
+ let t = Instant::now();
+ let mut b = Backoff::default();
+ assert!(b.ready(t));
+ let delays: Vec<_> = (0..5)
+ .map(|_| {
+ b.failed(t);
+ b.next_at.unwrap() - t
+ })
+ .collect();
+ assert_eq!(delays.iter().map(|d| d.as_secs()).collect::<Vec<_>>(), [60, 120, 240, 300, 300]);
+ assert!(!b.ready(t + Duration::from_secs(10)));
+ b.reset();
+ assert!(b.ready(t));
+ }
+
+ /// 回归用例 #8:等自动化密码时固定 60 秒重试,不指数退避
+ #[test]
+ fn pin_wait_retries_every_minute() {
+ let t = Instant::now();
+ let mut b = Backoff::default();
+ b.failed(t);
+ b.failed(t);
+ b.waiting_for_pin(t);
+ assert!(!b.ready(t + Duration::from_secs(59)));
+ assert!(b.ready(t + Duration::from_secs(60)));
+ assert_eq!(b.current_delay(), BACKOFF_START);
+ }
+
+ /// 回归用例 #7:sysfs 有设备但 usbmuxd 看不到,连续 3 次才重启
+ #[test]
+ fn usbmuxd_restart_after_three_misses() {
+ let mut w = MuxWatch::default();
+ assert!(!w.observe(true, false));
+ assert!(!w.observe(true, false));
+ assert!(w.observe(true, false));
+ assert!(!w.observe(true, false), "重启后重新计数");
+ assert!(!w.observe(false, false), "USB 上没有设备不算漏");
+ assert!(!w.observe(true, true));
+ }
+
+ #[test]
+ fn misses_need_three_in_a_row() {
+ let mut m = Misses::default();
+ assert!(!m.hit());
+ assert!(!m.hit());
+ m.reset();
+ assert!(!m.hit());
+ assert!(!m.hit());
+ assert!(m.hit());
+ }
+
+ #[test]
+ fn state_serializes_with_tag() {
+ let s = serde_json::to_string(&DeviceState::WdaStarting { last_error: None }).unwrap();
+ assert_eq!(s, r#"{"state":"wda_starting","last_error":null}"#);
+ }
+}
diff --git a/crates/ictl-daemon/src/notify.rs b/crates/ictl-daemon/src/notify.rs
new file mode 100644
index 0000000..0166d29
--- /dev/null
+++ b/crates/ictl-daemon/src/notify.rs
@@ -0,0 +1,174 @@
+//! 通知:Bark、Telegram。同一事件去重([`Dedup`]),恢复时推送一次。
+
+use std::collections::HashMap;
+use std::time::{Duration, Instant};
+
+use crate::config::NotifyConfig;
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum Event {
+ ResignFailed(String),
+ SessionExpired(String),
+ NeedsAutomationPin,
+ WdaRecovered,
+ UnlockDisabled,
+ DeviceOffline { minutes: u64 },
+ DeviceOnline { minutes: u64 },
+}
+
+impl Event {
+ /// 去重用的键:同一类事件只推一次,直到被对应的恢复事件清掉或过了冷却时间
+ fn key(&self) -> &'static str {
+ match self {
+ Self::ResignFailed(_) => "resign",
+ Self::SessionExpired(_) => "session",
+ Self::NeedsAutomationPin => "pin",
+ Self::WdaRecovered => "pin-recovered",
+ Self::UnlockDisabled => "unlock",
+ Self::DeviceOffline { .. } => "offline",
+ Self::DeviceOnline { .. } => "online",
+ }
+ }
+
+ pub fn title_body(&self) -> (String, String) {
+ match self {
+ Self::ResignFailed(why) => (
+ "iPhone WDA 重签失败".into(),
+ format!("{why}\n描述文件过期后 WDA 将无法启动(截图/点击的 HID 路线不受影响)。\n排查: iphone-control doctor"),
+ ),
+ Self::SessionExpired(why) => (
+ "Apple ID 会话已失效".into(),
+ format!("{why}\n下次重签前需要重新登录: iphone-control login"),
+ ),
+ Self::NeedsAutomationPin => (
+ "iPhone 需要输入锁屏密码".into(),
+ "手机重启后要启用 UI 自动化:请解锁手机,在「为 XCTest 输入 iPhone 密码」弹窗里输入锁屏密码。弹窗没出现或已关闭的话,1 分钟内会重新弹出。".into(),
+ ),
+ Self::WdaRecovered => ("iPhone WDA 已恢复".into(), "已输入密码,WDA 重新就绪,可以正常操作了。".into()),
+ Self::UnlockDisabled => (
+ "iPhone 自动解锁失败,已停用".into(),
+ "整串密码输完手机仍锁着,可能密码配置不对。为免累计输错,自动解锁已停用。\n请人工解锁手机、核对密码(iphone-control passcode set),再运行 iphone-control unlock-reset。".into(),
+ ),
+ Self::DeviceOffline { minutes } => (
+ format!("iPhone 已离线 {minutes} 分钟"),
+ "连不上手机:检查 USB 线、手机是否没电关机。重新连上后会自动恢复。".into(),
+ ),
+ Self::DeviceOnline { minutes } => ("iPhone 已重新连上".into(), format!("离线约 {minutes} 分钟,正在自动恢复。")),
+ }
+ }
+}
+
+/// 事件去重:同一键在冷却期内只放行一次;`clear` 后可以再次放行
+#[derive(Debug, Default)]
+pub struct Dedup {
+ sent: HashMap<&'static str, Instant>,
+}
+
+/// 冷却:重签失败、会话失效 20 小时内不重复推;其余等恢复事件清除
+fn cooldown(e: &Event) -> Option<Duration> {
+ match e {
+ Event::ResignFailed(_) | Event::SessionExpired(_) => Some(Duration::from_secs(20 * 3600)),
+ Event::WdaRecovered | Event::DeviceOnline { .. } => Some(Duration::ZERO),
+ _ => None,
+ }
+}
+
+impl Dedup {
+ pub fn should_send(&mut self, e: &Event, now: Instant) -> bool {
+ let key = e.key();
+ let ok = match (self.sent.get(key), cooldown(e)) {
+ (None, _) => true,
+ (Some(_), Some(cd)) if cd.is_zero() => true,
+ (Some(t), Some(cd)) => now.duration_since(*t) >= cd,
+ (Some(_), None) => false,
+ };
+ if ok {
+ self.sent.insert(key, now);
+ }
+ ok
+ }
+
+ pub fn clear(&mut self, key: &'static str) {
+ self.sent.remove(key);
+ }
+
+ /// 之前是否推过(用来决定恢复时要不要推「已恢复」)
+ pub fn was_sent(&self, key: &'static str) -> bool {
+ self.sent.contains_key(key)
+ }
+}
+
+/// 实际发送,返回成功的渠道数。失败只记日志,不影响守护进程
+pub async fn send(cfg: &NotifyConfig, title: &str, body: &str) -> usize {
+ let client = match reqwest::Client::builder().timeout(Duration::from_secs(20)).build() {
+ Ok(c) => c,
+ Err(e) => {
+ tracing::warn!("通知客户端创建失败:{e}");
+ return 0;
+ }
+ };
+ let mut ok = 0;
+ if let (Some(token), Some(chat)) = (&cfg.tg_bot_token, &cfg.tg_chat_id) {
+ let r = client
+ .post(format!("https://api.telegram.org/bot{token}/sendMessage"))
+ .form(&[("chat_id", chat.as_str()), ("text", &format!("{title}\n{body}"))])
+ .send()
+ .await
+ .and_then(|r| r.error_for_status());
+ match r {
+ Ok(_) => ok += 1,
+ Err(e) => tracing::warn!("Telegram 发送失败:{}", e.without_url()),
+ }
+ }
+ if let Some(key) = &cfg.bark_key {
+ let r = client
+ .post(format!("{}/{key}", cfg.bark_server.trim_end_matches('/')))
+ .form(&[("title", title), ("body", body), ("group", "iPhone")])
+ .send()
+ .await
+ .and_then(|r| r.error_for_status());
+ match r {
+ Ok(_) => ok += 1,
+ Err(e) => tracing::warn!("Bark 发送失败:{}", e.without_url()),
+ }
+ }
+ ok
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn same_event_is_sent_once_until_cleared() {
+ let mut d = Dedup::default();
+ let t = Instant::now();
+ assert!(d.should_send(&Event::NeedsAutomationPin, t));
+ assert!(!d.should_send(&Event::NeedsAutomationPin, t + Duration::from_secs(3600)));
+ d.clear("pin");
+ assert!(d.should_send(&Event::NeedsAutomationPin, t));
+ }
+
+ #[test]
+ fn resign_failure_has_20h_cooldown() {
+ let mut d = Dedup::default();
+ let t = Instant::now();
+ assert!(d.should_send(&Event::ResignFailed("x".into()), t));
+ assert!(!d.should_send(&Event::ResignFailed("y".into()), t + Duration::from_secs(19 * 3600)));
+ assert!(d.should_send(&Event::ResignFailed("z".into()), t + Duration::from_secs(21 * 3600)));
+ }
+
+ #[test]
+ fn recovery_events_always_pass() {
+ let mut d = Dedup::default();
+ let t = Instant::now();
+ assert!(d.should_send(&Event::WdaRecovered, t));
+ assert!(d.should_send(&Event::WdaRecovered, t));
+ }
+
+ #[test]
+ fn texts_match_toolkit() {
+ assert_eq!(Event::NeedsAutomationPin.title_body().0, "iPhone 需要输入锁屏密码");
+ assert_eq!(Event::DeviceOffline { minutes: 10 }.title_body().0, "iPhone 已离线 10 分钟");
+ }
+}
diff --git a/crates/ictl-daemon/src/protocol.rs b/crates/ictl-daemon/src/protocol.rs
index 068a3c3..b265f24 100644
--- a/crates/ictl-daemon/src/protocol.rs
+++ b/crates/ictl-daemon/src/protocol.rs
@@ -5,9 +5,10 @@ use serde::{Deserialize, Serialize};
pub const DEFAULT_SOCKET: &str = "/run/iphone-control/ctl.sock";
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Request {
+ /// MCP 的 iphone_status:与 toolkit 相同的文字
Status,
/// 区域单位为点;None 表示整屏
Screenshot { region: Option<(f64, f64, f64, f64)> },
@@ -22,10 +23,15 @@ pub enum Request {
LaunchApp { app: String },
TerminateApp { app: String },
OpenUrl { url: String },
+ /// 运维:守护进程和设备的状态快照(JSON 文本)
+ Daemon,
+ /// 运维:逐层诊断,返回多行文字
+ Doctor,
Resign { force: bool },
+ UnlockReset,
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Response {
Text { text: String },
@@ -33,3 +39,41 @@ pub enum Response {
Image { jpeg_base64: String, caption: String },
Error { message: String },
}
+
+impl Response {
+ pub fn text(s: impl Into<String>) -> Self {
+ Self::Text { text: s.into() }
+ }
+ pub fn error(s: impl Into<String>) -> Self {
+ Self::Error { message: s.into() }
+ }
+}
+
+/// 发一个请求、读一个响应(客户端用)
+pub async fn call(socket: &std::path::Path, req: &Request) -> std::io::Result<Response> {
+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+ let stream = tokio::net::UnixStream::connect(socket).await?;
+ let (r, mut w) = stream.into_split();
+ let mut line = serde_json::to_string(req)?;
+ line.push('\n');
+ w.write_all(line.as_bytes()).await?;
+ w.shutdown().await?;
+ let mut resp = String::new();
+ BufReader::new(r).read_line(&mut resp).await?;
+ serde_json::from_str(&resp).map_err(std::io::Error::other)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn requests_round_trip_as_tagged_json() {
+ let r = Request::Swipe { from: (1.0, 2.0), to: (3.0, 4.0), seconds: 0.3 };
+ let s = serde_json::to_string(&r).unwrap();
+ assert!(s.starts_with(r#"{"op":"swipe""#), "{s}");
+ assert_eq!(serde_json::from_str::<Request>(&s).unwrap(), r);
+ let e: Response = serde_json::from_str(r#"{"kind":"error","message":"x"}"#).unwrap();
+ assert_eq!(e, Response::error("x"));
+ }
+}