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(cli): end quietly when stdout's reader goes away (#53)
Qinghe Lic535d50781a3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 02cc8f0..0a76659 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,10 @@ All notable changes to this project are documented here. The format is based on- `iphone-control update rollback` and the previous executable kept after an upgrade. A new version that doesn't start is still replaced by the old one automatically.- The rollback compatibility mark in release manifests: any newer signed stable release can be installed directly, without stopping at "manual migration required".+### Fixed++- Piping output into a program that exits early, such as `iphone-control status | head -1`, no longer crashes with "Broken pipe"; the command ends quietly like other command-line tools.+## [0.2.2] - 2026-11-12### Upgrade notesdiff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex 8b91a58..731b791 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -17,6 +17,10 @@- `iphone-control update rollback` 和升级后保留的上一版程序。新版本起不来时仍会自动换回旧版本。- 发布清单里的回滚兼容标记:任何更新的签名稳定版都能直接升级,不再因“需要手动迁移”而停下。+### 修复++- `iphone-control status | head -1` 这类把输出接给提前退出的程序的用法,不再报 “Broken pipe” 崩溃,而是像其他命令行工具一样直接结束。+## [0.2.2] - 2026-11-12### 升级注意事项diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex 2edf7b4..5affff7 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -176,10 +176,43 @@ fn main() -> anyhow::Result<()> {tokio::runtime::Runtime::new()?.block_on(run())}+/// Commands that ask once, print the result and end; see [`restore_sigpipe`]+fn prints_and_exits(command: Option<&Command>) -> bool {+ matches!(+ command,+ Some(+ Command::Status+ | Command::Doctor+ | Command::Devices+ | Command::McpConfig+ | Command::Select { .. }+ | Command::UnlockReset+ | Command::NotifyTest { .. }+ | Command::Update { action: Some(UpdateAction::Check { .. }), .. }+ )+ )+}++/// Rust starts every program with SIGPIPE ignored, so once the reader of stdout has gone (`iphone-control status |+/// head -1`), the next write is an EPIPE error and `println!` panics on it (exit 101 and a panic message). Commands+/// that only print a result get the usual behaviour back: the reader going away ends the process quietly, like any+/// other command-line tool. Not for the long-running commands (daemon, mcp, viewer, wda-bridge), nor for those+/// that keep talking to the daemon across its restarts (update, service, setup): there a write to a socket or a+/// child's pipe whose other end closed would end the process instead of returning an error it handles+fn restore_sigpipe() {+ // SAFETY: setting a signal's disposition back to its default, before any other thread exists that writes+ unsafe {+ libc::signal(libc::SIGPIPE, libc::SIG_DFL);+ }+}+async fn run() -> anyhow::Result<()> {// 依赖树里 rustls 的 ring 和 aws-lc-rs 都开着,不装默认 provider 的话第一个 HTTPS 请求就 paniclet _ = rustls::crypto::ring::default_provider().install_default();let mut cli = Cli::parse();+ if prints_and_exits(cli.command.as_ref()) {+ restore_sigpipe();+ }let quiet = matches!(cli.command, Some(Command::Mcp));// ICTL_LOG 留空(配置文件里常见的 `ICTL_LOG=`)当作没设;原来空值会生成一个什么都不放行的过滤器let filter =@@ -1059,6 +1092,34 @@ mod tests {use ictl_l10n::{Lang, with_lang};use std::path::Path;+ /// Only the commands that print once and end get SIGPIPE's default disposition back+ #[test]+ fn sigpipe_default_only_for_commands_that_print_and_end() {+ use super::{Cli, prints_and_exits};+ use clap::Parser;++ let prints = |args: &[&str]| {+ let cli = Cli::try_parse_from(std::iter::once("iphone-control").chain(args.iter().copied())).unwrap();+ prints_and_exits(cli.command.as_ref())+ };+ for args in [&["status"][..], &["doctor"], &["devices"], &["mcp-config"], &["update", "check", "--json"]] {+ assert!(prints(args), "{args:?}");+ }+ for args in [+ &["daemon"][..],+ &["mcp"],+ &["viewer"],+ &["wda-bridge"],+ &["update"],+ &["update", "apply"],+ &["service", "restart"],+ &["setup"],+ &[],+ ] {+ assert!(!prints(args), "{args:?}");+ }+ }+#[test]fn update_accepts_no_subcommand_and_preserves_read_only_check() {use super::{Cli, Command, UpdateAction};diff --git a/apps/iphone-control/tests/update_viewer.rs b/apps/iphone-control/tests/update_viewer.rsindex 53cf4a2..ee1ea18 100644--- a/apps/iphone-control/tests/update_viewer.rs+++ b/apps/iphone-control/tests/update_viewer.rs@@ -57,3 +57,30 @@ async fn viewer_and_cli_share_the_unbound_report() -> Result<()> {viewer.kill().await?;Ok(())}++/// `iphone-control status | head -1`: the reader is gone before the command writes. It ends quietly on SIGPIPE+/// like other command-line tools instead of panicking (exit 101 and a panic message on stderr)+#[test]+fn a_closed_stdout_ends_printing_commands_quietly() -> Result<()> {+ use std::os::unix::process::ExitStatusExt;+ let temp = tempfile::tempdir_in("/tmp")?;+ let dir = temp.path();+ for args in [&["mcp-config"][..], &["update", "check"]] {+ // the read end is closed before the command starts, so its first write already fails+ let (reader, writer) = std::io::pipe()?;+ drop(reader);+ let out = std::process::Command::new(env!("CARGO_BIN_EXE_iphone-control"))+ .args(args)+ .env_clear()+ .env("HOME", dir)+ .env("PATH", "/usr/bin:/bin")+ .env("ICTL_SOCKET", dir.join("daemon.sock"))+ .stdout(writer)+ .stderr(Stdio::piped())+ .output()?;+ let stderr = String::from_utf8_lossy(&out.stderr);+ assert_eq!(out.status.signal(), Some(libc::SIGPIPE), "{args:?}: {:?} {stderr}", out.status);+ assert!(!stderr.contains("panicked"), "{args:?}: {stderr}");+ }+ Ok(())+}diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.mdindex dae6de5..3257718 100644--- a/docs/dev/regression-cases.md+++ b/docs/dev/regression-cases.md@@ -102,3 +102,4 @@| 96 | Homebrew、Debian 升级后后台服务还在跑旧版本 | 升级后服务在运行就重启,并确认守护进程报告的是新版本;确认不了时写出手动重启命令 | 单测 brew_upgrades_the_exact_active_formula_only_after_the_tap_is_ready(已是最新时不重启);真机:deb 安装下升级 || 97 | APT 锁定(hold)的包仍提示可直接升级,运行后才报错 | hold 当作“已固定”:升级命令带上 `sudo apt-mark unhold`,直接运行时先提示解除锁定 | 单测 a_held_deb_is_reported_like_a_pinned_installation || 98 | 发布清单只允许从声明过的某一个版本升级,其他版本一律“需要手动迁移” | 去掉回滚兼容标记和 `update rollback`;任何更新的签名稳定版都能升级,新版本起不来时仍自动换回旧版本;清单保留两个旧字段让 0.2.2 还能升级 | 单测 verifies_publisher_signed_bytes_before_staging_an_executable、unhealthy_daemon_restores_last_verified_executable_and_service;`test_installer.py` test_archive_manifest_still_lets_0_2_2_upgrade |+| 99 | `iphone-control status \| head -1`:读者先退出,后面的 `println!` 遇到 EPIPE 就 panic(退出码 101,打出崩溃信息)。Rust 启动时把 SIGPIPE 设成了忽略 | 只打印结果就结束的命令恢复 SIGPIPE 默认行为,安静退出;守护进程、MCP、viewer、wda-bridge 和跨守护进程重启的 update、service、setup 保持忽略 | 单测 sigpipe_default_only_for_commands_that_print_and_end、集成测试 a_closed_stdout_ends_printing_commands_quietly |