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(viewer): read-only tokens, and tasks opened from another machine (#80)

Qinghe Li831275b4ab94
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 091ec3f..02ffa05 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,8 @@ All notable changes to this project are documented here. The format is based on
### Added
+- Named login tokens, read-only ones among them: `iphone-control viewer token add <name> [--read-only]`, `list`, `show <name> [--new]`, `remove <name>`. A read-only token can watch the picture, the device's state and tasks; every action (taps, typing, starting, pausing or confirming tasks, switching devices, `/mcp`) is refused, and the page hides them. The task log records which token controlled it (`viewer:<name>`). Tokens moved to `viewer-tokens.json` and the earlier one became `owner`, so nobody logs in again after upgrading; adding, replacing and removing tokens takes effect at once, without restarting the viewer.
+- Tasks opened from another machine: `iphone-control task run --url https://<that machine>:8200 -- <command>` (the login token in `IPHONE_CONTROL_VIEWER_TOKEN`), or `POST /api/agent/tasks/open` directly, whose event stream is the lease. The agent on the other machine gets only the task's token: `/mcp` takes the token of an active task (header `Iphone-Control-Task-Token`), so it can act on the phone for that task but can't reach pausing or confirming, and can't approve itself.
- The viewer and its `/mcp` need a login, from this machine too (the viewer can't tell a local browser from a visit forwarded by frp, cloudflared or another reverse proxy). The token is made on the first start and kept in `viewer-token` in the data directory (0600); `iphone-control viewer token` shows it with links that log in here and on the local network and the command to connect to the HTTP MCP, and `--new` replaces it. A browser stays logged in for 30 days; programs and MCP clients send `Authorization: Bearer <token>`. After too many wrong tokens (20 in a minute) tokens aren't checked for a minute. The CLI, `iphone-control mcp` (stdio) and `task run` use the local Unix socket and are unaffected.
- MCP over HTTP: `/mcp` (Streamable HTTP) on the viewer's port serves the same tools as `iphone-control mcp`, for clients that only take a URL and for agents on another computer on the local network (`--lan`, over HTTPS), e.g. `claude mcp add --transport http iphone http://127.0.0.1:8200/mcp`. A task's agent sends the task's token in the `Iphone-Control-Task-Token` header. No login, as for the viewer; `--mcp off` (`IPHONE_CONTROL_VIEWER_MCP=off`) turns it off.
- The viewer opened to the local network (`--lan`) now speaks HTTPS, on the same port: opened from another machine the picture can be H.264 or the phone's own HEVC instead of MJPEG, and traffic is encrypted. It uses a self-signed certificate made on this machine (kept in `viewer-tls/` in the data directory and reused); the browser warns the first time, so check the SHA-256 fingerprint shown at startup or by `service status` and go on. `--tls-cert`/`--tls-key` (`IPHONE_CONTROL_VIEWER_TLS_CERT`/`_KEY`) use a certificate of your own. `http://` from the network is redirected to `https://`; `http://127.0.0.1` on this machine works as before. `--tls off` (`IPHONE_CONTROL_VIEWER_TLS=off`) goes back to HTTP. It isn't a login: anyone on the network who can reach the page can still control the phone.
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index ca13fb8..b892647 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -8,6 +8,8 @@
### 新增
+- 有名字的登录令牌,可以是只读的:`iphone-control viewer token add <名字> [--read-only]`、`list`、`show <名字> [--new]`、`remove <名字>`。只读令牌能看画面、设备状态和任务,所有操作(点按、输入、开任务、暂停、确认、切换设备、`/mcp`)都被拒绝,页面上也不显示操作入口。任务记录里写下是哪个令牌做的控制(`viewer:<名字>`)。令牌改存在 `viewer-tokens.json`,原来的令牌成了 `owner`,升级后不用重新登录;增删、换令牌马上生效,不用重启控制台。
+- 从另一台机器开任务:`iphone-control task run --url https://<那台机器>:8200 -- <命令>`(登录令牌放在 `IPHONE_CONTROL_VIEWER_TOKEN`),或者直接调 `POST /api/agent/tasks/open`,返回的事件流就是租约。另一台机器上的 agent 只拿任务口令:`/mcp` 认进行中任务的口令(请求头 `Iphone-Control-Task-Token`),它能为这个任务操作手机,但碰不到暂停、确认这些控制接口,不能批准自己。
- 控制台和它的 `/mcp` 要登录了,本机也一样(控制台分不清本机的浏览器和经 frp、cloudflared 等反向代理转发进来的访问)。令牌第一次启动时生成,存在数据目录的 `viewer-token`(0600);`iphone-control viewer token` 显示令牌、本机和局域网的登录链接以及接入 HTTP MCP 的命令,`--new` 换一个新令牌。浏览器登录一次后记住 30 天;程序和 MCP 客户端用 `Authorization: Bearer <令牌>`。输错太多次(一分钟 20 次)会暂停校验一分钟。命令行、`iphone-control mcp`(stdio)和 `task run` 走本机的 Unix socket,不受影响。
- MCP over HTTP:控制台同一个端口上的 `/mcp`(Streamable HTTP)提供和 `iphone-control mcp` 一样的工具,只能填 URL 的客户端、局域网里另一台电脑上的 agent(`--lan`,走 HTTPS)都能接入,例如 `claude mcp add --transport http iphone http://127.0.0.1:8200/mcp`。任务里的 agent 在请求头 `Iphone-Control-Task-Token` 里带上任务口令。和控制台一样没有登录,`--mcp off`(`IPHONE_CONTROL_VIEWER_MCP=off`)关掉。
- 控制台对局域网开放(`--lan`)时改用 HTTPS,还是同一个端口:局域网里打开时画面也能用 H.264 或手机自己的 HEVC,不再退回 MJPEG,传输也加了密。默认用本机生成的自签证书(存在数据目录的 `viewer-tls/`,一直沿用),浏览器第一次打开会提示不受信任,核对启动时或 `service status` 显示的 SHA-256 指纹后继续;也可以用 `--tls-cert`/`--tls-key`(`IPHONE_CONTROL_VIEWER_TLS_CERT`/`_KEY`)换成自己的证书。局域网来的 `http://` 跳转到 `https://`,本机的 `http://127.0.0.1` 照旧。`--tls off`(`IPHONE_CONTROL_VIEWER_TLS=off`)恢复成 HTTP。这不是登录:局域网里能连上的人照样能操作手机。
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index ae77d46..030b41e 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -187,11 +187,33 @@ enum ServiceAction {
#[derive(Subcommand)]
enum ViewerAction {
- #[command(about = ictl_l10n::tr!("显示控制台的登录令牌、点开就能登录的链接和 HTTP MCP 的接入方式;--new 换一个新令牌(所有已登录的浏览器都要重新登录)", "Show the viewer's login token, links that log in and how to connect to its HTTP MCP; --new replaces the token (every browser has to log in again)"))]
+ #[command(about = ictl_l10n::tr!("控制台的登录令牌。不带子命令:显示 owner 令牌、点开就能登录的链接和 HTTP MCP 的接入方式(--new 换一个新的);add / list / show / remove 管理有名字的令牌,可以是只读的", "The viewer's login tokens. Alone: show the owner token, links that log in and how to connect to its HTTP MCP (--new replaces it); add / list / show / remove manage named tokens, which may be read-only"))]
Token {
+ #[command(subcommand)]
+ action: Option<TokenAction>,
+ #[arg(long, help = ictl_l10n::tr!("换一个新的 owner 令牌(用它登录的浏览器都要重新登录)", "Replace the owner token (browsers logged in with it log in again)"))]
+ new: bool,
+ },
+}
+
+#[derive(Subcommand)]
+enum TokenAction {
+ #[command(about = ictl_l10n::tr!("加一个有名字的令牌(比如每人一个、每台设备一个),显示它和登录链接;--read-only 只能看画面、设备状态和任务,不能操作", "Add a named token (one per person or device, say) and show it with links that log in; --read-only can watch the picture, the device's state and tasks but not act"))]
+ Add {
+ name: String,
+ #[arg(long)]
+ read_only: bool,
+ },
+ #[command(about = ictl_l10n::tr!("列出令牌的名字和权限(不显示令牌本身)", "List the tokens' names and roles (not the tokens)"))]
+ List,
+ #[command(about = ictl_l10n::tr!("显示一个令牌和它的登录链接;--new 换一个新的", "Show a token and links that log in with it; --new replaces it"))]
+ Show {
+ name: String,
#[arg(long)]
new: bool,
},
+ #[command(about = ictl_l10n::tr!("删掉一个令牌,用它登录的浏览器和程序马上进不来;最后一个能操作的令牌不能删", "Remove a token: browsers and programs logged in with it are out at once; the last token that may operate stays"))]
+ Remove { name: String },
}
#[derive(Subcommand)]
@@ -327,7 +349,10 @@ async fn run() -> anyhow::Result<()> {
Command::Viewer { port, lan, lan_hosts, tls, tls_cert, tls_key, mcp, action } => {
let tls = viewer::tls::Setting { mode: tls, cert: tls_cert, key: tls_key };
match action {
- Some(ViewerAction::Token { new }) => viewer_token(&cli.data_dir, port, lan, &lan_hosts, &tls, mcp, new),
+ Some(ViewerAction::Token { action, new }) => {
+ let at = ViewerAt { port, lan, lan_hosts: &lan_hosts, tls: &tls, mcp };
+ viewer_token(&cli.data_dir, &at, action, new)
+ }
None => viewer::run(&cli.socket, &cli.data_dir, port, lan, &lan_hosts, &tls, mcp).await,
}
}
@@ -505,19 +530,69 @@ async fn service_cmd(socket: &Path, data_dir: &Path, action: ServiceAction) -> a
Ok(())
}
-/// `viewer token`: the login token, links that log in (with the viewer's own settings) and the HTTP MCP setup
-fn viewer_token(
- data_dir: &Path,
+/// `s` padded to `width` columns, CJK and other wide characters taking two
+fn pad(s: &str, width: usize) -> String {
+ let w: usize =
+ s.chars().map(|c| if ('\u{1100}'..='\u{ffdc}').contains(&c) && c > '\u{2e7f}' { 2 } else { 1 }).sum();
+ format!("{s}{}", " ".repeat(width.saturating_sub(w)))
+}
+
+/// Where the viewer listens, for links that log in
+struct ViewerAt<'a> {
port: u16,
lan: bool,
- lan_hosts: &[String],
- tls: &viewer::tls::Setting,
+ lan_hosts: &'a [String],
+ tls: &'a viewer::tls::Setting,
mcp: bool,
- new: bool,
-) -> anyhow::Result<()> {
- let token = if new { viewer::auth::replace(data_dir)? } else { viewer::auth::load_or_create(data_dir)? };
- let file = viewer::auth::token_file(data_dir);
- println!("{}", ictl_l10n::trf!("令牌 {token}(存在 {})", "Token {token} (kept in {})", file.display()));
+}
+
+/// `viewer token …`: the viewer's login tokens. The viewer reads the file again when it changes
+fn viewer_token(data_dir: &Path, at: &ViewerAt, action: Option<TokenAction>, new: bool) -> anyhow::Result<()> {
+ use viewer::auth;
+ let entry = match action {
+ None if new => auth::renew(data_dir, auth::OWNER)?,
+ None => auth::get(data_dir, auth::OWNER)?,
+ Some(TokenAction::Show { name, new: true }) => auth::renew(data_dir, &name)?,
+ Some(TokenAction::Show { name, new: false }) => auth::get(data_dir, &name)?,
+ Some(TokenAction::Add { name, read_only }) => {
+ auth::add(data_dir, &name, if read_only { auth::Role::View } else { auth::Role::Operate })?
+ }
+ Some(TokenAction::List) => {
+ for e in auth::load(data_dir)? {
+ let role = match e.role {
+ auth::Role::Operate => ictl_l10n::tr!("可操作", "operate"),
+ auth::Role::View => ictl_l10n::tr!("只读", "read-only"),
+ };
+ let created = chrono::DateTime::from_timestamp(e.created as i64, 0)
+ .map(|t| t.format("%Y-%m-%d").to_string())
+ .unwrap_or_default();
+ println!("{} {} {created}", pad(&e.name, 24), pad(role, 10));
+ }
+ println!("{}", ictl_l10n::trf!("(存在 {})", "(kept in {})", auth::tokens_file(data_dir).display()));
+ return Ok(());
+ }
+ Some(TokenAction::Remove { name }) => {
+ auth::remove(data_dir, &name)?;
+ println!(
+ "{}",
+ ictl_l10n::trf!(
+ "已删掉 {name}:用它登录的浏览器和程序马上进不来了。",
+ "Removed {name}: browsers and programs logged in with it are out now."
+ )
+ );
+ return Ok(());
+ }
+ };
+ let (token, port) = (&entry.token, at.port);
+ let role = match entry.role {
+ auth::Role::Operate => ictl_l10n::tr!("可操作", "may operate"),
+ auth::Role::View => ictl_l10n::tr!(
+ "只读:只能看画面、设备状态和任务",
+ "read-only: watches the picture, the device's state and tasks"
+ ),
+ };
+ println!("{}", ictl_l10n::trf!("令牌 {}({role})", "Token {} ({role})", entry.name));
+ println!(" {token}");
println!(
"{}",
ictl_l10n::trf!(
@@ -525,9 +600,9 @@ fn viewer_token(
"Here http://127.0.0.1:{port}/?token={token}"
)
);
- let scheme = if tls.enabled(lan) { "https" } else { "http" };
- if lan {
- for a in viewer::lan_addresses(lan_hosts) {
+ let scheme = if at.tls.enabled(at.lan) { "https" } else { "http" };
+ if at.lan {
+ for a in viewer::lan_addresses(at.lan_hosts) {
println!(
"{}",
ictl_l10n::trf!(
@@ -537,13 +612,9 @@ fn viewer_token(
);
}
}
- if mcp {
+ if at.mcp && entry.role == auth::Role::Operate {
println!(
- "{}",
- ictl_l10n::trf!(
- "MCP claude mcp add --transport http iphone http://127.0.0.1:{port}/mcp --header \"Authorization: Bearer {token}\"",
- "MCP claude mcp add --transport http iphone http://127.0.0.1:{port}/mcp --header \"Authorization: Bearer {token}\""
- )
+ "MCP claude mcp add --transport http iphone http://127.0.0.1:{port}/mcp --header \"Authorization: Bearer {token}\""
);
}
println!(
@@ -557,12 +628,10 @@ fn viewer_token(
println!(
"{}",
ictl_l10n::tr!(
- "已换成新令牌,之前登录的浏览器和 MCP 客户端都要用新令牌。控制台服务在运行就会重启;手动运行的 viewer 要自己重启。",
- "The token was replaced: browsers and MCP clients logged in before need the new one. A running viewer service is restarted; restart a viewer you started by hand yourself."
+ "已换成新令牌,马上生效:用旧令牌登录的浏览器和 MCP 客户端都要用新的。",
+ "The token was replaced, effective now: browsers and MCP clients that used the old one need the new one."
)
);
- // a running viewer reads the token when it starts
- service::restart_viewer_if_running();
}
Ok(())
}
@@ -1330,6 +1399,13 @@ mod tests {
/// 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 token_names_line_up_in_columns() {
+ assert_eq!(super::pad("owner", 8), "owner ");
+ assert_eq!(super::pad("客厅电视", 10), "客厅电视 ", "four wide characters are eight columns");
+ assert_eq!(super::pad("toolongname", 4), "toolongname");
+ }
+
#[test]
fn viewer_settings_from_the_environment() {
use clap::Parser;
diff --git a/apps/iphone-control/src/task.rs b/apps/iphone-control/src/task.rs
index a7f3a59..1b0c94b 100644
--- a/apps/iphone-control/src/task.rs
+++ b/apps/iphone-control/src/task.rs
@@ -7,8 +7,12 @@
//! taking over hold it, confirmations wait for the user). When the command exits the task ends with its exit
//! status; when the task ends elsewhere (stopped on the page, the phone changed), the command is stopped. Ctrl-C
//! stops the task. The other subcommands follow and steer tasks, whoever started them.
+//!
+//! `task run --url <viewer>` does the same for a phone on another machine, through its viewer ([`remote`]).
+
+mod remote;
-use std::path::Path;
+use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, bail};
@@ -25,6 +29,10 @@ pub enum TaskAction {
owner: String,
#[arg(long = "app", value_name = "APP", help = ictl_l10n::tr!("任务只在这些 App 里操作(App 名或 Bundle ID,可以写多次);到了别的 App 每一步都先等你确认。不写就不限制", "Limit the task to these apps (name or bundle ID, repeatable); in any other app each step waits for you first. No limit if not given"))]
apps: Vec<String>,
+ #[arg(long, value_name = "URL", help = ictl_l10n::tr!("手机接在另一台机器上:那台机器的控制台地址,比如 https://192.168.1.5:8200。登录令牌放在环境变量 IPHONE_CONTROL_VIEWER_TOKEN 里;命令拿到的是 IPHONE_CONTROL_MCP_URL 和任务口令,agent 用 HTTP 方式的 MCP 接入", "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; the command gets IPHONE_CONTROL_MCP_URL and the task's token, and its agent connects to MCP over HTTP"))]
+ url: Option<String>,
+ #[arg(long, value_name = "PEM", requires = "url", 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>,
#[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
command: Vec<String>,
},
@@ -80,8 +88,14 @@ pub async fn run(socket: &Path, action: TaskAction) -> anyhow::Result<()> {
for_pid: None,
};
let req = match action {
- TaskAction::Run { title, owner, apps, command } => {
- return run_command(socket, title, &owner, &apps, &command).await;
+ TaskAction::Run { title, owner, apps, url, ca, command } => {
+ let backend = match url {
+ Some(url) => {
+ Backend::Remote(remote::Remote::new(&url, ca.as_deref(), Some(remote::Remote::login_from_env()?))?)
+ }
+ None => Backend::Local(socket),
+ };
+ return run_command(&backend, title, &owner, &apps, &command).await;
}
TaskAction::List { json } => return list(socket, json).await,
TaskAction::Events { id } => {
@@ -95,6 +109,10 @@ pub async fn run(socket: &Path, action: TaskAction) -> anyhow::Result<()> {
let token = std::env::var(protocol::TASK_TOKEN_ENV).ok().filter(|t| !t.is_empty()).with_context(|| {
ictl_l10n::trf!("没有设 {}:不在任务里", "{} isn't set: not inside a task", protocol::TASK_TOKEN_ENV)
})?;
+ // under `task run --url`: the phone is on another machine
+ if let Some(r) = remote::Remote::from_env() {
+ return r?.finish(&token, !failed, &summary.join(" ")).await;
+ }
let req = Request::TaskFinish { ok: !failed, summary: summary.join(" ") };
return expect_ok(protocol::as_task(Some(token), None, ask(socket, &req)).await);
}
@@ -144,26 +162,124 @@ async fn list(socket: &Path, json: bool) -> anyhow::Result<()> {
Ok(())
}
+/// Where `task run` opens its task
+enum Backend<'a> {
+ /// The daemon's socket, on this machine
+ Local(&'a Path),
+ /// Another machine's viewer (`--url`)
+ Remote(remote::Remote),
+}
+
+/// The open task's lease, with its events
+enum Lease {
+ Local(protocol::TaskStream),
+ Remote(remote::Events),
+}
+
+impl Lease {
+ async fn next(&mut self) -> Option<protocol::TaskEvent> {
+ match self {
+ Self::Local(s) => s.next().await,
+ Self::Remote(e) => e.next().await,
+ }
+ }
+}
+
+impl Backend<'_> {
+ async fn open(&self, title: &str, owner: &str, apps: &[String]) -> anyhow::Result<(protocol::TaskOpened, Lease)> {
+ Ok(match self {
+ Self::Local(socket) => {
+ let (o, s) = protocol::open_task(socket, title, owner, apps).await.map_err(anyhow::Error::msg)?;
+ (o, Lease::Local(s))
+ }
+ Self::Remote(r) => {
+ let (o, e) = r.open(title, owner, apps).await?;
+ (o, Lease::Remote(e))
+ }
+ })
+ }
+
+ /// Before the command starts: what it starts is the task's agent, which may not control the task. On another
+ /// machine the agent never has the login that could
+ async fn agent_follows(&self, token: &str) {
+ if let Self::Local(socket) = self {
+ let _ = protocol::as_task(Some(token.to_owned()), None, ask(socket, &Request::TaskAgent)).await;
+ }
+ }
+
+ /// The command's environment, besides the task's token and id
+ fn env(&self) -> Vec<(&'static str, String)> {
+ match self {
+ Self::Local(_) => Vec::new(),
+ Self::Remote(r) => r.env(),
+ }
+ }
+
+ /// Ends the task with the command's result (nothing changes if it ended already)
+ async fn finish(&self, token: &str, ok: bool, summary: &str) {
+ match self {
+ Self::Local(socket) => {
+ let req = Request::TaskFinish { ok, summary: summary.to_owned() };
+ let _ = protocol::as_task(Some(token.to_owned()), None, ask(socket, &req)).await;
+ }
+ Self::Remote(r) => {
+ let _ = r.finish(token, ok, summary).await;
+ }
+ }
+ }
+
+ /// The user stops the task (Ctrl-C, SIGTERM); whether it was taken
+ async fn stop(&self, id: &str) -> bool {
+ match self {
+ Self::Local(socket) => {
+ let req = Request::TaskControl {
+ id: id.into(),
+ action: "stop".into(),
+ step: None,
+ approve: false,
+ by: Some("owner".into()),
+ for_pid: None,
+ };
+ matches!(ask(socket, &req).await, Ok(Response::Text { .. }))
+ }
+ Self::Remote(r) => r.stop(id).await,
+ }
+ }
+
+ async fn state(&self, id: &str) -> Option<String> {
+ match self {
+ Self::Local(socket) => {
+ protocol::task_list(socket).await.ok()?.into_iter().find(|t| t.id == id).map(|t| t.state)
+ }
+ Self::Remote(r) => r.state(id).await,
+ }
+ }
+}
+
/// `task run`: the task lives as long as the command
async fn run_command(
- socket: &Path,
+ backend: &Backend<'_>,
title: Option<String>,
owner: &str,
apps: &[String],
command: &[String],
) -> anyhow::Result<()> {
let title = title.unwrap_or_else(|| command.join(" "));
- let (opened, mut lease) = protocol::open_task(socket, &title, owner, apps).await.map_err(anyhow::Error::msg)?;
+ let (opened, mut lease) = backend.open(&title, owner, apps).await?;
eprintln!("{}", ictl_l10n::trf!("任务 {} 已开始", "Task {} started", opened.id));
if !apps.is_empty() {
eprintln!("{}", ictl_l10n::trf!("只在这些 App 里操作:{}", "Limited to these apps: {}", apps.join(", ")));
}
// the command and what it starts may not control the task, only stop it; said before it starts
- let _ = protocol::as_task(Some(opened.token.clone()), None, ask(socket, &Request::TaskAgent)).await;
+ backend.agent_follows(&opened.token).await;
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)
+ .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)
+ .env_remove(remote::LOGIN_ENV)
// its own group: stopping the task stops everything it started (an agent and its MCP server)
.process_group(0)
.kill_on_drop(true)
@@ -173,8 +289,7 @@ async fn run_command(
Err(e) => {
let why = ictl_l10n::trf!("启动不了 {}:{e}", "Can't start {}: {e}", command[0]);
// ended as failed while the lease is still held (dropping it first would make it abandoned)
- let req = Request::TaskFinish { ok: false, summary: why.clone() };
- let _ = protocol::as_task(Some(opened.token.clone()), None, ask(socket, &req)).await;
+ backend.finish(&opened.token, false, &why).await;
drop(lease);
bail!("{why}");
}
@@ -197,7 +312,7 @@ async fn run_command(
if finished_inside(outcome.as_deref()) {
grace = Some(Box::pin(tokio::time::sleep(FINISH_GRACE)));
} else {
- // stopped or interrupted elsewhere, or the daemon went away: the command can't go on
+ // stopped or interrupted elsewhere, or the daemon (viewer) went away: the command can't go on
stop_group(pid);
}
}
@@ -205,23 +320,17 @@ async fn run_command(
grace = None;
stop_group(pid);
}
- _ = tokio::signal::ctrl_c() => stop_here(socket, &opened.id, pid).await,
- _ = term.recv() => stop_here(socket, &opened.id, pid).await,
+ _ = tokio::signal::ctrl_c() => stop_here(backend, &opened.id, pid).await,
+ _ = term.recv() => stop_here(backend, &opened.id, pid).await,
}
};
if !ended {
// the command may have ended the task itself (`task finish`); then this changes nothing
- let req = Request::TaskFinish { ok: status.success(), summary: String::new() };
- let _ = protocol::as_task(Some(opened.token.clone()), None, ask(socket, &req)).await;
+ backend.finish(&opened.token, status.success(), "").await;
}
let outcome = match outcome {
Some(o) => o,
- None => protocol::task_list(socket)
- .await
- .ok()
- .and_then(|l| l.into_iter().find(|t| t.id == opened.id))
- .map(|t| t.state)
- .unwrap_or_default(),
+ None => backend.state(&opened.id).await.unwrap_or_default(),
};
eprintln!("{}", ictl_l10n::trf!("任务 {} 结束:{outcome}", "Task {} ended: {outcome}", opened.id));
drop(lease);
@@ -242,17 +351,9 @@ fn exit_code(code: Option<i32>, outcome: &str) -> i32 {
code.unwrap_or(if outcome == "completed" { 0 } else { 1 })
}
-/// Ctrl-C or SIGTERM: the user stops the task (the lease stream then reports it, and the command is stopped)
-async fn stop_here(socket: &Path, id: &str, pid: Option<libc::pid_t>) {
- let req = Request::TaskControl {
- id: id.into(),
- action: "stop".into(),
- step: None,
- approve: false,
- by: Some("owner".into()),
- for_pid: None,
- };
- if !matches!(ask(socket, &req).await, Ok(Response::Text { .. })) {
+/// Ctrl-C or SIGTERM: the user stops the task (the lease then reports it, and the command is stopped)
+async fn stop_here(backend: &Backend<'_>, id: &str, pid: Option<libc::pid_t>) {
+ if !backend.stop(id).await {
stop_group(pid);
}
}
diff --git a/apps/iphone-control/src/task/remote.rs b/apps/iphone-control/src/task/remote.rs
new file mode 100644
index 0000000..4d12fe1
--- /dev/null
+++ b/apps/iphone-control/src/task/remote.rs
@@ -0,0 +1,209 @@
+//! `task run --url`: a task on another machine's phone, through its viewer (docs/task-control.md 7.6).
+//!
+//! The viewer's `POST /api/agent/tasks/open` opens the task and keeps answering with its events (server-sent
+//! events); that response is the lease, as the socket's connection is for `task run` on the same machine. This side
+//! logs in with `IPHONE_CONTROL_VIEWER_TOKEN` (a token that may operate) and keeps it: the command only gets the
+//! task's token, with the viewer's address, so the agent can use `/mcp` for its task but can't control it.
+
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use anyhow::{Context, bail};
+use ictl_daemon::protocol::{TaskEvent, TaskOpened};
+use serde_json::{Value, json};
+
+/// The viewer's login token for `task run --url`
+pub const LOGIN_ENV: &str = "IPHONE_CONTROL_VIEWER_TOKEN";
+/// Given to the command: the viewer it works through
+pub const URL_ENV: &str = "IPHONE_CONTROL_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";
+/// Given to the command when `--ca` was: the certificate to trust
+pub const CA_ENV: &str = "IPHONE_CONTROL_CA";
+
+/// A viewer on another machine
+pub struct Remote {
+ client: reqwest::Client,
+ /// `https://host:port`, no trailing slash
+ base: String,
+ ca: Option<PathBuf>,
+ /// `None`: only the task's token (`task finish` from inside the command)
+ login: Option<String>,
+}
+
+impl Remote {
+ /// `url`: the viewer's address; `ca`: a certificate to trust besides the system's (the viewer's self-signed one)
+ pub fn new(url: &str, ca: Option<&Path>, login: Option<String>) -> anyhow::Result<Self> {
+ let base = url.trim().trim_end_matches('/').trim_end_matches("/mcp").to_owned();
+ if !base.starts_with("http://") && !base.starts_with("https://") {
+ bail!(ictl_l10n::trf!(
+ "--url 要是控制台的地址,比如 https://192.168.1.5:8200:{url}",
+ "--url takes the viewer's address, such as https://192.168.1.5:8200: {url}"
+ ));
+ }
+ // reqwest is built without a crypto provider of its own (main installs ring; so does this, for tests)
+ let _ = rustls::crypto::ring::default_provider().install_default();
+ // the viewer is on this network: never through a proxy from the environment
+ let mut b = reqwest::Client::builder().no_proxy().connect_timeout(Duration::from_secs(10));
+ if let Some(ca) = ca {
+ let pem = std::fs::read(ca).with_context(|| ca.display().to_string())?;
+ let cert = reqwest::Certificate::from_pem(&pem).with_context(|| ca.display().to_string())?;
+ b = b.tls_certs_merge([cert]);
+ }
+ Ok(Self { client: b.build()?, base, ca: ca.map(Path::to_owned), login })
+ }
+
+ /// From inside a command `task run --url` started (its environment), with the task's token only
+ pub fn from_env() -> Option<anyhow::Result<Self>> {
+ let url = std::env::var(URL_ENV).ok().filter(|u| !u.is_empty())?;
+ let ca = std::env::var_os(CA_ENV).filter(|c| !c.is_empty()).map(PathBuf::from);
+ Some(Self::new(&url, ca.as_deref(), None))
+ }
+
+ /// The login token for opening and controlling tasks
+ pub fn login_from_env() -> anyhow::Result<String> {
+ std::env::var(LOGIN_ENV).ok().filter(|t| !t.trim().is_empty()).map(|t| t.trim().to_owned()).with_context(|| {
+ ictl_l10n::trf!(
+ "--url 要用控制台的登录令牌:设 {LOGIN_ENV}(在接着手机的机器上运行 iphone-control viewer token 查看)",
+ "--url needs the viewer's login token: set {LOGIN_ENV} (iphone-control viewer token shows it, on the machine with the phone)"
+ )
+ })
+ }
+
+ /// The variables the command gets, besides the task's token and id
+ pub fn env(&self) -> Vec<(&'static str, String)> {
+ let mut v = vec![(URL_ENV, self.base.clone()), (MCP_URL_ENV, format!("{}/mcp", self.base))];
+ if let Some(ca) = &self.ca {
+ v.push((CA_ENV, ca.display().to_string()));
+ }
+ v
+ }
+
+ fn post(&self, path: &str, body: &Value) -> reqwest::RequestBuilder {
+ let r = self.client.post(format!("{}{path}", self.base)).json(body);
+ match &self.login {
+ Some(t) => r.bearer_auth(t),
+ None => r,
+ }
+ }
+
+ /// Opens a task: its id and token, and its events, whose response is the lease
+ pub async fn open(&self, title: &str, owner: &str, apps: &[String]) -> anyhow::Result<(TaskOpened, Events)> {
+ let body = json!({"title": title, "owner": owner, "apps": apps});
+ let resp = self.post("/api/agent/tasks/open", &body).send().await.with_context(|| self.base.clone())?;
+ if !resp.status().is_success() {
+ bail!("{}", failure(resp).await);
+ }
+ let mut events = Events { resp, buf: Vec::new() };
+ match events.next().await {
+ Some(e) if e.event == "opened" => Ok((serde_json::from_value(e.data)?, events)),
+ _ => bail!(ictl_l10n::tr!("控制台没有开出任务", "The viewer didn't open the task")),
+ }
+ }
+
+ /// Stops the task (the platform's Ctrl-C); whether the viewer took it
+ pub async fn stop(&self, id: &str) -> bool {
+ let r = self.post(&format!("/api/agent/tasks/{id}/stop"), &json!({})).send().await;
+ r.is_ok_and(|r| r.status().is_success())
+ }
+
+ /// Ends the task with the command's result, as the task (its token)
+ pub async fn finish(&self, token: &str, ok: bool, summary: &str) -> anyhow::Result<()> {
+ let r = self
+ .post("/api/agent/tasks/finish", &json!({"ok": ok, "summary": summary}))
+ .header(ictl_daemon::protocol::TASK_TOKEN_HEADER, token)
+ .timeout(Duration::from_secs(15))
+ .send()
+ .await
+ .with_context(|| self.base.clone())?;
+ if !r.status().is_success() {
+ bail!("{}", failure(r).await);
+ }
+ Ok(())
+ }
+
+ /// The task's state as the viewer lists it
+ pub async fn state(&self, id: &str) -> Option<String> {
+ let mut r = self.client.get(format!("{}/api/agent/tasks", self.base)).timeout(Duration::from_secs(15));
+ if let Some(t) = &self.login {
+ r = r.bearer_auth(t);
+ }
+ let v: Value = r.send().await.ok()?.json().await.ok()?;
+ v["tasks"].as_array()?.iter().find(|t| t["id"] == id)?["state"].as_str().map(str::to_owned)
+ }
+}
+
+/// What the viewer said when it refused
+async fn failure(r: reqwest::Response) -> String {
+ let status = r.status();
+ let text = r.text().await.unwrap_or_default();
+ let message = serde_json::from_str::<Value>(&text).ok().and_then(|v| v["message"].as_str().map(str::to_owned));
+ let why = message.unwrap_or_else(|| text.trim().chars().take(200).collect());
+ match status.as_u16() {
+ 401 => ictl_l10n::trf!("控制台没认这个登录令牌({why})", "The viewer didn't take the login token ({why})"),
+ 403 => ictl_l10n::trf!("控制台拒绝了({why})", "The viewer refused ({why})"),
+ _ => format!("HTTP {status}: {why}"),
+ }
+}
+
+/// A task's events as server-sent events
+pub struct Events {
+ resp: reqwest::Response,
+ buf: Vec<u8>,
+}
+
+impl Events {
+ /// The next event; `None` when the response ended (the task ended, or the viewer went away)
+ pub async fn next(&mut self) -> Option<TaskEvent> {
+ loop {
+ if let Some(i) = self.buf.windows(2).position(|w| w == b"\n\n") {
+ let block: Vec<u8> = self.buf.drain(..i + 2).collect();
+ if let Some(e) = parse_event(&String::from_utf8_lossy(&block)) {
+ return Some(e);
+ }
+ continue;
+ }
+ match self.resp.chunk().await {
+ Ok(Some(c)) => self.buf.extend_from_slice(&c),
+ _ => return None,
+ }
+ }
+ }
+}
+
+/// One server-sent event (`event:` and `data:` lines); comments (`: ping`) and malformed ones are `None`
+fn parse_event(block: &str) -> Option<TaskEvent> {
+ let (mut event, mut data) = (None, Vec::new());
+ for line in block.lines() {
+ if let Some(v) = line.strip_prefix("event:") {
+ event = Some(v.trim().to_owned());
+ } else if let Some(v) = line.strip_prefix("data:") {
+ data.push(v.strip_prefix(' ').unwrap_or(v));
+ }
+ }
+ Some(TaskEvent { event: event?, data: serde_json::from_str(&data.join("\n")).ok()? })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reads_server_sent_events() {
+ assert!(parse_event(": ping\n\n").is_none());
+ let e = parse_event("event: opened\ndata: {\"id\":\"a\",\"token\":\"b\"}\n\n").unwrap();
+ assert_eq!((e.event.as_str(), e.data["token"].as_str()), ("opened", Some("b")));
+ let e = parse_event("event: step\ndata:{\"id\":1}\n").unwrap();
+ assert_eq!(e.data["id"], 1);
+ assert!(parse_event("data: {}\n\n").is_none(), "no event name");
+ }
+
+ #[test]
+ fn the_address_is_the_viewer_s() {
+ let r = Remote::new("https://nas.local:8202/mcp/", None, None).unwrap();
+ assert_eq!(r.base, "https://nas.local:8202");
+ let env = r.env();
+ assert!(env.contains(&(MCP_URL_ENV, "https://nas.local:8202/mcp".into())));
+ assert!(Remote::new("nas.local:8202", None, None).is_err());
+ }
+}
diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.html
index 3c6785c..aa89399 100644
--- a/apps/iphone-control/src/viewer.html
+++ b/apps/iphone-control/src/viewer.html
@@ -844,6 +844,10 @@ button.nav-device:disabled { cursor: default; }
@media (pointer: coarse) and (max-width: 767.98px) {
.input, .textarea { font-size: max(1rem, 16px); }
}
+/* 只读令牌:只能看,操作的入口都不显示(服务端照样拒绝) */
+[data-readonly] #composer, [data-readonly] #prompt-error, [data-readonly] #dock, [data-readonly] .confirm .od-cluster { display: none !important; }
+.readonly-note { display: none; margin: 0; padding: 10px var(--sp-3); border-radius: var(--r-lg); background: var(--warn-soft, var(--hover)); color: var(--text); font-size: var(--fs-sm); line-height: 1.5; }
+[data-readonly] .readonly-note { display: block; }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: 1ms !important; animation-iteration-count: 1 !important; transition-duration: 1ms !important; }
.spin { animation: none !important; }
@@ -921,6 +925,7 @@ button.nav-device:disabled { cursor: default; }
</div>
</div>
<p class="field-error" id="prompt-error" hidden></p>
+ <p class="readonly-note" id="readonly-note" role="status"></p>
<div class="sidebar-footer">
<button type="button" class="sidebar-settings" id="appearance-btn" aria-haspopup="dialog" aria-controls="appearance"><span class="ic" data-icon="settings"></span><span>设置</span></button>
<button type="button" class="btn btn-ghost btn-icon btn-sm" id="about-updates" popovertarget="updates-dialog" aria-controls="updates-dialog" aria-haspopup="dialog" aria-expanded="false" aria-label="关于与更新" title="关于与更新"><span class="ic" data-icon="info"></span><span id="update-dot" aria-hidden="true" hidden></span></button>
@@ -1115,7 +1120,7 @@ const LANG = (() => {
return v === 'en' || v === 'zh' ? v : document.documentElement.dataset.lang === 'en' ? 'en' : 'zh';
})();
document.documentElement.lang = LANG === 'en' ? 'en' : 'zh-CN';
-const EN = {"登录已过期":"Login expired","任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","<div class=\"ph-kb\" data-type=\"Keyboard\">键盘</div>":"<div class=\"ph-kb\" data-type=\"Keyboard\">Keyboard</div>","<li class=\"empty-note\">打开这一页时会读取已安装的 App。</li>":"<li class=\"empty-note\">The installed apps are read when this tab opens.</li>","<li class=\"sr-only\">正在读取 App 列表…</li>":"<li class=\"sr-only\">Reading the app list…</li>","<li class=\"sr-only\">正在读取元素…</li>":"<li class=\"sr-only\">Reading elements…</li>","<option>没有可用的 AI</option>":"<option>No AI available</option>","<p class=\"empty-note\">正在连接 iphone-control 服务…</p>":"<p class=\"empty-note\">Connecting to the iphone-control service…</p>","<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>演示模式</span></span>":"<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>Demo</span></span>","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。":"Run <code>iphone-control sign</code> to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 <code>iphone-control setup --reconfigure</code> 选「手机」,在设备上点「信任」。":"Run <code>iphone-control setup --reconfigure</code>, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress"};
+const EN = {"登录已过期":"Login expired","只读登录":"Read-only login",":能看画面、设备状态和任务,不能操作手机,也不能开始、暂停或确认任务。":": you can watch the picture, the device's state and tasks, but not act on the phone or start, pause or confirm tasks.","只读":"Read-only","只读登录:只能看,不能操作":"Read-only login: you can watch, not act","任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","<div class=\"ph-kb\" data-type=\"Keyboard\">键盘</div>":"<div class=\"ph-kb\" data-type=\"Keyboard\">Keyboard</div>","<li class=\"empty-note\">打开这一页时会读取已安装的 App。</li>":"<li class=\"empty-note\">The installed apps are read when this tab opens.</li>","<li class=\"sr-only\">正在读取 App 列表…</li>":"<li class=\"sr-only\">Reading the app list…</li>","<li class=\"sr-only\">正在读取元素…</li>":"<li class=\"sr-only\">Reading elements…</li>","<option>没有可用的 AI</option>":"<option>No AI available</option>","<p class=\"empty-note\">正在连接 iphone-control 服务…</p>":"<p class=\"empty-note\">Connecting to the iphone-control service…</p>","<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>演示模式</span></span>":"<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>Demo</span></span>","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。":"Run <code>iphone-control sign</code> to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 <code>iphone-control setup --reconfigure</code> 选「手机」,在设备上点「信任」。":"Run <code>iphone-control setup --reconfigure</code>, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress"};
Object.assign(EN, {
'未连接设备':'No device connected', '用数据线连接 iPhone 或 iPad。':'Connect an iPhone or iPad with a USB cable.', '等待设备连接':'Waiting for a device',
'外观':'Appearance', '界面字号':'Text size', '标准':'Standard', '大':'Large', '特大':'Extra large',
@@ -1448,6 +1453,7 @@ const S = {
scope: [], scopeApps: null, scopeAppsFor: '', scopeErr: '',
elements: [], elState: 'idle', elErr: '',
tasks: [], expanded: new Set(), seq: 0,
+ login: null, readOnly: false, // 登录用的令牌 {name, role};只读令牌只能看
udid: null, deviceName: '', switching: false, signing: false, // 本页显示的设备:画面、操作、面板都跟着它
agents: [], agent: null // 本机可用的 AI(claude / codex)和选中的那个
};
@@ -1742,6 +1748,7 @@ async function api(path, body, device = S.udid) {
return r.json();
}
async function act(path, body, quiet) {
+ if (S.readOnly) { show(tr('只读登录:只能看,不能操作'), 'warn'); return { ok: false }; }
if (S.mode === 'live' && path !== '/api/select' && (S.switching || !S.udid)) return { ok: false };
const t0 = performance.now(), epoch = feedEpoch;
try {
@@ -1995,6 +2002,9 @@ function cancelGestures() {
}
function applyInfo(v) {
const udid = v.udid || null;
+ S.login = v.login || null; S.readOnly = S.login?.role === 'view';
+ document.documentElement.toggleAttribute('data-readonly', S.readOnly);
+ if (S.readOnly) $('#readonly-note').textContent = `${tr('只读登录')}(${S.login.name})${tr(':能看画面、设备状态和任务,不能操作手机,也不能开始、暂停或确认任务。')}`;
S.video = v.video || null; S.deviceVideo = !!v.device_video;
S.size = v.width > 0 && v.height > 0 ? { w: v.width, h: v.height } : null;
frame.toggleAttribute('data-absent', v.state === 'Absent' && !udid);
@@ -2511,6 +2521,8 @@ function renderChips() {
if (s && s.locked != null) {
chips.push(`<span class="chip"><span class="k">${tr('屏幕')}</span><span>${s.locked ? tr('已锁定') : tr('未锁定')}</span></span>`);
}
+ // first: the most important to see, and the row may be cut off on the right
+ if (S.readOnly) chips.unshift(`<span class="chip" title="${esc(S.login.name)}"><span class="chip-dot warn"></span><span>${tr('只读')}</span></span>`);
c.innerHTML = chips.join('');
}
// Keep the native disclosures and focused device buttons intact between status polls.
@@ -2907,6 +2919,7 @@ function sendPrompt() {
}
function startTask(text, apps = S.scope) {
if (activeTask()) return false;
+ if (S.readOnly) { show(tr('只读登录:只能看,不能操作'), 'warn'); return false; }
if (S.mode === 'detecting') { show(tr('还在连接服务,稍等一下再开始'), 'warn'); return false; }
S.pendingDelete = null;
const task = { id: 't' + (++S.seq), prompt: text, status: 'running', steps: [], startedAt: Date.now(), source: S.mode, agent: S.agent, apps: S.mode === 'live' ? [...apps] : [] };
diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs
index 90cbf7c..2aad13d 100644
--- a/apps/iphone-control/src/viewer.rs
+++ b/apps/iphone-control/src/viewer.rs
@@ -146,8 +146,7 @@ pub async fn run(
false => None,
};
let agents = Agents::new(socket)?;
- let token =
- auth::load_or_create(data_dir).map_err(|e| anyhow::anyhow!("{}: {e}", auth::token_file(data_dir).display()))?;
+ let auth = auth::Auth::load(data_dir, port)?;
println!(
"{}",
ictl_l10n::trf!(
@@ -284,7 +283,7 @@ pub async fn run(
acks: Arc::default(),
tls,
mcp: mcp.then(|| ictl_mcp::http_service(socket.to_path_buf())),
- auth: Some(auth::Auth::new(token, port)),
+ auth: Some(auth),
});
let slots = Arc::new(tokio::sync::Semaphore::new(crate::MAX_CONNECTIONS));
loop {
@@ -358,8 +357,15 @@ async fn handle(mut client: Conn, ctx: &Ctx, head: Vec<u8>, req: Head, mut body:
};
return redirect(&mut client, &to).await;
}
- if !login_gate(&mut client, ctx, &head, &req, &mut body).await? {
+ let Some(pass) = login_gate(&mut client, ctx, &head, &req, &mut body).await? else {
return Ok(());
+ };
+ if !pass.may(&req) {
+ let m = ictl_l10n::tr!(
+ "这是只读令牌:只能看画面、设备状态和任务,不能操作",
+ "This token is read-only: it can watch the picture, the device's state and tasks, but not act"
+ );
+ return json_reply(&mut client, 403, &json!({"ok": false, "message": m})).await;
}
let path = req.path.as_str();
match (req.method.as_str(), path) {
@@ -391,6 +397,10 @@ async fn handle(mut client: Conn, ctx: &Ctx, head: Vec<u8>, req: Head, mut body:
if let Some(id) = req.query("feed") {
v["feed_open"] = json!(ctx.feeds.lock().unwrap_or_else(|p| p.into_inner()).contains(&id));
}
+ // who the page is logged in as: a read-only token hides what it can't do
+ if let Some(w) = &pass.who {
+ v["login"] = json!({"name": w.name, "role": w.role.name()});
+ }
Ok(v)
}
"updates" => updates(ctx).await,
@@ -410,6 +420,39 @@ async fn handle(mut client: Conn, ctx: &Ctx, head: Vec<u8>, req: Head, mut body:
Err(m) => json_reply(&mut client, 502, &json!({"message": m})).await,
}
}
+ ("POST", "/api/agent/tasks/open" | "/api/agent/tasks/finish") => {
+ if !action_allowed(&req, &ctx.access, ctx.port, pass.program()) {
+ return reply(&mut client, 403, "text/plain", b"forbidden").await;
+ }
+ let len = req.content_length.unwrap_or(0);
+ if len > MAX_BODY {
+ return reply(&mut client, 413, "text/plain", b"too large").await;
+ }
+ read_body(&mut client, &mut body, len).await?;
+ let Ok(b) = serde_json::from_slice::<Value>(&body) else {
+ return json_reply(&mut client, 400, &json!({"ok": false, "message": "bad request"})).await;
+ };
+ if req.path == "/api/agent/tasks/open" {
+ let who = pass.who.as_ref().map_or("remote", |w| w.name.as_str());
+ return open_task(&mut client, ctx, &b, who).await;
+ }
+ let Some(token) = &req.task_token else {
+ let m = ictl_l10n::tr!("结束任务要带任务口令", "Ending a task needs its token");
+ return json_reply(&mut client, 400, &json!({"ok": false, "message": m})).await;
+ };
+ let req = Request::TaskFinish {
+ ok: b["ok"].as_bool().unwrap_or(true),
+ summary: b["summary"].as_str().unwrap_or_default().to_owned(),
+ };
+ let r = protocol::as_task(Some(token.clone()), None, protocol::call(&ctx.socket, &req, Some(SHORT))).await;
+ let (code, v) = match r {
+ Ok(Response::Text { .. }) => (200, json!({"ok": true})),
+ Ok(Response::Error { message, .. }) => (409, json!({"ok": false, "message": message})),
+ Ok(Response::Image { caption, .. }) => (409, json!({"ok": false, "message": caption})),
+ Err(e) => (502, json!({"ok": false, "message": e.to_string()})),
+ };
+ json_reply(&mut client, code, &v).await
+ }
("GET" | "POST" | "DELETE", "/mcp") if ctx.mcp.is_some() => {
// a browser says where it comes from: only the page itself. Other clients send no Origin
if req.origin.as_deref().is_some_and(|o| !ctx.access.origin_allowed(o, ctx.port)) {
@@ -427,7 +470,7 @@ async fn handle(mut client: Conn, ctx: &Ctx, head: Vec<u8>, req: Head, mut body:
mcp::serve(svc, &mut client, &head, body).await
}
("POST", p) if p.starts_with("/api/") => {
- if !action_allowed(&req, &ctx.access, ctx.port) {
+ if !action_allowed(&req, &ctx.access, ctx.port, pass.program()) {
return reply(&mut client, 403, "text/plain", b"forbidden").await;
}
let len = req.content_length.unwrap_or(0);
@@ -439,7 +482,11 @@ async fn handle(mut client: Conn, ctx: &Ctx, head: Vec<u8>, req: Head, mut body:
return json_reply(&mut client, 400, &json!({"ok": false, "message": "bad request"})).await;
};
// controlling a task: who, for its log, and which local process (the daemon refuses the task's agent)
- let caller = if p.starts_with("/api/agent/tasks/") { Caller::of(&client).await } else { Caller::default() };
+ let caller = if p.starts_with("/api/agent/tasks/") {
+ Caller::of(&client, pass.who.as_ref()).await
+ } else {
+ Caller::default()
+ };
let (code, v) = post(ctx, &p[5..], &b, req.device.as_deref(), caller).await;
json_reply(&mut client, code, &v).await
}
@@ -529,13 +576,17 @@ struct Caller {
}
impl Caller {
- async fn of(client: &Conn) -> Self {
+ /// `who`: the token it logged in with, by name in the task's log
+ async fn of(client: &Conn, who: Option<&auth::Who>) -> Self {
let (Ok(peer), Ok(local)) = (client.tcp().peer_addr(), client.tcp().local_addr()) else {
return Self::default();
};
// reads every process's open files: not on the runtime's threads
let pid = tokio::task::spawn_blocking(move || peer::local_client(peer, local)).await.ok().flatten();
- let by = if peer.ip().to_canonical().is_loopback() { "viewer".into() } else { format!("viewer {}", peer.ip()) };
+ let mut by = who.map_or_else(|| "viewer".to_owned(), |w| format!("viewer:{}", w.name));
+ if !peer.ip().to_canonical().is_loopback() {
+ by = format!("{by} {}", peer.ip());
+ }
Self { by, pid }
}
}
@@ -667,6 +718,61 @@ async fn events(client: &mut Conn, mut stream: protocol::TaskStream) -> anyhow::
}
}
+/// `POST /api/agent/tasks/open` (docs/task-control.md 7.6): a task opened from another machine, as `task_open` on
+/// the socket. The answer is server-sent events: `opened` with `{id, token}` first, then the task's events until it
+/// ends. The connection is the task's lease: when the client goes away before the task ended, it is abandoned.
+/// `by`: the login token's name, the task's owner unless the request names one
+async fn open_task(client: &mut Conn, ctx: &Ctx, b: &Value, by: &str) -> anyhow::Result<()> {
+ let title = b["title"].as_str().unwrap_or_default();
+ let owner = b["owner"].as_str().map(str::trim).filter(|o| !o.is_empty()).unwrap_or(by);
+ let apps: Vec<String> = match &b["apps"] {
+ Value::Null => Vec::new(),
+ Value::Array(a) if a.iter().all(Value::is_string) => {
+ a.iter().filter_map(Value::as_str).map(str::to_owned).collect()
+ }
+ _ => return json_reply(client, 400, &json!({"ok": false, "message": "apps must be a list of strings"})).await,
+ };
+ let (opened, mut lease) = match protocol::open_task(&ctx.socket, title, owner, &apps).await {
+ Ok(o) => o,
+ Err(m) => return json_reply(client, 409, &json!({"ok": false, "message": m})).await,
+ };
+ let (mut rd, mut wr) = tokio::io::split(client);
+ let head = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\n\
+ X-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\nevent: opened\ndata: {}\n\n",
+ json!({"id": opened.id, "token": opened.token})
+ );
+ wr.write_all(head.as_bytes()).await?;
+ wr.flush().await?;
+ let gone = async {
+ let mut buf = [0u8; 64];
+ while matches!(rd.read(&mut buf).await, Ok(n) if n > 0) {}
+ };
+ tokio::pin!(gone);
+ loop {
+ tokio::select! {
+ e = lease.next() => match e {
+ Some(e) => {
+ wr.write_all(sse(&e).as_bytes()).await?;
+ wr.flush().await?;
+ if e.event == "done" {
+ return Ok(());
+ }
+ }
+ // the daemon went away (restarting): the task was interrupted, which the client learns from the end
+ None => return Ok(()),
+ },
+ // the opener went away: dropping the lease abandons the task
+ () = &mut gone => return Ok(()),
+ // a comment now and then keeps proxies from closing a quiet connection
+ _ = tokio::time::sleep(Duration::from_secs(15)) => {
+ wr.write_all(b": ping\n\n").await?;
+ wr.flush().await?;
+ }
+ }
+ }
+}
+
fn sse(e: &protocol::TaskEvent) -> String {
format!("event: {}\ndata: {}\n\n", e.event, e.data)
}
@@ -718,14 +824,69 @@ async fn reply_with(client: &mut Conn, status: u16, kind: &str, body: &[u8], ext
client.write_all(body).await?;
// over TLS the last record may still be buffered
client.flush().await?;
+ linger(client).await;
Ok(())
}
-/// The login ([`auth`]) before anything else: `true` when the request may go on, otherwise it was answered (the
-/// login page, a login, or 401 / 429)
-async fn login_gate(client: &mut Conn, ctx: &Ctx, head: &[u8], req: &Head, body: &mut Vec<u8>) -> anyhow::Result<bool> {
+/// Closes after an answer without losing it: a socket closed with request data it never read (a body refused before
+/// it was read: 401, 403, 413) sends a reset, and the client may then never see the answer. So: end our side, then
+/// read what the client still sends until it closes too, for a second and 1 MB at most
+async fn linger(client: &mut Conn) {
+ let _ = client.shutdown().await;
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
+ let (mut buf, mut left) = ([0u8; 8192], 1usize << 20);
+ while left > 0 {
+ match tokio::time::timeout_at(deadline, client.read(&mut buf)).await {
+ Ok(Ok(n)) if n > 0 => left = left.saturating_sub(n),
+ _ => return,
+ }
+ }
+}
+
+/// Who a request is, once [`login_gate`] let it in
+#[derive(Default)]
+struct Pass {
+ /// Logged in with this token; `None` when the viewer has no login (tests), or came in by a task's token
+ who: Option<auth::Who>,
+ /// Came in by the token of an active task, without a login: an agent, which may only work for its task
+ /// ([`TASK_PATHS`])
+ agent: bool,
+}
+
+/// What an agent may use with its task's token alone: the tools, and ending the task with a summary
+const TASK_PATHS: [&str; 2] = ["/mcp", "/api/agent/tasks/finish"];
+
+impl Pass {
+ /// A program (`Authorization: Bearer`, or a task's token), which needs no `Origin`: a web page can't make a
+ /// browser send either
+ fn program(&self) -> bool {
+ self.agent || self.who.as_ref().is_some_and(|w| w.bearer)
+ }
+
+ /// A read-only token may look (any `GET` but `/mcp`, and report how much of a video it read); an agent only works
+ /// for its task
+ fn may(&self, req: &Head) -> bool {
+ match &self.who {
+ Some(w) if w.role == auth::Role::View => {
+ (req.method == "GET" && req.path != "/mcp") || (req.method == "POST" && req.path == "/api/video/ack")
+ }
+ None if self.agent => TASK_PATHS.contains(&req.path.as_str()),
+ _ => true,
+ }
+ }
+}
+
+/// The login ([`auth`]) before anything else: who the request is when it may go on, otherwise `None` and it was
+/// answered (the login page, a login, or 401 / 429)
+async fn login_gate(
+ client: &mut Conn,
+ ctx: &Ctx,
+ head: &[u8],
+ req: &Head,
+ body: &mut Vec<u8>,
+) -> anyhow::Result<Option<Pass>> {
use auth::Verdict;
- let Some(a) = &ctx.auth else { return Ok(true) };
+ let Some(a) = &ctx.auth else { return Ok(Some(Pass::default())) };
let secure = client.is_tls();
// the link `iphone-control viewer token` shows
if req.method == "GET"
@@ -733,33 +894,48 @@ async fn login_gate(client: &mut Conn, ctx: &Ctx, head: &[u8], req: &Head, body:
&& let Some(t) = req.query("token")
{
match a.try_token(&t) {
- Verdict::Ok => logged_in(client, a, secure).await?,
+ Verdict::Ok(w) => logged_in(client, a, &w.name, secure).await?,
v => login_page(client, v).await?,
}
- return Ok(false);
+ return Ok(None);
}
// the login page's form
if req.method == "POST" && req.path == "/login" {
if req.origin.as_deref().is_some_and(|o| !ctx.access.origin_allowed(o, ctx.port)) {
reply(client, 403, "text/plain", b"forbidden").await?;
- return Ok(false);
+ return Ok(None);
}
let len = req.content_length.unwrap_or(0);
if len > 4096 {
reply(client, 413, "text/plain", b"too large").await?;
- return Ok(false);
+ return Ok(None);
}
read_body(client, body, len).await?;
match auth::form_token(body).filter(|t| !t.trim().is_empty()).map(|t| a.try_token(&t)) {
- Some(Verdict::Ok) => logged_in(client, a, secure).await?,
+ Some(Verdict::Ok(w)) => logged_in(client, a, &w.name, secure).await?,
Some(v) => login_page(client, v).await?,
None => login_page(client, Verdict::Missing).await?,
}
- return Ok(false);
+ return Ok(None);
}
- let v = a.check(head);
- if v == Verdict::Ok {
- return Ok(true);
+ let mut v = match a.check(head) {
+ Verdict::Ok(w) => return Ok(Some(Pass { who: Some(w), agent: false })),
+ v => v,
+ };
+ // an agent on another machine: its task's token instead of a login, only for that task (docs/task-control.md 7.6)
+ if v != Verdict::Limited
+ && TASK_PATHS.contains(&req.path.as_str())
+ && let Some(t) = &req.task_token
+ {
+ if a.limited() {
+ v = Verdict::Limited;
+ } else if protocol::task_check(&ctx.socket, t).await.is_ok() {
+ return Ok(Some(Pass { who: None, agent: true }));
+ } else {
+ // a wrong task token counts like a wrong login
+ a.failed();
+ v = Verdict::Wrong;
+ }
}
let status = if v == Verdict::Limited { 429 } else { 401 };
match (req.method.as_str(), req.path.as_str()) {
@@ -771,12 +947,12 @@ async fn login_gate(client: &mut Conn, ctx: &Ctx, head: &[u8], req: &Head, body:
}
_ => reply(client, status, "text/plain", b"log in first").await?,
}
- Ok(false)
+ Ok(None)
}
/// Logged in: a session cookie, and the page without the token in its address (and history)
-async fn logged_in(client: &mut Conn, a: &auth::Auth, secure: bool) -> anyhow::Result<()> {
- let extra = format!("Location: /\r\nSet-Cookie: {}\r\n", a.set_cookie(secure));
+async fn logged_in(client: &mut Conn, a: &auth::Auth, name: &str, secure: bool) -> anyhow::Result<()> {
+ let extra = format!("Location: /\r\nSet-Cookie: {}\r\n", a.set_cookie(name, secure));
reply_with(client, 303, "text/plain", b"", &extra).await
}
@@ -823,6 +999,8 @@ struct Head {
fetch_site: Option<String>,
/// `X-Ictl-Lang`: the page's language
lang: Option<ictl_l10n::Lang>,
+ /// [`protocol::TASK_TOKEN_HEADER`]: an agent working for a task
+ task_token: Option<String>,
}
impl Head {
@@ -844,6 +1022,7 @@ impl Head {
fetch_site: None,
lang: None,
device: None,
+ task_token: None,
};
for l in lines {
let Some((k, v)) = l.split_once(':') else { continue };
@@ -855,6 +1034,7 @@ impl Head {
"sec-fetch-site" => h.fetch_site = Some(v.to_ascii_lowercase()),
"x-ictl-lang" => h.lang = ictl_l10n::parse(v),
"x-ictl-device" if !v.is_empty() => h.device = Some(v.to_owned()),
+ k if k == protocol::TASK_TOKEN_HEADER && !v.is_empty() => h.task_token = Some(v.to_owned()),
_ => {}
}
}
@@ -896,9 +1076,14 @@ fn percent_decode(s: &str) -> String {
/// An action must come from this page: `Origin` is the viewer's own address (one of this machine's names with
/// `--lan`), and the body is JSON, which a cross-origin page can't send without a preflight that this server never
/// answers
-fn action_allowed(req: &Head, access: &lan::Access, port: u16) -> bool {
+/// `bearer`: logged in with `Authorization: Bearer` (a program). A browser always sends `Origin` with a POST, and a
+/// web page can't make it send that header, so without `Origin` only a program's request is taken
+fn action_allowed(req: &Head, access: &lan::Access, port: u16, bearer: bool) -> bool {
let json = req.content_type.as_deref().is_some_and(|c| c.split(';').next() == Some("application/json"));
- json && req.origin.as_deref().is_some_and(|o| access.origin_allowed(o, port))
+ json && match req.origin.as_deref() {
+ Some(o) => access.origin_allowed(o, port),
+ None => bearer,
+ }
}
/// A read from another site (an `<img>` or `<script>` on some page) is refused: browsers say so in
@@ -1270,7 +1455,16 @@ mod tests {
let temp = tempfile::tempdir_in("/tmp").unwrap();
let mut ctx = test_ctx(temp.path(), &temp.path().join("none.sock"));
let token = "t".repeat(64);
- ctx.auth = Some(auth::Auth::new(token.clone(), 8202));
+ let entry = |name: &str, role, c: char| auth::Entry {
+ name: name.into(),
+ role,
+ token: c.to_string().repeat(64),
+ created: 0,
+ };
+ ctx.auth = Some(auth::Auth::fixed(
+ vec![entry("owner", auth::Role::Operate, 't'), entry("tv", auth::Role::View, 'v')],
+ 8202,
+ ));
let get = |path: &str, extra: &str| format!("GET {path} HTTP/1.1\r\nHost: 127.0.0.1:8202\r\n{extra}\r\n");
let status = |r: &str| r.split(' ').nth(1).unwrap_or_default().to_owned();
@@ -1306,9 +1500,101 @@ mod tests {
let r = exchange(&ctx, form("https://evil.example")).await;
assert_eq!(status(&r), "403", "{r}");
+ // refused before its body was read: the client still gets the answer, not a reset
+ let big = "x".repeat(256 * 1024);
+ let r = exchange(
+ &ctx,
+ format!("POST /api/button HTTP/1.1\r\nHost: 127.0.0.1:8202\r\nContent-Length: {}\r\n\r\n{big}", big.len()),
+ )
+ .await;
+ assert_eq!(status(&r), "401", "{}", &r[..r.len().min(200)]);
+
// MCP clients are told to send a bearer token
let r = exchange(&ctx, "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1:8202\r\nContent-Length: 0\r\n\r\n".into()).await;
assert!(status(&r) == "401" && r.contains("WWW-Authenticate: Bearer"), "{r}");
+
+ // a read-only token looks but doesn't act
+ let tv = format!("Authorization: Bearer {}\r\n", "v".repeat(64));
+ let r = exchange(&ctx, get("/api/agent/backends", &tv)).await;
+ assert_eq!(status(&r), "200", "{r}");
+ let post = |path: &str, auth: &str| {
+ format!(
+ "POST {path} HTTP/1.1\r\nHost: 127.0.0.1:8202\r\nContent-Type: application/json\r\n{auth}Content-Length: 2\r\n\r\n{{}}"
+ )
+ };
+ for p in ["/api/button", "/api/agent/tasks", "/api/agent/tasks/abc/pause", "/api/select"] {
+ let r = exchange(&ctx, post(p, &tv)).await;
+ assert!(status(&r) == "403" && (r.contains("只读") || r.contains("read-only")), "{p}: {r}");
+ }
+ let r = exchange(&ctx, post("/mcp", &tv)).await;
+ assert_eq!(status(&r), "403", "no MCP: its tools act: {r}");
+ let r = exchange(&ctx, post("/api/video/ack", &tv)).await;
+ assert_ne!(status(&r), "403", "it may say how much of the picture it read: {r}");
+ // a program with the operating token needs no Origin (no daemon here: past the checks it can't reach it)
+ let r = exchange(&ctx, post("/api/button", &format!("Authorization: Bearer {token}\r\n"))).await;
+ assert_ne!(status(&r), "403", "{r}");
+ // the same request from a browser's session cookie without Origin is refused
+ let r = exchange(&ctx, post("/api/button", &format!("Cookie: {cookie}\r\n"))).await;
+ assert_eq!(status(&r), "403", "{r}");
+ }
+
+ /// An agent on another machine has its task's token and nothing else: the tools and ending its task, no more
+ #[tokio::test]
+ async fn an_agent_works_for_its_task_by_its_token_alone() {
+ use tokio::io::{AsyncBufReadExt, BufReader};
+ let temp = tempfile::tempdir_in("/tmp").unwrap();
+ let socket = temp.path().join("daemon.sock");
+ let daemon = tokio::net::UnixListener::bind(&socket).unwrap();
+ // a daemon that knows one active task, with the token `good`
+ let seen = Arc::new(Mutex::new(Vec::<Value>::new()));
+ let log = seen.clone();
+ tokio::spawn(async move {
+ while let Ok((mut peer, _)) = daemon.accept().await {
+ let mut line = String::new();
+ BufReader::new(&mut peer).read_line(&mut line).await.unwrap();
+ let req: Value = serde_json::from_str(&line).unwrap();
+ let reply = if req["task"] == "good" { Response::text("t1") } else { Response::error("no such task") };
+ log.lock().unwrap().push(req);
+ let _ = peer.write_all(format!("{}\n", serde_json::to_string(&reply).unwrap()).as_bytes()).await;
+ }
+ });
+ let mut ctx = test_ctx(temp.path(), &socket);
+ let entry = auth::Entry { name: "owner".into(), role: auth::Role::Operate, token: "o".repeat(64), created: 0 };
+ ctx.auth = Some(auth::Auth::fixed(vec![entry], 8202));
+ ctx.mcp = Some(ictl_mcp::http_service(socket.clone()));
+ let status = |r: &str| r.split(' ').nth(1).unwrap_or_default().to_owned();
+ let post = |path: &str, token: &str, body: &str| {
+ format!(
+ "POST {path} HTTP/1.1\r\nHost: 127.0.0.1:8202\r\nContent-Type: application/json\r\n\
+ Accept: application/json, text/event-stream\r\nIphone-Control-Task-Token: {token}\r\n\
+ Content-Length: {}\r\n\r\n{body}",
+ body.len()
+ )
+ };
+ let init = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"1"}}}"#;
+ let r = exchange(&ctx, post("/mcp", "good", init)).await;
+ assert_eq!(status(&r), "200", "the tools: {r}");
+ let r = exchange(&ctx, post("/mcp", "ended", init)).await;
+ assert!(status(&r) == "401" && r.contains("WWW-Authenticate: Bearer"), "{r}");
+ let r = exchange(&ctx, post("/api/agent/tasks/finish", "good", r#"{"ok":true,"summary":"done"}"#)).await;
+ assert_eq!(status(&r), "200", "{r}");
+ let finish = seen.lock().unwrap().iter().find(|q| q["op"] == "task_finish").cloned().unwrap();
+ assert_eq!((finish["task"].as_str(), finish["summary"].as_str()), (Some("good"), Some("done")));
+ // nothing else: not the page's API, not controlling its task, not opening another
+ for p in ["/api/agent/tasks/t1/confirm", "/api/agent/tasks/t1/resume", "/api/agent/tasks/open", "/api/button"] {
+ let r = exchange(&ctx, post(p, "good", "{}")).await;
+ assert!(matches!(status(&r).as_str(), "401" | "403"), "{p}: {r}");
+ }
+ let r = exchange(
+ &ctx,
+ "GET /api/info HTTP/1.1\r\nHost: 127.0.0.1:8202\r\nIphone-Control-Task-Token: good\r\n\r\n".into(),
+ )
+ .await;
+ assert_eq!(status(&r), "401", "{r}");
+ assert!(
+ !seen.lock().unwrap().iter().any(|q| q["op"] == "task_control"),
+ "nothing reached the daemon's control"
+ );
}
#[test]
@@ -1458,18 +1744,46 @@ mod tests {
fn actions_need_own_origin_and_json() {
let local = lan::Access::local();
let ok = "POST /api/tap HTTP/1.1\r\nHost: 127.0.0.1:8200\r\nOrigin: http://127.0.0.1:8200\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n";
- assert!(action_allowed(&head(ok), &local, 8200));
- assert!(action_allowed(&head(&ok.replace("http://127.0.0.1:8200", "http://localhost:8200")), &local, 8200));
+ assert!(action_allowed(&head(ok), &local, 8200, false));
+ assert!(action_allowed(
+ &head(&ok.replace("http://127.0.0.1:8200", "http://localhost:8200")),
+ &local,
+ 8200,
+ false
+ ));
// another page, another port, no origin, a form post
- assert!(!action_allowed(&head(&ok.replace("http://127.0.0.1:8200", "http://evil.example")), &local, 8200));
- assert!(!action_allowed(&head(&ok.replace("http://127.0.0.1:8200", "http://127.0.0.1:3000")), &local, 8200));
- assert!(!action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200\r\n", "")), &local, 8200));
- assert!(!action_allowed(&head(&ok.replace("application/json", "text/plain")), &local, 8200));
- assert!(!action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200", "Origin: null")), &local, 8200));
+ assert!(!action_allowed(
+ &head(&ok.replace("http://127.0.0.1:8200", "http://evil.example")),
+ &local,
+ 8200,
+ false
+ ));
+ assert!(!action_allowed(
+ &head(&ok.replace("http://127.0.0.1:8200", "http://127.0.0.1:3000")),
+ &local,
+ 8200,
+ false
+ ));
+ assert!(!action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200\r\n", "")), &local, 8200, false));
+ // a program logged in with Authorization: Bearer sends no Origin; a cookie (a browser) needs it
+ assert!(action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200\r\n", "")), &local, 8200, true));
+ assert!(!action_allowed(
+ &head(&ok.replace("http://127.0.0.1:8200", "http://evil.example")),
+ &local,
+ 8200,
+ true
+ ));
+ assert!(!action_allowed(&head(&ok.replace("application/json", "text/plain")), &local, 8200, false));
+ assert!(!action_allowed(
+ &head(&ok.replace("Origin: http://127.0.0.1:8200", "Origin: null")),
+ &local,
+ 8200,
+ false
+ ));
// only open to the network with --lan
let on_lan = ok.replace("http://127.0.0.1:8200", "http://192.168.10.100:8200");
- assert!(!action_allowed(&head(&on_lan), &local, 8200));
- assert!(action_allowed(&head(&on_lan), &lan::Access::with_hosts(["192.168.10.100".into()]), 8200));
+ assert!(!action_allowed(&head(&on_lan), &local, 8200, false));
+ assert!(action_allowed(&head(&on_lan), &lan::Access::with_hosts(["192.168.10.100".into()]), 8200, false));
}
#[test]
diff --git a/apps/iphone-control/src/viewer/auth.rs b/apps/iphone-control/src/viewer/auth.rs
index ed6aa0a..fe94ac0 100644
--- a/apps/iphone-control/src/viewer/auth.rs
+++ b/apps/iphone-control/src/viewer/auth.rs
@@ -1,53 +1,176 @@
-//! Login for the control page and `/mcp` (docs/task-control.md 7.5).
+//! Login for the control page and `/mcp` (docs/task-control.md 7.5, 7.6).
//!
//! Every HTTP request needs it, from this machine too: a reverse proxy or tunnel on this machine (frp, nginx,
//! cloudflared, `tailscale serve`) makes every visitor's connection come from `127.0.0.1`, so the page can't tell
//! the user at their own browser from someone on the internet. The Unix socket (the CLI, `iphone-control mcp` over
//! stdio, `task run`) isn't HTTP and doesn't need it.
//!
-//! One token, made on the first start and kept in `<data dir>/viewer-token` (0600); `iphone-control viewer token`
-//! shows it with a link that logs in, `--new` replaces it (and every session with it). A browser logs in once (the
-//! login page, or the link with `?token=`) and gets a session cookie: `HttpOnly`, `SameSite=Lax`, `Secure` over
-//! HTTPS, 30 days. Its value is an HMAC of the token, so it shows nothing of the token and ends when the token is
-//! replaced. Programs send `Authorization: Bearer <token>`.
+//! Tokens have a name and a role ([`Role`]): `operate` may do everything, `view` may only look (the picture, the
+//! device's state, tasks and their events). They are kept in `<data dir>/viewer-tokens.json` (0600); the first one,
+//! `owner`, is made on the first start (from the single `viewer-token` of earlier versions, if there is one).
+//! `iphone-control viewer token …` shows, adds, replaces and removes them; the viewer reads the file again when it
+//! changes, so that takes effect at once. Who did what goes into a task's log by the token's name.
+//!
+//! A browser logs in once (the login page, or the link with `?token=`) and gets a session cookie: `HttpOnly`,
+//! `SameSite=Lax`, `Secure` over HTTPS, 30 days. Its value is an HMAC of the token, so it shows nothing of the token
+//! and ends when the token is replaced or removed. Programs send `Authorization: Bearer <token>`.
//!
//! Wrong tokens are counted for the whole page, not per address (behind a proxy every address is `127.0.0.1`): after
-//! [`MAX_FAILURES`] in a minute, tokens aren't checked until the minute is over. The token is 256 random bits, so
+//! [`MAX_FAILURES`] in a minute, tokens aren't checked until the minute is over. A token is 256 random bits, so
//! this only makes guessing slower still; a session that is already logged in isn't affected.
use std::collections::VecDeque;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
-use std::time::{Duration, Instant};
+use std::time::{Duration, Instant, SystemTime};
+
+use anyhow::{Context, bail};
+use serde::{Deserialize, Serialize};
-/// Under the data directory
-pub const TOKEN_FILE: &str = "viewer-token";
+/// Under the data directory: the tokens
+pub const TOKENS_FILE: &str = "viewer-tokens.json";
+/// Under the data directory: the single token of earlier versions, which becomes [`OWNER`]
+const OLD_TOKEN_FILE: &str = "viewer-token";
+/// The first token's name
+pub const OWNER: &str = "owner";
/// Wrong tokens in [`WINDOW`] before tokens are refused until it is over
const MAX_FAILURES: usize = 20;
const WINDOW: Duration = Duration::from_secs(60);
/// How long a browser stays logged in
const SESSION_DAYS: u64 = 30;
-pub fn token_file(data_dir: &Path) -> PathBuf {
- data_dir.join(TOKEN_FILE)
+/// What a token may do
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Role {
+ /// Everything: act on the phone, start and control tasks, `/mcp`
+ Operate,
+ /// Only look: the picture, the device's state, tasks and their events
+ View,
}
-/// The token, made now if there is none
-pub fn load_or_create(data_dir: &Path) -> io::Result<String> {
- match std::fs::read_to_string(token_file(data_dir)) {
- Ok(t) if valid_token(t.trim()) => Ok(t.trim().to_owned()),
- Ok(_) => replace(data_dir),
- Err(e) if e.kind() == io::ErrorKind::NotFound => replace(data_dir),
- Err(e) => Err(e),
+impl Role {
+ pub fn name(self) -> &'static str {
+ match self {
+ Self::Operate => "operate",
+ Self::View => "view",
+ }
}
}
-/// A new token in place of the old one; every browser has to log in again
-pub fn replace(data_dir: &Path) -> io::Result<String> {
- let token = new_token()?;
- write_private(&token_file(data_dir), token.as_bytes())?;
- Ok(token)
+/// A token in [`TOKENS_FILE`]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Entry {
+ pub name: String,
+ pub role: Role,
+ pub token: String,
+ /// Unix seconds
+ #[serde(default)]
+ pub created: u64,
+}
+
+pub fn tokens_file(data_dir: &Path) -> PathBuf {
+ data_dir.join(TOKENS_FILE)
+}
+
+/// The tokens; the first start makes [`OWNER`] (from the earlier single token if there is one)
+pub fn load(data_dir: &Path) -> anyhow::Result<Vec<Entry>> {
+ if let Some(v) = read(data_dir)? {
+ return Ok(v);
+ }
+ let old = data_dir.join(OLD_TOKEN_FILE);
+ let token = match std::fs::read_to_string(&old) {
+ Ok(t) if valid_token(t.trim()) => t.trim().to_owned(),
+ _ => new_token()?,
+ };
+ let v = vec![Entry { name: OWNER.into(), role: Role::Operate, token, created: now() }];
+ save(data_dir, &v)?;
+ let _ = std::fs::remove_file(old);
+ Ok(v)
+}
+
+/// The tokens as they are on disk; `None` when there is no file yet
+fn read(data_dir: &Path) -> anyhow::Result<Option<Vec<Entry>>> {
+ let file = tokens_file(data_dir);
+ match std::fs::read(&file) {
+ Ok(b) => {
+ let v: Vec<Entry> = serde_json::from_slice(&b).with_context(|| file.display().to_string())?;
+ Ok(Some(v.into_iter().filter(|e| valid_token(&e.token)).collect()))
+ }
+ Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
+ Err(e) => Err(anyhow::Error::new(e).context(file.display().to_string())),
+ }
+}
+
+fn save(data_dir: &Path, v: &[Entry]) -> anyhow::Result<()> {
+ let mut json = serde_json::to_vec_pretty(v)?;
+ json.push(b'\n');
+ write_private(&tokens_file(data_dir), &json)?;
+ Ok(())
+}
+
+/// A name the CLI and the task log can show: letters, digits, `-`, `_`, `.`, at most 40
+pub fn valid_name(name: &str) -> bool {
+ (1..=40).contains(&name.chars().count()) && name.chars().all(|c| c.is_alphanumeric() || "-_.".contains(c))
+}
+
+/// A new token named `name`
+pub fn add(data_dir: &Path, name: &str, role: Role) -> anyhow::Result<Entry> {
+ if !valid_name(name) {
+ bail!(ictl_l10n::trf!(
+ "名字只能用字母、数字和 - _ .,最多 40 个字:{name}",
+ "A name takes letters, digits and - _ . only, 40 at most: {name}"
+ ));
+ }
+ let mut v = load(data_dir)?;
+ if v.iter().any(|e| e.name == name) {
+ bail!(ictl_l10n::trf!(
+ "已经有叫 {name} 的令牌了;要换新的用 viewer token show {name} --new",
+ "There is already a token named {name}; to replace it: viewer token show {name} --new"
+ ));
+ }
+ let e = Entry { name: name.into(), role, token: new_token()?, created: now() };
+ v.push(e.clone());
+ save(data_dir, &v)?;
+ Ok(e)
+}
+
+/// The token named `name`
+pub fn get(data_dir: &Path, name: &str) -> anyhow::Result<Entry> {
+ load(data_dir)?.into_iter().find(|e| e.name == name).ok_or_else(|| no_such(name))
+}
+
+/// A new token in place of `name`'s; its browsers have to log in again
+pub fn renew(data_dir: &Path, name: &str) -> anyhow::Result<Entry> {
+ let mut v = load(data_dir)?;
+ let e = v.iter_mut().find(|e| e.name == name).ok_or_else(|| no_such(name))?;
+ e.token = new_token()?;
+ e.created = now();
+ let e = e.clone();
+ save(data_dir, &v)?;
+ Ok(e)
+}
+
+/// Removes `name`; the last token that may operate stays (nobody could act otherwise)
+pub fn remove(data_dir: &Path, name: &str) -> anyhow::Result<()> {
+ let mut v = load(data_dir)?;
+ let Some(i) = v.iter().position(|e| e.name == name) else { return Err(no_such(name)) };
+ if v[i].role == Role::Operate && v.iter().filter(|e| e.role == Role::Operate).count() == 1 {
+ bail!(ictl_l10n::trf!(
+ "{name} 是最后一个能操作的令牌,不能删;要换掉它用 viewer token show {name} --new",
+ "{name} is the last token that may operate, so it stays; to replace it: viewer token show {name} --new"
+ ));
+ }
+ v.remove(i);
+ save(data_dir, &v)
+}
+
+fn no_such(name: &str) -> anyhow::Error {
+ anyhow::anyhow!(ictl_l10n::trf!(
+ "没有叫 {name} 的令牌(viewer token list 列出所有令牌)",
+ "No token named {name} (viewer token list shows them)"
+ ))
}
fn valid_token(t: &str) -> bool {
@@ -61,6 +184,10 @@ fn new_token() -> io::Result<String> {
Ok(b.iter().map(|x| format!("{x:02x}")).collect())
}
+fn now() -> u64 {
+ SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
+}
+
/// Only this user may read it; written whole or not at all
fn write_private(file: &Path, data: &[u8]) -> io::Result<()> {
use std::io::Write;
@@ -76,11 +203,21 @@ fn write_private(file: &Path, data: &[u8]) -> io::Result<()> {
std::fs::rename(&tmp, file)
}
+/// Who a request is logged in as
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Who {
+ pub name: String,
+ pub role: Role,
+ /// With `Authorization: Bearer` (a program), not a session cookie (a browser): no `Origin` needed, since a web
+ /// page can't make a browser send it
+ pub bearer: bool,
+}
+
/// What a request shows of the login
#[derive(Debug, PartialEq, Eq)]
pub enum Verdict {
/// A valid session cookie or `Authorization: Bearer` token
- Ok,
+ Ok(Who),
/// Nothing (or only a stale cookie): log in
Missing,
/// A wrong token
@@ -89,21 +226,73 @@ pub enum Verdict {
Limited,
}
-pub struct Auth {
+/// A token as the viewer checks it
+struct Known {
+ name: String,
+ role: Role,
token: String,
/// The session cookie's value: HMAC-SHA256 of a fixed text under the token
session: String,
- /// One per port: cookies aren't separated by port, and another viewer on this machine has another token
+}
+
+impl Known {
+ fn of(e: Entry) -> Self {
+ let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, e.token.as_bytes());
+ let tag = ring::hmac::sign(&key, b"iphone-control viewer session v1");
+ let session = tag.as_ref().iter().map(|x| format!("{x:02x}")).collect();
+ Self { name: e.name, role: e.role, token: e.token, session }
+ }
+
+ fn who(&self, bearer: bool) -> Who {
+ Who { name: self.name.clone(), role: self.role, bearer }
+ }
+}
+
+/// The tokens, read again when the file changes (`viewer token …` while the viewer runs)
+struct Tokens {
+ known: Vec<Known>,
+ modified: Option<SystemTime>,
+}
+
+pub struct Auth {
+ /// `None`: fixed tokens (tests)
+ data_dir: Option<PathBuf>,
+ tokens: Mutex<Tokens>,
+ /// One per port: cookies aren't separated by port, and another viewer on this machine has other tokens
cookie: String,
failures: Mutex<VecDeque<Instant>>,
}
impl Auth {
- pub fn new(token: String, port: u16) -> Self {
- let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, token.as_bytes());
- let tag = ring::hmac::sign(&key, b"iphone-control viewer session v1");
- let session = tag.as_ref().iter().map(|x| format!("{x:02x}")).collect();
- Self { token, session, cookie: format!("ictl_viewer_{port}"), failures: Mutex::default() }
+ /// The tokens in `data_dir` ([`load`])
+ pub fn load(data_dir: &Path, port: u16) -> anyhow::Result<Self> {
+ let known = load(data_dir)?.into_iter().map(Known::of).collect();
+ let modified = std::fs::metadata(tokens_file(data_dir)).and_then(|m| m.modified()).ok();
+ Ok(Self::with(Some(data_dir.to_owned()), Tokens { known, modified }, port))
+ }
+
+ /// These tokens and no file
+ #[cfg(test)]
+ pub fn fixed(entries: Vec<Entry>, port: u16) -> Self {
+ Self::with(None, Tokens { known: entries.into_iter().map(Known::of).collect(), modified: None }, port)
+ }
+
+ fn with(data_dir: Option<PathBuf>, tokens: Tokens, port: u16) -> Self {
+ Self { data_dir, tokens: Mutex::new(tokens), cookie: format!("ictl_viewer_{port}"), failures: Mutex::default() }
+ }
+
+ /// The tokens, read again if the file changed. A file that can't be read leaves them as they were
+ fn tokens(&self) -> std::sync::MutexGuard<'_, Tokens> {
+ let mut t = self.tokens.lock().unwrap_or_else(|p| p.into_inner());
+ if let Some(dir) = &self.data_dir {
+ let modified = std::fs::metadata(tokens_file(dir)).and_then(|m| m.modified()).ok();
+ if modified != t.modified
+ && let Ok(Some(v)) = read(dir)
+ {
+ *t = Tokens { known: v.into_iter().map(Known::of).collect(), modified };
+ }
+ }
+ t
}
/// The request's session cookie or `Authorization: Bearer` token
@@ -115,8 +304,10 @@ impl Auth {
let k = k.trim();
if k.eq_ignore_ascii_case("cookie") {
let ours = v.split(';').filter_map(|c| c.trim().split_once('=')).find(|(n, _)| *n == self.cookie);
- if ours.is_some_and(|(_, v)| same(v.trim(), &self.session)) {
- return Verdict::Ok;
+ if let Some((_, v)) = ours
+ && let Some(k) = self.tokens().known.iter().find(|k| same(v.trim(), &k.session))
+ {
+ return Verdict::Ok(k.who(false));
}
} else if k.eq_ignore_ascii_case("authorization") {
let v = v.trim();
@@ -133,28 +324,46 @@ impl Auth {
/// A token someone typed or sent: right, wrong (counted), or not checked now
pub fn try_token(&self, presented: &str) -> Verdict {
+ if self.limited() {
+ return Verdict::Limited;
+ }
+ // every token is compared, so the time doesn't tell how many there are before the right one
+ let tokens = self.tokens();
+ let found =
+ tokens.known.iter().fold(None, |found, k| if same(presented.trim(), &k.token) { Some(k) } else { found });
+ match found {
+ Some(k) => Verdict::Ok(k.who(true)),
+ None => {
+ self.failed();
+ Verdict::Wrong
+ }
+ }
+ }
+
+ /// Too many wrong tokens just now
+ pub fn limited(&self) -> bool {
let mut f = self.failures.lock().unwrap_or_else(|p| p.into_inner());
let now = Instant::now();
while f.front().is_some_and(|t| now.duration_since(*t) > WINDOW) {
f.pop_front();
}
- if f.len() >= MAX_FAILURES {
- return Verdict::Limited;
- }
- if same(presented.trim(), &self.token) {
- Verdict::Ok
- } else {
- f.push_back(now);
- Verdict::Wrong
- }
+ f.len() >= MAX_FAILURES
}
- /// `Set-Cookie` for a browser that logged in; `secure` over HTTPS (the browser then only sends it there)
- pub fn set_cookie(&self, secure: bool) -> String {
+ /// A wrong token (or task token, see `viewer::login_gate`) was sent
+ pub fn failed(&self) {
+ self.failures.lock().unwrap_or_else(|p| p.into_inner()).push_back(Instant::now());
+ }
+
+ /// `Set-Cookie` for a browser that logged in with the token named `name`; `secure` over HTTPS (the browser then
+ /// only sends it there)
+ pub fn set_cookie(&self, name: &str, secure: bool) -> String {
+ let session =
+ self.tokens().known.iter().find(|k| k.name == name).map(|k| k.session.clone()).unwrap_or_default();
format!(
"{}={}; Path=/; Max-Age={}; HttpOnly; SameSite=Lax{}",
self.cookie,
- self.session,
+ session,
SESSION_DAYS * 24 * 60 * 60,
if secure { "; Secure" } else { "" }
)
@@ -176,7 +385,7 @@ pub fn login_page(error: Option<&str>) -> String {
"This control page needs its token.",
"Token",
"Log in",
- "Run <code>iphone-control viewer token</code> on the machine the phone is connected to: it shows the token and a link that logs in.",
+ "Run <code>iphone-control viewer token</code> on the machine the phone is connected to: it shows a token and a link that logs in.",
),
ictl_l10n::Lang::Zh => (
"zh-CN",
@@ -246,59 +455,112 @@ mod tests {
h.into_bytes()
}
+ fn entry(name: &str, role: Role, c: char) -> Entry {
+ Entry { name: name.into(), role, token: c.to_string().repeat(64), created: 0 }
+ }
+
+ fn who(name: &str, role: Role, bearer: bool) -> Verdict {
+ Verdict::Ok(Who { name: name.into(), role, bearer })
+ }
+
#[test]
- fn the_token_is_made_once_kept_private_and_replaced_on_demand() {
+ fn the_owner_is_made_once_from_the_earlier_single_token() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
- let a = load_or_create(tmp.path()).unwrap();
- assert_eq!(a.len(), 64);
- assert!(valid_token(&a));
- assert_eq!(load_or_create(tmp.path()).unwrap(), a, "kept");
- let mode = std::fs::metadata(token_file(tmp.path())).unwrap().permissions().mode();
+ std::fs::write(tmp.path().join(OLD_TOKEN_FILE), format!("{}\n", "a".repeat(64))).unwrap();
+ let v = load(tmp.path()).unwrap();
+ assert_eq!((v.len(), v[0].name.as_str(), v[0].role), (1, OWNER, Role::Operate));
+ assert_eq!(v[0].token, "a".repeat(64), "upgrading keeps the token: nobody logs in again");
+ assert!(!tmp.path().join(OLD_TOKEN_FILE).exists());
+ let mode = std::fs::metadata(tokens_file(tmp.path())).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o600);
- let b = replace(tmp.path()).unwrap();
- assert_ne!(a, b);
- assert_eq!(load_or_create(tmp.path()).unwrap(), b);
- std::fs::write(token_file(tmp.path()), "short").unwrap();
- assert_ne!(load_or_create(tmp.path()).unwrap(), "short", "a broken file is replaced");
+ assert_eq!(load(tmp.path()).unwrap()[0].token, v[0].token, "kept");
+
+ let fresh = tempfile::tempdir().unwrap();
+ let t = &load(fresh.path()).unwrap()[0].token;
+ assert!(t.len() == 64 && valid_token(t));
+ }
+
+ #[test]
+ fn tokens_are_added_renewed_and_removed_by_name() {
+ let tmp = tempfile::tempdir().unwrap();
+ let owner = load(tmp.path()).unwrap().remove(0);
+ let tv = add(tmp.path(), "客厅电视", Role::View).unwrap();
+ assert_eq!(tv.role, Role::View);
+ assert!(add(tmp.path(), "客厅电视", Role::Operate).is_err(), "taken");
+ assert!(add(tmp.path(), "has space", Role::View).is_err());
+ assert!(add(tmp.path(), "", Role::View).is_err());
+ assert_eq!(get(tmp.path(), "客厅电视").unwrap().token, tv.token);
+ let renewed = renew(tmp.path(), "客厅电视").unwrap();
+ assert_ne!(renewed.token, tv.token);
+ assert_eq!(get(tmp.path(), OWNER).unwrap().token, owner.token, "the others stay");
+ assert!(remove(tmp.path(), OWNER).is_err(), "the last that may operate");
+ remove(tmp.path(), "客厅电视").unwrap();
+ assert!(get(tmp.path(), "客厅电视").is_err());
+ add(tmp.path(), "ci", Role::Operate).unwrap();
+ remove(tmp.path(), OWNER).unwrap();
+ assert!(remove(tmp.path(), "nobody").is_err());
}
#[test]
- fn a_session_cookie_or_a_bearer_token_lets_a_request_in() {
- let auth = Auth::new("a".repeat(64), 8202);
- let cookie = auth.set_cookie(false);
+ fn a_session_cookie_or_a_bearer_token_says_who() {
+ let auth = Auth::fixed(vec![entry(OWNER, Role::Operate, 'a'), entry("tv", Role::View, 'b')], 8202);
+ let cookie = auth.set_cookie("tv", false);
let pair = cookie.split(';').next().unwrap();
assert!(cookie.contains("HttpOnly") && cookie.contains("SameSite=Lax") && !cookie.contains("Secure"));
- assert!(auth.set_cookie(true).ends_with("; Secure"));
- assert!(!pair.contains(&"a".repeat(64)), "the cookie doesn't carry the token");
+ assert!(auth.set_cookie(OWNER, true).ends_with("; Secure"));
+ assert!(!pair.contains(&"b".repeat(64)), "the cookie doesn't carry the token");
+ assert_ne!(pair, auth.set_cookie(OWNER, false).split(';').next().unwrap(), "one session per token");
assert_eq!(auth.check(&head(&[])), Verdict::Missing);
- assert_eq!(auth.check(&head(&[&format!("Cookie: theme=dark; {pair}")])), Verdict::Ok);
+ assert_eq!(auth.check(&head(&[&format!("Cookie: theme=dark; {pair}")])), who("tv", Role::View, false));
assert_eq!(auth.check(&head(&["Cookie: ictl_viewer_8202=deadbeef"])), Verdict::Missing, "stale: log in");
assert_eq!(auth.check(&head(&[&format!("Cookie: {}", pair.replace("8202", "8203"))])), Verdict::Missing);
- assert_eq!(auth.check(&head(&[&format!("Authorization: Bearer {}", "a".repeat(64))])), Verdict::Ok);
- assert_eq!(auth.check(&head(&[&format!("authorization: bearer {}", "a".repeat(64))])), Verdict::Ok);
+ let bearer = |t: char| format!("Authorization: Bearer {}", t.to_string().repeat(64));
+ assert_eq!(auth.check(&head(&[&bearer('a')])), who(OWNER, Role::Operate, true));
+ assert_eq!(auth.check(&head(&[&bearer('b').to_lowercase()])), who("tv", Role::View, true));
assert_eq!(auth.check(&head(&["Authorization: Bearer nope"])), Verdict::Wrong);
assert_eq!(auth.check(&head(&["Authorization: Basic Zm9vOmJhcg=="])), Verdict::Missing);
- // a new token ends the old sessions
- let other = Auth::new("b".repeat(64), 8202);
- assert_eq!(other.check(&head(&[pair])), Verdict::Missing);
+ // another set of tokens: the old sessions end
+ let other = Auth::fixed(vec![entry(OWNER, Role::Operate, 'c')], 8202);
assert_eq!(other.check(&head(&[&format!("Cookie: {pair}")])), Verdict::Missing);
}
+ /// `viewer token …` while the viewer runs takes effect without a restart
+ #[test]
+ fn the_viewer_follows_changes_to_the_file() {
+ let tmp = tempfile::tempdir().unwrap();
+ let auth = Auth::load(tmp.path(), 8202).unwrap();
+ let owner = get(tmp.path(), OWNER).unwrap();
+ let session = auth.set_cookie(OWNER, false).split(';').next().unwrap().to_owned();
+ assert!(matches!(auth.try_token(&owner.token), Verdict::Ok(_)));
+ // a file's time is often only accurate to the second
+ std::thread::sleep(Duration::from_millis(1100));
+ let tv = add(tmp.path(), "tv", Role::View).unwrap();
+ assert_eq!(auth.try_token(&tv.token), who("tv", Role::View, true));
+ std::thread::sleep(Duration::from_millis(1100));
+ let renewed = renew(tmp.path(), OWNER).unwrap();
+ assert_eq!(auth.try_token(&owner.token), Verdict::Wrong, "the old token");
+ assert_eq!(auth.check(&head(&[&format!("Cookie: {session}")])), Verdict::Missing, "and its sessions");
+ assert!(matches!(auth.try_token(&renewed.token), Verdict::Ok(_)));
+ }
+
#[test]
fn wrong_tokens_are_limited_for_everyone() {
- let auth = Auth::new("a".repeat(64), 8202);
- let session = auth.set_cookie(false).split(';').next().unwrap().to_owned();
+ let auth = Auth::fixed(vec![entry(OWNER, Role::Operate, 'a')], 8202);
+ let session = auth.set_cookie(OWNER, false).split(';').next().unwrap().to_owned();
for _ in 0..MAX_FAILURES {
assert_eq!(auth.try_token("guess"), Verdict::Wrong);
}
assert_eq!(auth.try_token("guess"), Verdict::Limited);
assert_eq!(auth.try_token(&"a".repeat(64)), Verdict::Limited, "not even checked for a minute");
- assert_eq!(auth.check(&head(&[&format!("Cookie: {session}")])), Verdict::Ok, "logged-in browsers go on");
+ assert!(
+ matches!(auth.check(&head(&[&format!("Cookie: {session}")])), Verdict::Ok(_)),
+ "logged-in browsers go on"
+ );
// the minute is over
auth.failures.lock().unwrap().iter_mut().for_each(|t| *t -= WINDOW + Duration::from_secs(1));
- assert_eq!(auth.try_token(&"a".repeat(64)), Verdict::Ok);
+ assert!(matches!(auth.try_token(&"a".repeat(64)), Verdict::Ok(_)));
}
#[test]
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index 802cd93..92cf76c 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -933,6 +933,7 @@ impl Daemon {
| Request::TaskList
| Request::TaskControl { .. }
| Request::TaskAgent
+ | Request::TaskCheck
| Request::TaskStep { .. }
| Request::TaskStepDone { .. }
| Request::TaskConfirm { .. }
@@ -980,6 +981,7 @@ fn lane(req: &Request) -> Lane {
| Request::TaskList
| Request::TaskControl { .. }
| Request::TaskAgent
+ | Request::TaskCheck
| Request::TaskStep { .. }
| Request::TaskStepDone { .. }
| Request::TaskConfirm { .. }
diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rs
index 6350dce..c597f85 100644
--- a/crates/ictl-daemon/src/tasks.rs
+++ b/crates/ictl-daemon/src/tasks.rs
@@ -237,6 +237,7 @@ pub fn scope_check(req: &Request) -> Option<Check> {
| Request::TaskList
| Request::TaskControl { .. }
| Request::TaskAgent
+ | Request::TaskCheck
| Request::TaskStep { .. }
| Request::TaskStepDone { .. }
| Request::TaskConfirm { .. }
@@ -939,6 +940,10 @@ impl Tasks {
)),
Err(r) => r,
},
+ Request::TaskCheck => match self.actor(token) {
+ Ok(t) => Response::text(t.id.clone()),
+ Err(r) => r,
+ },
Request::TaskStep { tool, args } => match self.actor(token) {
Ok(t) => t.step(tool, args, gone).await,
Err(r) => r,
@@ -1301,6 +1306,22 @@ mod tests {
assert_eq!(t.info().state, "cancelled");
}
+ /// What lets an agent on another machine use the viewer's `/mcp` by its task's token alone
+ #[tokio::test]
+ async fn a_task_s_token_is_checked_while_it_is_active() {
+ let ts = tasks();
+ let t = open(&ts);
+ let check = |token: Option<String>| {
+ let ts = &ts;
+ async move { ts.handle(&Request::TaskCheck, token.as_deref(), None, &mut None).await.unwrap() }
+ };
+ assert!(matches!(check(Some(t.token.clone())).await, Response::Text { text, .. } if text == t.id));
+ assert!(matches!(check(Some("nobody's".into())).await, Response::Error { .. }));
+ assert!(matches!(check(None).await, Response::Error { .. }));
+ t.control("stop", None, false, None).unwrap();
+ assert!(matches!(check(Some(t.token.clone())).await, Response::Error { .. }), "ended");
+ }
+
#[tokio::test]
async fn an_ended_or_unknown_token_is_refused_for_everything() {
let ts = Arc::new(tasks());
diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs
index c4113c6..89c16b9 100644
--- a/crates/ictl-mcp/src/lib.rs
+++ b/crates/ictl-mcp/src/lib.rs
@@ -854,6 +854,7 @@ pub fn wants_alert_check(req: &Request) -> bool {
| Request::TaskList
| Request::TaskControl { .. }
| Request::TaskAgent
+ | Request::TaskCheck
| Request::TaskStep { .. }
| Request::TaskStepDone { .. }
| Request::TaskConfirm { .. }
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index 8173c48..86e0e97 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -225,6 +225,9 @@ pub enum Request {
/// from now on (and the ones those start) is the task's agent, whose control requests are refused
/// ([`Request::TaskControl`])
TaskAgent,
+ /// With a task's token: the task's id while it is active, an error once it ended or for a token nobody knows.
+ /// The viewer lets an agent on another machine use `/mcp` by its task's token alone (docs/task-control.md 7.6)
+ TaskCheck,
/// With the task's token ([`TASK`]): a tool call starts. Waits while the task isn't running, then records the
/// step; the text is the step number. The calls the tool makes carry it ([`TASK_STEP`])
TaskStep {
@@ -379,6 +382,7 @@ impl Request {
| Self::TaskList
| Self::TaskControl { .. }
| Self::TaskAgent
+ | Self::TaskCheck
| Self::TaskStep { .. }
| Self::TaskStepDone { .. }
| Self::TaskConfirm { .. }
@@ -694,6 +698,16 @@ pub async fn task_events(socket: &std::path::Path, id: &str) -> Result<TaskStrea
}
}
+/// The id of the active task with `token` ([`Request::TaskCheck`]); `Err` is why not (ended, unknown, no daemon)
+pub async fn task_check(socket: &std::path::Path, token: &str) -> Result<String, String> {
+ let call = call(socket, &Request::TaskCheck, Some(std::time::Duration::from_secs(10)));
+ match as_task(Some(token.to_owned()), None, call).await.map_err(|e| e.to_string())? {
+ Response::Text { text, .. } => Ok(text),
+ Response::Error { message, .. } => Err(message),
+ Response::Image { caption, .. } => Err(caption),
+ }
+}
+
/// Recent tasks ([`Request::TaskList`])
pub async fn task_list(socket: &std::path::Path) -> Result<Vec<TaskInfo>, String> {
match call(socket, &Request::TaskList, Some(std::time::Duration::from_secs(10))).await.map_err(|e| e.to_string())? {
diff --git a/docs/task-control.md b/docs/task-control.md
index c31b208..43fbeb4 100644
--- a/docs/task-control.md
+++ b/docs/task-control.md
@@ -135,7 +135,8 @@ Running → Waiting(等确认)→ Running
| 四 | 局域网访问控制台(7.2)、控制台后台服务、HTTPS(7.3) | 已完成(2026-11-13) |
| 四 | HTTP MCP(7.4) | 已完成(2026-11-13) |
| 四 | 登录(7.5,一个令牌) | 已完成(2026-11-13) |
-| 四 | 只读/可操作两种令牌、跨主机开任务(HTTP 控制面)、多设备租约 | 等需要时 |
+| 四 | 有名字的令牌和只读令牌、跨主机开任务(7.6) | 已完成(2026-11-13) |
+| 四 | 远端 stdio MCP 转接、多设备租约 | 等需要时 |
## 5. 阶段一的具体设计
@@ -297,4 +298,24 @@ Running → Waiting(等确认)→ Running
- **程序**:`Authorization: Bearer <令牌>`。`/mcp` 的 401 带 `WWW-Authenticate: Bearer`(RFC 6750)。
- **限速**:按全局算,不按地址(经反向代理时地址都是 `127.0.0.1`)。一分钟里错 20 次后,这一分钟内不再校验令牌,一律 429;已经登录的会话不受影响。令牌是 256 位随机数,限速只是多一层保险。
- **比较**:令牌和 cookie 都用与内容无关的时间比较。
-- **还没有的**:只读和可操作两种令牌、事件里记下是哪个人(现在 `by` 只到 `viewer` / `viewer <IP>` / `cli`)、页面上的退出登录。
+- **还没有的**:页面上的退出登录。只读令牌和记下是哪个令牌见 7.6。
+
+### 7.6 只读令牌与跨主机开任务(2026-11-13)
+
+7.1 第 5、6 条,以及 2.5「真正的控制口令」在跨主机时的落地。
+
+**有名字的令牌**
+
+- 令牌改存 `<数据目录>/viewer-tokens.json`(0600),每个有名字(字母、数字、`-_.`,最多 40 个字)和权限:`operate` 什么都能做,`view` 只能看。第一次启动时把原来的 `viewer-token` 变成 `owner`(同一个令牌,会话 cookie 也不变),再删掉旧文件。
+- `viewer token` / `--new` 仍然是 `owner`;`viewer token add <名字> [--read-only]`、`list`(不显示令牌本身)、`show <名字> [--new]`、`remove <名字>`(最后一个能操作的令牌不能删)。
+- 控制台每次校验前看文件的修改时间,变了就重读:增删、换令牌马上生效,不用重启;被删或被换掉的令牌,它的会话随之失效。
+- 每个令牌的会话 cookie 值不同(各自的 HMAC),所以知道是谁;页面上的控制记成 `viewer:<名字>`(局域网来的再带 IP)。
+- **只读**:任何 `GET`(`/mcp` 除外)和 `POST /api/video/ack`(报告画面读到哪里)放行,其余一律 403。`/api/info` 带上 `login: {name, role}`,页面据此隐藏输入框、底栏按键和确认按钮,`act()` 也直接拦下。读元素、查系统弹窗会顺带自动解锁手机,算「看」,只读也能用。
+- **Origin**:带会话 cookie 的写请求(浏览器)照旧要 `Origin` 是控制台自己;用 `Authorization: Bearer` 或任务口令的(程序)可以不带 `Origin`,网页没法让浏览器带上这两种请求头。
+
+**跨主机开任务**
+
+- `POST /api/agent/tasks/open`(能操作的令牌,`{title, owner?, apps?}`):控制台替平台在守护进程的 socket 上 `task_open`,把 `{id, token}` 作为第一条 `opened` 事件发回,之后转发任务事件。这个 HTTP 响应就是租约:客户端断开,控制台丢掉 socket 上的租约,任务记为 abandoned。和本机一样不用心跳;每 15 秒一条注释防代理掐断空闲连接。控制台重启时这些任务也会中断。
+- **执行和控制分开**:平台留着登录令牌(控制方:`/api/agent/tasks/<id>/<动作>`),只把任务口令交给 agent(执行方)。`/mcp` 和 `POST /api/agent/tasks/finish` 认进行中任务的口令(请求头 `Iphone-Control-Task-Token`,控制台用新的守护进程请求 `task_check` 核对),别的路径不认。所以远端 agent 能为任务操作手机、结束任务,碰不到暂停、继续、接管、确认。这是 5.6 的进程检查在跨主机时做不到的部分;错的任务口令和错的登录令牌一起计入限速。
+- `task run --url <控制台> [--ca <证书>]`:登录令牌从 `IPHONE_CONTROL_VIEWER_TOKEN` 读,**不传给命令**(启动前从环境里去掉);命令拿到 `IPHONE_CONTROL_TASK_TOKEN`、`IPHONE_CONTROL_TASK_ID`、`IPHONE_CONTROL_URL`、`IPHONE_CONTROL_MCP_URL`(和 `IPHONE_CONTROL_CA`)。命令里的 `task finish` 看到 `IPHONE_CONTROL_URL` 就经控制台结束任务。其余行为(Ctrl-C 停止、命令结束任务结束、在别处停止时停掉命令、`task finish` 后给 5 秒退出)和本机一样。
+- **局限**:stdio 方式的 MCP 客户端在远端还用不了(要有一个 stdio 到 HTTP 的转接,比如以后的 `iphone-control mcp --url`);同一个控制台上的令牌都是全权或只读,还没有「只能开任务」这类更细的权限。
diff --git a/tests/device/mcp_http.py b/tests/device/mcp_http.py
index 8364794..d347a08 100644
--- a/tests/device/mcp_http.py
+++ b/tests/device/mcp_http.py
@@ -11,7 +11,8 @@ from contextlib import AsyncExitStack
import httpx2
from mcp.client.streamable_http import streamable_http_client
-URL = os.environ.get("MCP_URL", "")
+# under `task run --url` the command gets the viewer's MCP address and certificate (its task's token is enough)
+URL = os.environ.get("MCP_URL") or os.environ.get("IPHONE_CONTROL_MCP_URL", "")
TOKEN_HEADER = "Iphone-Control-Task-Token"
@@ -20,7 +21,7 @@ async def streams(stack: AsyncExitStack, token: str | None):
headers = {TOKEN_HEADER: token} if token else {}
if os.environ.get("ICTL_VIEWER_TOKEN"):
headers["Authorization"] = "Bearer " + os.environ["ICTL_VIEWER_TOKEN"]
- ca = os.environ.get("MCP_CA")
+ ca = os.environ.get("MCP_CA") or os.environ.get("IPHONE_CONTROL_CA")
verify = ssl.create_default_context(cafile=ca) if ca else True
# the SDK's default timeouts (create_mcp_http_client), plus the certificate; never through a proxy from the
# environment (the viewer is on this machine or the local network)
diff --git a/tests/device/tasks.py b/tests/device/tasks.py
index b7390af..8b8366a 100644
--- a/tests/device/tasks.py
+++ b/tests/device/tasks.py
@@ -27,6 +27,7 @@ import os
import shlex
import sys
import tempfile
+import traceback
import time
from contextlib import AsyncExitStack
@@ -477,6 +478,151 @@ async def run_cmd(stack):
code == want and dt < max_s and state == ("failed" if want else "completed"))
+async def remote(stack):
+ """docs/task-control.md 7.6: a platform on another machine opens a task over HTTP and keeps the login; its agent
+ has only the task's token, works through /mcp and can't control the task; closing the response abandons it.
+ Then `task run --url`, the same from the command line"""
+ c = "remote"
+ login = os.environ.get("ICTL_VIEWER_TOKEN")
+ if not (VIEWER and login and mcp_http.URL):
+ print(f"SKIP [{c}] needs ICTL_VIEWER, ICTL_VIEWER_TOKEN and MCP_URL (the branch's viewer)", flush=True)
+ return
+ import ssl
+
+ import httpx2
+
+ ca = os.environ.get("MCP_CA")
+ verify = ssl.create_default_context(cafile=ca) if ca else True
+ timeout = httpx2.Timeout(30, read=300)
+ platform = httpx2.AsyncClient(base_url=VIEWER, headers={"Authorization": f"Bearer {login}"}, verify=verify,
+ trust_env=False, timeout=timeout)
+ nobody = httpx2.AsyncClient(base_url=VIEWER, verify=verify, trust_env=False, timeout=timeout)
+ await stack.enter_async_context(platform)
+ await stack.enter_async_context(nobody)
+
+ # the platform opens the task; the response is the lease
+ opening = platform.stream("POST", "/api/agent/tasks/open", json={"title": "真机回归:远端开任务", "owner": OWNER})
+ resp = await opening.__aenter__()
+ closed = False
+
+ async def close_lease():
+ nonlocal closed
+ if not closed:
+ closed = True
+ await opening.__aexit__(None, None, None)
+
+ stack.push_async_callback(close_lease)
+ lines = resp.aiter_lines()
+
+ async def next_event():
+ name, data = None, []
+ async for line in lines:
+ if not line:
+ if name:
+ return name, json.loads("\n".join(data))
+ continue
+ if line.startswith("event:"):
+ name = line[6:].strip()
+ elif line.startswith("data:"):
+ data.append(line[5:].lstrip())
+ return None, None
+
+ name, opened = await asyncio.wait_for(next_event(), 30)
+ check(c, "the platform opens a task over HTTP (server-sent events)", resp.status_code == 200 and name == "opened",
+ f"{resp.status_code} {name}")
+ task_id, token = opened["id"], opened["token"]
+ seen: list[tuple[str, dict]] = []
+
+ async def follow():
+ while True:
+ n, d = await next_event()
+ if n is None:
+ return
+ seen.append((n, d))
+
+ follower = asyncio.create_task(follow())
+ stack.callback(follower.cancel)
+
+ # the agent: the task's token and the address, no login
+ saved = os.environ.pop("ICTL_VIEWER_TOKEN")
+ try:
+ agent = await mcp(stack, token)
+ finally:
+ os.environ["ICTL_VIEWER_TOKEN"] = saved
+ err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
+ check(c, "the agent acts through /mcp with the task's token alone", not err, text)
+ hdr = {"Iphone-Control-Task-Token": token}
+ for action, body in (("resume", {}), ("confirm", {"approve": True}), ("stop", {})):
+ r = await nobody.post(f"/api/agent/tasks/{task_id}/{action}", json=body, headers=hdr)
+ check(c, f"the agent can't {action} its task with that token", r.status_code == 401, f"{r.status_code} {r.text[:80]}")
+ r = await nobody.get("/api/info", headers=hdr)
+ check(c, "nor see the page's API", r.status_code == 401, str(r.status_code))
+
+ # the platform pauses: the agent's next call waits until it resumes
+ r = await platform.post(f"/api/agent/tasks/{task_id}/pause", json={})
+ check(c, "the platform pauses it over HTTP", r.status_code == 200 and await state_is(task_id, "paused"), r.text)
+ t0 = time.time()
+ held = asyncio.create_task(call(agent, "iphone_screenshot"))
+ await asyncio.sleep(3)
+ still = not held.done()
+ await platform.post(f"/api/agent/tasks/{task_id}/resume", json={})
+ err, text, _ = await asyncio.wait_for(held, 60)
+ check(c, f"the agent's call waited while paused ({time.time() - t0:.1f}s)", still and not err, text)
+
+ # a confirmation: only the platform answers it
+ args = {"action": "真机回归:远端确认", "detail": "只是测试,不会在手机上做任何事"}
+ asking = asyncio.create_task(call(agent, "iphone_confirm", args))
+ waiting = await state_is(task_id, "waiting", 30)
+ r = await nobody.post(f"/api/agent/tasks/{task_id}/confirm", json={"approve": True}, headers=hdr)
+ check(c, "the agent waits for a confirmation it can't give itself", waiting and r.status_code == 401, str(r.status_code))
+ r = await platform.post(f"/api/agent/tasks/{task_id}/confirm", json={"approve": True})
+ err, text, _ = await asyncio.wait_for(asking, 30)
+ check(c, "the platform approves it over HTTP", r.status_code == 200 and not err, text)
+ by = [d.get("by") for n, d in seen if n == "control"]
+ check(c, "the log names the login token", bool(by) and all(str(b).startswith("viewer:") for b in by), json.dumps(by))
+
+ # the platform goes away: the task is abandoned and the agent stops
+ await close_lease()
+ check(c, "closing the response abandons the task", await state_is(task_id, "abandoned", 15))
+ # with only the task's token, /mcp itself refuses it (401), which the client reports as an error
+ try:
+ err, text, _ = await call(agent, "iphone_screenshot")
+ except Exception as e: # noqa: BLE001 - any refusal will do
+ err, text = True, f"{type(e).__name__}: {e}"
+ check(c, "after that the agent is refused", err, text)
+
+ # `task run --url`: run.py under it, through the viewer only (no daemon socket here)
+ env = {k: v for k, v in os.environ.items() if k not in (TOKEN_ENV, "MCP_URL", "MCP_CA", "ICTL_VIEWER_TOKEN")}
+ env.update({"IPHONE_CONTROL_VIEWER_TOKEN": login, "ICTL_SOCKET": "/nonexistent/ctl.sock",
+ "SHOTS_DIR": tempfile.mkdtemp(prefix="ictl-shots-")})
+ url = ["--url", VIEWER] + (["--ca", ca] if ca else [])
+ steps = [["iphone_status", {}], ["iphone_press_button", {"button": "home"}], ["iphone_list_elements", {"limit": 3}]]
+ title = f"真机回归:task run --url {int(time.time())}"
+ p = await asyncio.create_subprocess_exec(
+ *BIN, "task", "run", *url, "--title", title, "--owner", OWNER, "--",
+ sys.executable, os.path.join(HERE, "run.py"), json.dumps(steps), env=env,
+ stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
+ )
+ out, _ = await asyncio.wait_for(p.communicate(), 300)
+ out = out.decode(errors="replace")
+ last = [line for line in out.splitlines() if line.startswith("---")]
+ t = next((t for t in reversed(await tasks()) if t["title"] == title), {})
+ check(c, "`task run --url` runs run.py through the viewer (exit 0)", p.returncode == 0, last[-1] if last else out[-300:])
+ check(c, "its task completed with every call as a step",
+ t.get("state") == "completed" and t.get("steps", 0) >= len(steps), json.dumps(t, ensure_ascii=False))
+
+ title = f"真机回归:task run --url finish {int(time.time())}"
+ script = '[ -z "$IPHONE_CONTROL_VIEWER_TOKEN" ] || exit 9; "$@" task finish 远端完成'
+ p = await asyncio.create_subprocess_exec(
+ *BIN, "task", "run", *url, "--title", title, "--owner", OWNER, "--", "sh", "-c", script, "sh", *BIN, env=env,
+ stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
+ )
+ out, _ = await asyncio.wait_for(p.communicate(), 60)
+ t = next((t for t in reversed(await tasks()) if t["title"] == title), {})
+ check(c, "the command doesn't get the login, and `task finish` ends its task remotely",
+ p.returncode == 0 and t.get("state") == "completed", f"exit {p.returncode}, {t.get('state')}: {out.decode(errors='replace')[-200:]}")
+
+
async def scope(stack):
"""#110: a task limited to Settings asks before going elsewhere; approving lets it in, rejecting refuses one step"""
c = "scope"
@@ -559,6 +705,7 @@ SCENARIOS = {
"lease": lease,
"run": run_cmd,
"scope": scope,
+ "remote": remote,
}
@@ -585,6 +732,7 @@ async def main() -> int:
try:
await (restart(stack, a.restart) if name == "restart" else SCENARIOS[name](stack))
except Exception as e: # noqa: BLE001 - a scenario that blew up is a failure, the next one still runs
+ traceback.print_exc()
check(name, f"scenario raised {type(e).__name__}", False, str(e))
finally:
# never leave a task holding the phone
diff --git a/tests/viewer/lan.test.mjs b/tests/viewer/lan.test.mjs
index 3f7b113..17850ab 100644
--- a/tests/viewer/lan.test.mjs
+++ b/tests/viewer/lan.test.mjs
@@ -24,3 +24,14 @@ test('WebCodecs and the clipboard are only used where they may be missing', () =
const clip = code.indexOf('navigator.clipboard.writeText');
assert.match(code.slice(clip - 40, clip), /try \{/, 'a failure falls back to selecting the text');
});
+
+// A read-only token (`viewer token add … --read-only`): the page says so and keeps its own hands off; the viewer
+// refuses the actions anyway
+test('a read-only login hides what it may not do', () => {
+ assert.match(html, /\[data-readonly\] #composer[^{]*#dock[^{]*\{ display: none !important; \}/);
+ const act = code.match(/^async function act\([^]*?^}/m)[0];
+ assert.match(act.split('\n')[1], /S\.readOnly/, 'act stops before sending anything');
+ const start = code.match(/^function startTask\([^]*?^}/m)[0];
+ assert.match(start, /S\.readOnly/);
+ assert.match(code, /S\.readOnly = S\.login\?\.role === 'view'/);
+});
diff --git a/website/en/guide/cli.md b/website/en/guide/cli.md
index 7f25623..da46c10 100644
--- a/website/en/guide/cli.md
+++ b/website/en/guide/cli.md
@@ -131,8 +131,9 @@ See [Auto-unlock](./auto-unlock). `--device` takes a UDID or name, and the devic
| `notify-test [event]` | Send test notifications: one per event type, or one type (`resign`, `session`, `pin`, `pin-recovered`, `unlock`, `offline`, `online`) |
| `wda-bridge [--port <port>]` | Expose WDA on `127.0.0.1` (default port 8100) for other tools. WDA has no authentication and every local user can reach it, so stop it when done |
| `viewer [--port <port>] [--lan] [--lan-host <name>…] [--tls auto\|on\|off] [--tls-cert <PEM> --tls-key <PEM>] [--mcp on\|off]` | Control page in the browser, **behind a login**: every HTTP visit (from this machine too; one forwarded by frp or another reverse proxy looks just like it) needs the token, and `viewer token` shows it with links that log in; a browser stays logged in for 30 days, programs and MCP clients send `Authorization: Bearer <token>`. (and MCP over HTTP at `/mcp` on the same port, see [Connect an AI Client](./mcp-clients#connect-by-url-http); `--mcp off` turns it off) at `http://127.0.0.1:8200/` (default port); with `--lan` also at `https://<this machine's address>:8200/` on the local network (same port; `http://` from the network is sent to `https://`). The certificate is a self-signed one made on this machine (kept in `viewer-tls/` in the data directory and reused), so the first time the browser warns that it isn't trusted: check that the SHA-256 fingerprint matches the one printed at startup or by `service status`, then go on. With a certificate of your own (`--tls-cert`/`--tls-key`: mkcert, `tailscale cert`…) there is no warning. With `--tls off` the network gets plain HTTP and the picture falls back to MJPEG (browsers only offer WebCodecs on localhost or HTTPS), in English or Chinese (follows `IPHONE_CONTROL_LANG`, switchable on the page). **Screen:** the live picture works like a touchscreen: click to tap, drag to swipe, hold to long-press, scroll with the mouse wheel or trackpad, plus a text field and the hardware buttons. On iOS 27 and later the finger follows the pointer as it moves (over CoreDevice HID, which keeps the phone awake until 30 seconds after the last touch); older versions get the whole gesture on release. Everything goes through the daemon like an MCP call, so it queues with the agent and unlocks the phone first. On iOS 27 and later the picture is the phone's own video; otherwise it comes from WDA (none until WDA is ready), as H.264 or MJPEG; see [Picture](#viewer-picture) below. Touch is available when the frame matches the measured size and orientation. After rotating or switching devices, start a new gesture on the updated picture. Settings at the bottom of the sidebar controls the theme and text size. The picture has its own zoom controls, the − and + above it (pinching doesn't zoom, so a drag can't turn into one). **Device panel:** state and readiness checks, installed apps, on-screen elements. The page follows the device the daemon controls: switch on the page or anywhere else, and the picture and panels move over; see [Several Devices](./multi-device#control-page). **AI tasks:** type a task and a local agent carries it out (Claude Code or Codex, whichever is on `PATH`; picked on the page). Before it starts you can limit it to some apps with the App button next to the agent; in any other app each step waits for you. You can pause, take over and hand back, or stop it, and it asks on the page before paying, deleting or sending messages. The token is the key: keep it to yourself |
-| `viewer token [--new]` | Show the viewer's login token (kept in `viewer-token` in the data directory, 0600), links that log in on this machine and the local network, and the command to connect to its HTTP MCP; `--new` replaces it: browsers and MCP clients logged in before need the new one, and a running viewer service is restarted |
-| `task run [--title <title>] [--app <app>…] -- <command>` | AI tasks for other agent platforms: opens a task on the controlled device and runs the command in it. An `iphone-control mcp` the command starts takes part (through `IPHONE_CONTROL_TASK_TOKEN`): the control page shows every step and can pause, take over and stop it, and it waits for you before paying or sending a message. The task ends when the command does; when the task is stopped elsewhere, so is the command; Ctrl-C stops the task. While a task runs, other clients can look but not act on the phone. `--app` (repeatable, name or bundle ID) limits the task to those apps: in any other app, or to open a link that isn't a web page, each step waits for you first |
+| `viewer token [--new]` | Show the viewer's `owner` login token, links that log in on this machine and the local network, and the command to connect to its HTTP MCP; `--new` replaces it: browsers and MCP clients that used the old one need the new one. Tokens are kept in `viewer-tokens.json` in the data directory (0600); changes take effect at once, without restarting the viewer |
+| `viewer token add <name> [--read-only]`, `list`, `show <name> [--new]`, `remove <name>` | Named tokens, one per person or device, say; the page's task log records which token paused, took over or confirmed. A `--read-only` token can watch the picture, the device's state and tasks; every action is refused and the page hides them. `list` doesn't show the tokens themselves; the last token that may operate stays |
+| `task run [--title <title>] [--app <app>…] -- <command>` | AI tasks for other agent platforms: opens a task on the controlled device and runs the command in it. An `iphone-control mcp` the command starts takes part (through `IPHONE_CONTROL_TASK_TOKEN`): the control page shows every step and can pause, take over and stop it, and it waits for you before paying or sending a message. The task ends when the command does; when the task is stopped elsewhere, so is the command; Ctrl-C stops the task. While a task runs, other clients can look but not act on the phone. `--app` (repeatable, name or bundle ID) limits the task to those apps: in any other app, or to open a link that isn't a web page, each step waits for you first. **With the phone on another machine**, add `--url https://<that machine>:8200` (and `--ca cert.pem` for a self-signed certificate) and put the login token in `IPHONE_CONTROL_VIEWER_TOKEN`: the task is opened through that machine's viewer, and the command gets the task's token and `IPHONE_CONTROL_MCP_URL`, for its agent to connect to MCP over HTTP (see [Connect an AI Client](./mcp-clients#connect-by-url-http)). The login token isn't passed to the command, so the agent can't pause or confirm its own task; `task finish` in the command works as usual |
| `task list` / `task events <id>` | Recent tasks (`--json` for programs); follow a task's events, one JSON per line |
| `task pause\|resume\|takeover\|handback\|stop <id>`, `task approve\|reject <id>` | Control a task from the command line, like the buttons on the control page. Only for a person: from inside the task (the agent's environment or a process it started) they are refused, except `stop` |
diff --git a/website/en/guide/configuration.md b/website/en/guide/configuration.md
index 620645f..172bb33 100644
--- a/website/en/guide/configuration.md
+++ b/website/en/guide/configuration.md
@@ -33,6 +33,7 @@ iphone-control service restart
| `IPHONE_CONTROL_VIEWER_TLS` | `auto` | The viewer's HTTPS, like `--tls`: `auto` turns it on when open to the network or given a certificate; `on`, `off`. `http://127.0.0.1` on this machine always works |
| `IPHONE_CONTROL_VIEWER_TLS_CERT`, `IPHONE_CONTROL_VIEWER_TLS_KEY` | empty | The viewer's own certificate and key (PEM), like `--tls-cert`, `--tls-key`; without them a self-signed one made on this machine |
| `IPHONE_CONTROL_VIEWER_MCP` | `on` | MCP over HTTP on the viewer's port (`/mcp`), like `--mcp`; `off` turns it off |
+| `IPHONE_CONTROL_VIEWER_TOKEN` | empty | Only on another machine: the token `task run --url` logs in to that machine's viewer with (shown there by `iphone-control viewer token`). It isn't passed to the command `task run` starts |
| `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 |
| `RESIGN_CHECK_HOURS` | `6` | How often to check; it is also checked within a minute after the phone reconnects or you switch devices |
diff --git a/website/en/guide/mcp-clients.md b/website/en/guide/mcp-clients.md
index ff3f149..f62f6c9 100644
--- a/website/en/guide/mcp-clients.md
+++ b/website/en/guide/mcp-clients.md
@@ -47,7 +47,8 @@ The viewer (`iphone-control viewer`, or the service from `service viewer install
- **Login**: like the page, it needs the token, as `Authorization: Bearer <token>`. `iphone-control viewer token` shows it and the command below.
- **This machine**: `http://127.0.0.1:8200/mcp` (the viewer's port). Claude Code: `claude mcp add --transport http iphone http://127.0.0.1:8200/mcp --header "Authorization: Bearer <token>"`; in a configuration file `{"type": "http", "url": "http://127.0.0.1:8200/mcp", "headers": {"Authorization": "Bearer <token>"}}`.
- **Another computer on the local network**: the viewer needs `--lan` (`IPHONE_CONTROL_VIEWER_LAN=1`); the address is `https://<this machine's address>:8200/mcp`. With the self-signed certificate made there, the client has to trust it: copy `~/.local/share/iphone-control/viewer-tls/cert.pem` from that machine and start Node-based clients (Claude Code and others) with `NODE_EXTRA_CA_CERTS=cert.pem`; or give the viewer a certificate of your own (`--tls-cert`/`--tls-key`). If the client uses a proxy, add the machine's address to `NO_PROXY`.
-- **In a task**: when an agent platform opens a task with `task run`, have the agent's MCP requests carry the header `Iphone-Control-Task-Token: <the value of IPHONE_CONTROL_TASK_TOKEN>`; it does what that variable does on stdio (each step shows on the page, calls wait while paused, `iphone_confirm` is listed).
+- **In a task**: when an agent platform opens a task with `task run`, have the agent's MCP requests carry the header `Iphone-Control-Task-Token: <the value of IPHONE_CONTROL_TASK_TOKEN>`; it does what that variable does on stdio (each step shows on the page, calls wait while paused, `iphone_confirm` is listed). **That header alone, without a login, is enough**: while the task runs, `/mcp` takes its token, and the agent can act on the phone for that task only, with no way to pause or confirm. Across machines that is how it should be: the platform keeps the login, the agent gets the task's token.
+- **A platform on another machine**: `iphone-control task run --url https://<address>:8200 -- <command>` opens the task and holds its lease for you; the command can set up its agent with `$IPHONE_CONTROL_MCP_URL` and `$IPHONE_CONTROL_TASK_TOKEN`. A platform without iphone-control calls the API: `POST /api/agent/tasks/open` (`Authorization: Bearer <login token>`, JSON `{title, owner?, apps?}`) answers with server-sent events, `opened` with `{id, token}` first; the open connection is the lease, and when it closes the task is abandoned. Pause, resume, take over, hand back, stop and confirm are `POST /api/agent/tasks/<id>/<action>` (confirm with `{"approve": true}`), events `GET /api/agent/tasks/<id>/events`, the list `GET /api/agent/tasks`; the agent ends its own task with `POST /api/agent/tasks/finish` (its task's token, `{ok, summary}`).
- **Off**: `viewer --mcp off` (`IPHONE_CONTROL_VIEWER_MCP=off`).
::: warning The token is the key
diff --git a/website/en/guide/security.md b/website/en/guide/security.md
index 2669907..b56ce60 100644
--- a/website/en/guide/security.md
+++ b/website/en/guide/security.md
@@ -12,7 +12,7 @@ This page has the essentials. What is stored, who can reach it and the details o
## Built-in protections
-- **No network ports.** WDA is reached through usbmuxd. `wda-bridge` and the live `viewer` are explicit opt-ins that bind 127.0.0.1 only, and other web pages in your browser can't act through them. `wda-bridge` has no login: every local user can use it, so stop it when done. The `viewer` and the MCP on its port (`/mcp`) need the login token, from this machine too, since the viewer can't tell a local browser from a visit forwarded by frp, cloudflared or another reverse proxy. The token is kept in the data directory (0600); `viewer token` shows it and `viewer token --new` replaces it. `viewer --lan` opens the viewer to the local network, only to local-network addresses and over HTTPS there.
+- **No network ports.** WDA is reached through usbmuxd. `wda-bridge` and the live `viewer` are explicit opt-ins that bind 127.0.0.1 only, and other web pages in your browser can't act through them. `wda-bridge` has no login: every local user can use it, so stop it when done. The `viewer` and the MCP on its port (`/mcp`) need the login token, from this machine too, since the viewer can't tell a local browser from a visit forwarded by frp, cloudflared or another reverse proxy. Tokens are kept in the data directory (0600); `viewer token` shows the owner's and `--new` replaces it, and named read-only tokens (`viewer token add <name> --read-only`) can watch but not act. An agent on another machine gets only its task's token: it acts for that task and can't pause or confirm it. `viewer --lan` opens the viewer to the local network, only to local-network addresses and over HTTPS there.
- **No root.** The daemon runs as your regular user, as a per-user service; the install script refuses to run as root.
- **Auto-unlock is off by default** and disables itself after one wrong attempt.
- **Developer tools are off by default.**
diff --git a/website/guide/cli.md b/website/guide/cli.md
index 54c335a..5ed8ea6 100644
--- a/website/guide/cli.md
+++ b/website/guide/cli.md
@@ -131,8 +131,9 @@ Viewer 只监听本机回环地址。同机其他用户也能查看安装信息
| `notify-test [事件]` | 发测试通知:每类事件各一条,或只发一类(`resign`、`session`、`pin`、`pin-recovered`、`unlock`、`offline`、`online`) |
| `wda-bridge [--port <端口>]` | 把 WDA 桥接到 `127.0.0.1`,端口默认 8100,给别的工具用。WDA 没有认证,本机任何用户都能连上,用完就停 |
| `viewer [--port <端口>] [--lan] [--lan-host <名字>…] [--tls auto\|on\|off] [--tls-cert <PEM> --tls-key <PEM>] [--mcp on\|off]` | 浏览器里的控制台,**要先登录**:所有经 HTTP 的访问(本机也一样,经 frp 等反向代理转发进来的访问看起来就是本机)都要令牌,`viewer token` 显示令牌和点开就能登录的链接;浏览器登录一次后记住 30 天,程序和 MCP 客户端用 `Authorization: Bearer <令牌>`。同一个端口的 `/mcp` 还提供 MCP over HTTP(见[接入 AI 客户端](./mcp-clients#通过-url-接入-http),`--mcp off` 关掉),地址 `http://127.0.0.1:8200/`(默认端口);加 `--lan` 时局域网里也能用 `https://<这台机器的 IP>:8200/` 打开(同一个端口;局域网来的 `http://` 会跳到 `https://`)。证书默认是本机生成的自签证书(存在数据目录的 `viewer-tls/`,一直沿用),浏览器第一次打开会提示不受信任:核对启动时或 `service status` 显示的 SHA-256 指纹一致后继续。用 `--tls-cert`/`--tls-key` 换成自己的证书(mkcert、`tailscale cert` 等)就没有这个提示。`--tls off` 时局域网里是 HTTP,画面退回 MJPEG(浏览器只在 localhost 或 HTTPS 上提供 WebCodecs)。中英文(默认跟着 `IPHONE_CONTROL_LANG`,页面上可切换)。**画面:** 实时画面像触摸屏一样用:点一下是点击,拖动是滑动,按住是长按,滚动鼠标滚轮或触控板也能滚动页面,另有输入框和硬件键。iOS 27 起手指跟着鼠标实时移动(经 CoreDevice HID,最后一次触摸后 30 秒内手机保持亮屏);更低的版本在松开后发整段手势。操作都和 MCP 调用一样经守护进程,和 agent 的操作排队,并先自动解锁。iOS 27 及以上画面直接用手机自己的视频;其余来自 WDA(WDA 没就绪时没有画面),是 H.264 或 MJPEG,见下面的[画面编码](#viewer-picture)。画面与设备实测的尺寸、方向一致时可以点按。转屏或换机后,请在新画面上重新操作。侧栏底部的「设置」可调整主题和字号,画面缩放用画面上方的加减号调整(双指捏合不缩放,免得拖动时误触)。**设备面板:** 状态和就绪检查、已安装的 App、屏幕上的元素。页面跟着守护进程控制的设备走,在页面上或别处切换设备,画面和面板都会跟过去,见[多台设备](./multi-device#control-page)。**AI 任务:** 写下任务,交给本机的 agent 执行(PATH 里有的 Claude Code 或 Codex,在页面上选)。开任务前可以用 Agent 旁边的 App 按钮限定范围,到了别的 App 每一步都先等你确认。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。令牌就是钥匙,别外传 |
-| `viewer token [--new]` | 显示控制台的登录令牌(存在数据目录的 `viewer-token`,0600)、本机和局域网的登录链接,以及接入 HTTP MCP 的命令;`--new` 换一个新令牌,之前登录的浏览器和 MCP 客户端都要用新令牌,控制台服务在运行就随之重启 |
-| `task run [--title <标题>] [--app <App>…] -- <命令>` | 给别的 agent 平台用的 AI 任务:在当前控制的设备上开一个任务,再运行这条命令。命令启动的 `iphone-control mcp` 自动加入任务(经环境变量 `IPHONE_CONTROL_TASK_TOKEN`),控制台上能看到每一步,可以暂停、接管、停止,付款、发消息之前会等你确认。命令结束,任务就结束;任务在别处被停止,命令也会被停止;按 Ctrl-C 等于停止任务。任务进行中,其他客户端只能看,不能操作手机。`--app`(可写多次,App 名或 Bundle ID)把任务限定在这些 App 里:到了别的 App、或者要打开网页以外的链接,每一步都先等你确认 |
+| `viewer token [--new]` | 显示控制台的 `owner` 登录令牌、本机和局域网的登录链接,以及接入 HTTP MCP 的命令;`--new` 换一个新的,用旧令牌登录的浏览器和 MCP 客户端都要用新的。令牌存在数据目录的 `viewer-tokens.json`(0600),改动马上生效,不用重启控制台 |
+| `viewer token add <名字> [--read-only]`、`list`、`show <名字> [--new]`、`remove <名字>` | 有名字的令牌,比如每人一个、每台设备一个;控制台的任务记录里记下是哪个令牌暂停、接管、确认的。`--read-only` 的令牌只能看画面、设备状态和任务,所有操作都被拒绝,页面上也不显示操作入口。`list` 不显示令牌本身;最后一个能操作的令牌不能删 |
+| `task run [--title <标题>] [--app <App>…] -- <命令>` | 给别的 agent 平台用的 AI 任务:在当前控制的设备上开一个任务,再运行这条命令。命令启动的 `iphone-control mcp` 自动加入任务(经环境变量 `IPHONE_CONTROL_TASK_TOKEN`),控制台上能看到每一步,可以暂停、接管、停止,付款、发消息之前会等你确认。命令结束,任务就结束;任务在别处被停止,命令也会被停止;按 Ctrl-C 等于停止任务。任务进行中,其他客户端只能看,不能操作手机。`--app`(可写多次,App 名或 Bundle ID)把任务限定在这些 App 里:到了别的 App、或者要打开网页以外的链接,每一步都先等你确认。**手机接在另一台机器上**时加 `--url https://<那台机器>:8200`(自签证书再加 `--ca cert.pem`),登录令牌放在环境变量 `IPHONE_CONTROL_VIEWER_TOKEN` 里:任务经那台机器的控制台开,命令拿到的是任务口令和 `IPHONE_CONTROL_MCP_URL`,它的 agent 用 HTTP 方式的 MCP 接入(见[接入 AI 客户端](./mcp-clients#通过-url-接入-http))。登录令牌不会传给命令,所以 agent 不能暂停、确认自己的任务;命令里的 `task finish` 照样能用 |
| `task list` / `task events <id>` | 最近的任务(`--json` 给程序读);跟着一个任务的事件,每行一个 JSON |
| `task pause\|resume\|takeover\|handback\|stop <id>`、`task approve\|reject <id>` | 在命令行里控制任务,和控制台上的按钮一样。只能由人来做:在任务里面(Agent 的环境或它启动的进程)执行会被拒绝,`stop` 除外 |
diff --git a/website/guide/configuration.md b/website/guide/configuration.md
index 196408e..01c3c37 100644
--- a/website/guide/configuration.md
+++ b/website/guide/configuration.md
@@ -33,6 +33,7 @@ iphone-control service restart
| `IPHONE_CONTROL_VIEWER_TLS` | `auto` | 控制台的 HTTPS,同 `--tls`:`auto` 在对局域网开放或给了证书时开启,`on`、`off`。本机的 `http://127.0.0.1` 一直能用 |
| `IPHONE_CONTROL_VIEWER_TLS_CERT`、`IPHONE_CONTROL_VIEWER_TLS_KEY` | 空 | 控制台用自己的证书和私钥(PEM),同 `--tls-cert`、`--tls-key`;不设就用本机生成的自签证书 |
| `IPHONE_CONTROL_VIEWER_MCP` | `on` | 控制台同一个端口上的 MCP over HTTP(`/mcp`),同 `--mcp`;`off` 关掉 |
+| `IPHONE_CONTROL_VIEWER_TOKEN` | 空 | 只在另一台机器上用:`task run --url` 登录那台机器的控制台用的令牌(那台机器上 `iphone-control viewer token` 显示的)。不会传给 `task run` 启动的命令 |
| `IPHONE_UDID` | 自动选 | 固定控制哪台设备。不设时自动选:正在控制的那台一直用到它断开;运行中可以用 `select` 命令或 `iphone_select_device` 工具切换。设了就不能切换 |
| `RESIGN_MIN_DAYS` | `2` | 描述文件剩余不到几天时重签 |
| `RESIGN_CHECK_HOURS` | `6` | 每隔几小时检查一次;手机重新连上或切换设备后 1 分钟内也查一次 |
diff --git a/website/guide/mcp-clients.md b/website/guide/mcp-clients.md
index 6c73294..8a8a555 100644
--- a/website/guide/mcp-clients.md
+++ b/website/guide/mcp-clients.md
@@ -47,7 +47,8 @@ MCP 服务经本机的 Unix socket 找守护进程。客户端在另一台电脑
- **登录**:和控制台一样要令牌,请求头 `Authorization: Bearer <令牌>`。`iphone-control viewer token` 显示令牌和下面这条命令。
- **本机**:`http://127.0.0.1:8200/mcp`(端口跟着控制台)。Claude Code:`claude mcp add --transport http iphone http://127.0.0.1:8200/mcp --header "Authorization: Bearer <令牌>"`;配置文件里写 `{"type": "http", "url": "http://127.0.0.1:8200/mcp", "headers": {"Authorization": "Bearer <令牌>"}}`。
- **局域网里另一台电脑**:控制台要开 `--lan`(`IPHONE_CONTROL_VIEWER_LAN=1`),地址是 `https://<这台机器的 IP>:8200/mcp`。证书是本机生成的自签证书时,客户端要信任它:把那台机器上的 `~/.local/share/iphone-control/viewer-tls/cert.pem` 拷过来,Node 写的客户端(Claude Code 等)用 `NODE_EXTRA_CA_CERTS=cert.pem` 启动;也可以用 `--tls-cert`/`--tls-key` 换成自己的证书。客户端配了代理时,把这台机器的 IP 加进 `NO_PROXY`。
-- **在任务里**:agent 平台用 `task run` 开任务时,让 agent 的 MCP 请求带上请求头 `Iphone-Control-Task-Token: <IPHONE_CONTROL_TASK_TOKEN 的值>`,作用和 stdio 方式下的环境变量一样(每一步显示在控制台上,暂停时等待,多出 `iphone_confirm`)。
+- **在任务里**:agent 平台用 `task run` 开任务时,让 agent 的 MCP 请求带上请求头 `Iphone-Control-Task-Token: <IPHONE_CONTROL_TASK_TOKEN 的值>`,作用和 stdio 方式下的环境变量一样(每一步显示在控制台上,暂停时等待,多出 `iphone_confirm`)。**只带这个请求头、不带登录令牌也行**:任务进行中,`/mcp` 认这个任务口令,agent 只能为这个任务操作手机,碰不到暂停、确认这些控制接口。跨机器时就该这样:登录令牌留在平台手里,agent 只拿任务口令。
+- **另一台机器上的平台**:`iphone-control task run --url https://<IP>:8200 -- <命令>` 替你开任务并持有租约,命令里能用 `$IPHONE_CONTROL_MCP_URL` 和 `$IPHONE_CONTROL_TASK_TOKEN` 配置 agent。不装 iphone-control 的平台直接调接口:`POST /api/agent/tasks/open`(`Authorization: Bearer <登录令牌>`,JSON `{title, owner?, apps?}`)返回事件流,第一条 `opened` 带 `{id, token}`,连接保持着就是租约,断开任务就记为 abandoned;暂停、继续、接管、交还、停止、确认是 `POST /api/agent/tasks/<id>/<动作>`(确认带 `{"approve": true}`),事件是 `GET /api/agent/tasks/<id>/events`,任务列表是 `GET /api/agent/tasks`;agent 自己结束任务用 `POST /api/agent/tasks/finish`(带任务口令,`{ok, summary}`)。
- **关掉**:`viewer --mcp off`(`IPHONE_CONTROL_VIEWER_MCP=off`)。
::: warning 令牌就是钥匙
diff --git a/website/guide/security.md b/website/guide/security.md
index 26184c5..780555b 100644
--- a/website/guide/security.md
+++ b/website/guide/security.md
@@ -12,7 +12,7 @@ iphone-control 本质上是一个手机遥控器:能访问它的人,就能
## 默认的保护
-- **不开网络端口。** WDA 经 usbmuxd 直连手机。`wda-bridge` 和实时画面 `viewer` 都要显式开启,只绑 127.0.0.1,浏览器里的其他网页借不了它们操作手机。`wda-bridge` 没有登录,本机任何用户都能用,用完就停。`viewer` 和它同一个端口上的 MCP(`/mcp`)要令牌登录,本机也一样:控制台分不清本机的浏览器和经 frp、cloudflared 等反向代理转发进来的访问。令牌存在数据目录(0600),`viewer token` 显示,`viewer token --new` 换掉。`viewer --lan` 会把控制台开放给局域网,只接受局域网地址来的连接,局域网里走 HTTPS。
+- **不开网络端口。** WDA 经 usbmuxd 直连手机。`wda-bridge` 和实时画面 `viewer` 都要显式开启,只绑 127.0.0.1,浏览器里的其他网页借不了它们操作手机。`wda-bridge` 没有登录,本机任何用户都能用,用完就停。`viewer` 和它同一个端口上的 MCP(`/mcp`)要令牌登录,本机也一样:控制台分不清本机的浏览器和经 frp、cloudflared 等反向代理转发进来的访问。令牌存在数据目录(0600),`viewer token` 显示、`--new` 换掉;可以加有名字的只读令牌(`viewer token add <名字> --read-only`),只能看不能操作。另一台机器上的 agent 只拿任务口令,只能为它的任务操作手机,不能暂停或确认自己的任务。`viewer --lan` 会把控制台开放给局域网,只接受局域网地址来的连接,局域网里走 HTTPS。
- **不用 root。** 守护进程以你的普通用户身份作为用户服务运行,安装脚本拒绝以 root 运行。
- **自动解锁默认关闭**,输错一次即停用。
- **开发者工具默认关闭**。