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

refactor: one list of environment variables, kept in step with the code and the docs (#96)

Qinghe Li14455393dd81
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 3b91faa..b7d669f 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -84,6 +84,7 @@ Notes:
- **Never commit** `data/`, `~/.config/iphone-control/env` or other settings files with secrets, certificates, provisioning profiles, pairing records or anything Apple ships (Developer Disk Images, frameworks).
- Comments explain *why*, especially device quirks; put measured numbers next to timeouts and thresholds.
- **Errors:** the daemon returns `crate::error::Result` (`ictl_daemon::error::Error`): WDA's, the device's and unlocking's errors pass through `?` as they are, the daemon's own messages are `Error::Msg`; small pure helpers may keep `Result<_, String>`. The caller gets the text in its language, so word messages for it. The CLI uses `anyhow` (with context for people reading it), the control page's JSON carries a `message` string. New facts a client acts on go into a structured field (`Outcome`, `Data`, `retry_as_gesture`), never into wording it has to match.
+- **Environment variables** are listed in one place, `crates/ictl-protocol/src/env.rs`: add a new one there (an `IPHONE_CONTROL_…` name, with its kind) and read it through the constant. Its tests fail when code uses a name that isn't there, or when a setting is missing from the configuration page (both languages) or `packaging/env.example`. Don't rename existing ones: they are in people's settings files.
## Required tests
diff --git a/apps/iphone-control/src/agent.rs b/apps/iphone-control/src/agent.rs
index af9fce6..6d3e85b 100644
--- a/apps/iphone-control/src/agent.rs
+++ b/apps/iphone-control/src/agent.rs
@@ -298,7 +298,7 @@ impl Agents {
let mut env = Map::new();
env.insert(protocol::TASK_TOKEN_ENV.into(), token.into());
// the agent's tools answer in the task's language (this runs in its scope, see `start`)
- env.insert("IPHONE_CONTROL_LANG".into(), ictl_l10n::lang().code().into());
+ env.insert(ictl_daemon::protocol::env::LANG.into(), ictl_l10n::lang().code().into());
let s = |v: &str| v.to_owned();
match backend {
Backend::Claude => {
diff --git a/apps/iphone-control/src/client.rs b/apps/iphone-control/src/client.rs
index 6514911..e180b9e 100644
--- a/apps/iphone-control/src/client.rs
+++ b/apps/iphone-control/src/client.rs
@@ -74,7 +74,7 @@ pub async fn target_device(socket: &Path, query: Option<&str>) -> anyhow::Result
let i = ictl_daemon::devices::resolve_device(&infos, q).map_err(anyhow::Error::msg)?;
return Ok(infos[i].clone());
}
- if let Some(u) = env_nonempty("IPHONE_UDID") {
+ if let Some(u) = env_nonempty(ictl_daemon::protocol::env::UDID) {
return Ok(pick(&u));
}
if let Some(s) = &snap {
diff --git a/apps/iphone-control/src/completions.rs b/apps/iphone-control/src/completions.rs
index 51fb153..9f23ce6 100644
--- a/apps/iphone-control/src/completions.rs
+++ b/apps/iphone-control/src/completions.rs
@@ -181,7 +181,7 @@ mod tests {
let mut cmd = super::super::Cli::command();
let help = cmd.find_subcommand_mut("completions").unwrap().render_long_help().to_string();
assert!(help.contains(expected));
- assert!(help.contains("IPHONE_CONTROL_LANG"));
+ assert!(help.contains(ictl_daemon::protocol::env::LANG));
});
}
}
diff --git a/apps/iphone-control/src/envfile.rs b/apps/iphone-control/src/envfile.rs
index db8921f..b130c0e 100644
--- a/apps/iphone-control/src/envfile.rs
+++ b/apps/iphone-control/src/envfile.rs
@@ -159,13 +159,13 @@ mod tests {
let dir = std::env::temp_dir().join(format!("ictl-env-{}", std::process::id()));
let p = dir.join("env");
let mut f = EnvFile { path: p.clone(), text: "# proxy\nHTTP_PROXY=\nBARK_KEY=old\nBARK_KEY=older\n".into() };
- assert_eq!(f.get("BARK_KEY").as_deref(), Some("older"), "the last one wins");
- assert!(f.set("BARK_KEY", Some("new")).unwrap());
- assert!(!f.set("BARK_KEY", Some("new")).unwrap(), "unchanged");
+ assert_eq!(f.get(ictl_daemon::protocol::env::BARK_KEY).as_deref(), Some("older"), "the last one wins");
+ assert!(f.set(ictl_daemon::protocol::env::BARK_KEY, Some("new")).unwrap());
+ assert!(!f.set(ictl_daemon::protocol::env::BARK_KEY, Some("new")).unwrap(), "unchanged");
assert!(f.set("HTTP_PROXY", Some("http://127.0.0.1:7890")).unwrap());
- assert!(f.set("TG_CHAT_ID", Some("-100 1")).unwrap());
+ assert!(f.set(ictl_daemon::protocol::env::TG_CHAT_ID, Some("-100 1")).unwrap());
assert_eq!(f.text, "# proxy\nHTTP_PROXY=http://127.0.0.1:7890\nBARK_KEY=new\nTG_CHAT_ID='-100 1'\n");
- assert_eq!(f.get("TG_CHAT_ID").as_deref(), Some("-100 1"));
+ assert_eq!(f.get(ictl_daemon::protocol::env::TG_CHAT_ID).as_deref(), Some("-100 1"));
assert!(f.set("HTTP_PROXY", None).unwrap());
assert_eq!(f.get("HTTP_PROXY"), None);
assert!(f.set("X", Some("it's")).is_err());
@@ -179,7 +179,7 @@ mod tests {
fn a_new_file_starts_from_the_example() {
let f = EnvFile::open(Path::new("/nonexistent/ictl/env")).unwrap();
assert!(f.text.contains("IPHONE_CONTROL_LANG="));
- assert_eq!(f.get("IPHONE_CONTROL_LANG"), None);
- assert_eq!(f.get("BARK_SERVER").as_deref(), Some("https://api.day.app"));
+ assert_eq!(f.get(ictl_daemon::protocol::env::LANG), None);
+ assert_eq!(f.get(ictl_daemon::protocol::env::BARK_SERVER).as_deref(), Some("https://api.day.app"));
}
}
diff --git a/apps/iphone-control/src/guide.rs b/apps/iphone-control/src/guide.rs
index 810665b..b4055b0 100644
--- a/apps/iphone-control/src/guide.rs
+++ b/apps/iphone-control/src/guide.rs
@@ -424,8 +424,8 @@ async fn passcode(cli: &Cli, force: bool) -> anyhow::Result<()> {
/// Asks for a notification channel. Returns whether the file changed, and the settings to test if there are any
fn notifications(env: &mut EnvFile, force: bool) -> anyhow::Result<(bool, Option<ictl_daemon::config::NotifyConfig>)> {
- let bark = env.get("BARK_KEY");
- let tg = env.get("TG_BOT_TOKEN").zip(env.get("TG_CHAT_ID"));
+ let bark = env.get(ictl_daemon::protocol::env::BARK_KEY);
+ let tg = env.get(ictl_daemon::protocol::env::TG_BOT_TOKEN).zip(env.get(ictl_daemon::protocol::env::TG_CHAT_ID));
println!(
"{}",
ictl_l10n::tr!(
@@ -466,9 +466,13 @@ fn notifications(env: &mut EnvFile, force: bool) -> anyhow::Result<(bool, Option
" Bark 服务器(回车用 https://api.day.app): ",
" Bark server (Enter for https://api.day.app): "
))?;
- changed |= env.set("BARK_KEY", Some(&key))?;
- changed |= env.set("BARK_SERVER", Some(if server.is_empty() { "https://api.day.app" } else { &server }))?;
- changed |= env.set("TG_BOT_TOKEN", None)? | env.set("TG_CHAT_ID", None)?;
+ changed |= env.set(ictl_daemon::protocol::env::BARK_KEY, Some(&key))?;
+ changed |= env.set(
+ ictl_daemon::protocol::env::BARK_SERVER,
+ Some(if server.is_empty() { "https://api.day.app" } else { &server }),
+ )?;
+ changed |= env.set(ictl_daemon::protocol::env::TG_BOT_TOKEN, None)?
+ | env.set(ictl_daemon::protocol::env::TG_CHAT_ID, None)?;
}
2 => {
let token = crate::read_secret(ictl_l10n::tr!(
@@ -482,11 +486,14 @@ fn notifications(env: &mut EnvFile, force: bool) -> anyhow::Result<(bool, Option
if token.is_empty() || chat.is_empty() {
bail!("{}", ictl_l10n::tr!("token 和 chat id 都要填", "Both the token and the chat id are needed"));
}
- changed |= env.set("TG_BOT_TOKEN", Some(&token))? | env.set("TG_CHAT_ID", Some(&chat))?;
- changed |= env.set("BARK_KEY", None)?;
+ changed |= env.set(ictl_daemon::protocol::env::TG_BOT_TOKEN, Some(&token))?
+ | env.set(ictl_daemon::protocol::env::TG_CHAT_ID, Some(&chat))?;
+ changed |= env.set(ictl_daemon::protocol::env::BARK_KEY, None)?;
}
_ => {
- changed |= env.set("BARK_KEY", None)? | env.set("TG_BOT_TOKEN", None)? | env.set("TG_CHAT_ID", None)?;
+ changed |= env.set(ictl_daemon::protocol::env::BARK_KEY, None)?
+ | env.set(ictl_daemon::protocol::env::TG_BOT_TOKEN, None)?
+ | env.set(ictl_daemon::protocol::env::TG_CHAT_ID, None)?;
return Ok((changed, None));
}
}
@@ -496,10 +503,12 @@ fn notifications(env: &mut EnvFile, force: bool) -> anyhow::Result<(bool, Option
Ok((
true,
Some(ictl_daemon::config::NotifyConfig {
- tg_bot_token: env.get("TG_BOT_TOKEN"),
- tg_chat_id: env.get("TG_CHAT_ID"),
- bark_server: env.get("BARK_SERVER").unwrap_or_else(|| "https://api.day.app".into()),
- bark_key: env.get("BARK_KEY"),
+ tg_bot_token: env.get(ictl_daemon::protocol::env::TG_BOT_TOKEN),
+ tg_chat_id: env.get(ictl_daemon::protocol::env::TG_CHAT_ID),
+ bark_server: env
+ .get(ictl_daemon::protocol::env::BARK_SERVER)
+ .unwrap_or_else(|| "https://api.day.app".into()),
+ bark_key: env.get(ictl_daemon::protocol::env::BARK_KEY),
}),
))
}
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index 780dcab..b5b187e 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -35,10 +35,10 @@ mod viewer;
#[command(name = "iphone-control", version, about = ictl_l10n::tr!("在 Linux 或 macOS 上控制 iPhone,并提供 MCP 工具", "Control an iPhone from Linux or macOS, with MCP tools"))]
struct Cli {
#[arg(help = ictl_l10n::tr!("数据根目录(账号、描述文件、日志等)。默认:root 是 /var/lib/iphone-control,普通用户是 ~/.local/share/iphone-control", "Data directory (account, provisioning profiles, logs, ...). Default: /var/lib/iphone-control for root, ~/.local/share/iphone-control for a regular user"))]
- #[arg(long, env = "ICTL_DATA_DIR", default_value_os_t = protocol::default_data_dir())]
+ #[arg(long, env = ictl_daemon::protocol::env::DATA_DIR, default_value_os_t = protocol::default_data_dir())]
data_dir: PathBuf,
#[arg(help = ictl_l10n::tr!("守护进程控制接口。默认:root 是 /run/iphone-control/ctl.sock,普通用户是 $XDG_RUNTIME_DIR/iphone-control/ctl.sock", "Daemon control socket. Default: /run/iphone-control/ctl.sock for root, $XDG_RUNTIME_DIR/iphone-control/ctl.sock for a regular user"))]
- #[arg(long, env = "ICTL_SOCKET", default_value_os_t = protocol::default_socket())]
+ #[arg(long, env = ictl_daemon::protocol::env::SOCKET, default_value_os_t = protocol::default_socket())]
socket: PathBuf,
/// 不给就是首次运行引导(设置好以后显示状态)
#[command(subcommand)]
@@ -64,9 +64,9 @@ enum Command {
Daemon,
#[command(about = ictl_l10n::tr!("MCP stdio 服务(由 agent 拉起)。--url(或 IPHONE_CONTROL_URL)时转接另一台机器的控制台 /mcp:给只能填命令的 MCP 客户端用", "MCP stdio server (started by the agent). With --url (or IPHONE_CONTROL_URL), a bridge to another machine's viewer /mcp, for MCP clients that only start a command"))]
Mcp {
- #[arg(long, value_name = "URL", env = "IPHONE_CONTROL_URL", help = ictl_l10n::tr!("手机接在另一台机器上:那台机器的控制台地址。有任务口令(IPHONE_CONTROL_TASK_TOKEN)就只带它,否则用 IPHONE_CONTROL_VIEWER_TOKEN 登录;task run --url 启动的命令会自动设好", "The phone is on another machine: that machine's viewer. With a task's token (IPHONE_CONTROL_TASK_TOKEN) only that is sent, otherwise the login from IPHONE_CONTROL_VIEWER_TOKEN; a command under task run --url has it set already"))]
+ #[arg(long, value_name = "URL", env = ictl_daemon::protocol::env::URL, help = ictl_l10n::tr!("手机接在另一台机器上:那台机器的控制台地址。有任务口令(IPHONE_CONTROL_TASK_TOKEN)就只带它,否则用 IPHONE_CONTROL_VIEWER_TOKEN 登录;task run --url 启动的命令会自动设好", "The phone is on another machine: that machine's viewer. With a task's token (IPHONE_CONTROL_TASK_TOKEN) only that is sent, otherwise the login from IPHONE_CONTROL_VIEWER_TOKEN; a command under task run --url has it set already"))]
url: Option<String>,
- #[arg(long, value_name = "PEM", env = "IPHONE_CONTROL_CA", help = ictl_l10n::tr!("--url 是本机生成的自签证书时,信任这张证书", "With --url and a self-signed certificate: trust it"))]
+ #[arg(long, value_name = "PEM", env = ictl_daemon::protocol::env::CA, help = ictl_l10n::tr!("--url 是本机生成的自签证书时,信任这张证书", "With --url and a self-signed certificate: trust it"))]
ca: Option<PathBuf>,
},
#[command(about = ictl_l10n::tr!("打印把 MCP 注册到 Claude Code 的命令", "Print the command that registers the MCP server with Claude Code"))]
@@ -119,29 +119,29 @@ enum Command {
},
#[command(about = ictl_l10n::tr!("浏览器里的控制台:实时画面上直接操作手机、看设备状态,把任务交给本机的 Claude Code 或 Codex 执行。默认只开在 127.0.0.1(--lan 也对局域网开放,走 HTTPS),要用令牌登录(iphone-control viewer token),操作都经守护进程(不开控制台时不监听任何端口)", "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 by default (--lan opens it to the local network too, over HTTPS), behind a login token (iphone-control viewer token); every action goes through the daemon (without the viewer no port is opened)"))]
Viewer {
- #[arg(long, env = "IPHONE_CONTROL_VIEWER_PORT", default_value_t = 8200)]
+ #[arg(long, env = ictl_daemon::protocol::env::VIEWER_PORT, default_value_t = 8200)]
port: u16,
// 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!("也对局域网开放(同一个端口,局域网里用 HTTPS,要令牌登录:iphone-control viewer token),只接受局域网地址来的连接", "Also open to the local network (same port, HTTPS there, login with the token: iphone-control viewer token); only connections from local-network addresses"))]
+ #[arg(long, env = ictl_daemon::protocol::env::VIEWER_LAN, value_parser = clap::builder::BoolishValueParser::new(), help = ictl_l10n::tr!("也对局域网开放(同一个端口,局域网里用 HTTPS,要令牌登录:iphone-control viewer token),只接受局域网地址来的连接", "Also open to the local network (same port, HTTPS there, login with the token: iphone-control viewer token); only connections from local-network addresses"))]
lan: bool,
- #[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"))]
+ #[arg(long = "lan-host", value_name = "HOST", env = ictl_daemon::protocol::env::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>,
- #[arg(long, value_enum, env = "IPHONE_CONTROL_VIEWER_TLS", default_value = "auto", help = ictl_l10n::tr!("HTTPS(同一个端口,本机仍可用 http://127.0.0.1):auto 在 --lan 或给了证书时开启;on、off", "HTTPS (same port; http://127.0.0.1 still works on this machine): auto turns it on with --lan or a certificate; on, off"))]
+ #[arg(long, value_enum, env = ictl_daemon::protocol::env::VIEWER_TLS, default_value = "auto", help = ictl_l10n::tr!("HTTPS(同一个端口,本机仍可用 http://127.0.0.1):auto 在 --lan 或给了证书时开启;on、off", "HTTPS (same port; http://127.0.0.1 still works on this machine): auto turns it on with --lan or a certificate; on, off"))]
tls: viewer::tls::Mode,
- #[arg(long = "tls-cert", value_name = "PEM", env = "IPHONE_CONTROL_VIEWER_TLS_CERT", requires = "tls_key", help = ictl_l10n::tr!("自己的证书(PEM,可带证书链),比如 mkcert 或 tailscale cert 生成的;不给就用本机生成的自签证书", "Your own certificate (PEM, chain allowed), such as one from mkcert or tailscale cert; without it a self-signed one made on this machine"))]
+ #[arg(long = "tls-cert", value_name = "PEM", env = ictl_daemon::protocol::env::VIEWER_TLS_CERT, requires = "tls_key", help = ictl_l10n::tr!("自己的证书(PEM,可带证书链),比如 mkcert 或 tailscale cert 生成的;不给就用本机生成的自签证书", "Your own certificate (PEM, chain allowed), such as one from mkcert or tailscale cert; without it a self-signed one made on this machine"))]
tls_cert: Option<PathBuf>,
- #[arg(long = "tls-key", value_name = "PEM", env = "IPHONE_CONTROL_VIEWER_TLS_KEY", requires = "tls_cert", help = ictl_l10n::tr!("--tls-cert 的私钥(PEM)", "The private key of --tls-cert (PEM)"))]
+ #[arg(long = "tls-key", value_name = "PEM", env = ictl_daemon::protocol::env::VIEWER_TLS_KEY, requires = "tls_cert", help = ictl_l10n::tr!("--tls-cert 的私钥(PEM)", "The private key of --tls-cert (PEM)"))]
tls_key: Option<PathBuf>,
- #[arg(long, env = "IPHONE_CONTROL_VIEWER_MCP", value_name = "on|off", default_value = "on", action = clap::ArgAction::Set, value_parser = clap::builder::BoolishValueParser::new(), help = ictl_l10n::tr!("同一个端口上的 MCP(HTTP):/mcp,本机和(--lan 时)局域网的客户端用 URL 接入;off 关掉", "MCP over HTTP on the same port: /mcp, for clients on this machine and (with --lan) the local network that connect by URL; off turns it off"))]
+ #[arg(long, env = ictl_daemon::protocol::env::VIEWER_MCP, value_name = "on|off", default_value = "on", action = clap::ArgAction::Set, value_parser = clap::builder::BoolishValueParser::new(), help = ictl_l10n::tr!("同一个端口上的 MCP(HTTP):/mcp,本机和(--lan 时)局域网的客户端用 URL 接入;off 关掉", "MCP over HTTP on the same port: /mcp, for clients on this machine and (with --lan) the local network that connect by URL; off turns it off"))]
mcp: bool,
#[command(subcommand)]
action: Option<ViewerAction>,
},
#[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"))]
Task {
- #[arg(long, global = true, value_name = "URL", env = "IPHONE_CONTROL_URL", help = ictl_l10n::tr!("手机接在另一台机器上:那台机器的控制台地址,比如 https://192.168.1.5:8200;登录令牌放在 IPHONE_CONTROL_VIEWER_TOKEN 里(task finish 用任务口令)", "The phone is on another machine: that machine's viewer, such as https://192.168.1.5:8200; the login token goes in IPHONE_CONTROL_VIEWER_TOKEN (task finish uses the task's token)"))]
+ #[arg(long, global = true, value_name = "URL", env = ictl_daemon::protocol::env::URL, help = ictl_l10n::tr!("手机接在另一台机器上:那台机器的控制台地址,比如 https://192.168.1.5:8200;登录令牌放在 IPHONE_CONTROL_VIEWER_TOKEN 里(task finish 用任务口令)", "The phone is on another machine: that machine's viewer, such as https://192.168.1.5:8200; the login token goes in IPHONE_CONTROL_VIEWER_TOKEN (task finish uses the task's token)"))]
url: Option<String>,
- #[arg(long, global = true, value_name = "PEM", env = "IPHONE_CONTROL_CA", help = ictl_l10n::tr!("--url 是本机生成的自签证书时,信任这张证书(那台机器上的 viewer-tls/cert.pem)", "With --url and a self-signed certificate made there: trust it (viewer-tls/cert.pem on that machine)"))]
+ #[arg(long, global = true, value_name = "PEM", env = ictl_daemon::protocol::env::CA, help = ictl_l10n::tr!("--url 是本机生成的自签证书时,信任这张证书(那台机器上的 viewer-tls/cert.pem)", "With --url and a self-signed certificate made there: trust it (viewer-tls/cert.pem on that machine)"))]
ca: Option<PathBuf>,
#[command(subcommand)]
action: task::TaskAction,
@@ -311,8 +311,9 @@ async fn run() -> anyhow::Result<()> {
}
let quiet = matches!(cli.command, Some(Command::Mcp { .. }));
// ICTL_LOG 留空(配置文件里常见的 `ICTL_LOG=`)当作没设;原来空值会生成一个什么都不放行的过滤器
- let filter =
- env_nonempty("ICTL_LOG").and_then(|v| tracing_subscriber::EnvFilter::try_new(v).ok()).unwrap_or_else(|| {
+ let filter = env_nonempty(ictl_daemon::protocol::env::LOG)
+ .and_then(|v| tracing_subscriber::EnvFilter::try_new(v).ok())
+ .unwrap_or_else(|| {
tracing_subscriber::EnvFilter::new(if quiet { "warn" } else { "info,idevice=warn,apple_codesign=warn" })
});
tracing_subscriber::fmt()
@@ -373,7 +374,7 @@ async fn run() -> anyhow::Result<()> {
}
Command::Task { url, ca, action } => task::run(&cli.socket, url, ca, action).await,
#[cfg(feature = "debug-cmds")]
- Command::Debug(args) => debug::run(env_nonempty("IPHONE_UDID").as_deref(), args).await,
+ Command::Debug(args) => debug::run(env_nonempty(ictl_daemon::protocol::env::UDID).as_deref(), args).await,
Command::NotifyTest { event } => notify_test(&cli.socket, &cli.data_dir, event.as_deref()).await,
}
}
@@ -669,10 +670,12 @@ fn viewer_service_cmd(action: ViewerServiceAction) -> anyhow::Result<()> {
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);
+ let port = env_nonempty(ictl_daemon::protocol::env::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")
+ let lan = env_nonempty(ictl_daemon::protocol::env::VIEWER_LAN)
.is_some_and(|v| !matches!(v.as_str(), "0" | "false" | "no" | "off"));
println!(
"{}",
@@ -1343,16 +1346,16 @@ mod tests {
_ => panic!("not mcp"),
};
// SAFETY: only this test sets this variable
- unsafe { std::env::remove_var("IPHONE_CONTROL_URL") };
+ unsafe { std::env::remove_var(ictl_daemon::protocol::env::URL) };
assert_eq!(task(&["i", "task", "pause", "abc"]), None);
assert_eq!(mcp(&["i", "mcp"]), None, "the local stdio server, as before");
assert_eq!(task(&["i", "task", "--url", "https://a:1", "pause", "abc"]).as_deref(), Some("https://a:1"));
assert_eq!(task(&["i", "task", "approve", "abc", "--url", "https://a:1"]).as_deref(), Some("https://a:1"));
assert_eq!(mcp(&["i", "mcp", "--url", "https://a:1"]).as_deref(), Some("https://a:1"));
- unsafe { std::env::set_var("IPHONE_CONTROL_URL", "https://b:2") };
+ unsafe { std::env::set_var(ictl_daemon::protocol::env::URL, "https://b:2") };
assert_eq!(task(&["i", "task", "finish", "done"]).as_deref(), Some("https://b:2"));
assert_eq!(mcp(&["i", "mcp"]).as_deref(), Some("https://b:2"));
- unsafe { std::env::remove_var("IPHONE_CONTROL_URL") };
+ unsafe { std::env::remove_var(ictl_daemon::protocol::env::URL) };
}
#[test]
@@ -1369,11 +1372,11 @@ mod tests {
// 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"),
+ Some(v) => std::env::set_var(ictl_daemon::protocol::env::VIEWER_LAN, v),
+ None => std::env::remove_var(ictl_daemon::protocol::env::VIEWER_LAN),
}
- std::env::set_var("IPHONE_CONTROL_VIEWER_PORT", "8202");
- std::env::set_var("IPHONE_CONTROL_VIEWER_LAN_HOSTS", "nas.example,nas2");
+ std::env::set_var(ictl_daemon::protocol::env::VIEWER_PORT, "8202");
+ std::env::set_var(ictl_daemon::protocol::env::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, action: None, .. })) => (port, lan, lan_hosts),
@@ -1388,8 +1391,8 @@ mod tests {
}
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");
+ std::env::remove_var(ictl_daemon::protocol::env::VIEWER_PORT);
+ std::env::remove_var(ictl_daemon::protocol::env::VIEWER_LAN_HOSTS);
}
}
use ictl_l10n::{Lang, with_lang};
diff --git a/apps/iphone-control/src/remote.rs b/apps/iphone-control/src/remote.rs
index ec4b417..4eda2d4 100644
--- a/apps/iphone-control/src/remote.rs
+++ b/apps/iphone-control/src/remote.rs
@@ -15,13 +15,13 @@ use ictl_daemon::protocol::{TaskEvent, TaskInfo, TaskOpened};
use serde_json::{Value, json};
/// The viewer's login token for `task run --url`
-pub const LOGIN_ENV: &str = "IPHONE_CONTROL_VIEWER_TOKEN";
+pub const LOGIN_ENV: &str = ictl_daemon::protocol::env::VIEWER_TOKEN;
/// Given to the command: the viewer it works through
-pub const URL_ENV: &str = "IPHONE_CONTROL_URL";
+pub const URL_ENV: &str = ictl_daemon::protocol::env::URL;
/// Given to the command: the viewer's MCP endpoint, for an agent that connects by URL
-pub const MCP_URL_ENV: &str = "IPHONE_CONTROL_MCP_URL";
+pub const MCP_URL_ENV: &str = ictl_daemon::protocol::env::MCP_URL;
/// Given to the command when `--ca` was: the certificate to trust
-pub const CA_ENV: &str = "IPHONE_CONTROL_CA";
+pub const CA_ENV: &str = ictl_daemon::protocol::env::CA;
/// A viewer on another machine
pub struct Remote {
diff --git a/apps/iphone-control/src/task.rs b/apps/iphone-control/src/task.rs
index 513f6af..cfc988b 100644
--- a/apps/iphone-control/src/task.rs
+++ b/apps/iphone-control/src/task.rs
@@ -310,7 +310,7 @@ async fn run_command(
let spawned = tokio::process::Command::new(&command[0])
.args(&command[1..])
.env(protocol::TASK_TOKEN_ENV, &opened.token)
- .env("IPHONE_CONTROL_TASK_ID", &opened.id)
+ .env(ictl_daemon::protocol::env::TASK_ID, &opened.id)
.envs(backend.env())
// the login stays with whoever runs `task run`: the agent only works for its task (it can't approve its own
// confirmations with a login)
diff --git a/apps/iphone-control/src/video/ffmpeg.rs b/apps/iphone-control/src/video/ffmpeg.rs
index 1ca7be0..899d896 100644
--- a/apps/iphone-control/src/video/ffmpeg.rs
+++ b/apps/iphone-control/src/video/ffmpeg.rs
@@ -341,7 +341,7 @@ pub struct Encoders {
impl Encoders {
/// Finds and checks an encoder. `Err`: why the page keeps MJPEG (no ffmpeg, none works, or turned off)
pub async fn detect() -> Result<Arc<Self>, String> {
- let want = env("IPHONE_CONTROL_VIEWER_CODEC").map(|v| v.to_ascii_lowercase());
+ let want = env(ictl_daemon::protocol::env::VIEWER_CODEC).map(|v| v.to_ascii_lowercase());
let want = want.as_deref().filter(|v| *v != "auto");
if want == Some("mjpeg") {
return Err(ictl_l10n::tr!("IPHONE_CONTROL_VIEWER_CODEC=mjpeg", "IPHONE_CONTROL_VIEWER_CODEC=mjpeg").into());
@@ -396,7 +396,7 @@ impl Encoders {
});
let e = Arc::new(Self {
ffmpeg,
- qp: qp_from(env("IPHONE_CONTROL_VIEWER_QP").as_deref()),
+ qp: qp_from(env(ictl_daemon::protocol::env::VIEWER_QP).as_deref()),
old,
list,
sample,
diff --git a/apps/iphone-control/src/video/mod.rs b/apps/iphone-control/src/video/mod.rs
index 315143c..cd93170 100644
--- a/apps/iphone-control/src/video/mod.rs
+++ b/apps/iphone-control/src/video/mod.rs
@@ -45,7 +45,7 @@ use flv::Packet;
/// `IPHONE_CONTROL_VIEWER_CODEC` allows the phone's own screen video ([`device`]): `auto` (the default) or `device`
pub fn device_allowed() -> bool {
- ictl_daemon::config::env("IPHONE_CONTROL_VIEWER_CODEC")
+ ictl_daemon::config::env(ictl_daemon::protocol::env::VIEWER_CODEC)
.is_none_or(|v| v.eq_ignore_ascii_case("auto") || v.eq_ignore_ascii_case("device"))
}
diff --git a/apps/iphone-control/src/video/vt.rs b/apps/iphone-control/src/video/vt.rs
index 53bdcc6..d6c347c 100644
--- a/apps/iphone-control/src/video/vt.rs
+++ b/apps/iphone-control/src/video/vt.rs
@@ -1152,7 +1152,7 @@ mod measure {
#[tokio::test]
#[ignore]
async fn measure_recording() {
- let dir = std::env::var("ICTL_RECORDING").expect("ICTL_RECORDING=<dir of <ms>.jpg>");
+ let dir = std::env::var(ictl_daemon::protocol::env::RECORDING).expect("ICTL_RECORDING=<dir of <ms>.jpg>");
let mut files: Vec<(u64, std::path::PathBuf)> = std::fs::read_dir(&dir)
.unwrap()
.flatten()
@@ -1178,7 +1178,7 @@ mod measure {
span as f64 / 1000.0,
jpeg_bytes as f64 / 1024.0 / (span as f64 / 1000.0)
);
- let qps: Vec<u8> = std::env::var("ICTL_QPS")
+ let qps: Vec<u8> = std::env::var(ictl_daemon::protocol::env::QPS)
.unwrap_or_else(|_| "20".into())
.split(',')
.filter_map(|q| q.trim().parse().ok())
diff --git a/crates/ictl-daemon/src/config.rs b/crates/ictl-daemon/src/config.rs
index a288f4e..450b401 100644
--- a/crates/ictl-daemon/src/config.rs
+++ b/crates/ictl-daemon/src/config.rs
@@ -46,14 +46,14 @@ impl NotifyConfig {
/// 读环境变量,去掉首尾空白,空值当作没设(配置文件里常留着 `KEY=`)
pub fn env(k: &str) -> Option<String> {
- std::env::var(k).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty())
+ crate::protocol::env::get(k)
}
/// Where to look for ffmpeg (the viewer's H.264 picture; on macOS only the fallback for the native VideoToolbox
/// encoder), in order: `ICTL_FFMPEG`, else `ffmpeg` on `PATH` and, on macOS, Homebrew's places (a launchd service
/// doesn't have them on its `PATH`)
pub fn ffmpeg_paths() -> Vec<PathBuf> {
- if let Some(p) = env("ICTL_FFMPEG") {
+ if let Some(p) = env(crate::protocol::env::FFMPEG) {
return vec![PathBuf::from(p)];
}
let mut v = vec![PathBuf::from("ffmpeg")];
@@ -73,32 +73,37 @@ fn env_num<T: std::str::FromStr>(k: &str, default: T) -> T {
impl Config {
pub fn from_env(data_dir: &Path) -> Self {
- let screen_fallback =
- match (env("SCREEN_W").and_then(|v| v.parse().ok()), env("SCREEN_H").and_then(|v| v.parse().ok())) {
- (Some(width), Some(height)) => Some(ScreenSize { width, height }),
- _ => None,
- };
+ let screen_fallback = match (
+ env(crate::protocol::env::SCREEN_W).and_then(|v| v.parse().ok()),
+ env(crate::protocol::env::SCREEN_H).and_then(|v| v.parse().ok()),
+ ) {
+ (Some(width), Some(height)) => Some(ScreenSize { width, height }),
+ _ => None,
+ };
Self {
data_dir: data_dir.to_owned(),
// 实际值由命令行给(--socket / ICTL_SOCKET,见 apps/iphone-control)
socket: crate::protocol::default_socket(),
- udid: env("IPHONE_UDID"),
- wda_unsigned: env("ICTL_WDA_UNSIGNED").map(PathBuf::from).unwrap_or_else(|| wda_unsigned_cache(data_dir)),
- ddi_url: env("ICTL_DDI_URL").unwrap_or_else(|| ictl_device::ddi::DEFAULT_BASE_URL.into()),
- ddi_dir: env("ICTL_DDI_DIR").map(PathBuf::from),
- anisette_url: env("ICTL_ANISETTE_URL"),
+ udid: env(crate::protocol::env::UDID),
+ wda_unsigned: env(crate::protocol::env::WDA_UNSIGNED)
+ .map(PathBuf::from)
+ .unwrap_or_else(|| wda_unsigned_cache(data_dir)),
+ ddi_url: env(crate::protocol::env::DDI_URL).unwrap_or_else(|| ictl_device::ddi::DEFAULT_BASE_URL.into()),
+ ddi_dir: env(crate::protocol::env::DDI_DIR).map(PathBuf::from),
+ anisette_url: env(crate::protocol::env::ANISETTE_URL),
screen_fallback,
- resign_min: Duration::from_secs(env_num("RESIGN_MIN_DAYS", 2u64) * 86400),
- resign_check: Duration::from_secs(env_num("RESIGN_CHECK_HOURS", 6u64) * 3600),
+ resign_min: Duration::from_secs(env_num(crate::protocol::env::RESIGN_MIN_DAYS, 2u64) * 86400),
+ resign_check: Duration::from_secs(env_num(crate::protocol::env::RESIGN_CHECK_HOURS, 6u64) * 3600),
session_check: Duration::from_secs(24 * 3600),
- offline_alert: Duration::from_secs(env_num("OFFLINE_ALERT_MIN", 10u64) * 60),
+ offline_alert: Duration::from_secs(env_num(crate::protocol::env::OFFLINE_ALERT_MIN, 10u64) * 60),
notify: NotifyConfig {
- tg_bot_token: env("TG_BOT_TOKEN"),
- tg_chat_id: env("TG_CHAT_ID"),
- bark_server: env("BARK_SERVER").unwrap_or_else(|| "https://api.day.app".into()),
- bark_key: env("BARK_KEY"),
+ tg_bot_token: env(crate::protocol::env::TG_BOT_TOKEN),
+ tg_chat_id: env(crate::protocol::env::TG_CHAT_ID),
+ bark_server: env(crate::protocol::env::BARK_SERVER).unwrap_or_else(|| "https://api.day.app".into()),
+ bark_key: env(crate::protocol::env::BARK_KEY),
},
- wda_detached: env("ICTL_WDA_DETACHED").is_some_and(|v| matches!(v.as_str(), "1" | "true" | "yes")),
+ wda_detached: env(crate::protocol::env::WDA_DETACHED)
+ .is_some_and(|v| matches!(v.as_str(), "1" | "true" | "yes")),
}
}
diff --git a/crates/ictl-daemon/src/doctor.rs b/crates/ictl-daemon/src/doctor.rs
index a5a4e89..8452b9c 100644
--- a/crates/ictl-daemon/src/doctor.rs
+++ b/crates/ictl-daemon/src/doctor.rs
@@ -280,7 +280,7 @@ impl Daemon {
/// 其他系统要有 ffmpeg,Linux 上用显卡编码还要能打开 `/dev/dri/renderD*`(`render` 组)。只看前提,不试编码:
/// 用哪个编码器,`viewer` 启动时会说
async fn viewer_picture() -> String {
- if crate::config::env("IPHONE_CONTROL_VIEWER_CODEC").is_some_and(|v| v.eq_ignore_ascii_case("mjpeg")) {
+ if crate::config::env(crate::protocol::env::VIEWER_CODEC).is_some_and(|v| v.eq_ignore_ascii_case("mjpeg")) {
return ictl_l10n::tr!(
"✅ 控制台画面按设置用 MJPEG(IPHONE_CONTROL_VIEWER_CODEC=mjpeg)",
"✅ Viewer picture uses MJPEG as set (IPHONE_CONTROL_VIEWER_CODEC=mjpeg)"
diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs
index c3339e0..d4bc2cf 100644
--- a/crates/ictl-mcp/src/lib.rs
+++ b/crates/ictl-mcp/src/lib.rs
@@ -133,7 +133,7 @@ pub const DEV_TOOLS: [&str; 6] = [
/// `IPHONE_CONTROL_DEV_TOOLS=1` (or true/yes/on) adds the developer tools; off by default, so agents that don't
/// need them don't pay for their descriptions
pub fn dev_tools_enabled() -> bool {
- std::env::var("IPHONE_CONTROL_DEV_TOOLS")
+ std::env::var(ictl_protocol::env::DEV_TOOLS)
.is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
}
diff --git a/crates/ictl-protocol/src/env.rs b/crates/ictl-protocol/src/env.rs
new file mode 100644
index 0000000..28621e0
--- /dev/null
+++ b/crates/ictl-protocol/src/env.rs
@@ -0,0 +1,265 @@
+//! Every environment variable of this project, in one place: the code reads them through these names, and the
+//! tests below keep the list, the code and the documentation in step (a name only in the code, or a setting the
+//! configuration page doesn't mention, fails them).
+//!
+//! The names stay as they are, whatever their prefix: they are in people's settings files
+//! (`~/.config/iphone-control/env`), service units and scripts. `IPHONE_CONTROL_*` is for new ones; the unprefixed
+//! ones (`IPHONE_UDID`, `SCREEN_W`, `BARK_KEY`…) and `ICTL_*` come from earlier versions.
+//! System and other programs' variables (`HOME`, `PATH`, `XDG_*`, `CODEX_HOME`…) aren't listed.
+
+/// What a variable is for, which says where it is documented
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Kind {
+ /// The user's setting: on the configuration page (website/guide/configuration.md, and the English one)
+ Setting,
+ /// Where notifications go: on the notifications page
+ Notify,
+ /// An experiment that is off by default: in docs/architecture.md
+ Experiment,
+ /// Set by this program for a command it starts (`task run`, the control page's agent), read by
+ /// `iphone-control` inside it
+ Given,
+ /// Read when building (`option_env!`): who publishes releases and their signing keys
+ /// (docs/dev/release-updates.md)
+ Build,
+ /// For diagnostics and tests only
+ Dev,
+}
+
+/// One variable: its name, what it is for, and whether `packaging/env.example` (the settings file's template)
+/// lists it
+#[derive(Debug, Clone, Copy)]
+pub struct Var {
+ pub name: &'static str,
+ pub kind: Kind,
+ pub in_settings_file: bool,
+}
+
+// the device and the daemon
+pub const UDID: &str = "IPHONE_UDID";
+pub const SCREEN_W: &str = "SCREEN_W";
+pub const SCREEN_H: &str = "SCREEN_H";
+pub const RESIGN_CHECK_HOURS: &str = "RESIGN_CHECK_HOURS";
+pub const RESIGN_MIN_DAYS: &str = "RESIGN_MIN_DAYS";
+pub const OFFLINE_ALERT_MIN: &str = "OFFLINE_ALERT_MIN";
+pub const DATA_DIR: &str = "ICTL_DATA_DIR";
+pub const SOCKET: &str = "ICTL_SOCKET";
+pub const LOG: &str = "ICTL_LOG";
+pub const ANISETTE_URL: &str = "ICTL_ANISETTE_URL";
+pub const DDI_URL: &str = "ICTL_DDI_URL";
+pub const DDI_DIR: &str = "ICTL_DDI_DIR";
+pub const FFMPEG: &str = "ICTL_FFMPEG";
+pub const WDA_UNSIGNED: &str = "ICTL_WDA_UNSIGNED";
+pub const WDA_DETACHED: &str = "ICTL_WDA_DETACHED";
+/// Read by `ictl_l10n` (below this crate), so its name is kept there
+pub const LANG: &str = ictl_l10n::ENV;
+pub const DEV_TOOLS: &str = "IPHONE_CONTROL_DEV_TOOLS";
+
+// notifications
+pub const TG_BOT_TOKEN: &str = "TG_BOT_TOKEN";
+pub const TG_CHAT_ID: &str = "TG_CHAT_ID";
+pub const BARK_SERVER: &str = "BARK_SERVER";
+pub const BARK_KEY: &str = "BARK_KEY";
+
+// the control page
+pub const VIEWER_PORT: &str = "IPHONE_CONTROL_VIEWER_PORT";
+pub const VIEWER_LAN: &str = "IPHONE_CONTROL_VIEWER_LAN";
+pub const VIEWER_LAN_HOSTS: &str = "IPHONE_CONTROL_VIEWER_LAN_HOSTS";
+pub const VIEWER_MCP: &str = "IPHONE_CONTROL_VIEWER_MCP";
+pub const VIEWER_TLS: &str = "IPHONE_CONTROL_VIEWER_TLS";
+pub const VIEWER_TLS_CERT: &str = "IPHONE_CONTROL_VIEWER_TLS_CERT";
+pub const VIEWER_TLS_KEY: &str = "IPHONE_CONTROL_VIEWER_TLS_KEY";
+pub const VIEWER_CODEC: &str = "IPHONE_CONTROL_VIEWER_CODEC";
+pub const VIEWER_QP: &str = "IPHONE_CONTROL_VIEWER_QP";
+
+// another machine's control page (`--url`)
+pub const URL: &str = "IPHONE_CONTROL_URL";
+pub const CA: &str = "IPHONE_CONTROL_CA";
+pub const VIEWER_TOKEN: &str = "IPHONE_CONTROL_VIEWER_TOKEN";
+
+// given to a task's command
+pub const TASK_TOKEN: &str = "IPHONE_CONTROL_TASK_TOKEN";
+pub const TASK_ID: &str = "IPHONE_CONTROL_TASK_ID";
+pub const MCP_URL: &str = "IPHONE_CONTROL_MCP_URL";
+
+// diagnostics (`cargo test … -- --ignored`)
+pub const RECORDING: &str = "ICTL_RECORDING";
+pub const QPS: &str = "ICTL_QPS";
+
+const fn var(name: &'static str, kind: Kind, in_settings_file: bool) -> Var {
+ Var { name, kind, in_settings_file }
+}
+
+/// All of them
+pub const ALL: &[Var] = &[
+ var(UDID, Kind::Setting, true),
+ var(SCREEN_W, Kind::Setting, true),
+ var(SCREEN_H, Kind::Setting, true),
+ var(RESIGN_CHECK_HOURS, Kind::Setting, true),
+ var(RESIGN_MIN_DAYS, Kind::Setting, true),
+ var(OFFLINE_ALERT_MIN, Kind::Setting, true),
+ var(DATA_DIR, Kind::Setting, true),
+ var(SOCKET, Kind::Setting, true),
+ var(LOG, Kind::Setting, true),
+ var(ANISETTE_URL, Kind::Setting, true),
+ var(DDI_URL, Kind::Setting, true),
+ var(DDI_DIR, Kind::Setting, true),
+ var(FFMPEG, Kind::Setting, false),
+ var(WDA_UNSIGNED, Kind::Setting, true),
+ var(WDA_DETACHED, Kind::Experiment, true),
+ var(LANG, Kind::Setting, true),
+ var(DEV_TOOLS, Kind::Setting, true),
+ var(TG_BOT_TOKEN, Kind::Notify, true),
+ var(TG_CHAT_ID, Kind::Notify, true),
+ var(BARK_SERVER, Kind::Notify, true),
+ var(BARK_KEY, Kind::Notify, true),
+ var(VIEWER_PORT, Kind::Setting, true),
+ var(VIEWER_LAN, Kind::Setting, true),
+ var(VIEWER_LAN_HOSTS, Kind::Setting, true),
+ var(VIEWER_MCP, Kind::Setting, true),
+ var(VIEWER_TLS, Kind::Setting, true),
+ var(VIEWER_TLS_CERT, Kind::Setting, true),
+ var(VIEWER_TLS_KEY, Kind::Setting, true),
+ var(VIEWER_CODEC, Kind::Setting, true),
+ var(VIEWER_QP, Kind::Setting, true),
+ var(URL, Kind::Setting, false),
+ var(CA, Kind::Setting, false),
+ var(VIEWER_TOKEN, Kind::Setting, false),
+ var(TASK_TOKEN, Kind::Given, false),
+ var(TASK_ID, Kind::Given, false),
+ var(MCP_URL, Kind::Given, false),
+ var("ICTL_UPDATE_PUBLISHER", Kind::Build, false),
+ var("ICTL_UPDATE_PUBLIC_KEYS", Kind::Build, false),
+ var("ICTL_UPDATE_TAP", Kind::Build, false),
+ var(RECORDING, Kind::Dev, false),
+ var(QPS, Kind::Dev, false),
+];
+
+/// A variable's value, trimmed; `None` when it isn't set or is empty
+pub fn get(name: &str) -> Option<String> {
+ std::env::var(name).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::BTreeSet;
+ use std::path::{Path, PathBuf};
+
+ fn root() -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
+ }
+
+ fn read(rel: &str) -> String {
+ std::fs::read_to_string(root().join(rel)).unwrap_or_else(|e| panic!("{rel}: {e}"))
+ }
+
+ fn known() -> BTreeSet<&'static str> {
+ ALL.iter().map(|v| v.name).collect()
+ }
+
+ /// Every name a text mentions that looks like one of ours (`IPHONE_CONTROL_…`, `ICTL_…` and the earlier
+ /// unprefixed ones)
+ fn mentioned(text: &str) -> BTreeSet<String> {
+ let unprefixed: BTreeSet<&str> = ALL
+ .iter()
+ .map(|v| v.name)
+ .filter(|n| !n.starts_with("IPHONE_CONTROL_") && !n.starts_with("ICTL_"))
+ .collect();
+ let mut out = BTreeSet::new();
+ for word in text.split(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')) {
+ let word = word.trim_matches('_');
+ if ((word.starts_with("IPHONE_CONTROL_") || word.starts_with("ICTL_")) && !word.ends_with('_'))
+ || unprefixed.contains(word)
+ {
+ out.insert(word.to_owned());
+ }
+ }
+ out
+ }
+
+ #[test]
+ fn each_name_once() {
+ assert_eq!(known().len(), ALL.len());
+ }
+
+ /// The pages describe what there is, and nothing that isn't there any more
+ #[test]
+ fn the_documentation_matches_the_list() {
+ let check = |page: &str, kinds: &[Kind]| {
+ let text = read(page);
+ let on_page = mentioned(&text);
+ for v in ALL.iter().filter(|v| kinds.contains(&v.kind)) {
+ assert!(on_page.contains(v.name), "{page} doesn't mention {}", v.name);
+ }
+ on_page
+ };
+ for page in ["website/guide/configuration.md", "website/en/guide/configuration.md"] {
+ let on_page = check(page, &[Kind::Setting]);
+ // a mention of the task's variables, given to `task run`'s command, is fine on this page too
+ for name in on_page {
+ assert!(known().contains(name.as_str()), "{page} mentions {name}, which isn't in env::ALL");
+ }
+ }
+ for page in ["website/guide/notifications.md", "website/en/guide/notifications.md"] {
+ check(page, &[Kind::Notify]);
+ }
+ check("docs/architecture.md", &[Kind::Experiment]);
+ check("docs/dev/release-updates.md", &[Kind::Build]);
+ let template = read("packaging/env.example");
+ let in_template = mentioned(&template);
+ for v in ALL {
+ assert_eq!(in_template.contains(v.name), v.in_settings_file, "packaging/env.example and {}", v.name);
+ }
+ }
+
+ fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
+ for e in std::fs::read_dir(dir).unwrap().flatten() {
+ let p = e.path();
+ if p.is_dir() {
+ sources(&p, out);
+ } else if p.extension().is_some_and(|x| x == "rs") {
+ out.push(p);
+ }
+ }
+ }
+
+ /// The code reads them through the names here (`env::VIEWER_PORT`), so this list is all there is: a name in a
+ /// string elsewhere fails this. Build-time ones (`option_env!` takes only a literal) and the test harnesses'
+ /// own (`ICTL_TEST_…`, integration tests) are the exceptions
+ #[test]
+ fn the_code_uses_the_names_from_here() {
+ let mut files = Vec::new();
+ for dir in ["crates", "apps"] {
+ sources(&root().join(dir), &mut files);
+ }
+ let this = Path::new(file!()).file_name().unwrap();
+ let mut found = Vec::new();
+ for f in files {
+ let rel = f.strip_prefix(root()).unwrap().display().to_string();
+ // ictl-l10n is below this crate: it keeps the language's name itself, and LANG is that one
+ if f.file_name() == Some(this) && rel.contains("ictl-protocol")
+ || rel.contains("/tests/")
+ || rel.contains("ictl-l10n")
+ {
+ continue;
+ }
+ let text = std::fs::read_to_string(&f).unwrap();
+ for (n, l) in text.lines().enumerate() {
+ if l.contains("option_env!") || l.trim_start().starts_with("//") {
+ continue;
+ }
+ for quoted in l.split('"').skip(1).step_by(2) {
+ let ours = known().contains(quoted)
+ || (quoted.starts_with("IPHONE_CONTROL_") || quoted.starts_with("ICTL_"))
+ && quoted.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
+ && !quoted.starts_with("ICTL_TEST_");
+ if ours {
+ found.push(format!("{rel}:{}: \"{quoted}\"", n + 1));
+ }
+ }
+ }
+ }
+ assert!(found.is_empty(), "use the names in ictl_protocol::env instead:\n{}", found.join("\n"));
+ }
+}
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index 98c54d9..0b80e0b 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -1,6 +1,8 @@
//! 守护进程控制接口:Unix socket(0600,默认位置见 [`default_socket`]),每行一个 JSON。
//! MCP 进程和 CLI 都通过它访问设备;本机不开 TCP 端口。
+pub mod env;
+
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
@@ -608,7 +610,7 @@ pub const TASK: &str = "task";
/// Request key with the step (from [`Request::TaskStep`]) a request belongs to; see [`as_task`]
pub const TASK_STEP: &str = "task_step";
/// The environment variable that hands a task's token to `iphone-control mcp` (and anything else using this crate)
-pub const TASK_TOKEN_ENV: &str = "IPHONE_CONTROL_TASK_TOKEN";
+pub const TASK_TOKEN_ENV: &str = env::TASK_TOKEN;
/// The HTTP header that does the same for MCP over HTTP (the viewer's `/mcp`), per request
pub const TASK_TOKEN_HEADER: &str = "iphone-control-task-token";
diff --git a/docs/architecture.md b/docs/architecture.md
index c1619c7..22d257b 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -148,7 +148,7 @@
| `viewer-tls/` | 控制台局域网 HTTPS 的自签证书和私钥 | 0700 | 否 |
| `tasks/` | 最近 50 个 AI 任务的事件记录,每个任务一个 `<id>.jsonl` | 默认 | 否 |
-守护进程的配置全部来自环境变量(`crates/ictl-daemon/src/config.rs`),都有默认值。设置文件 `~/.config/iphone-control/env`(`KEY=value`,0600,模板 `packaging/env.example`)由首次运行引导和 `setup --reconfigure` 写(`envfile.rs`:改一项就地替换,注释和其他项保留);后台服务(launchd、systemd、`brew services`)把它读进守护进程的环境,其他命令启动时也读一遍,已有的环境变量优先。通知渠道的密钥也在这个文件里;其余秘密只放数据目录里的文件。
+守护进程的配置全部来自环境变量(`crates/ictl-daemon/src/config.rs`),都有默认值。整个项目的环境变量都登记在 `crates/ictl-protocol/src/env.rs`(名字、用途、是否在设置文件模板里),代码只经它的常量读;它的测试核对代码、配置页和 `packaging/env.example` 三者一致。设置文件 `~/.config/iphone-control/env`(`KEY=value`,0600,模板 `packaging/env.example`)由首次运行引导和 `setup --reconfigure` 写(`envfile.rs`:改一项就地替换,注释和其他项保留);后台服务(launchd、systemd、`brew services`)把它读进守护进程的环境,其他命令启动时也读一遍,已有的环境变量优先。通知渠道的密钥也在这个文件里;其余秘密只放数据目录里的文件。
## 7. 重签与通知