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
feat(service): run the viewer as a background service of its own (#74)
Qinghe Li83ff3783bd48
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3942f13..851e804 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ All notable changes to this project are documented here. The format is based on### Added+- `iphone-control service viewer install` runs the viewer as a background service of its own that starts at login (`uninstall`, `start`, `stop`, `restart` too). It reads its port and whether it is open to the local network from the settings file (`IPHONE_CONTROL_VIEWER_PORT`, new; `IPHONE_CONTROL_VIEWER_LAN`; `IPHONE_CONTROL_VIEWER_LAN_HOSTS`, new) and keeps the installing shell's `PATH` to find `claude` and `codex`. Updates stop it and start it again; an automatic update waits while an AI task runs.- Navigate setup menus with arrow keys, confirm with Enter, or cancel with Esc. Number selection remains available, and basic terminals keep the line-by-line prompts.- Generate Bash, Zsh and Fish completion scripts with `iphone-control completions <shell>`, without starting the daemon or accessing a device.- `iphone-control viewer --lan` (or `IPHONE_CONTROL_VIEWER_LAN=1`) also opens the control page to the local network, on the same port. There is no login yet: anyone on the network who can reach the machine can control the phone, so only use it on a trusted network. It only accepts connections from local-network addresses and only answers to this machine's own names; `--lan-host` adds another name. Opened at a network address the picture is MJPEG, since browsers only offer WebCodecs on localhost or HTTPS.diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex e59f02d..632eace 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -8,6 +8,7 @@### 新增+- `iphone-control service viewer install` 把控制台装成登录后自动启动的后台服务(还有 `uninstall`、`start`、`stop`、`restart`)。端口和是否对局域网开放读设置文件(新增 `IPHONE_CONTROL_VIEWER_PORT`;`IPHONE_CONTROL_VIEWER_LAN`;新增 `IPHONE_CONTROL_VIEWER_LAN_HOSTS`),并记下安装时终端的 `PATH` 以找到 `claude` 和 `codex`。升级时先停下它、升级完再启动;有 AI 任务在跑时自动升级会推迟。- 设置菜单支持方向键选择、Enter 确认和 Esc 取消,保留数字选择;基础终端继续使用逐行提示。- `iphone-control completions <shell>` 可生成 Bash、Zsh 和 Fish 补全脚本,不启动守护进程、不访问设备。- `iphone-control viewer --lan`(或 `IPHONE_CONTROL_VIEWER_LAN=1`)让控制台也对局域网开放,还是同一个端口。还没有登录:局域网里任何能连上这台机器的人都能操作手机,只在可信的网络里开。只接受局域网地址来的连接,只认本机自己的名字和地址;`--lan-host` 可以再加名字。从局域网地址打开时画面是 MJPEG,因为浏览器只在 localhost 或 HTTPS 上提供 WebCodecs。diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex 31cf6d3..e58c6a3 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -109,11 +109,12 @@ enum Command {},#[command(about = ictl_l10n::tr!("浏览器里的控制台:实时画面上直接操作手机、看设备状态,把任务交给本机的 Claude Code 或 Codex 执行。只开在 127.0.0.1,操作都经守护进程(默认不监听任何端口)", "Control page in a browser: act on the live screen, see the device's state, and hand tasks to a local Claude Code or Codex. Serves 127.0.0.1 only, every action goes through the daemon (by default no port is opened)"))]Viewer {- #[arg(long, default_value_t = 8200)]+ #[arg(long, env = "IPHONE_CONTROL_VIEWER_PORT", default_value_t = 8200)]port: u16,- #[arg(long, env = "IPHONE_CONTROL_VIEWER_LAN", help = ictl_l10n::tr!("也对局域网开放(同一个端口、HTTP、还没有登录:局域网里任何人都能操作手机),只接受局域网地址来的连接", "Also open to the local network (same port, HTTP, no login yet: anyone on the network can control the phone); only connections from local-network addresses"))]+ // from the settings file as 1/0, yes/no, on/off or true/false (a plain flag's parser only takes true/false)+ #[arg(long, env = "IPHONE_CONTROL_VIEWER_LAN", value_parser = clap::builder::BoolishValueParser::new(), help = ictl_l10n::tr!("也对局域网开放(同一个端口、HTTP、还没有登录:局域网里任何人都能操作手机),只接受局域网地址来的连接", "Also open to the local network (same port, HTTP, no login yet: anyone on the network can control the phone); only connections from local-network addresses"))]lan: bool,- #[arg(long = "lan-host", value_name = "HOST", help = ictl_l10n::tr!("--lan 时还认可的主机名(可写多次);本机主机名、<主机名>.local 和各网卡 IP 已自动认可", "With --lan, another host name the page answers to (repeatable); this machine's name, <name>.local and its addresses are already accepted"))]+ #[arg(long = "lan-host", value_name = "HOST", env = "IPHONE_CONTROL_VIEWER_LAN_HOSTS", value_delimiter = ',', help = ictl_l10n::tr!("--lan 时还认可的主机名(可写多次);本机主机名、<主机名>.local 和各网卡 IP 已自动认可", "With --lan, another host name the page answers to (repeatable); this machine's name, <name>.local and its addresses are already accepted"))]lan_hosts: Vec<String>,},#[command(about = ictl_l10n::tr!("AI 任务:在任务里运行外部 agent(task run),查看、暂停、接管、停止、确认任务", "AI tasks: run an external agent in a task (task run); list, pause, take over, stop and confirm tasks"))]@@ -167,6 +168,22 @@ enum ServiceAction {#[command(about = ictl_l10n::tr!("重启,改过 ~/.config/iphone-control/env 后用", "Restart, after editing ~/.config/iphone-control/env"))]Restart,Status,+ #[command(about = ictl_l10n::tr!("控制台(viewer)的后台服务:install / uninstall / start / stop / restart。设置在 ~/.config/iphone-control/env 的 IPHONE_CONTROL_VIEWER_*", "The viewer's own service: install / uninstall / start / stop / restart. Settings: IPHONE_CONTROL_VIEWER_* in ~/.config/iphone-control/env"))]+ Viewer {+ #[command(subcommand)]+ action: ViewerServiceAction,+ },+}++#[derive(Subcommand)]+enum ViewerServiceAction {+ #[command(about = ictl_l10n::tr!("装成登录后自动启动的服务并启动;会记下当前终端的 PATH(找 claude、codex 用),PATH 变了再装一次", "Set up the service that starts at login and start it; it keeps this shell's PATH (to find claude and codex), so install again if that changes"))]+ Install,+ Uninstall,+ Start,+ Stop,+ #[command(about = ictl_l10n::tr!("重启,改过 IPHONE_CONTROL_VIEWER_* 设置后用", "Restart, after changing the IPHONE_CONTROL_VIEWER_* settings"))]+ Restart,}/// 锁屏密码按设备分开存:一台的密码不会输进另一台@@ -412,6 +429,7 @@ async fn service_cmd(socket: &Path, action: ServiceAction) -> anyhow::Result<()>ServiceAction::Start => service::start(&service::find().ok_or_else(none)?)?,ServiceAction::Stop => service::stop(&service::find().ok_or_else(none)?)?,ServiceAction::Restart => service::restart(&service::find().ok_or_else(none)?)?,+ ServiceAction::Viewer { action } => viewer_service_cmd(action)?,ServiceAction::Status => {match service::find() {Some(s) => println!("{}", ictl_l10n::trf!("后台服务 {}", "Service {}", s.describe())),@@ -423,6 +441,23 @@ async fn service_cmd(socket: &Path, action: ServiceAction) -> anyhow::Result<()>)),}+ match service::viewer_find() {+ Some(s) => println!(+ "{}",+ if service::running(&s) {+ ictl_l10n::trf!("控制台 {},在运行", "Viewer {}, running", s.describe())+ } else {+ ictl_l10n::trf!("控制台 {},没在运行", "Viewer {}, not running", s.describe())+ }+ ),+ None => println!(+ "{}",+ ictl_l10n::tr!(+ "控制台 没装成服务(iphone-control service viewer install)",+ "Viewer no service (iphone-control service viewer install)"+ )+ ),+ }let up = snapshot(socket).await.is_ok();println!("{}",@@ -437,6 +472,57 @@ async fn service_cmd(socket: &Path, action: ServiceAction) -> anyhow::Result<()>Ok(())}+fn viewer_service_cmd(action: ViewerServiceAction) -> anyhow::Result<()> {+ let none = || {+ anyhow::anyhow!(+ "{}",+ ictl_l10n::tr!(+ "没有装控制台服务:iphone-control service viewer install",+ "No viewer service is set up: iphone-control service viewer install"+ )+ )+ };+ match action {+ ViewerServiceAction::Install => {+ let s = service::viewer_install()?;+ let port = env_nonempty("IPHONE_CONTROL_VIEWER_PORT").and_then(|p| p.parse::<u16>().ok()).unwrap_or(8200);+ println!("{}", ictl_l10n::trf!("已安装并启动:{}", "Installed and started: {}", s.describe()));+ println!("{}", ictl_l10n::trf!("控制台:http://127.0.0.1:{port}/", "Viewer: http://127.0.0.1:{port}/"));+ let lan = env_nonempty("IPHONE_CONTROL_VIEWER_LAN")+ .is_some_and(|v| !matches!(v.as_str(), "0" | "false" | "no" | "off"));+ println!(+ "{}",+ if lan {+ ictl_l10n::tr!(+ "已对局域网开放(IPHONE_CONTROL_VIEWER_LAN),还没有登录:只在可信的网络里开。",+ "Open to the local network (IPHONE_CONTROL_VIEWER_LAN), with no login yet: only on a trusted network."+ )+ } else {+ ictl_l10n::tr!(+ "只在本机。要对局域网开放:设置文件里设 IPHONE_CONTROL_VIEWER_LAN=1,再 iphone-control service viewer restart。",+ "Local only. To open it to the local network: IPHONE_CONTROL_VIEWER_LAN=1 in the settings file, then iphone-control service viewer restart."+ )+ }+ );+ let found: Vec<&str> = agent::Backend::ALL.iter().filter(|b| b.find().is_some()).map(|b| b.id()).collect();+ if found.is_empty() {+ println!(+ "{}",+ ictl_l10n::tr!(+ "这个终端的 PATH 里没有 claude 或 codex,服务里的控制台也用不了 AI 任务;装好后在 PATH 里能找到它们的终端里再装一次。",+ "Neither claude nor codex is on this shell's PATH, so the service's viewer can't run AI tasks either; install again from a shell where they are."+ )+ );+ }+ }+ ViewerServiceAction::Uninstall => service::viewer_uninstall()?,+ ViewerServiceAction::Start => service::start(&service::viewer_find().ok_or_else(none)?)?,+ ViewerServiceAction::Stop => service::stop(&service::viewer_find().ok_or_else(none)?)?,+ ViewerServiceAction::Restart => service::restart(&service::viewer_find().ok_or_else(none)?)?,+ }+ Ok(())+}+fn mcp_command(exe: &Path, socket: &Path) -> String {let lang = if ictl_l10n::is_en() { format!("-e {}=en ", ictl_l10n::ENV) } else { String::new() };let dev = if ictl_mcp::dev_tools_enabled() { "-e IPHONE_CONTROL_DEV_TOOLS=1 " } else { "" };@@ -1146,6 +1232,39 @@ fn host_is_loopback(head: &[u8]) -> bool {#[cfg(test)]mod tests {use super::{host_is_loopback, mcp_command};++ /// The viewer's settings come from the settings file as environment variables (also for the viewer service):+ /// `IPHONE_CONTROL_VIEWER_LAN=1` turns `--lan` on. A plain flag only took true/false, so the service didn't start+ #[test]+ fn viewer_settings_from_the_environment() {+ use clap::Parser;+ let parse = |lan: Option<&str>| {+ // SAFETY: only this test sets these variables+ unsafe {+ match lan {+ Some(v) => std::env::set_var("IPHONE_CONTROL_VIEWER_LAN", v),+ None => std::env::remove_var("IPHONE_CONTROL_VIEWER_LAN"),+ }+ std::env::set_var("IPHONE_CONTROL_VIEWER_PORT", "8202");+ std::env::set_var("IPHONE_CONTROL_VIEWER_LAN_HOSTS", "nas.example,nas2");+ }+ match super::Cli::try_parse_from(["iphone-control", "viewer"]).map(|c| c.command) {+ Ok(Some(super::Command::Viewer { port, lan, lan_hosts })) => (port, lan, lan_hosts),+ other => panic!("{lan:?}: {:?}", other.err()),+ }+ };+ for v in ["1", "yes", "on", "true"] {+ assert!(parse(Some(v)).1, "{v}");+ }+ for v in ["0", "no", "off", "false"] {+ assert!(!parse(Some(v)).1, "{v}");+ }+ assert_eq!(parse(None), (8202, false, vec!["nas.example".to_owned(), "nas2".to_owned()]));+ unsafe {+ std::env::remove_var("IPHONE_CONTROL_VIEWER_PORT");+ std::env::remove_var("IPHONE_CONTROL_VIEWER_LAN_HOSTS");+ }+ }use ictl_l10n::{Lang, with_lang};use std::path::Path;diff --git a/apps/iphone-control/src/service.rs b/apps/iphone-control/src/service.rsindex 5366650..995bd99 100644--- a/apps/iphone-control/src/service.rs+++ b/apps/iphone-control/src/service.rs@@ -5,6 +5,12 @@//! the agent or unit `brew services` writes. `install` only writes our own file when none of these exists; the other//! commands act on whichever is there. The service reads `~/.config/iphone-control/env`, starts at login and is//! restarted after a crash.+//!+//! The control page can be a service of its own too (`iphone-control service viewer install`): launchd label+//! [`VIEWER_LABEL`], unit `iphone-control-viewer.service`, running `iphone-control viewer` with its settings from the+//! same file (`IPHONE_CONTROL_VIEWER_PORT`, `_LAN`, `_LAN_HOSTS`). It gets the `PATH` of the shell that installed+//! it, so it finds `claude` and `codex` (a user service's own `PATH` usually lacks `~/.local/bin`, npm's bin…).+//! It is an always-running client: an update stops it first and starts it again afterwards ([`pause_viewer`]).use std::os::unix::fs::MetadataExt;use std::path::{Path, PathBuf};@@ -16,6 +22,8 @@ use crate::envfile::home;pub const LABEL: &str = "io.github.derrors.iphone-control";const UNIT: &str = "iphone-control";+pub const VIEWER_LABEL: &str = "io.github.derrors.iphone-control.viewer";+const VIEWER_UNIT: &str = "iphone-control-viewer";#[derive(Debug, Clone, PartialEq)]pub enum Service {@@ -70,6 +78,14 @@ fn our_unit() -> PathBuf {crate::envfile::config_dir().parent().unwrap_or(Path::new("/")).join("systemd/user/iphone-control.service")}+fn viewer_plist() -> PathBuf {+ launch_agents().join(format!("{VIEWER_LABEL}.plist"))+}++fn viewer_unit_file() -> PathBuf {+ our_unit().with_file_name(format!("{VIEWER_UNIT}.service"))+}+fn run(cmd: &mut Command) -> bool {cmd.stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success())}@@ -390,6 +406,192 @@ pub fn uninstall() -> anyhow::Result<()> {Ok(())}+/// The control page's service, if it is set up (no package brings one: only ours)+pub fn viewer_find() -> Option<Service> {+ if cfg!(target_os = "macos") {+ return viewer_plist().is_file().then(|| Service::Launchd {+ label: VIEWER_LABEL.into(),+ plist: viewer_plist(),+ ours: true,+ });+ }+ viewer_unit_file().is_file().then(|| Service::Systemd { unit: VIEWER_UNIT.into(), ours: true })+}++/// The service's process is running now+pub fn running(s: &Service) -> bool {+ match s {+ Service::Systemd { unit, .. } => systemctl(&["is-active", "--quiet", unit]),+ Service::Launchd { label, .. } => Command::new("launchctl")+ .arg("print")+ .arg(format!("gui/{}/{label}", uid()))+ .stderr(Stdio::null())+ .output()+ .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("state = running")),+ }+}++/// `PATH` for the control page's service: the installing shell's, so the agents are found. Characters that can't+/// be written into a unit or a plist safely are refused+fn service_path(path: &str) -> anyhow::Result<&str> {+ ensure!(+ !path.is_empty() && !path.contains(['"', '\\', '\n', '\r', '\'', '`', '$']),+ "{}",+ ictl_l10n::tr!(+ "PATH 里有服务文件写不了的字符(引号、反斜杠、$、换行),装不了控制台服务",+ "PATH has characters a service file can't hold (quotes, backslashes, $, newlines), so the viewer service can't be set up"+ )+ );+ Ok(path)+}++/// The control page's systemd unit+fn viewer_unit_text(exe: &str, path: &str) -> anyhow::Result<String> {+ // systemd expands %-specifiers in Environment=+ let path = service_path(path)?.replace('%', "%%");+ Ok(format!(+ "# Written by iphone-control. Settings: ~/.config/iphone-control/env (IPHONE_CONTROL_VIEWER_*)\n[Unit]\n\+ Description=iphone-control viewer (control page)\nAfter=iphone-control.service\n\n[Service]\n\+ ExecStart={exe} viewer\nEnvironmentFile=-%h/.config/iphone-control/env\nEnvironment=\"PATH={path}\"\n\+ Restart=on-failure\nRestartSec=10\n\n[Install]\nWantedBy=default.target\n"+ ))+}++fn xml(s: &str) -> String {+ s.replace('&', "&").replace('<', "<").replace('>', ">")+}++/// The control page's launch agent+fn viewer_plist_text(exe: &str, path: &str, log: &Path) -> anyhow::Result<String> {+ let path = xml(service_path(path)?);+ Ok(format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key><string>{VIEWER_LABEL}</string>+ <key>ProgramArguments</key>+ <array>+ <string>/bin/sh</string>+ <string>-c</string>+ <string>set -a; f="$HOME/.config/iphone-control/env"; [ -f "$f" ] && . "$f"; set +a; exec "{exe}" viewer</string>+ </array>+ <key>EnvironmentVariables</key>+ <dict><key>PATH</key><string>{path}</string></dict>+ <key>RunAtLoad</key><true/>+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>+ <key>ThrottleInterval</key><integer>10</integer>+ <key>StandardOutPath</key><string>{log}</string>+ <key>StandardErrorPath</key><string>{log}</string>+</dict>+</plist>+"#,+ exe = xml(exe),+ log = xml(&log.to_string_lossy())+ ))+}++/// Sets up the control page's service (or rewrites it, e.g. for a new `PATH`) and starts it+pub fn viewer_install() -> anyhow::Result<Service> {+ let exe = stable_exe()?;+ let exe = exe.to_string_lossy();+ if exe.contains(['"', '\'', '\\', '&', '<', '>']) {+ bail!(+ "{}",+ ictl_l10n::trf!(+ "程序路径里有特殊字符,装不了服务:{exe}",+ "The program path has special characters, can't set up a service: {exe}"+ )+ );+ }+ let path = std::env::var("PATH").unwrap_or_default();+ if let Some(s) = viewer_find() {+ // rewritten below with the current PATH and program; stop the old one first+ let _ = stop(&s);+ }+ if cfg!(target_os = "macos") {+ let logs = home().join("Library/Logs/iphone-control");+ std::fs::create_dir_all(&logs)?;+ std::fs::create_dir_all(launch_agents())?;+ std::fs::write(viewer_plist(), viewer_plist_text(&exe, &path, &logs.join("viewer.log"))?)?;+ let s = Service::Launchd { label: VIEWER_LABEL.into(), plist: viewer_plist(), ours: true };+ start(&s)?;+ return Ok(s);+ }+ if !has_systemd_user() {+ bail!(+ "{}",+ ictl_l10n::tr!(+ "没有可用的 systemd 用户会话,装不了服务;在另一个终端运行 iphone-control viewer",+ "No systemd user session, so no service can be set up; run iphone-control viewer in another terminal"+ )+ );+ }+ let unit = viewer_unit_file();+ std::fs::create_dir_all(unit.parent().unwrap_or(Path::new("/")))?;+ std::fs::write(&unit, viewer_unit_text(&exe, &path)?)?;+ systemctl(&["daemon-reload"]);+ let s = Service::Systemd { unit: VIEWER_UNIT.into(), ours: true };+ start(&s)?;+ Ok(s)+}++/// Stops and removes the control page's service+pub fn viewer_uninstall() -> anyhow::Result<()> {+ let Some(s) = viewer_find() else {+ println!("{}", ictl_l10n::tr!("没有装控制台服务", "No viewer service is set up"));+ return Ok(());+ };+ match &s {+ Service::Launchd { plist, .. } => {+ stop(&s)?;+ std::fs::remove_file(plist)?;+ }+ Service::Systemd { unit, .. } => {+ systemctl(&["disable", "--now", unit]);+ std::fs::remove_file(viewer_unit_file())?;+ systemctl(&["daemon-reload"]);+ }+ }+ println!("{}", ictl_l10n::trf!("已移除控制台服务 {}", "Removed the viewer service {}", s.describe()));+ Ok(())+}++/// For an update: stops the control page's service if it is running (it is an `iphone-control` process holding a+/// client lease, so the update would wait for it forever) and waits until it is gone. `Some` to start it again+/// with [`resume_viewer`]+pub fn pause_viewer() -> anyhow::Result<Option<Service>> {+ let Some(s) = viewer_find().filter(running) else { return Ok(None) };+ stop(&s)?;+ for _ in 0..50 {+ if !running(&s) {+ return Ok(Some(s));+ }+ std::thread::sleep(std::time::Duration::from_millis(200));+ }+ let _ = start(&s);+ bail!("busy: the viewer service didn't stop")+}++/// Starts the control page's service again after [`pause_viewer`]; a failure is only reported+pub fn resume_viewer(paused: Option<Service>) {+ if let Some(s) = paused+ && let Err(e) = start(&s)+ {+ eprintln!("{e:#}");+ }+}++/// After a package manager replaced the program: a running control page service runs the new one+pub fn restart_viewer_if_running() {+ if let Some(s) = viewer_find().filter(running) {+ match restart(&s) {+ Ok(()) => println!("{}", ictl_l10n::tr!("控制台服务已重启。", "The viewer service was restarted.")),+ Err(e) => eprintln!("{e:#}"),+ }+ }+}+#[cfg(test)]mod tests {use super::*;@@ -413,6 +615,33 @@ mod tests {assert!(launchd_pid(&print("running", Some(1)), Path::new("/elsewhere.plist"), false).is_err());}+ #[test]+ fn the_viewer_service_runs_the_viewer_with_this_path() {+ let path = "/home/u/.local/bin:/home/u/.npm-global/bin:/usr/bin";+ let unit = viewer_unit_text("/home/u/.local/bin/iphone-control", path).unwrap();+ assert!(unit.contains("ExecStart=/home/u/.local/bin/iphone-control viewer\n"), "{unit}");+ assert!(unit.contains(&format!("Environment=\"PATH={path}\"\n")));+ assert!(unit.contains("EnvironmentFile=-%h/.config/iphone-control/env"));+ assert!(unit.contains("After=iphone-control.service"));+ assert!(+ viewer_unit_text("x", "/odd%dir:/usr/bin").unwrap().contains("PATH=/odd%%dir:/usr/bin"),+ "not a specifier"+ );+ for bad in ["/a\"b", "/a\\b", "/a$HOME", "/a\nb", "/a`b`", ""] {+ assert!(viewer_unit_text("x", bad).is_err(), "{bad:?}");+ }+ let plist = viewer_plist_text(+ "/opt/homebrew/opt/iphone-control/bin/iphone-control",+ "/a&b:/usr/bin",+ Path::new("/L/viewer.log"),+ )+ .unwrap();+ assert!(plist.contains(r#"exec "/opt/homebrew/opt/iphone-control/bin/iphone-control" viewer</string>"#));+ assert!(plist.contains("<key>PATH</key><string>/a&b:/usr/bin</string>"));+ assert!(plist.contains(&format!("<string>{VIEWER_LABEL}</string>")));+ assert!(plist::Value::from_reader_xml(plist.as_bytes()).is_ok(), "a valid plist");+ }+#[test]fn homebrew_paths_use_the_opt_link() {assert_eq!(diff --git a/apps/iphone-control/src/update/channel.rs b/apps/iphone-control/src/update/channel.rsindex 2afc93e..a927975 100644--- a/apps/iphone-control/src/update/channel.rs+++ b/apps/iphone-control/src/update/channel.rs@@ -95,6 +95,12 @@ async fn brew_service_running(brew: &Path) -> bool {/// Restarts the background service if it was `running` and waits until the daemon answers with `version`. Failing/// that only prints what to run: the new program is installed either wayasync fn restart(socket: &Path, version: &str, running: bool, cmd: &[&std::ffi::OsStr], by_hand: &str) {+ restart_daemon(socket, version, running, cmd, by_hand).await;+ // the control page's own service runs the old program until it starts again+ crate::service::restart_viewer_if_running();+}++async fn restart_daemon(socket: &Path, version: &str, running: bool, cmd: &[&std::ffi::OsStr], by_hand: &str) {if !running {println!("{}",diff --git a/apps/iphone-control/src/update/transaction.rs b/apps/iphone-control/src/update/transaction.rsindex 601d451..aba5c06 100644--- a/apps/iphone-control/src/update/transaction.rs+++ b/apps/iphone-control/src/update/transaction.rs@@ -443,40 +443,58 @@ pub async fn apply(socket: &Path, background: bool, report: super::Report) -> Relet version = report.available_version.context("no stable release is available")?;eligible(&receipt.version, &version, background)?;let host = Host { service, socket, binary: &store.binary };- if background {- ensure!(matches!(report.policy, super::Policy::AutoPatch), "automatic installation is disabled");- let suppressed = outcome(&store.binary)?.and_then(|o| o.suppressed_version);- ensure!(- suppressed.as_ref() != Some(&version),- "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.- if let Err(e) = host.exclusive() {- store.record("busy", &version, format!("{e:#}"), suppressed)?;- return Err(e);- }- }- let stage = store.stage()?;- let work = async {- let candidate = match archive::stage(&stage, &receipt, &version, background).await {- Ok(candidate) => candidate,- Err(e) => {- let suppressed = if e.downcast_ref::<reqwest::Error>().is_some() {- outcome(&store.binary)?.and_then(|o| o.suppressed_version)- } else {- Some(version.clone())- };- store.record(failure_status(&e), &version, format!("{e:#}"), suppressed)?;+ // the control page's service is an always-running client: it would keep the update busy forever, so it stops+ // for the update and starts again afterwards (not while it runs an AI task: that would end the task)+ let paused = pause_viewer(socket).await?;+ let result = async {+ if background {+ ensure!(matches!(report.policy, super::Policy::AutoPatch), "automatic installation is disabled");+ let suppressed = outcome(&store.binary)?.and_then(|o| o.suppressed_version);+ ensure!(+ suppressed.as_ref() != Some(&version),+ "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.+ if let Err(e) = host.exclusive() {+ store.record("busy", &version, format!("{e:#}"), suppressed)?;return Err(e);}- };- let next = Receipt { version, sha256: digest(&candidate)?, ..receipt.clone() };- replace(&store, &host, receipt, next, &candidate, background).await+ }+ let stage = store.stage()?;+ let work = async {+ let candidate = match archive::stage(&stage, &receipt, &version, background).await {+ Ok(candidate) => candidate,+ Err(e) => {+ let suppressed = if e.downcast_ref::<reqwest::Error>().is_some() {+ outcome(&store.binary)?.and_then(|o| o.suppressed_version)+ } else {+ Some(version.clone())+ };+ store.record(failure_status(&e), &version, format!("{e:#}"), suppressed)?;+ return Err(e);+ }+ };+ let next = Receipt { version, sha256: digest(&candidate)?, ..receipt.clone() };+ replace(&store, &host, receipt, next, &candidate, background).await+ }+ .await;+ let _ = fs::remove_dir_all(&stage);+ work}.await;- let _ = fs::remove_dir_all(&stage);- work+ crate::service::resume_viewer(paused);+ result+}++/// [`service::pause_viewer`], unless an AI task is running+async fn pause_viewer(socket: &Path) -> Result<Option<Service>> {+ if crate::service::viewer_find().is_some_and(|s| crate::service::running(&s))+ && ictl_daemon::protocol::task_list(socket).await.is_ok_and(|l| l.iter().any(|t| t.active()))+ {+ anyhow::bail!("busy: an AI task is running");+ }+ service::pause_viewer()}/// The outcome recorded when staging a release fails. A release that only isn't marked for unattended@@ -535,9 +553,15 @@ pub async fn recover(socket: &Path, scheduled: bool) -> Result<()> {"invalid recovery entry point");let service = service::managed(&store.binary, &receipt.service)?;- check_clients(service::managed_pid(&service, true)?)?;- let host = Host { service, socket, binary: &store.binary };- resume(&store, &host, &tx).await+ let paused = pause_viewer(socket).await?;+ let result = async {+ check_clients(service::managed_pid(&service, true)?)?;+ let host = Host { service, socket, binary: &store.binary };+ resume(&store, &host, &tx).await+ }+ .await;+ crate::service::resume_viewer(paused);+ result}#[cfg(test)]diff --git a/docs/task-control.md b/docs/task-control.mdindex 3d4f388..86f525c 100644--- a/docs/task-control.md+++ b/docs/task-control.md@@ -240,5 +240,5 @@ Running → Waiting(等确认)→ Running之后:-1. 控制台做成后台服务(`iphone-control service` 管,开机自启,跟着设置文件里的 `--lan` 开关)。+1. 控制台做成后台服务(`iphone-control service viewer install`,开机自启,跟着设置文件里的 `IPHONE_CONTROL_VIEWER_*`):已完成(2026-11-13)。升级时先停下它(它是常驻客户端,会让升级一直 busy),升级完再启动;有 AI 任务在跑时自动升级推迟。2. 登录:一个令牌,存在数据目录,登录后用 `HttpOnly; SameSite=Strict` 的 cookie,程序用 `Authorization: Bearer`,失败限速;局域网口子开了登录才放行。HTTPS 和 HTTP MCP 届时再定。diff --git a/packaging/env.example b/packaging/env.exampleindex 359db16..5056568 100644--- a/packaging/env.example+++ b/packaging/env.example@@ -28,6 +28,10 @@ IPHONE_CONTROL_VIEWER_QP=# 设为 1:控制台也对局域网开放(同一个端口、HTTP、还没有登录:局域网里任何能连上这台机器的人都能操作手机),只接受局域网地址来的连接# Set to 1: the viewer is also open to the local network (same port, HTTP, no login yet: anyone on the network can control the phone); only local-network addresses may connect.IPHONE_CONTROL_VIEWER_LAN=+# 控制台的端口(默认 8200)和 --lan 时还认可的主机名(逗号分隔);控制台服务(iphone-control service viewer install)也读它们+# The viewer's port (default 8200) and, with --lan, more host names it answers to (comma-separated); the viewer service reads them too.+IPHONE_CONTROL_VIEWER_PORT=+IPHONE_CONTROL_VIEWER_LAN_HOSTS=# 固定控制哪台设备,设了就不能切换。留空为自动选:正在控制的那台一直用到它断开;# 运行中可以用 `iphone-control select` 或 iphone_select_device 工具切换diff --git a/website/en/guide/cli.md b/website/en/guide/cli.mdindex a279090..1d36de9 100644--- a/website/en/guide/cli.md+++ b/website/en/guide/cli.md@@ -75,7 +75,9 @@ The daemon runs as a per-user service: launchd on macOS, a systemd user service| `service uninstall` | Stop and remove the service this program set up; data is kept. A service that came with Homebrew or the .deb isn't removed: it is disabled, or you're told how to stop it || `service start` / `stop` | Start or stop it || `service restart` | Restart it, after editing `~/.config/iphone-control/env` |-| `service status` | Which service is set up, and whether the daemon is running |+| `service status` | Which service is set up, whether the daemon is running, and whether the viewer service is set up and running |+| `service viewer install` | Set up the viewer as a service of its own that starts at login, and start it. Its port and whether it is open to the local network come from `IPHONE_CONTROL_VIEWER_PORT`, `IPHONE_CONTROL_VIEWER_LAN` and `IPHONE_CONTROL_VIEWER_LAN_HOSTS` in the settings file. It keeps this shell's `PATH` so the viewer finds `claude` and `codex`; install again if that changes |+| `service viewer uninstall` / `start` / `stop` / `restart` | Remove, start or stop the viewer service; `restart` after changing those settings. An update stops it first and starts it again afterwards (an automatic update waits while an AI task runs) |These commands find the service set up by the one-command install, `iphone-control service install`, `brew services` or the .deb, and act on whichever is there.diff --git a/website/en/guide/configuration.md b/website/en/guide/configuration.mdindex 3eb0983..b7108ee 100644--- a/website/en/guide/configuration.md+++ b/website/en/guide/configuration.md@@ -27,6 +27,8 @@ iphone-control service restart| `IPHONE_CONTROL_DEV_TOOLS` | off | `1` adds the [developer tools](./tools#developer-tools-opt-in) to the MCP server: logs, crash reports, installing and removing apps, and Web Inspector (JavaScript in web pages and WebViews). See [Security](./security) for the risks. See the note below the table || `IPHONE_CONTROL_VIEWER_CODEC` | `auto` | The control page's picture: `auto` uses the phone's own video (HEVC) on iOS 27 and later, else H.264 (on macOS with VideoToolbox directly, on Linux when ffmpeg is installed), GPU encoding first; `device` only the phone's own video, MJPEG where it can't be used; `mjpeg` only MJPEG; or name one of `nvenc`, `vaapi`, `qsv`, `v4l2m2m`, `videotoolbox`, `x264`. `iphone-control viewer` says which one it uses when it starts, see [CLI](./cli#viewer-picture) || `IPHONE_CONTROL_VIEWER_QP` | `20` | H.264 quality, 1 to 51: lower is sharper and larger. `20` looks like the source in normal use; `24` saves about a third of the traffic, small text blurs a little while scrolling fast |+| `IPHONE_CONTROL_VIEWER_PORT` | `8200` | The viewer's port, like `viewer --port` (the viewer service reads it too) |+| `IPHONE_CONTROL_VIEWER_LAN_HOSTS` | empty | With `--lan`, more host names the page answers to, comma-separated, like `--lan-host` || `IPHONE_CONTROL_VIEWER_LAN` | off | Set to `1` to open the viewer to the local network too, like `viewer --lan`. There is no login yet: anyone on the network who can reach this machine can control the phone and start AI tasks, so only on a trusted network || `IPHONE_UDID` | automatic | Pin the device to control. Unset: the controlled device is kept until it disconnects, and you can switch with the `select` command or the `iphone_select_device` tool. When set, switching is refused || `RESIGN_MIN_DAYS` | `2` | Re-sign when fewer days than this remain |diff --git a/website/guide/cli.md b/website/guide/cli.mdindex e89d67c..e878b34 100644--- a/website/guide/cli.md+++ b/website/guide/cli.md@@ -75,7 +75,9 @@ Viewer 只监听本机回环地址。同机其他用户也能查看安装信息| `service uninstall` | 停止并移除本程序装的服务,数据保留。Homebrew 或 deb 包带的服务不删,只停用或提示怎么停 || `service start` / `stop` | 启动、停止 || `service restart` | 重启,改过 `~/.config/iphone-control/env` 后用 |-| `service status` | 装的是哪个服务、守护进程在不在运行 |+| `service status` | 装的是哪个服务、守护进程在不在运行,控制台服务装了没有、在不在运行 |+| `service viewer install` | 把控制台(`viewer`)也装成登录后自动启动的服务并启动。端口、是否对局域网开放读设置文件里的 `IPHONE_CONTROL_VIEWER_PORT`、`IPHONE_CONTROL_VIEWER_LAN`、`IPHONE_CONTROL_VIEWER_LAN_HOSTS`。会记下当前终端的 `PATH`,好让控制台找到 `claude` 和 `codex`;PATH 变了再装一次 |+| `service viewer uninstall` / `start` / `stop` / `restart` | 移除、启动、停止控制台服务;改过上面几项设置后 `restart`。升级时它会先停下,升级完再启动(有 AI 任务在跑时自动升级会推迟) |这些命令认得一行命令安装、`iphone-control service install`、`brew services` 和 deb 包装的服务,哪个在就作用于哪个。diff --git a/website/guide/configuration.md b/website/guide/configuration.mdindex 4821a8e..4718e2a 100644--- a/website/guide/configuration.md+++ b/website/guide/configuration.md@@ -27,6 +27,8 @@ iphone-control service restart| `IPHONE_CONTROL_DEV_TOOLS` | 关 | 设为 `1` 时 MCP 服务多出[开发者工具](./tools#开发者工具-显式开启):日志、崩溃报告、安装和卸载 App、Web Inspector(在网页和 WebView 里执行 JavaScript)。风险见[安全与隐私](./security)。见表下说明 || `IPHONE_CONTROL_VIEWER_CODEC` | `auto` | 控制台画面的编码:`auto` 在 iOS 27 及以上用手机自己的视频(HEVC),其余用 H.264(macOS 上直接用 VideoToolbox;Linux 上要装 ffmpeg),先试显卡编码;`device` 只用手机自己的视频,用不了时是 MJPEG;`mjpeg` 只用 MJPEG;也可以指定 `nvenc`、`vaapi`、`qsv`、`v4l2m2m`、`videotoolbox`、`x264`。`iphone-control viewer` 启动时会显示用的是哪个,见[命令行](./cli#viewer-picture) || `IPHONE_CONTROL_VIEWER_QP` | `20` | H.264 的画质,1~51,越小越清晰、流量越大。`20` 正常使用看不出和原画的差别;`24` 约省三分之一流量,快速滚动时小字略糊 |+| `IPHONE_CONTROL_VIEWER_PORT` | `8200` | 控制台的端口,同 `viewer --port`(控制台服务也读它) |+| `IPHONE_CONTROL_VIEWER_LAN_HOSTS` | 空 | `--lan` 时还认可的主机名,逗号分隔,同 `--lan-host` || `IPHONE_CONTROL_VIEWER_LAN` | 关 | 设为 `1` 时控制台也对局域网开放,同 `viewer --lan`。还没有登录:局域网里任何能连上这台机器的人都能操作手机、开 AI 任务,只在可信的网络里开 || `IPHONE_UDID` | 自动选 | 固定控制哪台设备。不设时自动选:正在控制的那台一直用到它断开;运行中可以用 `select` 命令或 `iphone_select_device` 工具切换。设了就不能切换 || `RESIGN_MIN_DAYS` | `2` | 描述文件剩余不到几天时重签 |