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(notify): name the device in notifications (#85)
Qinghe Li410cbb8e0407
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eb2b5b9..2ae5e35 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -36,6 +36,7 @@ All notable changes to this project are documented here. The format is based on### Fixed+- Notification titles name the device: they always said "iPhone", also when an iPad needed its passcode, went offline or failed to re-sign, and with several devices you couldn't tell which. On an iPad the prompt is quoted as iOS shows it there ("Enter iPad passcode for XCTest"). `notify-test` samples use the controlled device.- Checking a new version during an update (running its `--version`) could fail now and then with "Text file busy": another thread started a process while the new program was still open for writing. It now waits a moment and tries again.- `task run`: a command that ended its task with `task finish` is no longer stopped on its way out with exit code 1. It now has 5 seconds to exit with its own code; if it is stopped after that, the exit code is 0 when the task completed.- Holding an arrow key in a setup menu keeps moving the selection without echoing key sequences into the menu.diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex 38c571a..3e2bc80 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -36,6 +36,7 @@### 修复+- 通知标题写设备自己的名字:之前一律写「iPhone」,iPad 需要输入锁屏密码、离线、重签失败时也是,接着多台设备时看不出是哪一台。iPad 上的提示也改用系统弹窗的说法(「为 XCTest 输入 iPad 密码」)。`notify-test` 的样例用正在控制的设备。- 升级时检查新程序(运行它的 `--version`)偶尔会因为「Text file busy」失败:同一进程的其他线程恰好在新程序还以写方式打开时启动了子进程。现在遇到这种情况会稍等重试。- `task run`:命令自己用 `task finish` 结束任务后,不再在它正常退出时被立刻停掉、退出码变成 1。现在它有 5 秒自己退出,退出码就是它自己的;超时才停掉,这时任务完成则退出码为 0。- 在设置菜单中长按方向键时,选项会连续移动,按键序列不会回显到菜单里。diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex 1432630..3d54aa2 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -371,7 +371,7 @@ async fn run() -> anyhow::Result<()> {Command::Task { url, ca, action } => task::run(&cli.socket, url, ca, action).await,#[cfg(feature = "debug-cmds")]Command::Debug(args) => debug::run(env_nonempty("IPHONE_UDID").as_deref(), args).await,- Command::NotifyTest { event } => notify_test(&cli.data_dir, event.as_deref()).await,+ Command::NotifyTest { event } => notify_test(&cli.socket, &cli.data_dir, event.as_deref()).await,}}@@ -414,8 +414,8 @@ async fn update_command(action: UpdateAction, socket: &Path) -> anyhow::Result<(}}-async fn notify_test(data_dir: &Path, only: Option<&str>) -> anyhow::Result<()> {- use ictl_daemon::notify::{Event, send};+async fn notify_test(socket: &Path, data_dir: &Path, only: Option<&str>) -> anyhow::Result<()> {+ use ictl_daemon::notify::{Event, Target, send};let cfg = ictl_daemon::Config::from_env(data_dir).notify;let channels =usize::from(cfg.bark_key.is_some()) + usize::from(cfg.tg_bot_token.is_some() && cfg.tg_chat_id.is_some());@@ -435,9 +435,14 @@ async fn notify_test(data_dir: &Path, only: Option<&str>) -> anyhow::Result<()>let names: Vec<&str> = Event::samples().iter().map(|e| e.sample_name()).collect();bail!("{}", ictl_l10n::trf!("没有这类事件,可选:{}", "No such event; choose from: {}", names.join(" / ")));}+ // the device the daemon controls, as a real notification names it; without the daemon, a sample+ let target = match tokio::time::timeout(Duration::from_secs(2), snapshot(socket)).await {+ Ok(Ok(s)) if s.device.is_some() => Target::of(s.device.as_ref()),+ _ => Target::sample(),+ };let mut failed = 0;for e in &events {- let (title, body) = e.title_body();+ let (title, body) = e.title_body(&target);let ok = send(&cfg, &ictl_l10n::trf!("[测试] {title}", "[test] {title}"), &body).await;println!("{}",diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex 92cf76c..77738dc 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -317,6 +317,8 @@ pub(crate) struct Inner {/// 连续列不出设备的次数(usbmuxd 抖一下不立刻当成离线)pub list_errors: u32,pub offline_since: Option<Instant>,+ /// The device that went offline, for the notification once it has been gone long enough (its details are gone)+ pub offline_target: Option<crate::notify::Target>,/// HID 会话最近一次使用的时间;空闲超过 [`crate::supervise::HID_IDLE`] 就关掉(它持有屏幕媒体流)pub hid_used: Option<Instant>,/// Control pages watching the screen media stream (`screen.rs`): while there are any, the HID session (which owns@@ -433,6 +435,7 @@ impl Daemon {backoff: Backoff::default(),list_errors: 0,offline_since: Some(now),+ offline_target: None,hid_used: None,screen_viewers: 0,elements_cache: None,@@ -525,7 +528,12 @@ impl Daemon {return;}// 通知和事件日志按守护进程自己的语言:触发它的可能是另一种语言的请求(例如自动解锁失败)- let (title, body) = ictl_l10n::in_own_lang(|| e.title_body());+ // the device it is about; one that went offline has lost its details, so the one kept then+ let target = match (&e, &g.offline_target) {+ (Event::DeviceOffline { .. }, Some(t)) => t.clone(),+ _ => ictl_l10n::in_own_lang(|| notify::Target::of(g.info.as_ref())),+ };+ let (title, body) = ictl_l10n::in_own_lang(|| e.title_body(&target));self.log.log(&ictl_l10n::log_trf!("通知:{title}", "Notification: {title}"));let cfg = self.cfg.notify.clone();if cfg.any() {diff --git a/crates/ictl-daemon/src/notify.rs b/crates/ictl-daemon/src/notify.rsindex 90a8c4c..bdf7bb6 100644--- a/crates/ictl-daemon/src/notify.rs+++ b/crates/ictl-daemon/src/notify.rs@@ -24,6 +24,37 @@ pub enum Event {},}+/// Which device a notification is about: its name for the title, and its kind for the words iOS itself shows+/// (the passcode prompt says “iPad passcode” on an iPad)+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Target {+ pub name: String,+ pub kind: &'static str,+}++impl Target {+ /// The device as the daemon knows it; without its details, the device in general+ pub fn of(info: Option<&ictl_device::DeviceInfo>) -> Self {+ let Some(i) = info else {+ return Self { name: ictl_l10n::tr!("设备", "Device").into(), kind: "iPhone" };+ };+ let kind = if i.product_type.starts_with("iPad") {+ "iPad"+ } else if i.product_type.starts_with("iPod") {+ "iPod"+ } else {+ "iPhone"+ };+ let name = i.name.trim();+ Self { name: if name.is_empty() { kind.into() } else { name.into() }, kind }+ }++ /// For `notify-test`+ pub fn sample() -> Self {+ Self { name: "iPhone".into(), kind: "iPhone" }+ }+}+impl Event {/// 去重用的键:同一类事件只推一次,直到被对应的恢复事件清掉或过了冷却时间fn key(&self) -> &'static str {@@ -60,10 +91,12 @@ impl Event {self.key()}- pub fn title_body(&self) -> (String, String) {+ /// `t`: the device it is about (titles name it; the passcode prompt is called what iOS calls it there)+ pub fn title_body(&self, t: &Target) -> (String, String) {+ let (name, kind) = (&t.name, t.kind);match self {Self::ResignFailed(why) => (- ictl_l10n::tr!("iPhone WDA 重签失败", "iPhone: re-signing WDA failed").into(),+ ictl_l10n::trf!("{name} WDA 重签失败", "{name}: re-signing WDA failed"),ictl_l10n::trf!("{why}\n描述文件过期后 WDA 将无法启动(截图/点击的 HID 路线不受影响)。\n排查: iphone-control doctor", "{why}\nOnce the provisioning profile expires WDA can't start (the HID path for screenshots/taps is not affected).\nTroubleshoot: iphone-control doctor"),),Self::SessionExpired(why) => (@@ -71,19 +104,19 @@ impl Event {ictl_l10n::trf!("{why}\n下次重签前需要重新登录: iphone-control login", "{why}\nSign in again before the next re-sign: iphone-control login"),),Self::NeedsAutomationPin => (- ictl_l10n::tr!("iPhone 需要输入锁屏密码", "iPhone needs the passcode").into(),- ictl_l10n::tr!("手机重启后要启用 UI 自动化:请解锁手机,在「为 XCTest 输入 iPhone 密码」弹窗里输入锁屏密码。弹窗没出现或已关闭的话,1 分钟内会重新弹出。", "After a reboot, UI automation has to be enabled: unlock the phone and enter the passcode in the “Enter iPhone passcode for XCTest” prompt. If the prompt didn't appear or was dismissed, it comes back within a minute.").into(),+ ictl_l10n::trf!("{name} 需要输入锁屏密码", "{name} needs the passcode"),+ ictl_l10n::trf!("设备重启后要启用 UI 自动化:请解锁 {kind},在「为 XCTest 输入 {kind} 密码」弹窗里输入锁屏密码。弹窗没出现或已关闭的话,1 分钟内会重新弹出。", "After a reboot, UI automation has to be enabled: unlock the {kind} and enter the passcode in the “Enter {kind} passcode for XCTest” prompt. If the prompt didn't appear or was dismissed, it comes back within a minute."),),- Self::WdaRecovered => (ictl_l10n::tr!("iPhone WDA 已恢复", "iPhone WDA is back").into(), ictl_l10n::tr!("已输入密码,WDA 重新就绪,可以正常操作了。", "Passcode entered, WDA is ready again and everything works.").into()),+ Self::WdaRecovered => (ictl_l10n::trf!("{name} WDA 已恢复", "{name}: WDA is back"), ictl_l10n::tr!("已输入密码,WDA 重新就绪,可以正常操作了。", "Passcode entered, WDA is ready again and everything works.").into()),Self::UnlockDisabled => (- ictl_l10n::tr!("iPhone 自动解锁失败,已停用", "iPhone auto-unlock failed and was disabled").into(),+ ictl_l10n::trf!("{name} 自动解锁失败,已停用", "{name}: auto-unlock failed and was disabled"),ictl_l10n::tr!("整串密码输完手机仍锁着(可能密码配置不对),或输入途中出错、无法确认密码是否已提交。为免累计输错,自动解锁已停用。\n请人工解锁手机、核对密码(iphone-control passcode set),再运行 iphone-control unlock-reset。", "The phone stayed locked after entering the whole passcode (the configured passcode may be wrong), or an error happened while entering it so it's unclear whether it was submitted. Auto-unlock is now disabled so wrong attempts don't pile up.\nUnlock the phone by hand, check the passcode (iphone-control passcode set), then run iphone-control unlock-reset.").into(),),Self::DeviceOffline { minutes } => (- ictl_l10n::trf!("iPhone 已离线 {minutes} 分钟", "iPhone offline for {minutes} minutes"),+ ictl_l10n::trf!("{name} 已离线 {minutes} 分钟", "{name} offline for {minutes} minutes"),ictl_l10n::tr!("连不上手机:检查 USB 线、手机是否没电关机。重新连上后会自动恢复。", "Can't reach the phone: check the USB cable and whether the phone ran out of battery. It recovers automatically once reconnected.").into(),),- Self::DeviceOnline { minutes } => (ictl_l10n::tr!("iPhone 已重新连上", "iPhone reconnected").into(), ictl_l10n::trf!("离线约 {minutes} 分钟,正在自动恢复。", "Offline for about {minutes} minutes, recovering automatically.")),+ Self::DeviceOnline { minutes } => (ictl_l10n::trf!("{name} 已重新连上", "{name} reconnected"), ictl_l10n::trf!("离线约 {minutes} 分钟,正在自动恢复。", "Offline for about {minutes} minutes, recovering automatically.")),Self::CertificateChanged { revoked: true } => (ictl_l10n::tr!("签名证书换了,旧证书已被吊销", "Signing certificate replaced, an old one was revoked").into(),ictl_l10n::tr!("这次签名新建了证书;免费 Apple ID 最多两张,满了就吊销了一张旧的。用旧证书签的 WDA(可能在别的设备,或用同一个 Apple ID 的其他机器、其他侧载工具上)起不来了:这里控制的设备切过去时会自动重签,也可以运行 iphone-control sign。", "This signing created a new certificate; a free Apple ID holds at most two, so an old one was revoked. WDA signed with it (maybe on other devices, or on other machines or sideloading tools using the same Apple ID) won't start any more: devices controlled here are re-signed automatically when you switch to them, or run iphone-control sign.").into(),@@ -227,7 +260,29 @@ mod tests {#[test]fn texts_match_toolkit() {- assert_eq!(Event::NeedsAutomationPin.title_body().0, "iPhone 需要输入锁屏密码");- assert_eq!(Event::DeviceOffline { minutes: 10 }.title_body().0, "iPhone 已离线 10 分钟");+ let t = Target::sample();+ assert_eq!(Event::NeedsAutomationPin.title_body(&t).0, "iPhone 需要输入锁屏密码");+ assert_eq!(Event::DeviceOffline { minutes: 10 }.title_body(&t).0, "iPhone 已离线 10 分钟");+ }++ /// The device by its name, and iOS's own words for an iPad+ #[test]+ fn a_notification_names_its_device() {+ let info = |name: &str, product_type: &str| ictl_device::DeviceInfo {+ name: name.into(),+ product_type: product_type.into(),+ ..Default::default()+ };+ let ipad = Target::of(Some(&info("客厅的iPad", "iPad11,1")));+ assert_eq!((ipad.name.as_str(), ipad.kind), ("客厅的iPad", "iPad"));+ let (title, body) = ictl_l10n::with_lang(ictl_l10n::Lang::Zh, || Event::NeedsAutomationPin.title_body(&ipad));+ assert_eq!(title, "客厅的iPad 需要输入锁屏密码");+ assert!(body.contains("为 XCTest 输入 iPad 密码") && !body.contains("iPhone"), "{body}");+ assert_eq!(Target::of(Some(&info("", "iPhone16,2"))).name, "iPhone", "no name: its kind");+ let unknown = ictl_l10n::with_lang(ictl_l10n::Lang::En, || Target::of(None));+ assert_eq!(unknown.name, "Device");+ let (title, _) =+ ictl_l10n::with_lang(ictl_l10n::Lang::En, || Event::DeviceOffline { minutes: 3 }.title_body(&ipad));+ assert_eq!(title, "客厅的iPad offline for 3 minutes");}}diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rsindex 0e28fb2..a7f910f 100644--- a/crates/ictl-daemon/src/supervise.rs+++ b/crates/ictl-daemon/src/supervise.rs@@ -223,6 +223,7 @@ impl Daemon {let now = Instant::now();if g.device.take().is_some() {self.log.log(ictl_l10n::log_tr!("手机离线", "Phone offline"));+ g.offline_target = Some(ictl_l10n::in_own_lang(|| crate::notify::Target::of(g.info.as_ref())));// 名字、型号、iOS 版本是这台的:留着的话状态、提示文字会把它当成还在控制的设备g.info = None;self.forget_device(g).await;diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.mdindex a45aba3..6b21a67 100644--- a/docs/dev/regression-cases.md+++ b/docs/dev/regression-cases.md@@ -1,6 +1,6 @@# 必须覆盖的回归用例-#1~#34 来自 toolkit 和本项目早期实际踩过的坑,#35~#45 是多设备和 HID 横屏,#46~#58 是实时画面、开发者工具和英文界面,#59~#63 是 iPhone 18 Pro Max(iOS 27.2.1)真机全量测试发现的问题,#64 起是 viewer 的 AI 任务和新页面,#116~#122 是任务的控制权、控制台的局域网访问与登录、跨主机。能单测的写单测,不能单测的进真机回归清单。**每个 PR 都必须保持这里的全部用例通过**:单测的由 `cargo test` 覆盖;改到的范围里测试方式是真机、无头 Chrome 或手动测量的,要重跑并在 PR 里列出编号,写明设备和 iOS 版本;修了清单里没有的问题,要加一行。完整要求见 [CONTRIBUTING.md 的 Required tests](../../CONTRIBUTING.md#required-tests)。+#1~#34 来自 toolkit 和本项目早期实际踩过的坑,#35~#45 是多设备和 HID 横屏,#46~#58 是实时画面、开发者工具和英文界面,#59~#63 是 iPhone 18 Pro Max(iOS 27.2.1)真机全量测试发现的问题,#64 起是 viewer 的 AI 任务和新页面,#116~#122 是任务的控制权、控制台的局域网访问与登录、跨主机,#123 起是 0.2.4 发版前回归中发现的。能单测的写单测,不能单测的进真机回归清单。**每个 PR 都必须保持这里的全部用例通过**:单测的由 `cargo test` 覆盖;改到的范围里测试方式是真机、无头 Chrome 或手动测量的,要重跑并在 PR 里列出编号,写明设备和 iOS 版本;修了清单里没有的问题,要加一行。完整要求见 [CONTRIBUTING.md 的 Required tests](../../CONTRIBUTING.md#required-tests)。| # | 坑 | 正确行为 | 测试方式 ||---|---|---|---|@@ -126,3 +126,4 @@| 120 | 带请求体的请求被提前拒绝(没登录 401、403、413)时,控制台没读请求体就关连接,TCP 发 RST,客户端收不到回复(`connection reset by peer`,复用连接的程序约三次一次) | 回复后先关写方向,读完对方剩下的数据(最多 1 秒、1 MB)再关 | 单测 `every_request_needs_the_login`(256 KB 请求体仍收到 401);真机 `tasks.py remote` 连跑 8 次 || 121 | 任务事件流(SSE)的一块数据断在中文字符中间时,先整体转成文字会把这个字变成乱码 | 在字节里找事件边界,只转换完整的事件 | 单测 `remote::reads_server_sent_events` || 122 | 升级时运行新程序的 `--version` 偶尔失败:`Text file busy`(同一进程的其他线程 fork 时,新程序还以写方式打开) | 遇到 `ETXTBSY` 等 50 毫秒重试,最多 20 次 | 单测 `the_candidate_runs_once_it_is_no_longer_open_for_writing`(修复前稳定复现) |+| 123 | iPad(iPadOS 26)重启后要输入密码启用 UI 自动化时,通知写的是「iPhone 需要输入锁屏密码」;所有通知标题都写死「iPhone」,多台设备时看不出是哪一台 | 标题用设备名(没有名字时用型号类别),密码提示按设备类别写系统弹窗的说法;离线通知用离线前记下的名字 | 单测 `a_notification_names_its_device`;真机 `notify-test pin`(控制 iPad,经本地假 Bark 截到标题) |