Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools
Rust ai-agentautomationclaudeclaude-codedockeriosiphonelinuxmcpmcp-servermodel-context-protocolrustwebdriveragent
feat(tasks): an agent can't control its own task (#75)
Qinghe Li9bc696c26666
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex aa9fec7..c60ab81 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ All notable changes to this project are documented here. The format is based on### Added- `iphone-control service viewer install` runs the viewer as a background service of its own that starts at login (`uninstall`, `start`, `stop`, `restart` too). It reads its port and whether it is open to the local network from the settings file (`IPHONE_CONTROL_VIEWER_PORT`, new; `IPHONE_CONTROL_VIEWER_LAN`; `IPHONE_CONTROL_VIEWER_LAN_HOSTS`, new) and keeps the installing shell's `PATH` to find `claude` and `codex`. Updates stop it and start it again; an automatic update waits while an AI task runs.+- An AI task's agent can no longer pause, resume, take over, hand back or confirm its own task, so only a person answers out-of-scope steps and `iphone_confirm`. Control requests carrying the task's token (`IPHONE_CONTROL_TASK_TOKEN`) are refused, and so are those from an agent the control page or `task run` started, or any process it starts, even without the token or through the page's API. On macOS, calls through the page's API can't be traced to a process yet. Stopping a task is always allowed. The task's log records who controlled it (the page, the command line, the task's opener).- Navigate setup menus with arrow keys, confirm with Enter, or cancel with Esc. Number selection remains available, and basic terminals keep the line-by-line prompts.- Generate Bash, Zsh and Fish completion scripts with `iphone-control completions <shell>`, without starting the daemon or accessing a device.- `iphone-control viewer --lan` (or `IPHONE_CONTROL_VIEWER_LAN=1`) also opens the control page to the local network, on the same port. There is no login yet: anyone on the network who can reach the machine can control the phone, so only use it on a trusted network. It only accepts connections from local-network addresses and only answers to this machine's own names; `--lan-host` adds another name. Opened at a network address the picture is MJPEG, since browsers only offer WebCodecs on localhost or HTTPS.diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex e422831..022fdfc 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -9,6 +9,7 @@### 新增- `iphone-control service viewer install` 把控制台装成登录后自动启动的后台服务(还有 `uninstall`、`start`、`stop`、`restart`)。端口和是否对局域网开放读设置文件(新增 `IPHONE_CONTROL_VIEWER_PORT`;`IPHONE_CONTROL_VIEWER_LAN`;新增 `IPHONE_CONTROL_VIEWER_LAN_HOSTS`),并记下安装时终端的 `PATH` 以找到 `claude` 和 `codex`。升级时先停下它、升级完再启动;有 AI 任务在跑时自动升级会推迟。+- AI 任务的 Agent 不能再自己暂停、继续、接管、交还或确认,越界确认和 `iphone_confirm` 只能由人回答。带任务口令(`IPHONE_CONTROL_TASK_TOKEN`)的控制请求会被拒绝;控制台和 `task run` 启动的 Agent,连同它再启动的进程,也会被拒绝,即使去掉了口令,或者调用控制台的接口。在 macOS 上,调用控制台接口的这条路还查不出是哪个进程。停止任务不受限制。任务记录里会写下谁做了控制(控制台、命令行、任务的发起方)。- 设置菜单支持方向键选择、Enter 确认和 Esc 取消,保留数字选择;基础终端继续使用逐行提示。- `iphone-control completions <shell>` 可生成 Bash、Zsh 和 Fish 补全脚本,不启动守护进程、不访问设备。- `iphone-control viewer --lan`(或 `IPHONE_CONTROL_VIEWER_LAN=1`)让控制台也对局域网开放,还是同一个端口。还没有登录:局域网里任何能连上这台机器的人都能操作手机,只在可信的网络里开。只接受局域网地址来的连接,只认本机自己的名字和地址;`--lan-host` 可以再加名字。从局域网地址打开时画面是 MJPEG,因为浏览器只在 localhost 或 HTTPS 上提供 WebCodecs。diff --git a/apps/iphone-control/src/agent.rs b/apps/iphone-control/src/agent.rsindex 30e0e6d..cfa9c99 100644--- a/apps/iphone-control/src/agent.rs+++ b/apps/iphone-control/src/agent.rs@@ -129,13 +129,23 @@ impl Agents {Ok(id)}- /// pause / resume / takeover / handback / stop / confirm from the page- pub async fn control(&self, id: &str, action: &str, body: &Value) -> Result<(), String> {+ /// pause / resume / takeover / handback / stop / confirm from the page. `by`: who, for the task's log;+ /// `from`: the local process that called the page's API, when known (the daemon refuses the task's agent)+ pub async fn control(+ &self,+ id: &str,+ action: &str,+ body: &Value,+ by: String,+ from: Option<u32>,+ ) -> Result<(), String> {let req = Request::TaskControl {id: id.to_owned(),action: action.to_owned(),step: body["step"].as_u64(),approve: body["approve"].as_bool().unwrap_or(false),+ by: Some(by),+ for_pid: from,};match protocol::call(&self.socket, &req, Some(Duration::from_secs(10))).await {Ok(Response::Text { .. }) => Ok(()),@@ -177,6 +187,9 @@ impl Agents {.env("MCP_TOOL_TIMEOUT", "86400000").process_group(0).kill_on_drop(true);+ // the agent and what it starts may not control its task (answer its own confirmations, resume itself);+ // said before it starts, so nothing it does comes first+ self.as_task(token, Request::TaskAgent).await;let mut child = cmd.spawn()?;let pid = child.id();let stdout = child.stdout.take().ok_or_else(|| anyhow::anyhow!("no stdout"))?;diff --git a/apps/iphone-control/src/task.rs b/apps/iphone-control/src/task.rsindex dfffdd2..9b5440e 100644--- a/apps/iphone-control/src/task.rs+++ b/apps/iphone-control/src/task.rs@@ -76,6 +76,8 @@ pub async fn run(socket: &Path, action: TaskAction) -> anyhow::Result<()> {action: action.into(),step,approve,+ by: Some("cli".into()),+ for_pid: None,};let req = match action {TaskAction::Run { title, owner, apps, command } => {@@ -104,7 +106,9 @@ pub async fn run(socket: &Path, action: TaskAction) -> anyhow::Result<()> {TaskAction::Approve { id, step } => control(id, "confirm", step, true),TaskAction::Reject { id, step } => control(id, "confirm", step, false),};- expect_ok(ask(socket, &req).await)+ // inside a task (its agent's shell) the token goes along, and the daemon refuses: only the user controls a task+ let token = std::env::var(protocol::TASK_TOKEN_ENV).ok().filter(|t| !t.is_empty());+ expect_ok(protocol::as_task(token, None, ask(socket, &req)).await)}async fn ask(socket: &Path, req: &Request) -> anyhow::Result<Response> {@@ -154,6 +158,8 @@ async fn run_command(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;let spawned = tokio::process::Command::new(&command[0]).args(&command[1..]).env(protocol::TASK_TOKEN_ENV, &opened.token)@@ -214,7 +220,14 @@ async fn run_command(/// 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 };+ 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 { .. })) {stop_group(pid);}diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rsindex cc24bc0..ecf801a 100644--- a/apps/iphone-control/src/viewer.rs+++ b/apps/iphone-control/src/viewer.rs@@ -27,6 +27,7 @@//! replug (new usbmuxd id) doesn't break the picture.mod lan;+mod peer;use std::collections::{HashMap, HashSet};use std::path::{Path, PathBuf};@@ -325,7 +326,9 @@ async fn handle(mut client: TcpStream, ctx: &Ctx, head: Vec<u8>, req: Head, mutlet Ok(b) = serde_json::from_slice::<Value>(&body) else {return json_reply(&mut client, 400, &json!({"ok": false, "message": "bad request"})).await;};- let (code, v) = post(ctx, &p[5..], &b, req.device.as_deref()).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 (code, v) = post(ctx, &p[5..], &b, req.device.as_deref(), caller).await;json_reply(&mut client, code, &v).await}_ => reply(&mut client, 404, "text/plain", b"not found").await,@@ -405,7 +408,24 @@ async fn updates(ctx: &Ctx) -> Result<Value, String> {/// A POST under `/api/`: status code and JSON answer/// `device`: the one the page shows (`X-Ictl-Device`); actions only go to it-async fn post(ctx: &Ctx, name: &str, b: &Value, device: Option<&str>) -> (u16, Value) {+/// Who called the page's API to control a task+#[derive(Default)]+struct Caller {+ by: String,+ pid: Option<u32>,+}++impl Caller {+ async fn of(client: &TcpStream) -> Self {+ let (Ok(peer), Ok(local)) = (client.peer_addr(), client.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()) };+ Self { by, pid }+ }+}++async fn post(ctx: &Ctx, name: &str, b: &Value, device: Option<&str>, caller: Caller) -> (u16, Value) {let conflict = |m: String| (409, json!({"ok": false, "message": m}));if name == "updates/check" {if !b.as_object().is_some_and(serde_json::Map::is_empty) {@@ -448,7 +468,7 @@ async fn post(ctx: &Ctx, name: &str, b: &Value, device: Option<&str>) -> (u16, Vif let Some(rest) = name.strip_prefix("agent/tasks/")&& let Some((id, action)) = rest.split_once('/'){- return match ctx.agents.control(id, action, b).await {+ return match ctx.agents.control(id, action, b, caller.by, caller.pid).await {Ok(()) => (200, json!({"ok": true})),Err(m) => conflict(m),};@@ -1054,11 +1074,11 @@ mod tests {let ctx = test_ctx(temp.path(), &socket);let body = json!({"text": "Settings", "index": 1});*ctx.udid.lock().unwrap() = "different-device".into();- assert_eq!(post(&ctx, "tap_element", &body, None).await.0, 409);- assert_eq!(post(&ctx, "tap", &json!({"x": 1, "y": 2}), Some("phone")).await.0, 409);+ assert_eq!(post(&ctx, "tap_element", &body, None, Caller::default()).await.0, 409);+ assert_eq!(post(&ctx, "tap", &json!({"x": 1, "y": 2}), Some("phone"), Caller::default()).await.0, 409);let (result, req) = tokio::time::timeout(Duration::from_secs(3), async {tokio::join!(- post(&ctx, "tap_element", &body, Some("phone")),+ post(&ctx, "tap_element", &body, Some("phone"), Caller::default()),reply_to_action(&daemon, Response::text("ok")))})@@ -1082,7 +1102,10 @@ mod tests {let reply = Response::Error { message: "touch failed".into(), retry_as_gesture: daemon_retry };// The result comes directly from the action, with no follow-up status request.let ((_, result), req) = tokio::time::timeout(Duration::from_secs(3), async {- tokio::join!(post(&ctx, "touch", &body, Some("phone")), reply_to_action(&daemon, reply))+ tokio::join!(+ post(&ctx, "touch", &body, Some("phone"), Caller::default()),+ reply_to_action(&daemon, reply)+ )}).await.unwrap();diff --git a/apps/iphone-control/src/viewer/peer.rs b/apps/iphone-control/src/viewer/peer.rsnew file mode 100644index 0000000..ca52f2a--- /dev/null+++ b/apps/iphone-control/src/viewer/peer.rs@@ -0,0 +1,128 @@+//! Which local process is on the other end of a connection to the page. A task's agent could call the page's API+//! (`curl`, a browser it drives) to answer its own confirmations; the daemon refuses that when it knows the process+//! (`ictl_daemon::procs`). Linux only (`/proc`); elsewhere `None`, and only the daemon's own checks apply.++use std::net::SocketAddr;++/// The process holding the client end of a loopback connection from `client` to `server` (our end); `None` for a+/// client on another machine, or when it can't be found+pub fn local_client(client: SocketAddr, server: SocketAddr) -> Option<u32> {+ let client = unmapped(client);+ if !client.ip().is_loopback() {+ return None;+ }+ find(client, unmapped(server))+}++fn unmapped(a: SocketAddr) -> SocketAddr {+ match a {+ SocketAddr::V6(v6) => match v6.ip().to_ipv4_mapped() {+ Some(v4) => SocketAddr::new(v4.into(), v6.port()),+ None => a,+ },+ SocketAddr::V4(_) => a,+ }+}++#[cfg(target_os = "linux")]+fn find(client: SocketAddr, server: SocketAddr) -> Option<u32> {+ let inode = ["/proc/net/tcp", "/proc/net/tcp6"]+ .iter()+ .filter_map(|f| std::fs::read_to_string(f).ok())+ .find_map(|table| socket_inode(&table, client, server))?;+ let want = format!("socket:[{inode}]");+ let me = std::process::id();+ // the processes this user may look into; another user's fds can't be read, and aren't an agent of ours+ for proc in std::fs::read_dir("/proc").ok()?.flatten() {+ let Some(pid) = proc.file_name().to_str().and_then(|n| n.parse::<u32>().ok()) else { continue };+ if pid == me {+ continue;+ }+ let Ok(fds) = std::fs::read_dir(proc.path().join("fd")) else { continue };+ if fds.flatten().any(|fd| std::fs::read_link(fd.path()).is_ok_and(|l| l.as_os_str() == want.as_str())) {+ return Some(pid);+ }+ }+ None+}++#[cfg(not(target_os = "linux"))]+fn find(_client: SocketAddr, _server: SocketAddr) -> Option<u32> {+ None+}++/// In a `/proc/net/tcp{,6}` table, the inode of the socket whose own address is `local` and whose peer is `remote`+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn socket_inode(table: &str, local: SocketAddr, remote: SocketAddr) -> Option<u64> {+ table.lines().skip(1).find_map(|line| {+ let f: Vec<&str> = line.split_whitespace().collect();+ let (l, r, inode) = (f.get(1)?, f.get(2)?, f.get(9)?);+ (parse_addr(l)? == local && parse_addr(r)? == remote).then(|| inode.parse().ok()).flatten()+ })+}++/// `0100007F:1F92` (IPv4) or 32 hex digits (IPv6), each 32-bit word in the kernel's byte order, then the port+fn parse_addr(s: &str) -> Option<SocketAddr> {+ let (addr, port) = s.split_once(':')?;+ let port = u16::from_str_radix(port, 16).ok()?;+ let word = |i: usize| u32::from_str_radix(addr.get(i * 8..i * 8 + 8)?, 16).ok().map(u32::to_ne_bytes);+ let a = match addr.len() {+ 8 => SocketAddr::new(std::net::Ipv4Addr::from(word(0)?).into(), port),+ 32 => {+ let mut b = [0u8; 16];+ for i in 0..4 {+ b[i * 4..i * 4 + 4].copy_from_slice(&word(i)?);+ }+ SocketAddr::new(std::net::Ipv6Addr::from(b).into(), port)+ }+ _ => return None,+ };+ Some(unmapped(a))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ #[cfg(target_endian = "little")]+ fn reads_the_kernel_s_socket_table() {+ let table = " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode+ 0: 0100007F:2012 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 111 1 0 100 0 0 10 0+ 1: 0100007F:D431 0100007F:2012 01 00000000:00000000 00:00000000 00000000 1000 0 222 1 0 20 4 30 10 -1+ 2: 0100007F:2012 0100007F:D431 01 00000000:00000000 00:00000000 00000000 1000 0 333 1 0 20 4 30 10 -1";+ let (client, server): (SocketAddr, SocketAddr) =+ ("127.0.0.1:54321".parse().unwrap(), "127.0.0.1:8210".parse().unwrap());+ assert_eq!(socket_inode(table, client, server), Some(222), "the client's end, not ours");+ assert_eq!(socket_inode(table, server, client), Some(333));+ let v6 = " sl local_address remote_address st+ 0: 0000000000000000FFFF00000100007F:D431 0000000000000000FFFF00000100007F:2012 01 00000000:00000000 00:00000000 00000000 1000 0 444 1";+ assert_eq!(socket_inode(v6, client, server), Some(444), "an IPv4-mapped address is the IPv4 one");+ assert_eq!(parse_addr("00000000000000000000000001000000:0050"), Some("[::1]:80".parse().unwrap()));+ }++ #[test]+ fn a_client_on_another_machine_isn_t_looked_up() {+ assert_eq!(local_client("192.168.1.5:5000".parse().unwrap(), "0.0.0.0:8202".parse().unwrap()), None);+ }++ /// The real thing: a child connects (no process of its own holds the socket: `read` is a builtin)+ #[test]+ #[cfg(target_os = "linux")]+ fn finds_the_process_on_the_other_end() {+ let server = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = server.local_addr().unwrap();+ let script = format!("exec 3<>/dev/tcp/127.0.0.1/{}; read -t 5 -u 3", addr.port());+ let Ok(mut child) = std::process::Command::new("bash").args(["-c", &script]).spawn() else { return };+ let (_conn, peer) = server.accept().unwrap();+ let found = (0..50).find_map(|_| {+ local_client(peer, addr).or_else(|| {+ std::thread::sleep(std::time::Duration::from_millis(20));+ None+ })+ });+ assert_eq!(found, Some(child.id()));+ let _ = child.kill();+ let _ = child.wait();+ }+}diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex c9cc601..802cd93 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -203,6 +203,8 @@ pub struct CallCtx {pub task: Option<String>,/// The task's step it belongs to ([`ictl_protocol::TASK_STEP`])pub task_step: Option<u64>,+ /// The process that sent it (the socket's peer), when the system says+ pub peer: Option<u32>,}/// Logical points measured on this connection. A different id invalidates queued coordinates.@@ -683,7 +685,7 @@ impl Daemon {if let Err(e) = check_request(&req) {return Response::error(e);}- if let Some(r) = self.tasks.handle(&req, ctx.task.as_deref(), &mut ctx.gone).await {+ if let Some(r) = self.tasks.handle(&req, ctx.task.as_deref(), ctx.peer, &mut ctx.gone).await {return r;}// while a task runs, only it acts on the phone (or the user, after taking over): see `crate::tasks`@@ -930,6 +932,7 @@ impl Daemon {| Request::TaskEvents { .. }| Request::TaskList| Request::TaskControl { .. }+ | Request::TaskAgent| Request::TaskStep { .. }| Request::TaskStepDone { .. }| Request::TaskConfirm { .. }@@ -976,6 +979,7 @@ fn lane(req: &Request) -> Lane {| Request::TaskEvents { .. }| Request::TaskList| Request::TaskControl { .. }+ | Request::TaskAgent| Request::TaskStep { .. }| Request::TaskStepDone { .. }| Request::TaskConfirm { .. }diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rsindex 0af62c0..a99e763 100644--- a/crates/ictl-daemon/src/lib.rs+++ b/crates/ictl-daemon/src/lib.rs@@ -16,6 +16,7 @@ pub mod imaging;pub mod machine;pub mod maintenance;pub mod notify;+pub mod procs;mod screen;mod supervise;pub mod tasks;@@ -114,6 +115,8 @@ async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::Resul}async fn serve_conn(daemon: Arc<Daemon>, stream: tokio::net::UnixStream) {+ // the process on the other end: a task's agent may not control its task (`tasks::Tasks::handle`)+ let peer = stream.peer_cred().ok().and_then(|c| c.pid()).and_then(|p| u32::try_from(p).ok());let (r, mut w) = stream.into_split();let mut reader = BufReader::new(r);loop {@@ -126,7 +129,10 @@ async fn serve_conn(daemon: Arc<Daemon>, stream: tokio::net::UnixStream) {let resp = if line.len() as u64 > MAX_REQUEST_LINE {protocol::Response::error(ictl_l10n::tr!("请求太长", "request too long"))} else {- let parsed = parse_request(&line);+ let parsed = parse_request(&line).map(|(r, cancel, mut ctx, lang)| {+ ctx.peer = peer;+ (r, cancel, ctx, lang)+ });// Status snapshots remain available throughout maintenance (including health probes).let needs_device = parsed.as_ref().is_ok_and(|(r, ..)| !matches!(r, protocol::Request::Daemon));let lease = needs_device.then(maintenance::shared).transpose();@@ -147,7 +153,7 @@ async fn serve_conn(daemon: Arc<Daemon>, stream: tokio::net::UnixStream) {Ok(lease),) => {drop(lease);- ictl_l10n::scope(lang, task_stream(&daemon, reader, w, req)).await;+ ictl_l10n::scope(lang, task_stream(&daemon, reader, w, req, peer)).await;return;}(Ok((req, false, ctx, lang)), Ok(_lease)) => {@@ -205,7 +211,7 @@ fn parse_request(line: &[u8]) -> serde_json::Result<(protocol::Request, bool, coOk((serde_json::from_value(v)?,cancel,- core::CallCtx { gone: None, expect_udid: udid, expect_view: view, task, task_step },+ core::CallCtx { gone: None, expect_udid: udid, expect_view: view, task, task_step, peer: None },lang.unwrap_or(ictl_l10n::Lang::Zh),))}@@ -217,6 +223,7 @@ async fn task_stream(mut reader: BufReader<tokio::net::unix::OwnedReadHalf>,mut w: tokio::net::unix::OwnedWriteHalf,req: protocol::Request,+ peer: Option<u32>,) {async fn send<T: serde::Serialize>(w: &mut tokio::net::unix::OwnedWriteHalf, v: &T) -> bool {let mut line = serde_json::to_string(v).unwrap_or_default();@@ -226,7 +233,7 @@ async fn task_stream(let found = match req {protocol::Request::TaskOpen { title, owner, apps } => match daemon.resolve_scope(&apps).await {Err(m) => Err(m),- Ok(apps) => daemon.tasks.open(&title, &owner, daemon.controlled_udid().as_deref(), apps).map(|t| {+ Ok(apps) => daemon.tasks.open(&title, &owner, daemon.controlled_udid().as_deref(), apps, peer).map(|t| {daemon.log.log(&ictl_l10n::log_trf!("开始任务 {}({owner}):{title}","Task {} started ({owner}): {title}",diff --git a/crates/ictl-daemon/src/procs.rs b/crates/ictl-daemon/src/procs.rsnew file mode 100644index 0000000..99c1ac3--- /dev/null+++ b/crates/ictl-daemon/src/procs.rs@@ -0,0 +1,76 @@+//! Which process is on the other end, and whether it was started by an agent: a task's agent may not answer the+//! questions it asks the user, nor resume itself (docs/task-control.md §2.5).+//!+//! Not a security boundary: the agent runs as the same user, and a process it double-forks into a daemon is+//! adopted by init (or a subreaper) and no longer descends from it. It does stop an agent that runs+//! `iphone-control task approve`, or calls the page's API, from its own shell.++/// The process that started `pid`; `None` when it is gone or can't be read+pub fn parent(pid: u32) -> Option<u32> {+ parent_of(pid).filter(|&p| p != pid)+}++#[cfg(target_os = "linux")]+fn parent_of(pid: u32) -> Option<u32> {+ let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;+ // `pid (name) state ppid …`; the name may hold spaces and parentheses+ stat[stat.rfind(')')? + 1..].split_whitespace().nth(1)?.parse().ok()+}++#[cfg(target_os = "macos")]+fn parent_of(pid: u32) -> Option<u32> {+ let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };+ let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;+ // SAFETY: `info` is a plain C struct of exactly `size` bytes, which proc_pidinfo fills+ let n = unsafe { libc::proc_pidinfo(pid as libc::c_int, libc::PROC_PIDTBSDINFO, 0, (&raw mut info).cast(), size) };+ (n == size).then_some(info.pbi_ppid)+}++#[cfg(not(any(target_os = "linux", target_os = "macos")))]+fn parent_of(_pid: u32) -> Option<u32> {+ None+}++/// Whether `pid` is `ancestor` or was started by it, directly or further down+pub fn descends_from(pid: u32, ancestor: u32) -> bool {+ if ancestor <= 1 {+ return false;+ }+ let mut cur = pid;+ // a chain of processes is short; the bound only guards against a loop read while pids are reused+ for _ in 0..128 {+ if cur == ancestor {+ return true;+ }+ match parent(cur) {+ Some(p) if p > 1 => cur = p,+ _ => return false,+ }+ }+ false+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ #[cfg(any(target_os = "linux", target_os = "macos"))]+ fn a_child_descends_from_its_parent_and_not_the_other_way() {+ let me = std::process::id();+ let mut child = std::process::Command::new("sleep").arg("5").spawn().unwrap();+ let kid = child.id();+ assert_eq!(parent(kid), Some(me));+ assert!(descends_from(kid, me));+ assert!(descends_from(me, me), "a process counts as its own");+ assert!(!descends_from(me, kid));+ let _ = child.kill();+ let _ = child.wait();+ }++ #[test]+ fn init_or_nothing_is_nobody_s_ancestor() {+ assert!(!descends_from(std::process::id(), 1));+ assert!(!descends_from(std::process::id(), 0));+ }+}diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rsindex b4edb3d..6350dce 100644--- a/crates/ictl-daemon/src/tasks.rs+++ b/crates/ictl-daemon/src/tasks.rs@@ -13,6 +13,10 @@//! over; lifting a finger is always allowed, switching the device never is;//! - a token of a task that ended, or that the daemon doesn't know, is refused for everything: the agent stops.//!+//! Controlling a task (pause, resume, take over, hand back, answer a confirmation) is the user's+//! ([`Tasks::handle`]): refused with a task's token, and from the processes the opener starts as its agent+//! ([`crate::procs`]). Stopping is always allowed: an agent may give up. Who controlled it goes into the log.+//!//! Steps: a tool call announces itself ([`Tasks::step`]); the requests it makes carry the step number. An action//! with the token but no step (a client that doesn't announce) becomes a step of its own, so nothing the task does//! is missing from it. Every event goes to `tasks/<id>.jsonl` too; tasks that hadn't ended when the daemon stopped@@ -102,6 +106,8 @@ struct TaskState {scope: Vec<String>,/// Steps whose action the user kept out of the task's scope: shown as rejected, not as faileddeclined: Vec<u64>,+ /// The processes the opener starts are the agent ([`Request::TaskAgent`]): they may not control the task+ agent_below_opener: bool,}pub struct Task {@@ -111,6 +117,8 @@ pub struct Task {owner: String,udid: String,started: u64,+ /// The process that opened it (holds the lease); only it may name the agent+ opener: Option<u32>,file: Option<PathBuf>,st: Mutex<TaskState>,tx: broadcast::Sender<TaskEvent>,@@ -228,6 +236,7 @@ pub fn scope_check(req: &Request) -> Option<Check> {| Request::TaskEvents { .. }| Request::TaskList| Request::TaskControl { .. }+ | Request::TaskAgent| Request::TaskStep { .. }| Request::TaskStepDone { .. }| Request::TaskConfirm { .. }@@ -629,11 +638,16 @@ impl Task {self.end(end, if summary.is_empty() { fallback } else { summary });}- fn control(&self, action: &str, step: Option<u64>, approve: bool) -> Result<(), String> {+ /// `by`: who asked, for the log (a `control` event after the change)+ fn control(&self, action: &str, step: Option<u64>, approve: bool, by: Option<&str>) -> Result<(), String> {let mut st = self.lock();if !st.status.active() {return Err(ictl_l10n::tr!("任务已经结束", "The task has ended").into());}+ let mut what = json!({"action": action});+ if let Some(by) = by.map(|b| b.trim().chars().take(80).collect::<String>()).filter(|b| !b.is_empty()) {+ what["by"] = json!(by);+ }match (action, st.status) {("pause", Status::Running) => self.set_status(&mut st, Status::Paused),("resume", Status::Paused) => self.set_status(&mut st, Status::Running),@@ -644,6 +658,8 @@ impl Task {}("confirm", Status::Waiting) => match st.confirm.take() {Some((waiting, tx)) if step.is_none_or(|s| s == waiting) => {+ what["step"] = json!(waiting);+ what["approve"] = json!(approve);let _ = tx.send(approve);}other => {@@ -657,6 +673,7 @@ impl Task {},("stop", _) => {let n = st.next_step - 1;+ self.emit(&mut st, "control", what);drop(st);self.end(End::Cancelled,@@ -669,6 +686,7 @@ impl Task {}(a, s) => return Err(ictl_l10n::trf!("现在({})不能{a}", "Can't {a} now ({})", s.name())),}+ self.emit(&mut st, "control", what);Ok(())}}@@ -719,7 +737,15 @@ impl Tasks {/// Opens a task on `udid` (the controlled device). `Err` is a message/// `apps`: bundle IDs it may act in, empty for no limit (see [`Task::check_scope`])- pub fn open(&self, title: &str, owner: &str, udid: Option<&str>, apps: Vec<String>) -> Result<Arc<Task>, String> {+ /// `opener`: the process opening it, which may then name its agent ([`Request::TaskAgent`])+ pub fn open(+ &self,+ title: &str,+ owner: &str,+ udid: Option<&str>,+ apps: Vec<String>,+ opener: Option<u32>,+ ) -> Result<Arc<Task>, String> {let title = title.trim();if title.is_empty() {return Err(ictl_l10n::tr!("任务要有标题", "A task needs a title").into());@@ -748,6 +774,7 @@ impl Tasks {title: title.chars().take(4000).collect(),owner: owner.trim().chars().take(80).collect(),udid: udid.to_owned(),+ opener,// after every task before it, even within the same millisecond: logs are ordered by it on the next startstarted: now_ms().max(list.iter().map(|t| t.started + 1).max().unwrap_or(0)),st: Mutex::new(TaskState {@@ -763,6 +790,7 @@ impl Tasks {ended: None,scope: apps,declined: Vec::new(),+ agent_below_opener: false,}),tx: broadcast::channel(4096).0,changed: Notify::new(),@@ -875,21 +903,42 @@ impl Tasks {}/// The task requests that aren't about the device; `None` for any other request+ /// `peer`: the process that sent itpub async fn handle(&self,req: &Request,token: Option<&str>,+ peer: Option<u32>,gone: &mut Option<oneshot::Receiver<()>>,) -> Option<Response> {Some(match req {Request::TaskList => Response::text(serde_json::to_string(&self.infos()).unwrap_or_default()),- Request::TaskControl { id, action, step, approve } => match self.get(id) {- Some(t) => match t.control(action, *step, *approve) {- Ok(()) => Response::text("ok"),- Err(m) => Response::error(m),- },+ Request::TaskControl { id, action, step, approve, by, for_pid } => match self.get(id) {+ Some(t) => {+ if action != "stop" && from_agent(&t, token, [peer, *for_pid]) {+ return Some(refuse(ictl_l10n::tr!(+ "AI 任务不能自己暂停、继续、接管、交还或确认:这些要由人在控制台或命令行(另开一个终端)里操作。要放弃任务,可以停止它",+ "An AI task can't pause, resume, take over, hand back or confirm itself: the user does that on the control page or from the command line (in a terminal of their own). To give up, stop the task"+ )));+ }+ match t.control(action, *step, *approve, by.as_deref()) {+ Ok(()) => Response::text("ok"),+ Err(m) => Response::error(m),+ }+ }None => Response::error(ictl_l10n::tr!("没有这个任务", "No such task")),},+ Request::TaskAgent => match self.actor(token) {+ Ok(t) if peer.is_some() && peer == t.opener => {+ t.lock().agent_below_opener = true;+ Response::text("ok")+ }+ Ok(_) => refuse(ictl_l10n::tr!(+ "只有开任务的进程能说明 Agent 是谁",+ "Only the process that opened the task can say which processes are its agent"+ )),+ Err(r) => r,+ },Request::TaskStep { tool, args } => match self.actor(token) {Ok(t) => t.step(tool, args, gone).await,Err(r) => r,@@ -940,6 +989,17 @@ impl Tasks {}}+/// A control request that comes from inside the task: it carries a task's token, or one of `pids` (the+/// connection's process, the one the request was passed on for) was started by the opener after it said its children+/// are the agent ([`Request::TaskAgent`]). The opener itself is the user's side (the page, `task run`)+fn from_agent(task: &Task, token: Option<&str>, pids: [Option<u32>; 2]) -> bool {+ if token.is_some() {+ return true;+ }+ let Some(opener) = task.opener.filter(|_| task.lock().agent_below_opener) else { return false };+ pids.into_iter().flatten().any(|p| p != opener && crate::procs::descends_from(p, opener))+}+fn append(file: &Path, e: &TaskEvent) {use std::io::Write;let line = json!({"t": now_ms(), "event": e.event, "data": e.data});@@ -985,6 +1045,7 @@ fn restore(file: &Path) -> Option<Task> {owner: s("owner"),udid: s("udid"),started: first["started"].as_u64().unwrap_or(0),+ opener: None,file: Some(file.to_owned()),st: Mutex::new(TaskState {status: Status::Running,@@ -998,6 +1059,7 @@ fn restore(file: &Path) -> Option<Task> {rejected: false,ended: None,declined: Vec::new(),+ agent_below_opener: false,scope: first["apps"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect())@@ -1081,7 +1143,7 @@ mod tests {}fn open(ts: &Tasks) -> Arc<Task> {- ts.open("看看设置", "test", Some(PHONE), Vec::new()).unwrap()+ ts.open("看看设置", "test", Some(PHONE), Vec::new(), None).unwrap()}fn tap() -> Request {@@ -1111,12 +1173,12 @@ mod tests {#[tokio::test]async fn only_one_task_and_only_on_a_device() {let ts = tasks();- assert!(ts.open("x", "", None, Vec::new()).is_err());- assert!(ts.open(" ", "", Some(PHONE), Vec::new()).is_err());+ assert!(ts.open("x", "", None, Vec::new(), None).is_err());+ assert!(ts.open(" ", "", Some(PHONE), Vec::new(), None).is_err());let t = open(&ts);- assert!(ts.open("another", "", Some(PHONE), Vec::new()).err().unwrap().contains(&t.id));+ assert!(ts.open("another", "", Some(PHONE), Vec::new(), None).err().unwrap().contains(&t.id));t.end(End::Completed, "");- assert!(ts.open("another", "", Some(PHONE), Vec::new()).is_ok());+ assert!(ts.open("another", "", Some(PHONE), Vec::new(), None).is_ok());}/// The point of D17: while a task runs, a caller without its token can look but not act@@ -1133,7 +1195,7 @@ mod tests {let select = Request::SelectDevice { device: "auto".into() };assert!(admit(&ts, &select, None).await.is_err());- t.control("takeover", None, false).unwrap();+ t.control("takeover", None, false, None).unwrap();assert!(matches!(admit(&ts, &tap(), None).await, Ok((Admission::Supervisor(_), _))));assert!(admit(&ts, &select, None).await.is_err(), "not even while taken over");}@@ -1154,12 +1216,12 @@ mod tests {async fn a_paused_task_holds_its_requests_until_resumed() {let ts = Arc::new(tasks());let t = open(&ts);- t.control("pause", None, false).unwrap();+ t.control("pause", None, false, None).unwrap();let (ts2, token) = (ts.clone(), t.token.clone());let held = tokio::spawn(async move { admit(&ts2, &tap(), Some(&token)).await.map(|(_, w)| w) });tokio::time::sleep(Duration::from_millis(50)).await;assert!(!held.is_finished());- t.control("resume", None, false).unwrap();+ t.control("resume", None, false, None).unwrap();assert!(matches!(held.await.unwrap(), Ok(true)), "let through, and it says it waited");}@@ -1167,7 +1229,7 @@ mod tests {async fn a_held_request_whose_caller_left_is_dropped() {let ts = tasks();let t = open(&ts);- t.control("pause", None, false).unwrap();+ t.control("pause", None, false, None).unwrap();let (tx, rx) = oneshot::channel();tx.send(()).unwrap();let r = ts.admit(&tap(), Some(&t.token), &mut None, &mut Some(rx)).await;@@ -1178,9 +1240,9 @@ mod tests {async fn after_someone_else_acted_the_agent_looks_before_acting() {let ts = tasks();let t = open(&ts);- t.control("takeover", None, false).unwrap();+ t.control("takeover", None, false, None).unwrap();assert!(admit(&ts, &tap(), None).await.is_ok());- t.control("handback", None, false).unwrap();+ t.control("handback", None, false, None).unwrap();assert!(message(admit(&ts, &tap(), Some(&t.token)).await).contains("重新看"));assert!(admit(&ts, &tap(), Some(&t.token)).await.is_err(), "until it has looked, not just once");assert!(admit(&ts, &Request::Status, Some(&t.token)).await.is_ok(), "status isn't acting");@@ -1189,20 +1251,70 @@ mod tests {assert!(admit(&ts, &tap(), Some(&t.token)).await.is_ok());}+ /// The agent may not answer its own questions or resume itself; it may give up+ #[tokio::test]+ async fn the_agent_cant_control_its_own_task() {+ let ts = tasks();+ let me = std::process::id();+ // this test process stands in for the agent: its parent opened the task+ let opener = crate::procs::parent(me).expect("the test has a parent");+ let t = ts.open("看看设置", "test", Some(PHONE), Vec::new(), Some(opener)).unwrap();+ let control = |action: &str, for_pid: Option<u32>| Request::TaskControl {+ id: t.id.clone(),+ action: action.into(),+ step: None,+ approve: false,+ by: Some("cli".into()),+ for_pid,+ };+ let refused = |r: Option<Response>| matches!(r, Some(Response::Error { .. }));+ let pause = |token: Option<&'static str>, peer: Option<u32>, for_pid: Option<u32>| {+ let (ts, req) = (&ts, control("pause", for_pid));+ let token = token.map(|_| t.token.clone());+ async move { ts.handle(&req, token.as_deref(), peer, &mut None).await }+ };+ let agent = |from: Option<u32>| {+ let (ts, token) = (&ts, t.token.clone());+ async move { ts.handle(&Request::TaskAgent, Some(&token), from, &mut None).await }+ };++ // with the task's token (the CLI in the agent's environment sends it)+ assert!(refused(pause(Some("token"), None, None).await));+ // before the opener says its children are the agent, they are anyone+ assert!(!refused(pause(None, Some(me), None).await));+ assert!(!refused(ts.handle(&control("resume", None), None, Some(me), &mut None).await));+ // only the opener says so+ assert!(refused(agent(Some(me)).await));+ assert!(refused(agent(None).await));+ assert!(!refused(agent(Some(opener)).await));+ assert!(refused(pause(None, Some(me), None).await), "the opener's child");+ assert!(refused(pause(None, None, Some(me)).await), "passed on for it");+ assert_eq!(t.info().state, "running");+ // the opener itself (the page passing on the user's click), or someone else (the user's own terminal)+ assert!(!refused(pause(None, Some(opener), None).await));+ assert!(!refused(ts.handle(&control("resume", None), None, Some(1), &mut None).await));+ let by: Vec<_> = t.subscribe().0.into_iter().filter(|e| e.event == "control").map(|e| e.data).collect();+ assert_eq!(by.len(), 4);+ assert_eq!((by[0]["action"].as_str(), by[0]["by"].as_str()), (Some("pause"), Some("cli")));+ // giving up is allowed from anywhere+ assert!(!refused(ts.handle(&control("stop", None), Some(&t.token), Some(me), &mut None).await));+ assert_eq!(t.info().state, "cancelled");+ }+#[tokio::test]async fn an_ended_or_unknown_token_is_refused_for_everything() {let ts = Arc::new(tasks());let t = open(&ts);- t.control("pause", None, false).unwrap();+ t.control("pause", None, false, None).unwrap();let (ts2, token) = (ts.clone(), t.token.clone());let held = tokio::spawn(async move { admit(&ts2, &Request::Status, Some(&token)).await.map(|_| ()) });tokio::time::sleep(Duration::from_millis(20)).await;- t.control("stop", None, false).unwrap();+ t.control("stop", None, false, None).unwrap();assert!(held.await.unwrap().is_err(), "a held request is released with a refusal");assert!(message(admit(&ts, &Request::Status, Some(&t.token)).await).contains("结束"));assert!(message(admit(&ts, &Request::Status, Some("nobody")).await).contains("结束"));assert!(- ts.handle(&Request::TaskNote { text: "x".into() }, Some(&t.token), &mut None)+ ts.handle(&Request::TaskNote { text: "x".into() }, Some(&t.token), None, &mut None).await.is_some_and(|r| matches!(r, Response::Error { .. })));@@ -1216,12 +1328,12 @@ mod tests {let (ts2, token) = (ts.clone(), t.token.clone());let waiting = tokio::spawn(async move {let req = Request::TaskConfirm { action: "发送消息".into(), detail: "给妈妈".into() };- ts2.handle(&req, Some(&token), &mut None).await.unwrap()+ ts2.handle(&req, Some(&token), None, &mut None).await.unwrap()});tokio::time::sleep(Duration::from_millis(20)).await;assert_eq!(t.info().state, "waiting");- assert!(t.control("confirm", Some(99), false).is_err(), "another step");- t.control("confirm", Some(1), false).unwrap();+ assert!(t.control("confirm", Some(99), false, None).is_err(), "another step");+ t.control("confirm", Some(1), false, None).unwrap();assert!(matches!(waiting.await.unwrap(), Response::Error { message, .. } if message.contains("拒绝")));assert_eq!(t.info().state, "running");t.finish(true, "done");@@ -1234,11 +1346,11 @@ mod tests {let t = open(&ts);let req = |tool: &str, args: Value| Request::TaskStep { tool: tool.into(), args };t.thought("先点「通用」");- let r = ts.handle(&req("iphone_tap_element", json!({"text": "通用"})), Some(&t.token), &mut None).await;+ let r = ts.handle(&req("iphone_tap_element", json!({"text": "通用"})), Some(&t.token), None, &mut None).await;assert_eq!(r, Some(Response::text("1")));t.step_done(1, true, 120, "已点击「通用」 @(200,300) 100x40", None);// a thought arriving just after its step started joins it- let r = ts.handle(&req("iphone_tap", json!({"x": 5, "y": 6})), Some(&t.token), &mut None).await;+ let r = ts.handle(&req("iphone_tap", json!({"x": 5, "y": 6})), Some(&t.token), None, &mut None).await;assert_eq!(r, Some(Response::text("2")));t.thought("点一下");let n = ts.auto_step(&t, &Request::Swipe { from: (1.0, 2.0), to: (3.0, 4.0), seconds: 0.3 });@@ -1359,14 +1471,14 @@ mod tests {while t.info().state != "waiting" {tokio::time::sleep(Duration::from_millis(5)).await;}- t.control("confirm", None, approve).unwrap();+ t.control("confirm", None, approve, None).unwrap();});}#[tokio::test]async fn an_approved_app_joins_the_scope_for_the_rest_of_the_task() {let ts = tasks();- let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"])).unwrap();+ let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"]), None).unwrap();assert!(t.scoped());let wechat = Target::Foreground("com.tencent.xin".into());answer_soon(&t, true).await;@@ -1379,7 +1491,7 @@ mod tests {#[tokio::test]async fn a_rejected_app_refuses_that_step_but_the_task_can_go_back() {let ts = tasks();- let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"])).unwrap();+ let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"]), None).unwrap();answer_soon(&t, false).await;// the tool call that tried it (step 7) shows as rejected, not failed; another failing call stays an errorlet r = t.check_scope(&Target::Launch("com.apple.MobileSMS".into()), Some(7), &mut None).await;@@ -1403,7 +1515,7 @@ mod tests {#[tokio::test]async fn a_question_nobody_waits_for_leaves_the_page() {let ts = tasks();- let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"])).unwrap();+ let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"]), None).unwrap();let (tx, rx) = oneshot::channel();let t2 = t.clone();let asking = tokio::spawn(async move {@@ -1415,7 +1527,7 @@ mod tests {tx.send(()).unwrap();assert!(matches!(asking.await.unwrap(), Err(Response::Error { message, .. }) if message.contains("取消")));assert_eq!(t.info().state, "running");- assert!(t.control("confirm", None, true).is_err(), "nothing waits for an answer any more");+ assert!(t.control("confirm", None, true, None).is_err(), "nothing waits for an answer any more");}#[test]@@ -1423,7 +1535,7 @@ mod tests {let dir = std::env::temp_dir().join(format!("ictl-tasks-scope-{}", std::process::id()));let _ = std::fs::remove_dir_all(&dir);let ts = Tasks::load(Some(dir.clone()));- let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"])).unwrap();+ let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"]), None).unwrap();t.end(End::Completed, "");let ts = Tasks::load(Some(dir.clone()));assert_eq!(ts.get(&t.id).unwrap().info().apps, scope(&["com.apple.Preferences"]));diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rsindex 9b438a7..82d2b1b 100644--- a/crates/ictl-mcp/src/lib.rs+++ b/crates/ictl-mcp/src/lib.rs@@ -853,6 +853,7 @@ pub fn wants_alert_check(req: &Request) -> bool {| Request::TaskEvents { .. }| Request::TaskList| Request::TaskControl { .. }+ | Request::TaskAgent| Request::TaskStep { .. }| Request::TaskStepDone { .. }| Request::TaskConfirm { .. }diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rsindex 5734921..9daa19b 100644--- a/crates/ictl-protocol/src/lib.rs+++ b/crates/ictl-protocol/src/lib.rs@@ -203,7 +203,9 @@ pub enum Request {},/// Recent tasks, newest last, as a JSON array of [`TaskInfo`]TaskList,- /// `pause` / `resume` / `takeover` / `handback` / `stop` / `confirm` (with `approve` and the waiting `step`)+ /// `pause` / `resume` / `takeover` / `handback` / `stop` / `confirm` (with `approve` and the waiting `step`).+ /// The user's: refused with a task's token, or from the task's agent ([`Request::TaskAgent`]), for everything but+ /// `stop`TaskControl {id: String,action: String,@@ -211,7 +213,18 @@ pub enum Request {step: Option<u64>,#[serde(default)]approve: bool,+ /// Who asks, for the task's log: `viewer`, `cli`, `owner`…+ #[serde(default, skip_serializing_if = "Option::is_none")]+ by: Option<String>,+ /// The process the request comes from when it is passed on (the page's API: the local client that called+ /// it); checked like the connection's own process+ #[serde(default, skip_serializing_if = "Option::is_none")]+ for_pid: Option<u32>,},+ /// From the process that opened the task, with its token, before it starts the agent: every process it starts+ /// from now on (and the ones those start) is the task's agent, whose control requests are refused+ /// ([`Request::TaskControl`])+ TaskAgent,/// 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 {@@ -365,6 +378,7 @@ impl Request {| Self::TaskEvents { .. }| Self::TaskList| Self::TaskControl { .. }+ | Self::TaskAgent| Self::TaskStep { .. }| Self::TaskStepDone { .. }| Self::TaskConfirm { .. }diff --git a/docs/task-control.md b/docs/task-control.mdindex 86f525c..6d18bae 100644--- a/docs/task-control.md+++ b/docs/task-control.md@@ -131,7 +131,7 @@ Running → Waiting(等确认)→ Running| 一 | 任务和租约放进守护进程:控制面请求、准入检查、状态机、落盘、设备绑定、观察版本(简化版)、子步骤;内建 runner 和 MCP 改走守护进程;`iphone-control task` 命令给外部平台用 | 已完成(2026-11-12) || 二 | 控制台接上正在进行的任务(刷新后、在别处开的);命令行查看事件 | 已完成(2026-11-12) || 三 | 任务范围(App 白名单)和越界确认 | 已完成(2026-11-13,见 5.5) |-| 三 | 执行口令与控制口令分开 | 等需要时 |+| 三 | 执行方不能控制自己的任务(2.5 的落地版,见 5.6) | 已完成(2026-11-13) || 四 | 带认证的 HTTP 控制面、HTTP MCP;局域网访问控制台(第 7 节);`SO_PEERCRED`;多设备租约 | 等需要时 |## 5. 阶段一的具体设计@@ -190,11 +190,26 @@ Running → Waiting(等确认)→ Running- 查前台只短暂拿设备锁,等人回答时不持锁(人可以先接管);调用方中途断开,问题从页面上撤掉。- 局限:检查的是动作之前的前台。在范围内的 App 里点一下跳进了别的 App,这一下本身不会被拦,进去之后的下一步才会。+### 5.6 执行方不能控制自己的任务(2.5 的落地版)++**问题**:`task_control` 原先只看任务 ID。Agent 用自己的 Bash 跑一句 `iphone-control task approve <id>`,就能批准自己的越界确认,或者在用户暂停后自己继续,任务范围和 `iphone_confirm` 都形同虚设。++**为什么不发控制口令**:命令行和控制台要能控制任务,就得能拿到控制口令,比如放在 0600 的文件里;Agent 和用户是同一个系统用户,同样读得到。在同一个 uid 下,口令分不开执行方和控制方。++**做法**:暂停、继续、接管、交还、确认这几种控制只能由人来做;停止不限,Agent 可以放弃。下面两种请求会被拒绝:++1. **带任务口令的控制请求**:`iphone-control task …` 会自动带上环境里的 `IPHONE_CONTROL_TASK_TOKEN`,所以 Agent 在自己的环境里执行就会被拒绝。+2. **Agent 进程发来的控制请求**:开任务的进程(控制台、`task run`)在启动 Agent 之前发 `task_agent`(带口令;守护进程用 `SO_PEERCRED` 核对它就是开任务的进程),说明「我之后启动的进程都是 Agent」。之后,控制请求如果来自它的子孙进程(`SO_PEERCRED` 取 pid,再沿父进程链往上找),就拒绝;开任务的进程自己发的不拒绝(控制台转发页面上的点击,`task run` 收到 Ctrl-C 后停止任务)。控制台的接口也一样:本机来的请求,控制台在 Linux 上通过 `/proc/net/tcp` 和 `/proc/*/fd` 查出是哪个进程连过来的,作为 `for_pid` 一起交给守护进程判断。在 macOS 上查不出,这条路只能靠第 1 条。++成功的控制会记一条 `control` 事件 `{action, by, step?, approve?}`,`by` 是 `viewer`(局域网来的带上 IP)、`cli` 或 `owner`。++**局限**:这不是安全边界。Agent 如果故意把进程挂到别处,比如两次 fork 后被 init 或 systemd 收养,或者用 `systemd-run` 启动,就不再是开任务进程的子孙。这里拦住的是最常见的情况:Agent 用自己的 Shell 去批准。要真正分开,需要 Agent 换一个 uid 运行或放进沙箱(2.5)。+## 6. 阶段一、二之后还差什么和第 2 节的目标架构相比:-- **口令只有一种**(2.5):开任务的一方拿到的口令同时交给 Agent,控制请求(暂停、确认)不验口令。在同一个用户下这本来就不是边界(D13、D17),等 Agent 跑进沙箱时再分开,届时加上 `SO_PEERCRED`。+- **口令只有一种**(2.5):开任务的一方拿到的口令同时交给 Agent,没有单独的控制口令;改为按口令和进程拒绝执行方的控制请求(5.6)。等 Agent 跑进沙箱、换了 uid,或者有了跨主机的控制面时,再发真正的控制口令。- **任务范围已有,策略还没有**(2.6):限定 App 后越界会停下来问人(5.5);但范围内的敏感动作(在微信里发消息)仍然靠 Agent 调 `iphone_confirm`。控制台上开任务时也能设范围(Agent 旁边的 App 按钮,2026-11-13)。- **观察版本是简化版**(2.7):只有一个「需要重新看」的标记,在交还、或别人在接管期间动过手机后置上,Agent 截图、读元素或等文字之后清掉。动作不带「基于哪次观察」,所以 Agent 自己连续操作时不做这项检查。- **事件不带编号**(2.10):重连时从头重放,没有从断点继续。任务事件全是文字,从头重放代价不大。diff --git a/tests/device/tasks.py b/tests/device/tasks.pyindex b15e118..212866c 100644--- a/tests/device/tasks.py+++ b/tests/device/tasks.py@@ -1,4 +1,4 @@-"""Real-device scenarios for AI tasks kept by the daemon (docs/task-control.md; regression cases #65–67, #106–110).+"""Real-device scenarios for AI tasks kept by the daemon (docs/task-control.md; regression cases #65–67, #106–110, and an agent controlling itself).pip install -r tests/device/requirements.txtpython tests/device/tasks.py # every scenario except `restart`@@ -15,7 +15,9 @@ Harmless by design: it presses Home, opens Settings and Clock, takes screenshotsto open (one of them a scheme no app handles). Nothing is sent, bought, deleted or changed.Environment: ICTL_BIN (default `iphone-control`; your branch's build for a pull request), MCP_CMD (default-`$ICTL_BIN mcp`), ICTL_SOCKET (default `$XDG_RUNTIME_DIR/iphone-control/ctl.sock`).+`$ICTL_BIN mcp`), ICTL_SOCKET (default `$XDG_RUNTIME_DIR/iphone-control/ctl.sock`), ICTL_VIEWER (the control page of+the same build, such as `http://127.0.0.1:8202`; the `self` scenario then also tries the page's API from inside a+task)."""import argparse@@ -39,6 +41,20 @@ SOCKET = os.environ.get("ICTL_SOCKET") or os.path.join(TOKEN_ENV = "IPHONE_CONTROL_TASK_TOKEN"OWNER = "device-test"HERE = os.path.dirname(os.path.abspath(__file__))+VIEWER = os.environ.get("ICTL_VIEWER", "").rstrip("/")++# Run under `task run`: asks the control page to pause the task it runs in, prints the answer+PAGE_PAUSE = """+import json, os, sys, urllib.error, urllib.request+v, task = sys.argv[1], os.environ["IPHONE_CONTROL_TASK_ID"]+req = urllib.request.Request(f"{v}/api/agent/tasks/{task}/pause", data=b"{}", method="POST",+ headers={"Content-Type": "application/json", "Origin": v})+try:+ r = urllib.request.urlopen(req, timeout=15)+ print(r.status, r.read().decode())+except urllib.error.HTTPError as e:+ print(e.code, e.read().decode())+"""results: list[bool] = []@@ -67,6 +83,21 @@ async def ask(req: dict, timeout: float = 15) -> dict:w.close()+async def events(task_id: str, timeout: float = 10) -> list[dict]:+ """A task's events so far (it has ended, so the stream closes)"""+ r, w = await asyncio.open_unix_connection(SOCKET)+ try:+ w.write((json.dumps({"op": "task_events", "id": task_id}) + "\n").encode())+ await w.drain()+ await asyncio.wait_for(r.readline(), timeout)+ out = []+ while line := await asyncio.wait_for(r.readline(), timeout):+ out.append(json.loads(line))+ return out+ finally:+ w.close()++async def tasks() -> list[dict]:r = await ask({"op": "task_list"})if r.get("kind") != "text":@@ -166,10 +197,14 @@ async def call(s: ClientSession, name: str, args: dict | None = None, timeout: freturn bool(res.is_error), text, time.time() - t-async def cli(*args: str, timeout: float = 30):- """`iphone-control task …`: (exit code, output)"""+async def cli(*args: str, timeout: float = 30, token: str | None = None):+ """`iphone-control task …`: (exit code, output). `token`: run it inside that task (the agent's environment)"""+ env = dict(os.environ)+ env.pop(TOKEN_ENV, None)+ if token:+ env[TOKEN_ENV] = tokenp = await asyncio.create_subprocess_exec(- *BIN, "task", *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT+ *BIN, "task", *args, env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)out, _ = await asyncio.wait_for(p.communicate(), timeout)return p.returncode, out.decode(errors="replace").strip()@@ -291,6 +326,56 @@ async def confirm(stack):check(c, "the task ends as rejected though the agent said ok", await state_is(lease.id, "rejected"))+async def self_control(stack):+ """An agent can't answer its own confirmation or pause itself: not with the task's token, nor from a process+ `task run` started without it; the user can, and the log says who"""+ c = "self"+ lease = await Lease.open("真机回归:Agent 不能自己确认")+ stack.callback(lease.close)+ agent = await mcp(stack, lease.token)+ args = {"action": "真机回归:Agent 自己确认", "detail": "只是测试,不会在手机上做任何事"}+ asking = asyncio.create_task(call(agent, "iphone_confirm", args))+ shown = await confirm_asked(lease, 0)+ check(c, "the task waits for a confirmation", bool(shown), json.dumps(shown, ensure_ascii=False))+ code, out = await cli("approve", lease.id, token=lease.token)+ check(c, "`task approve` with the task's token is refused", code != 0, out)+ check(c, "and the task still waits", (await info(lease.id)).get("state") == "waiting")+ code, out = await cli("reject", lease.id)+ err, text, _ = await asyncio.wait_for(asking, 30)+ check(c, "the user's `task reject` answers it", code == 0 and err, text)+ by = [d.get("by") for d in lease.of("control")]+ check(c, "the log says it was the command line", by == ["cli"], json.dumps(by))+ await lease.finish(ok=False)++ # under `task run`, the command drops the token and tries anyway: it was started by the task, so no+ title = f"真机回归:task run 里自己暂停 {int(time.time())}"+ script = 'env -u IPHONE_CONTROL_TASK_TOKEN "$@" task pause "$IPHONE_CONTROL_TASK_ID"'+ p = await asyncio.create_subprocess_exec(+ *BIN, "task", "run", "--title", title, "--owner", OWNER, "--", "sh", "-c", script, "sh", *BIN,+ stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,+ )+ out, _ = await asyncio.wait_for(p.communicate(), 60)+ out = out.decode(errors="replace")+ t = next((t for t in reversed(await tasks()) if t["title"] == title), {})+ check(c, "a process `task run` started can't pause its task, even without the token",+ p.returncode != 0 and t.get("state") == "failed", f"exit {p.returncode}, {t.get('state')}: {out}")++ if not VIEWER:+ print(f"SKIP [{c}] the page's API from inside a task: set ICTL_VIEWER", flush=True)+ return+ title = f"真机回归:task run 里调控制台暂停 {int(time.time())}"+ p = await asyncio.create_subprocess_exec(+ *BIN, "task", "run", "--title", title, "--owner", OWNER, "--", sys.executable, "-c", PAGE_PAUSE, VIEWER,+ stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,+ )+ out, _ = await asyncio.wait_for(p.communicate(), 60)+ out = out.decode(errors="replace")+ t = next((t for t in reversed(await tasks()) if t["title"] == title), {})+ paused = any(e["event"] == "control" for e in await events(t["id"])) if t else True+ check(c, "nor through the control page's API (Linux)", '"ok":false' in out.replace(" ", "") and not paused,+ f"{t.get('state')}: {out}")++async def stop(stack):"""#65: once stopped, the task's token is refused for everything"""c = "stop"@@ -444,6 +529,7 @@ SCENARIOS = {"pause": pause,"handback": handback,"confirm": confirm,+ "self": self_control,"stop": stop,"lease": lease,"run": run_cmd,diff --git a/website/en/guide/cli.md b/website/en/guide/cli.mdindex 1d36de9..b8772ae 100644--- a/website/en/guide/cli.md+++ b/website/en/guide/cli.md@@ -133,7 +133,7 @@ See [Auto-unlock](./auto-unlock). `--device` takes a UDID or name, and the devic| `viewer [--port <port>] [--lan] [--lan-host <name>…]` | Control page in the browser at `http://127.0.0.1:8200/` (default port); with `--lan` also at `http://<this machine's address>:8200/` on the local network (no login yet, so anyone on the network can control the phone; the picture is MJPEG there, since 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. Every local user can reach the port, so stop it when done || `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 || `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 |+| `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` |The `debug` subcommand for diagnostics isn't compiled by default; see the [contributing guide](https://github.com/Derrors/iphone-control/blob/main/CONTRIBUTING.md#testing-on-a-real-phone).diff --git a/website/guide/cli.md b/website/guide/cli.mdindex e878b34..fce9bf0 100644--- a/website/guide/cli.md+++ b/website/guide/cli.md@@ -133,7 +133,7 @@ Viewer 只监听本机回环地址。同机其他用户也能查看安装信息| `viewer [--port <端口>] [--lan] [--lan-host <名字>…]` | 浏览器里的控制台,地址 `http://127.0.0.1:8200/`(默认端口);加 `--lan` 时局域网里也能用 `http://<这台机器的 IP>:8200/` 打开(还没有登录,局域网里任何人都能操作手机;画面是 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 每一步都先等你确认。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。本机任何用户都能连上这个端口,用完就停 || `task run [--title <标题>] [--app <App>…] -- <命令>` | 给别的 agent 平台用的 AI 任务:在当前控制的设备上开一个任务,再运行这条命令。命令启动的 `iphone-control mcp` 自动加入任务(经环境变量 `IPHONE_CONTROL_TASK_TOKEN`),控制台上能看到每一步,可以暂停、接管、停止,付款、发消息之前会等你确认。命令结束,任务就结束;任务在别处被停止,命令也会被停止;按 Ctrl-C 等于停止任务。任务进行中,其他客户端只能看,不能操作手机。`--app`(可写多次,App 名或 Bundle ID)把任务限定在这些 App 里:到了别的 App、或者要打开网页以外的链接,每一步都先等你确认 || `task list` / `task events <id>` | 最近的任务(`--json` 给程序读);跟着一个任务的事件,每行一个 JSON |-| `task pause\|resume\|takeover\|handback\|stop <id>`、`task approve\|reject <id>` | 在命令行里控制任务,和控制台上的按钮一样 |+| `task pause\|resume\|takeover\|handback\|stop <id>`、`task approve\|reject <id>` | 在命令行里控制任务,和控制台上的按钮一样。只能由人来做:在任务里面(Agent 的环境或它启动的进程)执行会被拒绝,`stop` 除外 |调试用的 `debug` 子命令默认不编译,见[贡献指南](https://github.com/Derrors/iphone-control/blob/main/CONTRIBUTING.md#testing-on-a-real-phone)。