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

feat(cli): check and install host upgrades with a single update command (#51)

MSK5f9c92331740
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 776d8d6..16a697e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,10 @@ All notable changes to this project are documented here. The format is based on
## [Unreleased]
+### Added
+
+- Run `iphone-control update` to check for a new stable release and install it through your managed service, Homebrew or Debian package. It reports when you already have the latest version. `update check` remains available for a check only.
+
## [0.2.2] - 2026-11-12
### Upgrade notes
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 8072f33..db128e3 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -6,6 +6,10 @@
## [Unreleased]
+### 新增
+
+- 运行 `iphone-control update` 可检查并通过受管服务、Homebrew 或 Debian 软件包升级到新稳定版。已是最新时会直接提示。只想检查可继续用 `update check`。
+
## [0.2.2] - 2026-11-12
### 升级注意事项
diff --git a/README.md b/README.md
index 411d0a0..b31f9a3 100644
--- a/README.md
+++ b/README.md
@@ -72,7 +72,7 @@ You need an iPhone or iPad on iOS 17+ connected by a **data** cable, a free Appl
curl -fsSLo iphone-control-install.sh https://github.com/Derrors/iphone-control/releases/latest/download/install.sh && sh iphone-control-install.sh
```
-It downloads the release for your machine, verifies the Ed25519 release manifest and archive SHA-256 (Python 3 and OpenSSL 3 required), installs `iphone-control` into `~/.local/bin` and runs the daemon as a per-user service that starts at login (launchd on macOS, systemd on Linux). Run it as your regular user. Use `iphone-control update apply` to upgrade this managed service. Running `sh iphone-control-install.sh --uninstall` removes it and keeps your data.
+It downloads the release for your machine, verifies the Ed25519 release manifest and archive SHA-256 (Python 3 and OpenSSL 3 required), installs `iphone-control` into `~/.local/bin` and runs the daemon as a per-user service that starts at login (launchd on macOS, systemd on Linux). Run it as your regular user. Use `iphone-control update` to upgrade this managed service. Running `sh iphone-control-install.sh --uninstall` removes it and keeps your data.
Upstream v0.2.0 predates the signed installer. To install that release or migrate an existing script installation, follow the [v0.2.0 instructions](https://derrors.github.io/iphone-control/en/guide/getting-started#legacy-script).
@@ -150,7 +150,11 @@ Tool texts, results, CLI output and logs are in Simplified Chinese by default; s
All commands and options: [CLI reference](https://derrors.github.io/iphone-control/en/guide/cli).
-Check in Viewer → **About & updates** or run `iphone-control update check --json`. For a managed user service, use `iphone-control update apply`. To opt in to signed patches when no device clients or tasks are active, use `iphone-control update policy auto-patch`; return to background checks with `iphone-control update policy notify`. Other channels upgrade with `brew upgrade iphone-control`, or by installing the new `.deb`; for a source build, see [build from source](https://derrors.github.io/iphone-control/en/deploy/source). Read the upgrade notes in the [changelog](CHANGELOG.md) first. Uninstall with `sh iphone-control-install.sh --uninstall`, `brew uninstall iphone-control` or `sudo apt remove iphone-control`; your data stays. Settings live in `~/.config/iphone-control/env`: the guide writes it, and after editing it by hand run `iphone-control service restart` — see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration). All state lives in `~/.local/share/iphone-control`: the Apple ID session and signing key, and the passcode if auto-unlock is on. **Back it up; never commit or share it.**
+Run `iphone-control update` to check for a stable release. When an upgrade is available, it uses the signed update for a managed service, Homebrew for a tap installation, or apt for a Debian package. It reports when you're up to date. Source installations follow the [source upgrade instructions](https://derrors.github.io/iphone-control/en/deploy/source#upgrade).
+
+To check versions, open **About & updates** in Viewer or run `iphone-control update check --json`. Managed services can opt in to signed patches while idle with `iphone-control update policy auto-patch`. Use `iphone-control update policy notify` to return to checks only. Read the [upgrade notes](CHANGELOG.md) before upgrading.
+
+Uninstall with `sh iphone-control-install.sh --uninstall`, `brew uninstall iphone-control` or `sudo apt remove iphone-control`; your data stays. Settings live in `~/.config/iphone-control/env`: the guide writes it, and after editing it by hand run `iphone-control service restart` — see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration). All state lives in `~/.local/share/iphone-control`: the Apple ID session and signing key, and the passcode if auto-unlock is on. **Back it up; never commit or share it.**
## Documentation
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 0cb5dbd..56faba9 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -74,7 +74,7 @@ iphone-control 在 Linux 或 macOS 上用**一个 Rust 二进制**把这些事
curl -fsSLo iphone-control-install.sh https://github.com/Derrors/iphone-control/releases/latest/download/install.sh && sh iphone-control-install.sh
```
-安装器会下载适合这台机器的版本,用 Python 3 和 OpenSSL 3 验证发行清单签名和安装包 SHA-256,把 `iphone-control` 装到 `~/.local/bin`,并把守护进程装成登录后自动启动的用户服务(macOS 用 launchd,Linux 用 systemd)。以普通用户运行。受管服务用 `iphone-control update apply` 升级,用 `sh iphone-control-install.sh --uninstall` 卸载,数据保留。国内网络下载 Release 慢的话,先在终端里设好 `HTTPS_PROXY` 再运行。
+安装器会下载适合这台机器的版本,用 Python 3 和 OpenSSL 3 验证发行清单签名和安装包 SHA-256,把 `iphone-control` 装到 `~/.local/bin`,并把守护进程装成登录后自动启动的用户服务(macOS 用 launchd,Linux 用 systemd)。以普通用户运行。受管服务用 `iphone-control update` 升级,用 `sh iphone-control-install.sh --uninstall` 卸载,数据保留。国内网络下载 Release 慢的话,先在终端里设好 `HTTPS_PROXY` 再运行。
上游 v0.2.0 发布时还没有签名安装器。安装该版本,或从已有的脚本安装迁移,请按 [v0.2.0 安装与迁移说明](https://derrors.github.io/iphone-control/guide/getting-started#legacy-script)操作。
@@ -152,7 +152,11 @@ iphone-control
全部命令和参数见[命令行](https://derrors.github.io/iphone-control/guide/cli)。
-在 Viewer「关于与更新」或通过 `iphone-control update check --json` 检查。受管用户服务用 `iphone-control update apply` 升级。需要空闲时自动安装签名补丁,可主动运行 `iphone-control update policy auto-patch`。用 `iphone-control update policy notify` 恢复为只检查。其他渠道:`brew upgrade iphone-control`,或装上新的 `.deb`;从源码编译的见[从源码编译](https://derrors.github.io/iphone-control/deploy/source)。升级前先看[更新日志](CHANGELOG.zh-CN.md)里的升级注意事项。卸载:`sh iphone-control-install.sh --uninstall`、`brew uninstall iphone-control` 或 `sudo apt remove iphone-control`,数据保留。设置在 `~/.config/iphone-control/env`,由设置引导写好;手改后运行 `iphone-control service restart`,见[配置说明](https://derrors.github.io/iphone-control/guide/configuration)。所有状态都在 `~/.local/share/iphone-control`:Apple ID 会话和签名私钥,开启自动解锁时还有锁屏密码。**要备份,不要提交或分享。**
+运行 `iphone-control update` 检查最新稳定版。有新版时,受管服务安装签名更新,Homebrew 安装通过原来的 tap 升级,Debian 软件包通过 apt 升级。版本已是最新时会直接提示。源码安装请按[源码升级说明](https://derrors.github.io/iphone-control/deploy/source#升级)操作。
+
+只想检查版本,可打开 Viewer 的「关于与更新」,或运行 `iphone-control update check --json`。受管服务可用 `iphone-control update policy auto-patch` 开启空闲时自动安装签名补丁,用 `iphone-control update policy notify` 改回只检查。升级前请阅读[更新日志](CHANGELOG.zh-CN.md)。
+
+卸载:`sh iphone-control-install.sh --uninstall`、`brew uninstall iphone-control` 或 `sudo apt remove iphone-control`,数据保留。设置在 `~/.config/iphone-control/env`,由设置引导写好;手改后运行 `iphone-control service restart`,见[配置说明](https://derrors.github.io/iphone-control/guide/configuration)。所有状态都在 `~/.local/share/iphone-control`:Apple ID 会话和签名私钥,开启自动解锁时还有锁屏密码。**要备份,不要提交或分享。**
## 文档
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index 161ee1c..aa3935b 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -40,10 +40,10 @@ struct Cli {
#[derive(Subcommand)]
enum Command {
- #[command(about = ictl_l10n::tr!("检查和管理主机软件更新", "Check for and manage host software updates"))]
+ #[command(about = ictl_l10n::tr!("检查主机软件版本,有新版时升级", "Check for a new host software release and install it if available"))]
Update {
#[command(subcommand)]
- action: UpdateAction,
+ action: Option<UpdateAction>,
},
#[command(about = ictl_l10n::tr!("常驻守护进程(安装时装成用户服务:macOS 是 launchd,Linux 是 systemd;也可以手动启动)", "The long-running daemon (installed as a user service: launchd on macOS, systemd on Linux; can also be started by hand)"))]
Daemon,
@@ -200,7 +200,8 @@ async fn run() -> anyhow::Result<()> {
};
let Some(command) = cli.command.take() else { return guide::first_run(&cli).await };
match command {
- Command::Update { action } => update_command(action, &cli.socket).await,
+ Command::Update { action: None } => update::upgrade(&cli.socket, update::check(false).await?).await,
+ Command::Update { action: Some(action) } => update_command(action, &cli.socket).await,
Command::Daemon => {
let mut cfg = ictl_daemon::Config::from_env(&cli.data_dir);
cfg.socket = cli.socket;
@@ -256,14 +257,14 @@ async fn update_command(action: UpdateAction, socket: &Path) -> anyhow::Result<(
}
UpdateAction::Policy { policy } => schedule::set_policy(socket, policy),
UpdateAction::Schedule => schedule::configure(socket),
- UpdateAction::Apply => transaction::apply(socket, false).await,
+ UpdateAction::Apply => transaction::apply(socket, false, update::check(false).await?).await,
UpdateAction::Unpin => transaction::unpin(),
UpdateAction::Rollback => transaction::rollback(socket).await,
UpdateAction::Recover { scheduled } => transaction::recover(socket, scheduled).await,
UpdateAction::Run => {
let report = update::check(true).await?;
if report.automatic_patch() {
- transaction::apply(socket, true).await?;
+ transaction::apply(socket, true, report).await?;
}
Ok(())
}
@@ -1059,6 +1060,19 @@ mod tests {
use ictl_l10n::{Lang, with_lang};
use std::path::Path;
+ #[test]
+ fn update_accepts_no_subcommand_and_preserves_read_only_check() {
+ use super::{Cli, Command, UpdateAction};
+ use clap::Parser;
+
+ let parse = |args: &[&str]| Cli::try_parse_from(args).unwrap().command;
+ assert!(matches!(parse(&["iphone-control", "update"]), Some(Command::Update { action: None })));
+ assert!(matches!(
+ parse(&["iphone-control", "update", "check", "--json"]),
+ Some(Command::Update { action: Some(UpdateAction::Check { json: true }) })
+ ));
+ }
+
/// 英文时注册命令带上语言(MCP 客户端不带用户 shell 的环境);中文时不带
#[test]
fn mcp_config_carries_english() {
diff --git a/apps/iphone-control/src/service.rs b/apps/iphone-control/src/service.rs
index 504319e..5366650 100644
--- a/apps/iphone-control/src/service.rs
+++ b/apps/iphone-control/src/service.rs
@@ -43,7 +43,7 @@ pub fn stable_exe() -> anyhow::Result<PathBuf> {
Ok(stable_path(&exe))
}
-fn stable_path(exe: &Path) -> PathBuf {
+pub(super) fn stable_path(exe: &Path) -> PathBuf {
let s = exe.to_string_lossy();
if let Some(i) = s.find("/Cellar/iphone-control/") {
let rest = &s[i + "/Cellar/iphone-control/".len()..];
diff --git a/apps/iphone-control/src/update.rs b/apps/iphone-control/src/update.rs
index fb2d9c8..914b061 100644
--- a/apps/iphone-control/src/update.rs
+++ b/apps/iphone-control/src/update.rs
@@ -1,6 +1,7 @@
//! Host program updates. Only release builds explicitly bound to a GitHub publisher
//! contact the release API. CLI and Viewer use the same local cache and channel evidence.
mod archive;
+mod channel;
mod install;
mod release;
pub mod transaction;
@@ -10,7 +11,7 @@ use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
-use anyhow::{Result, ensure};
+use anyhow::{Result, bail, ensure};
use ictl_l10n::{tr, trf};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
@@ -241,7 +242,9 @@ fn availability_with(
}
if method == InstallMethod::Debian {
return match deb_asset(&version.to_string(), platform) {
- Some(asset) if latest.assets.contains(&asset) => Available,
+ Some(asset) if latest.assets.contains(&asset) && latest.assets.contains(&format!("{asset}.sha256")) => {
+ Available
+ }
Some(_) => PlatformPending,
None => Unsupported,
};
@@ -268,39 +271,22 @@ fn availability_with(
Available
}
-fn upgrade_command(
- status: Availability,
- installation: &Installation,
- exe: Option<&Path>,
- release: Option<&Release>,
- platform: Option<&str>,
- tap: Option<&str>,
-) -> Option<String> {
+fn upgrade_command(status: Availability, installation: &Installation, exe: Option<&Path>) -> Option<String> {
+ let exe = exe?;
+ let exe =
+ if installation.method == InstallMethod::Homebrew { crate::service::stable_path(exe) } else { exe.to_owned() };
+ let exe = crate::shell_quote(exe.to_str()?);
match (status, installation.method) {
- (Availability::Available, InstallMethod::Managed) => {
- let exe = crate::shell_quote(exe?.to_str()?);
- Some(if installation.pinned? {
- format!("{exe} update unpin && {exe} update apply")
- } else {
- format!("{exe} update apply")
- })
- }
- (Availability::BrewCheck, InstallMethod::Homebrew) => {
- let tap = tap.filter(|tap| repository(tap))?;
- let brew = install::brew_program(exe?.ancestors().nth(4)?)?;
- let brew = crate::shell_quote(brew.to_str()?);
- Some(format!("{brew} update && {brew} upgrade {tap}/iphone-control"))
- }
- (Availability::Available, InstallMethod::Debian) => {
- let version = release::stable_tag(&release?.tag)?;
- let asset = deb_asset(&version.to_string(), platform?)?;
- Some(format!("sudo apt install ./{asset}"))
+ (Availability::Available, InstallMethod::Managed) if installation.pinned == Some(true) => {
+ Some(format!("{exe} update unpin && {exe} update"))
}
+ (Availability::Available, InstallMethod::Managed | InstallMethod::Debian)
+ | (Availability::BrewCheck, InstallMethod::Homebrew) => Some(format!("{exe} update")),
_ => None,
}
}
-fn guidance(status: Availability, method: InstallMethod, version: Option<&str>, pinned: Option<bool>) -> String {
+fn guidance(status: Availability, method: InstallMethod, pinned: Option<bool>) -> String {
match status {
Availability::Development => {
tr!("开发构建。在对应源码仓库检出目标版本,按原来的构建或安装方式更新本机程序。", "Development build. Check out the desired revision in its source repository and update this copy using its original build or install method.").into()
@@ -327,8 +313,8 @@ fn guidance(status: Availability, method: InstallMethod, version: Option<&str>,
Availability::Unchecked => tr!("尚无成功检查记录。", "No successful release check yet.").into(),
Availability::BrewCheck => {
tr!(
- "在主机终端运行 Homebrew 命令。可安装版本取决于 tap 的发布进度及本机是否固定了版本。",
- "Run the Homebrew command in a terminal on the host. The local tap and Homebrew pin determine the upgrade."
+ "通过 Homebrew 升级。可安装版本取决于 tap 的发布进度及本机是否固定了版本。",
+ "Update through Homebrew. The local tap and Homebrew pin determine the upgrade."
).into()
}
Availability::Available => match method {
@@ -342,13 +328,10 @@ fn guidance(status: Availability, method: InstallMethod, version: Option<&str>,
"Close Viewer and MCP clients and let tasks finish before running the upgrade command in a host terminal. It verifies the signature and checks rollback compatibility before installing."
)
.into(),
- InstallMethod::Debian => {
- let asset = deb_asset(version.unwrap_or_default(), target().unwrap_or_default()).unwrap_or_default();
- trf!(
- "从发行页下载并校验 {asset},在下载目录中运行安装命令。",
- "Download and verify {asset} from the release, then run the install command in the download directory."
- )
- }
+ InstallMethod::Debian => tr!(
+ "升级命令会下载并校验匹配本机架构的 .deb,再通过 APT 安装。",
+ "The update command downloads and verifies the .deb for this architecture, then installs it with APT."
+ ).into(),
_ => tr!(
"关闭正在运行的客户端和服务,再按发行说明手动更新。",
"Close running clients and services, then follow the manual release instructions."
@@ -416,7 +399,7 @@ impl Local {
"The verified release manifest requires a manual migration from the installed version. Follow the release notes to upgrade."
).into())
} else {
- (status, guidance(status, self.install.method, version.as_deref(), self.install.pinned))
+ (status, guidance(status, self.install.method, self.install.pinned))
};
let command = if self.source_command.is_some() {
guidance = tr!(
@@ -430,7 +413,7 @@ impl Local {
.into();
None
} else {
- upgrade_command(status, &self.install, self.exe.as_deref(), release, target(), tap())
+ upgrade_command(status, &self.install, self.exe.as_deref())
};
if status == Availability::Current && self.install.version.as_deref().is_some_and(|v| v != VERSION) {
guidance.push_str(tr!(
@@ -491,6 +474,42 @@ pub async fn check(background: bool) -> Result<Report> {
local.report(cache)
}
+/// The user explicitly requested an update. Use this check's release and installation channel.
+pub async fn upgrade(socket: &Path, report: Report) -> Result<()> {
+ if let Some(code) = &report.error_code {
+ bail!("{}", trf!("检查更新失败:{code}", "Update check failed: {code}"));
+ }
+ match (report.availability, report.install_method) {
+ (Availability::Current | Availability::Ahead, _) => {
+ println!("{} ({})", report.guidance, report.installed_version.as_deref().unwrap_or(VERSION));
+ }
+ (Availability::Available, InstallMethod::Managed) => {
+ ensure!(
+ report.pinned != Some(true),
+ "{}",
+ tr!(
+ "已固定安装版本。若要升级,请先运行 iphone-control update unpin。",
+ "This installation is pinned. To upgrade, run iphone-control update unpin first."
+ )
+ );
+ let version = report.available_version.clone().ok_or_else(|| anyhow::anyhow!("missing release version"))?;
+ transaction::apply(socket, false, report).await?;
+ println!("{}", trf!("已升级到 {version}。", "Updated to {version}."));
+ }
+ (Availability::Available, InstallMethod::Debian) | (Availability::BrewCheck, InstallMethod::Homebrew) => {
+ channel::apply(&report).await?;
+ }
+ _ => {
+ let next = report.upgrade_command.as_deref().or(report.release_url.as_deref());
+ if let Some(next) = next {
+ bail!("{}\n{next}", report.guidance);
+ }
+ bail!("{}", report.guidance);
+ }
+ }
+ Ok(())
+}
+
impl fmt::Display for Report {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let unknown = tr!("未知", "unknown");
@@ -594,7 +613,7 @@ mod tests {
fn managed_guidance_explains_verification_before_installation() {
ictl_l10n::with_lang(ictl_l10n::Lang::En, || {
for pinned in [false, true] {
- let guide = guidance(Availability::Available, InstallMethod::Managed, Some("0.2.1"), Some(pinned));
+ let guide = guidance(Availability::Available, InstallMethod::Managed, Some(pinned));
assert!(guide.contains("signature") && guide.contains("rollback compatibility"), "{guide}");
}
});
@@ -654,6 +673,40 @@ mod tests {
assert!(report.upgrade_command.is_none());
}
+ #[tokio::test]
+ async fn user_update_checks_the_release_before_choosing_an_installer() {
+ let report = |installed: &str, error: Option<&str>, pinned| {
+ let local = Local {
+ source_command: None,
+ exe: None,
+ install: Installation {
+ method: InstallMethod::Managed,
+ version: Some(installed.into()),
+ pinned: Some(pinned),
+ },
+ policy: Policy::Manual,
+ };
+ let mut cache = Cache::default();
+ cache.release = Some(Release { tag: "v1.2.3".into(), published_at: None, assets: vec![], notes: None });
+ cache.error_code = error.map(str::to_owned);
+ local.report(cache).unwrap()
+ };
+ let socket = Path::new("/unused");
+ // Current or newer local versions succeed even when pinned and without an installer or daemon.
+ for version in ["1.2.3", "1.2.4"] {
+ upgrade(socket, report(version, None, true)).await.unwrap();
+ }
+ // A cached version from an unsuccessful refresh cannot authorize any installation.
+ let mut stale = report("1.2.2", Some("rate_limited"), false);
+ stale.availability = Availability::Available;
+ let err = upgrade(socket, stale).await.unwrap_err();
+ assert!(err.to_string().contains("rate_limited"), "{err}");
+ let mut pinned = report("1.2.2", None, true);
+ pinned.availability = Availability::Available;
+ let err = upgrade(socket, pinned).await.unwrap_err();
+ assert!(err.to_string().contains("update unpin"), "{err}");
+ }
+
#[test]
fn cached_report_uses_viewer_request_language() {
let cache: Cache = serde_json::from_value(serde_json::json!({
@@ -674,43 +727,30 @@ mod tests {
#[test]
fn upgrade_commands_follow_the_verified_channel_and_release_state() {
+ use Availability::*;
+ use InstallMethod::{Debian, Homebrew, Managed, Script, Unknown};
+
let exe = Path::new("/Users/it's me/bin/iphone-control");
- let release = Release { tag: "v0.2.1".into(), published_at: None, assets: vec![], notes: None };
- let brew = Path::new("/opt/homebrew/bin/brew");
- let keg = Path::new("/opt/homebrew/Cellar/iphone-control/0.2.0/bin/iphone-control");
- let command = |method, pinned, status, platform, tap| {
- let exe = if method == InstallMethod::Homebrew { keg } else { exe };
+ let command = |method, pinned, status| {
let installation = Installation { method, version: Some("0.2.0".into()), pinned };
- upgrade_command(status, &installation, Some(exe), Some(&release), Some(platform), tap)
+ upgrade_command(status, &installation, Some(exe))
};
- use Availability::*;
- use InstallMethod::{Debian, Homebrew, Managed, Script, Unknown};
let quoted = crate::shell_quote(exe.to_str().unwrap());
- for (pinned, expected) in [
- (false, format!("{quoted} update apply")),
- (true, format!("{quoted} update unpin && {quoted} update apply")),
- ] {
- assert_eq!(command(Managed, Some(pinned), Available, "macos-arm64", None), Some(expected));
- }
+ let brew = Installation { method: Homebrew, version: Some("0.2.0".into()), pinned: None };
+ let keg = Path::new("/opt/homebrew/Cellar/iphone-control/0.2.0/bin/iphone-control");
assert_eq!(
- command(Homebrew, None, BrewCheck, "macos-arm64", Some("Example/tap")),
- Some(format!(
- "{brew} update && {brew} upgrade Example/tap/iphone-control",
- brew = crate::shell_quote(brew.to_str().unwrap())
- ))
+ upgrade_command(BrewCheck, &brew, Some(keg)),
+ Some(format!("{} update", crate::shell_quote("/opt/homebrew/opt/iphone-control/bin/iphone-control")))
);
- assert!(command(Homebrew, None, BrewCheck, "macos-arm64", Some("unverified tap")).is_none());
- for (target, arch) in [("linux-aarch64", "arm64"), ("linux-x86_64", "amd64")] {
- assert_eq!(
- command(Debian, None, Available, target, None),
- Some(format!("sudo apt install ./iphone-control_0.2.1_{arch}.deb"))
- );
+ for (method, status) in [(Managed, Available), (Debian, Available)] {
+ assert_eq!(command(method, Some(false), status), Some(format!("{quoted} update")));
}
+ assert_eq!(command(Managed, Some(true), Available), Some(format!("{quoted} update unpin && {quoted} update")));
for method in [Unknown, Script] {
- assert!(command(method, None, Available, "macos-arm64", None).is_none());
+ assert!(command(method, None, Available).is_none());
}
for status in [Development, Unchecked, Current, Ahead, PlatformPending, Unsupported, ManualOnly] {
- assert!(command(Managed, Some(false), status, "macos-arm64", None).is_none());
+ assert!(command(Managed, Some(false), status).is_none());
}
}
@@ -719,7 +759,11 @@ mod tests {
let release = Release {
tag: "v0.2.1".into(),
published_at: None,
- assets: vec!["iphone-control-v0.2.1-linux-x86_64.tar.gz".into(), "iphone-control_0.2.1_amd64.deb".into()],
+ assets: vec![
+ "iphone-control-v0.2.1-linux-x86_64.tar.gz".into(),
+ "iphone-control_0.2.1_amd64.deb".into(),
+ "iphone-control_0.2.1_amd64.deb.sha256".into(),
+ ],
notes: None,
};
let for_install = |running, method, platform| availability(running, method, platform, Some(&release));
@@ -733,6 +777,18 @@ mod tests {
assert_eq!(for_install("0.2.0", InstallMethod::Unknown, None), Availability::Unsupported);
}
+ #[test]
+ fn deb_upgrade_waits_for_the_matching_checksum_sidecar() {
+ let asset = "iphone-control_0.2.1_amd64.deb";
+ let mut release = Release { tag: "v0.2.1".into(), assets: vec![asset.into()], published_at: None, notes: None };
+ let status = |r: &Release| availability("0.2.0", InstallMethod::Debian, Some("linux-x86_64"), Some(r));
+ assert_eq!(status(&release), Availability::PlatformPending);
+ release.assets.push("iphone-control_0.2.1_arm64.deb.sha256".into());
+ assert_eq!(status(&release), Availability::PlatformPending);
+ release.assets.push(format!("{asset}.sha256"));
+ assert_eq!(status(&release), Availability::Available);
+ }
+
/// A managed install with signing keys: the archive alone (the signing job hasn't published the manifest and
/// its signature yet, or waits for approval) is pending, not a manual upgrade; with both it is available.
/// Without keys, or from a prerelease, it stays manual
diff --git a/apps/iphone-control/src/update/archive.rs b/apps/iphone-control/src/update/archive.rs
index 406ec7b..8a52d5c 100644
--- a/apps/iphone-control/src/update/archive.rs
+++ b/apps/iphone-control/src/update/archive.rs
@@ -47,7 +47,7 @@ pub(super) struct NeedsOperator(pub String);
impl std::fmt::Display for NeedsOperator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{} is not marked for automatic installation; install it with: iphone-control update apply", self.0)
+ write!(f, "{} is not marked for automatic installation; install it with: iphone-control update", self.0)
}
}
@@ -64,7 +64,7 @@ fn trusted(url: &Url) -> bool {
)
}
-fn client() -> anyhow::Result<Client> {
+pub(super) fn client() -> anyhow::Result<Client> {
Ok(Client::builder()
.user_agent("iphone-control-updater")
.https_only(true)
@@ -80,7 +80,7 @@ fn client() -> anyhow::Result<Client> {
.build()?)
}
-async fn download(client: &Client, url: &str, max: u64, mut out: impl Write) -> anyhow::Result<u64> {
+pub(super) async fn download(client: &Client, url: &str, max: u64, mut out: impl Write) -> anyhow::Result<u64> {
let mut response =
client.get(url).send().await.and_then(|r| r.error_for_status()).map_err(reqwest::Error::without_url)?;
ensure!(response.content_length().is_none_or(|s| s <= max), "release asset exceeds size limit");
diff --git a/apps/iphone-control/src/update/channel.rs b/apps/iphone-control/src/update/channel.rs
new file mode 100644
index 0000000..3f078a2
--- /dev/null
+++ b/apps/iphone-control/src/update/channel.rs
@@ -0,0 +1,346 @@
+//! Operator-initiated upgrades for verified package-manager installations.
+use std::fs::File;
+use std::path::Path;
+use std::process::Stdio;
+
+use anyhow::{Context, Result, bail, ensure};
+use ictl_l10n::tr;
+use tokio::process::Command;
+
+use super::{Availability, InstallMethod, Report, archive, deb_asset, digest, install, publisher, release, tap};
+
+pub(super) async fn apply(report: &Report) -> Result<()> {
+ let exe = report.executable.as_deref().context("missing installation path")?;
+ let latest = report.available_version.as_deref().context("missing release version")?;
+ ensure!(release::stable_tag(&format!("v{latest}")).is_some(), "invalid stable release version");
+ match (report.install_method, report.availability) {
+ (InstallMethod::Homebrew, Availability::BrewCheck) => {
+ let cellar = exe.ancestors().nth(4).context("missing Homebrew Cellar")?;
+ let tap = tap().context("missing Homebrew tap")?;
+ let brew = install::brew_program(cellar).context("cannot locate the Homebrew executable")?;
+ homebrew(&brew, cellar, tap, latest).await
+ }
+ (InstallMethod::Debian, Availability::Available) => {
+ let repo = publisher().context("missing release publisher")?;
+ let target = super::target().context("unsupported Debian architecture")?;
+ debian(repo, target, latest, exe).await
+ }
+ _ => bail!("{}", report.guidance),
+ }
+}
+
+async fn run(cmd: &mut Command) -> Result<()> {
+ let status =
+ cmd.status().await.with_context(|| format!("starting {}", cmd.as_std().get_program().to_string_lossy()))?;
+ ensure!(status.success(), "{}: {status}", cmd.as_std().get_program().to_string_lossy());
+ Ok(())
+}
+
+async fn output(cmd: &mut Command) -> Result<String> {
+ let result = cmd
+ .stderr(Stdio::inherit())
+ .output()
+ .await
+ .with_context(|| format!("starting {}", cmd.as_std().get_program().to_string_lossy()))?;
+ ensure!(result.status.success(), "{}: {}", cmd.as_std().get_program().to_string_lossy(), result.status);
+ Ok(String::from_utf8(result.stdout)?)
+}
+
+async fn homebrew(brew: &Path, cellar: &Path, tap: &str, latest: &str) -> Result<()> {
+ let formula = format!("{tap}/iphone-control");
+ let active = cellar.parent().context("invalid Homebrew prefix")?.join("opt/iphone-control/bin/iphone-control");
+ let installed = || {
+ active
+ .canonicalize()
+ .ok()
+ .and_then(|exe| install::brew_keg(&exe, cellar, tap))
+ .context("Homebrew's active keg does not match this installation and tap")
+ };
+ let before = semver::Version::parse(&installed()?)?;
+ if before >= semver::Version::parse(latest)? {
+ println!("{}", ictl_l10n::trf!("Homebrew 当前版本为 {before}。", "Homebrew already has {before}."));
+ return Ok(());
+ }
+ run(Command::new(brew).arg("update")).await?;
+ // Use exactly the metadata refreshed above for the check and upgrade.
+ let cmd = || {
+ let mut c = Command::new(brew);
+ c.env("HOMEBREW_NO_AUTO_UPDATE", "1");
+ c
+ };
+ let info = output(cmd().args(["info", "--formula", "--json=v2", &formula])).await?;
+ let info: serde_json::Value = serde_json::from_str(&info)?;
+ let f = &info["formulae"][0];
+ ensure!(
+ f["full_name"].as_str().is_some_and(|s| s.eq_ignore_ascii_case(&formula)),
+ "Homebrew formula identity changed"
+ );
+ ensure!(f["pinned"] == false, "{}", tr!("Homebrew 已固定此版本。", "This formula is pinned in Homebrew."));
+ ensure!(
+ f["versions"]["stable"] == latest,
+ "{}",
+ ictl_l10n::trf!(
+ "Homebrew tap 尚未提供目标版本 {latest}。",
+ "The Homebrew tap does not offer version {latest} yet."
+ )
+ );
+ run(cmd().args(["upgrade", "--formula", &formula])).await?;
+ ensure!(installed()? == latest, "Homebrew did not activate {latest}");
+ println!(
+ "{}",
+ ictl_l10n::trf!(
+ "Homebrew 已升级至 {latest}。如果正在使用 Homebrew 后台服务,运行 brew services restart iphone-control 加载新版。Viewer 和 MCP 客户端将在下次启动时加载新版。",
+ "Homebrew upgraded to {latest}. If your Homebrew service is running, run brew services restart iphone-control to load it. Viewer and MCP clients load the new version on their next start."
+ )
+ );
+ Ok(())
+}
+
+fn checksum<'a>(text: &'a str, asset: &str) -> Result<&'a str> {
+ // The release job emits exactly one sha256sum record using this filename.
+ let (hash, name) = text.trim_end_matches(['\r', '\n']).split_once(" ").context("invalid release checksum file")?;
+ ensure!(
+ name == asset && hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()),
+ "invalid checksum or Debian asset name"
+ );
+ Ok(hash)
+}
+
+fn check_deb_metadata<'a>(fields: &'a str, version: &str, arch: &str) -> Result<&'a str> {
+ let mut lines = fields.lines();
+ let (name, package_version, architecture) = (lines.next(), lines.next(), lines.next());
+ let package_version = package_version.context("missing Debian package version")?;
+ // cargo-deb adds its Debian revision to the upstream package version.
+ ensure!(
+ name == Some("iphone-control")
+ && architecture == Some(arch)
+ && lines.next().is_none()
+ && (package_version == version || package_version.strip_suffix("-1") == Some(version)),
+ "Debian package metadata does not match iphone-control {version} {arch}"
+ );
+ Ok(package_version)
+}
+
+async fn inspect_deb(path: &Path, latest: &str, arch: &str) -> Result<String> {
+ let fields = output(
+ Command::new("/usr/bin/dpkg-deb")
+ .args(["--showformat=${Package}\\n${Version}\\n${Architecture}\\n", "--show"])
+ .arg(path),
+ )
+ .await?;
+ Ok(check_deb_metadata(&fields, latest, arch)?.to_owned())
+}
+
+async fn check_apt_candidate(apt_cache: &mut Command, path: &Path, deb_version: &str) -> Result<()> {
+ // A direct .deb argument selects that version explicitly; also honor local
+ // APT priorities as if the verified file were a package source.
+ let policy =
+ output(apt_cache.env("LC_ALL", "C").arg("--with-source").arg(path).args(["policy", "iphone-control"])).await?;
+ let candidate = policy.lines().find_map(|line| line.trim().strip_prefix("Candidate: "));
+ ensure!(
+ candidate == Some(deb_version),
+ "{}",
+ ictl_l10n::trf!("APT 本机策略未选择 {deb_version}。", "Local APT policy did not select {deb_version}.")
+ );
+ Ok(())
+}
+
+async fn debian(repo: &str, target: &str, latest: &str, exe: &Path) -> Result<()> {
+ let asset = deb_asset(latest, target).context("unsupported Debian architecture")?;
+ let arch = asset.rsplit_once('_').and_then(|(_, s)| s.strip_suffix(".deb")).context("invalid Debian asset name")?;
+ let base = format!("https://github.com/{repo}/releases/download/v{latest}/{asset}");
+ let client = archive::client()?;
+ let mut sidecar = Vec::new();
+ archive::download(&client, &format!("{base}.sha256"), 1024, &mut sidecar).await?;
+ let expected = checksum(std::str::from_utf8(&sidecar)?, &asset)?;
+ let temp = tempfile::tempdir()?;
+ let path = temp.path().canonicalize()?.join(&asset);
+ archive::download(&client, &base, 128 << 20, File::create_new(&path)?).await?;
+ ensure!(digest(&path)? == expected, "Debian package SHA-256 mismatch");
+ let deb_version = inspect_deb(&path, latest, arch).await?;
+ let current = install::detect(Some(exe));
+ ensure!(current.method == InstallMethod::Debian, "Debian package ownership changed");
+ let current = semver::Version::parse(&current.version.context("missing installed Debian version")?)?;
+ if current >= semver::Version::parse(latest)? {
+ println!("{}", ictl_l10n::trf!("APT 当前版本为 {current}。", "APT already has {current}."));
+ return Ok(());
+ }
+ let held = output(Command::new("/usr/bin/apt-mark").args(["showhold", "iphone-control"])).await?;
+ ensure!(held.trim().is_empty(), "{}", tr!("APT 已锁定 iphone-control。", "iphone-control is on hold in APT."));
+
+ check_apt_candidate(&mut Command::new("/usr/bin/apt-cache"), &path, &deb_version).await?;
+ // Make APT reject late downgrades, removals or hold changes while it owns
+ // its locks, even if the package state changed during the sudo prompt.
+ run(Command::new("/usr/bin/sudo")
+ .args([
+ "/usr/bin/apt-get",
+ "install",
+ "--only-upgrade",
+ "--assume-yes",
+ "--no-remove",
+ "-o",
+ "APT::Get::allow-downgrades=false",
+ "-o",
+ "APT::Get::allow-change-held-packages=false",
+ "-o",
+ "APT::Ignore-Hold=false",
+ "-o",
+ "APT::Get::force-yes=false",
+ ])
+ .arg(&path))
+ .await?;
+ let installed = install::detect(Some(exe));
+ ensure!(
+ installed.method == InstallMethod::Debian && installed.version.as_deref() == Some(latest),
+ "APT did not install {latest}"
+ );
+ println!(
+ "{}",
+ ictl_l10n::trf!(
+ "APT 已升级至 {latest}。如果正在使用 systemd 用户服务,运行 systemctl --user restart iphone-control 加载新版。Viewer 和 MCP 客户端将在下次启动时加载新版。",
+ "APT upgraded to {latest}. If your systemd user service is running, run systemctl --user restart iphone-control to load it. Viewer and MCP clients load the new version on their next start."
+ )
+ );
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn brew_upgrades_the_exact_active_formula_only_after_the_tap_is_ready() {
+ use std::os::unix::fs::{PermissionsExt, symlink};
+ let temp = tempfile::tempdir().unwrap();
+ let prefix = temp.path().canonicalize().unwrap();
+ let cellar = prefix.join("Cellar");
+ let rack = cellar.join("iphone-control");
+ let tap = "example/tools";
+ for version in ["1.2.2", "1.2.3"] {
+ let keg = rack.join(version);
+ std::fs::create_dir_all(keg.join("bin")).unwrap();
+ std::fs::write(keg.join("bin/iphone-control"), b"").unwrap();
+ std::fs::write(keg.join("INSTALL_RECEIPT.json"), br#"{"source":{"tap":"example/tools"}}"#).unwrap();
+ }
+ std::fs::create_dir(prefix.join("opt")).unwrap();
+ let active = prefix.join("opt/iphone-control");
+ symlink(rack.join("1.2.2"), &active).unwrap();
+ let brew = prefix.join("brew");
+ std::fs::write(
+ &brew,
+ r#"#!/bin/sh
+set -eu
+cd "$(dirname "$0")"
+case "$*" in
+ update) ;;
+ "info --formula --json=v2 example/tools/iphone-control") cat info ;;
+ "upgrade --formula example/tools/iphone-control")
+ touch attempted
+ test -f allow || exit 17
+ rm opt/iphone-control
+ ln -s "$PWD/Cellar/iphone-control/1.2.3" opt/iphone-control ;;
+ *) exit 12 ;;
+esac
+"#,
+ )
+ .unwrap();
+ std::fs::set_permissions(&brew, std::fs::Permissions::from_mode(0o755)).unwrap();
+ let set_info = |formula, version, pinned| {
+ let info =
+ serde_json::json!({"formulae":[{"full_name":formula, "versions":{"stable":version}, "pinned":pinned}]});
+ std::fs::write(prefix.join("info"), info.to_string()).unwrap();
+ };
+ for (name, version, pinned) in [
+ ("other/tools/iphone-control", "1.2.3", false),
+ ("example/tools/iphone-control", "1.2.2", false),
+ ("example/tools/iphone-control", "1.2.3", true),
+ ] {
+ set_info(name, version, pinned);
+ assert!(homebrew(&brew, &cellar, tap, "1.2.3").await.is_err());
+ assert!(!prefix.join("attempted").exists());
+ }
+ set_info("example/tools/iphone-control", "1.2.3", false);
+ let err = homebrew(&brew, &cellar, tap, "1.2.3").await.unwrap_err();
+ assert!(err.to_string().contains("17"));
+ std::fs::write(prefix.join("allow"), b"").unwrap();
+ homebrew(&brew, &cellar, tap, "1.2.3").await.unwrap();
+ assert_eq!(active.canonicalize().unwrap(), rack.join("1.2.3"));
+ }
+
+ #[test]
+ fn deb_checksum_is_bound_to_one_exact_asset_and_the_payload() {
+ let temp = tempfile::tempdir().unwrap();
+ let asset = "iphone-control_1.2.3_arm64.deb";
+ let path = temp.path().join(asset);
+ std::fs::write(&path, b"package").unwrap();
+ let sha = digest(&path).unwrap();
+ let record = format!("{sha} {asset}\n");
+ assert_eq!(checksum(&record, asset).unwrap(), digest(&path).unwrap());
+ std::fs::write(&path, b"different").unwrap();
+ assert_ne!(checksum(&record, asset).unwrap(), digest(&path).unwrap());
+ for bad in [record.replace(asset, "../pkg.deb"), record.repeat(2), record.replace(&sha, "1234")] {
+ assert!(checksum(&bad, asset).is_err());
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ #[tokio::test]
+ async fn inspect_a_real_deb_archive_before_install() {
+ let dpkg = Path::new("/usr/bin/dpkg-deb");
+ // Non-Debian Linux hosts need no Debian tools.
+ if !dpkg.exists() {
+ return;
+ }
+ let temp = tempfile::tempdir().unwrap();
+ let root = temp.path().join("pkg");
+ let data = root.join("DEBIAN");
+ std::fs::create_dir_all(&data).unwrap();
+ let arch = output(Command::new("/usr/bin/dpkg").arg("--print-architecture")).await.unwrap();
+ let arch = arch.trim();
+ let fields = format!(
+ "Package: iphone-control\nVersion: 1.2.3-1\nArchitecture: {arch}\nMaintainer: Test <[email protected]>\nDescription: Local update test\n"
+ );
+ std::fs::write(data.join("control"), fields).unwrap();
+ let path = temp.path().join(format!("iphone-control_1.2.3_{arch}.deb"));
+ run(Command::new(dpkg).arg("--build").arg(&root).arg(&path)).await.unwrap();
+ assert_eq!(inspect_deb(&path, "1.2.3", arch).await.unwrap(), "1.2.3-1");
+ assert!(inspect_deb(&path, "1.3.0", arch).await.is_err());
+ assert!(inspect_deb(&path, "1.2.3", "wrong-arch").await.is_err());
+
+ // Use APT's actual policy engine with an empty package inventory. A
+ // negative version pin must win even though we supply a valid local file.
+ let empty = temp.path().join("empty");
+ std::fs::create_dir(&empty).unwrap();
+ let prefs = temp.path().join("preferences");
+ std::fs::write(&prefs, b"").unwrap();
+ let policy = || {
+ let mut cmd = Command::new("/usr/bin/apt-cache");
+ for option in [
+ "Dir::State::status=/dev/null".to_owned(),
+ "Dir::Etc::sourcelist=/dev/null".to_owned(),
+ format!("Dir::Etc::sourceparts={}", empty.display()),
+ format!("Dir::Etc::preferences={}", prefs.display()),
+ format!("Dir::Etc::preferencesparts={}", empty.display()),
+ ] {
+ cmd.arg("-o").arg(option);
+ }
+ cmd
+ };
+ check_apt_candidate(&mut policy(), &path, "1.2.3-1").await.unwrap();
+ std::fs::write(&prefs, "Package: iphone-control\nPin: version 1.2.3-1\nPin-Priority: -1\n").unwrap();
+ assert!(check_apt_candidate(&mut policy(), &path, "1.2.3-1").await.is_err());
+ }
+
+ #[test]
+ fn deb_metadata_must_match_the_release_and_host() {
+ let fields = "iphone-control\n1.2.3-1\narm64\n";
+ check_deb_metadata(fields, "1.2.3", "arm64").unwrap();
+ for bad in [
+ fields.replace("iphone-control", "other"),
+ fields.replace("1.2.3", "1.2.2"),
+ fields.replace("arm64", "amd64"),
+ ] {
+ assert!(check_deb_metadata(&bad, "1.2.3", "arm64").is_err());
+ }
+ }
+}
diff --git a/apps/iphone-control/src/update/install.rs b/apps/iphone-control/src/update/install.rs
index 3ef8169..46ec876 100644
--- a/apps/iphone-control/src/update/install.rs
+++ b/apps/iphone-control/src/update/install.rs
@@ -164,7 +164,7 @@ pub(super) fn cargo_source(exe: &Path, manifest_dir: &Path) -> Option<(String, S
Some((version, command))
}
-fn brew_keg(exe: &Path, cellar: &Path, tap: &str) -> Option<String> {
+pub(super) fn brew_keg(exe: &Path, cellar: &Path, tap: &str) -> Option<String> {
let version = exe.strip_prefix(cellar.join("iphone-control")).ok()?.components().next()?.as_os_str();
let keg = cellar.join("iphone-control").join(version);
if exe != keg.join("bin/iphone-control") {
@@ -228,7 +228,7 @@ fn deb_package(exe: &Path) -> Option<String> {
return None;
}
let installed = dpkg(&["-W", "-f=${db:Status-Abbrev} ${Version}", owner])?;
- let version = installed.strip_prefix("ii ")?.trim();
+ let version = installed.strip_prefix("ii ").or_else(|| installed.strip_prefix("hi "))?.trim();
let upstream = version.rsplit_once('-').map_or(version, |(upstream, _)| upstream);
Some(Version::parse(upstream).ok()?.to_string())
}
diff --git a/apps/iphone-control/src/update/transaction.rs b/apps/iphone-control/src/update/transaction.rs
index 4af41c5..d77f51b 100644
--- a/apps/iphone-control/src/update/transaction.rs
+++ b/apps/iphone-control/src/update/transaction.rs
@@ -478,11 +478,10 @@ fn managed(receipt: &Receipt) -> Result<(Store, Service)> {
Ok((store, svc))
}
-pub async fn apply(socket: &Path, background: bool) -> Result<()> {
+pub async fn apply(socket: &Path, background: bool, report: super::Report) -> Result<()> {
let receipt = read_receipt()?;
let (store, service) = managed(&receipt)?;
ensure!(!receipt.pinned, "this installation is pinned; unpin it locally first");
- let report = super::check(background).await?;
ensure!(report.error_code.is_none(), "release check failed: {:?}", report.error_code);
ensure!(matches!(report.availability, super::Availability::Available), "{}", report.guidance);
let version = report.available_version.context("no stable release is available")?;
@@ -493,7 +492,7 @@ pub async fn apply(socket: &Path, background: bool) -> Result<()> {
let suppressed = outcome(&store.binary)?.and_then(|o| o.suppression_for(&receipt));
ensure!(
suppressed.as_ref() != Some(&version),
- "automatic retry suppressed for {version}; run update apply to retry"
+ "automatic retry suppressed for {version}; run iphone-control update to retry"
);
// An always-open client may stay busy for days. The lease here is deliberately
// short-lived; replacement reacquires it and rechecks identity after download.
diff --git a/apps/iphone-control/src/update/transaction/tests.rs b/apps/iphone-control/src/update/transaction/tests.rs
index 2a104e2..084cf39 100644
--- a/apps/iphone-control/src/update/transaction/tests.rs
+++ b/apps/iphone-control/src/update/transaction/tests.rs
@@ -357,6 +357,6 @@ async fn confirmed_checkpoint_finishes_metadata_and_unknown_disk_is_preserved()
fn a_release_without_unattended_mark_is_not_a_failure() {
let e = anyhow::Error::from(archive::NeedsOperator("0.2.2".into()));
assert_eq!(failure_status(&e), "needs_operator");
- assert!(e.to_string().contains("update apply"), "{e}");
+ assert!(e.to_string().ends_with("iphone-control update"), "{e}");
assert_eq!(failure_status(&anyhow::anyhow!("archive digest mismatch")), "failed");
}
diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.html
index 3aca8cf..6252b43 100644
--- a/apps/iphone-control/src/viewer.html
+++ b/apps/iphone-control/src/viewer.html
@@ -2005,7 +2005,7 @@ function drawUpdates(r) {
needs_operator: t('等待手动升级', 'Waiting for manual upgrade'),
busy: t('等待空闲', 'Waiting for idle'), recovery_failed: t('需要手动恢复', 'Recovery needs attention') };
const last = r.last_update?.status;
- const outcome = last === 'needs_operator' ? t('需手动运行 iphone-control update apply', 'Run iphone-control update apply manually') : outcomes[last] || last;
+ const outcome = last === 'needs_operator' ? t('需手动运行 iphone-control update', 'Run iphone-control update manually') : outcomes[last] || last;
$('#update-outcome').textContent = r.last_update ? [r.last_update.target_version, outcome, r.last_update.detail].filter(Boolean).join(' · ') : '';
$('#update-mismatch').textContent = [r.installed_version, r.daemon_version].some(v => v && v !== r.running_version) ?
t('进程版本不同。重新打开 Viewer,重连 MCP 客户端,并按安装渠道重启 daemon。', 'Versions differ. Reopen Viewer, reconnect MCP clients and restart the daemon through its installation channel.') : '';
diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md
index a403d35..3d261c4 100644
--- a/docs/dev/regression-cases.md
+++ b/docs/dev/regression-cases.md
@@ -96,3 +96,4 @@
| 90 | 新页面一直黑屏:刚开流时要的关键帧手机不理,流自带的第一个关键帧在订阅前就过去了 | 没收到关键帧时每 250 毫秒再要一次 | 真机:刚开流 1.6~1.8 秒出第一帧 |
| 91 | 手机按请求补发的关键帧不带参数集,新页面从它开始解不了 | 组帧时记下 VPS/SPS/PPS,补到这样的关键帧前面 | 单测 keyframes_get_the_parameter_sets |
| 92 | 横屏时页面上的画面上下颠倒(转正方向写反) | 按「竖放顶边顺时针转过的角度」同向转回来;方向每秒问一次 | 真机:向左、向右横屏的画面和手机截图一致,1.1~2.7 秒跟上;横屏点地址栏点中 |
+| 93 | 在本机运行 `iphone-control update` 只出现子命令帮助,还要再查该用哪种升级命令 | 先检查当前版本。已是最新则提示并结束,有可升级版本时按核实的安装渠道处理,固定版本仍需显式解除 | 单测(`user_update_checks_the_release_before_choosing_an_installer`) |
diff --git a/website/deploy/macos.md b/website/deploy/macos.md
index a015fc2..f0a71ff 100644
--- a/website/deploy/macos.md
+++ b/website/deploy/macos.md
@@ -111,7 +111,9 @@ sudo launchctl kickstart -k system/com.apple.usbmuxd
升级前先看[更新日志](https://github.com/Derrors/iphone-control/blob/main/CHANGELOG.zh-CN.md)里的升级注意事项。
-受管脚本安装:关闭 Viewer、MCP 等客户端后,运行 `iphone-control update apply`。Homebrew:`brew upgrade iphone-control && brew services restart iphone-control`。从源码编译:
+受管脚本安装先关闭 Viewer、MCP 等客户端,再运行 `iphone-control update`。Homebrew 安装也可使用这条命令,它会通过对应的 tap 升级磁盘上的程序。已经通过 Homebrew 运行后台服务的,升级后运行 `brew services restart iphone-control`。原先未启用服务则跳过这一步。重新打开 Viewer、重连 MCP 客户端后即可使用新版。
+
+源码安装请运行以下命令。
```bash
cd iphone-control && git pull
diff --git a/website/en/deploy/macos.md b/website/en/deploy/macos.md
index 604cdcf..834ef39 100644
--- a/website/en/deploy/macos.md
+++ b/website/en/deploy/macos.md
@@ -111,7 +111,9 @@ sudo launchctl kickstart -k system/com.apple.usbmuxd
Read the upgrade notes in the [changelog](https://github.com/Derrors/iphone-control/blob/main/CHANGELOG.md) first.
-For a managed script installation, close active clients and run `iphone-control update apply`. Homebrew: `brew upgrade iphone-control && brew services restart iphone-control`. From source:
+For a managed script installation, close Viewer, MCP and other device clients, then run `iphone-control update`. On Homebrew the same command upgrades the executable on disk through the tap. If you already run the Homebrew service, restart it with `brew services restart iphone-control`. Skip this step if you do not use a service. Reopen Viewer and reconnect your MCP client to use the new version.
+
+For a source build, run the following commands.
```bash
cd iphone-control && git pull
diff --git a/website/en/guide/cli.md b/website/en/guide/cli.md
index 7a0ce6c..de0f108 100644
--- a/website/en/guide/cli.md
+++ b/website/en/guide/cli.md
@@ -23,11 +23,22 @@ These go before the command, for example `iphone-control --socket /path/ctl.sock
## Host software updates
-`iphone-control update check [--json]` and **About & updates** in Viewer share the local release cache. A source build without a publisher makes no network request. A failed check keeps the previous successful result. A red dot on the ⓘ button next to **Settings** indicates a newer stable release. Open it to read the version and release excerpt in the selected language and copy the command for your installation. For Homebrew, the tap determines when the upgrade is available. For Debian or Ubuntu, download the listed package before running the command.
+Run `iphone-control update` to check the publisher's latest stable release. It reports when you are up to date. When an upgrade is available, it uses the installation method of the running executable.
-Viewer listens on loopback. Other users on the same host can see installation information and request a version check. Installation, rollback and policy changes use the local CLI.
+| Installation | What `iphone-control update` does |
+| --- | --- |
+| Managed per-user service installed by the signed release script | Verifies and installs the signed update, then restarts the service and checks its health. Close Viewer, MCP and other device clients first. If you pinned a version with `--version`, run `iphone-control update unpin` when you are ready to upgrade. |
+| Homebrew | Runs the Homebrew upgrade through the tap bound to this installation. The tap determines which version is available. |
+| Debian / Ubuntu package | Downloads the matching `.deb` for the target version and host architecture from the same publisher, verifies it and passes it to apt for installation. |
+| Source builds, script installs without a managed service, or unrecognized installations | Shows instructions for a manual upgrade. A development build without a publisher displays guidance locally. |
-A managed per-user service installed by the release script checks in the background by default. Use `update apply` to install from the terminal, `update rollback` for the previous verified executable, or `update recover` after an interrupted replacement. A version selected with `install.sh --version` remains pinned until `update unpin`.
+Homebrew and apt upgrade the executable on disk. If you already run a background service, restart it after the upgrade with `brew services restart iphone-control` for Homebrew or `systemctl --user restart iphone-control` for a Debian user service. Skip this step if you do not use a service. Reopen Viewer and reconnect your MCP client to use the new executable.
+
+Use `iphone-control update check` for a version check only, or `iphone-control update check --json` for machine-readable output. This check and **About & updates** in Viewer share the local release cache. If the network check fails, the previous successful record is kept. A red dot on the ⓘ button beside **Settings** indicates a newer release. Open the panel to read the release notes and copy the update command for the current executable into a local terminal.
+
+Viewer listens on loopback. Other users on the same host can read installation information and request a version check. Upgrade, rollback and policy changes are performed from a local terminal.
+
+Managed services check in the background by default. You can still use `update apply` to install, `update rollback` to restore the previous verified executable and `update recover` after an interrupted replacement. If you currently run the 0.2.2 CLI, use `iphone-control update check` and follow the command it shows to upgrade to a version with the new `iphone-control update` command.
Run `iphone-control update policy auto-patch` to opt in to installing compatible patches when idle. Viewer, MCP and direct device clients (including paused tasks) must exit before the service can restart. If the new daemon fails its health checks the updater restores the old executable and holds the failed version for an explicit retry. `update policy notify` checks without installing; `update policy manual` removes the scheduled job.
diff --git a/website/en/guide/getting-started.md b/website/en/guide/getting-started.md
index 859b4cc..34e0f3d 100644
--- a/website/en/guide/getting-started.md
+++ b/website/en/guide/getting-started.md
@@ -23,7 +23,7 @@ Pick one of the three. Install as your regular user; don't run `iphone-control`
curl -fsSLo iphone-control-install.sh https://github.com/Derrors/iphone-control/releases/latest/download/install.sh && sh iphone-control-install.sh
```
-It installs the program into `~/.local/bin` and the daemon as a per-user service (launchd on macOS, a systemd user service on Linux) that starts when you log in. Run `iphone-control update check` for upgrade instructions. Pass `--version vX.Y.Z` for a specific signed release, `--prefix DIR` to install into `DIR/bin`, or `--no-service` to install only the program. For upstream v0.2.0, use the [legacy script instructions](#legacy-script).
+It installs the program into `~/.local/bin` and the daemon as a per-user service (launchd on macOS, a systemd user service on Linux) that starts when you log in. Run `iphone-control update` to check for and install an upgrade, or `iphone-control update check` to check versions only. Pass `--version vX.Y.Z` for a specific signed release, `--prefix DIR` to install into `DIR/bin`, or `--no-service` to install only the program. For upstream v0.2.0, use the [legacy script instructions](#legacy-script).
**Homebrew** (macOS, Linux):
diff --git a/website/guide/cli.md b/website/guide/cli.md
index de47f20..0ea5eed 100644
--- a/website/guide/cli.md
+++ b/website/guide/cli.md
@@ -23,11 +23,22 @@
## 主机软件更新
-`iphone-control update check [--json]` 和 Viewer 的「关于与更新」读取同一份本地缓存。未绑定发布者的源码构建不会联网;网络检查失败会保留上次成功的结果。有更新时,侧栏底部「设置」旁的 ⓘ 会显示红点。点开可查看版本号和当前界面语言的发行说明摘录,复制适合当前安装方式的升级命令。Homebrew 以对应 tap 提供的版本为准。Debian 或 Ubuntu 用户先下载面板指定的安装包,再运行命令。
+运行 `iphone-control update` 检查发布者的最新稳定版。已是最新时,命令会显示结果并退出。有新版时,它按当前程序的安装方式升级。
+
+| 安装方式 | 运行 `iphone-control update` 后 |
+| --- | --- |
+| 签名安装脚本部署的受管用户服务 | 验证并安装签名更新,重启服务并检查健康状态。先关闭 Viewer、MCP 和其他设备客户端。通过 `--version` 固定版本的安装,须先显式运行 `iphone-control update unpin` 才能升级。 |
+| Homebrew | 通过该安装绑定的 tap 运行 Homebrew 升级,以 tap 提供的版本为准。 |
+| Debian / Ubuntu 软件包 | 下载同一发布者提供的、匹配目标版本和主机架构的 `.deb`,经过校验后交给 apt 安装。 |
+| 源码安装、没有受管服务的脚本安装或无法识别的安装 | 显示适用的手动升级指引。未绑定发布者的开发构建在本地给出说明。 |
+
+Homebrew 和 apt 升级的是磁盘上的程序。如果原先已经运行后台服务,升级后用 `brew services restart iphone-control` 重启 Homebrew 服务,或用 `systemctl --user restart iphone-control` 重启 Debian 的用户服务。原先未启用服务的安装可跳过这一步。重新打开 Viewer、重连 MCP 客户端后,这些进程也会使用新版。
+
+只想查看版本可运行 `iphone-control update check`,脚本可用 `iphone-control update check --json` 读取结果。该检查与 Viewer「关于与更新」共用本地缓存,网络失败时保留上次成功的记录。Viewer 在「设置」旁的 ⓘ 上用红点提示新版本。打开面板可查看发行说明,并复制针对当前程序路径的更新命令,在本机终端执行。
Viewer 只监听本机回环地址。同机其他用户也能查看安装信息、触发版本检查。安装、回滚和更改策略都通过本机 CLI 执行。
-由发行版安装脚本部署的受管用户服务默认只做后台检查。本机运行 `update apply` 安装,`update rollback` 恢复上一份已验证的程序。替换意外中断时可运行 `update recover`。用安装器 `--version` 固定的版本需先 `update unpin`。
+受管服务默认只做后台检查。显式安装仍可用 `update apply`,恢复前一个已验证版本用 `update rollback`,替换意外中断后用 `update recover`。如果正在使用 0.2.2 的 CLI,先运行 `iphone-control update check` 并按该版本显示的命令升级。新版 CLI 才支持直接运行 `iphone-control update`。
主动运行 `iphone-control update policy auto-patch` 后,服务只在空闲时自动安装兼容补丁。请退出 Viewer、MCP 和直连设备的客户端;暂停的任务也视为占用。新 daemon 健康检查失败会恢复旧程序,失败版本须手动重试。`update policy notify` 改回仅检查,`update policy manual` 移除定时任务。
diff --git a/website/guide/getting-started.md b/website/guide/getting-started.md
index b62df26..8298ec0 100644
--- a/website/guide/getting-started.md
+++ b/website/guide/getting-started.md
@@ -23,7 +23,7 @@
curl -fsSLo iphone-control-install.sh https://github.com/Derrors/iphone-control/releases/latest/download/install.sh && sh iphone-control-install.sh
```
-程序装到 `~/.local/bin`,守护进程装成用户服务(macOS 用 launchd,Linux 用 systemd),登录后自动启动。运行 `iphone-control update check` 查看升级指引。给脚本传入 `--version vX.Y.Z` 可装指定的签名版本,`--prefix DIR` 可装到 `DIR/bin`,`--no-service` 可只装程序。上游 v0.2.0 请按[旧版脚本说明](#legacy-script)操作。
+程序装到 `~/.local/bin`,守护进程装成用户服务(macOS 用 launchd,Linux 用 systemd),登录后自动启动。运行 `iphone-control update` 检查并升级。只想查看版本可用 `iphone-control update check`。给脚本传入 `--version vX.Y.Z` 可装指定的签名版本,`--prefix DIR` 可装到 `DIR/bin`,`--no-service` 可只装程序。上游 v0.2.0 请按[旧版脚本说明](#legacy-script)操作。
**Homebrew**(macOS、Linux):