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(tasks): keep AI tasks and their leases in the daemon (#64)

Qinghe Lia2c5a4ee6863
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 04c4e73..a9dbdca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,9 +6,19 @@ All notable changes to this project are documented here. The format is based on
## [Unreleased]
+### Added
+
+- AI tasks for any agent platform: `iphone-control task run -- <command>` runs a command in a task, and an `iphone-control mcp` it starts takes part (the control page shows its steps and can pause, take over, stop and confirm). `task list`, `task events`, `task pause`/`resume`/`takeover`/`handback`/`stop` and `task approve`/`reject` follow and steer tasks from the command line.
+- The control page picks up a task in progress: after a reload, and for tasks started elsewhere.
+
### Changed
- On the control page the picture zooms only with the − and + buttons above it: pinching on a trackpad or touch screen, or Ctrl/⌘ + scroll, no longer zooms it (a drag easily turned into a zoom).
+- AI tasks are kept by the daemon instead of the control page. While a task runs, other clients (another MCP server, the command line) can look, but their actions and device switches are refused until the user takes over; the task stays on the device it started on. Tasks are logged in the data directory (`tasks/`, the last 50); one that was running when the daemon stopped shows as interrupted.
+
+### Removed
+
+- The `ICTL_AGENT_GATE` / `ICTL_AGENT_TOKEN` variables of the MCP server: a task's MCP server gets `IPHONE_CONTROL_TASK_TOKEN` instead.
### Fixed
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 621ab2c..545cb4c 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -6,9 +6,19 @@
## [Unreleased]
+### 新增
+
+- 任何 agent 平台都能用 AI 任务:`iphone-control task run -- <命令>` 在任务里运行命令,它启动的 `iphone-control mcp` 自动加入任务(控制台能看到每一步,可以暂停、接管、停止、确认)。`task list`、`task events`、`task pause`/`resume`/`takeover`/`handback`/`stop`、`task approve`/`reject` 在命令行里查看和控制任务。
+- 控制台会接上正在进行的任务:页面刷新后,以及在别处开的任务。
+
### 变更
- 控制台的画面只能用上方的加减号缩放:触控板或触屏上双指捏合、按住 Ctrl/⌘ 滚动滚轮都不再缩放画面(拖动时很容易误触成缩放)。
+- AI 任务改由守护进程管理,不再由控制台管理。任务进行中,其他客户端(另一个 MCP 服务、命令行)可以看,但操作和切换设备都会被拒绝,用户接管后才放行;任务只操作开始时的那台设备。任务记录在数据目录(`tasks/`,最近 50 个);守护进程停止时还在进行的任务显示为已中断。
+
+### 移除
+
+- MCP 服务的 `ICTL_AGENT_GATE` / `ICTL_AGENT_TOKEN` 环境变量:任务里的 MCP 服务改用 `IPHONE_CONTROL_TASK_TOKEN`。
### 修复
diff --git a/apps/iphone-control/src/agent.rs b/apps/iphone-control/src/agent.rs
index 457f26a..8226a2d 100644
--- a/apps/iphone-control/src/agent.rs
+++ b/apps/iphone-control/src/agent.rs
@@ -1,36 +1,25 @@
-//! AI tasks for the web viewer: a prompt typed on the page goes to a local agent (Claude Code or Codex), which works
+//! AI tasks from the web viewer: a prompt typed on the page goes to a local agent (Claude Code or Codex), which works
//! the phone through `iphone-control mcp`, and the page follows every step.
//!
-//! - The agent runs as a child process (`claude -p … --output-format stream-json` or `codex exec --json …`) in its
-//! own process group, with only this program's MCP server and none of its built-in tools that touch the machine.
-//! - Its MCP server gets the task gate ([`ictl_mcp::gate`]): before each tool call it asks the viewer over a Unix
-//! socket next to the daemon's ([`GateServer`]), after the call it reports the result. That is where steps come
-//! from, where a pause or the user taking over holds the agent, and where [`ictl_mcp::gate::CONFIRM_TOOL`] waits
-//! for the user's answer. The agent's own output only adds what it says it is doing (attached to the next step)
-//! and its final summary.
-//! - The page gets the task as server-sent events: `step`, `confirm`, `state`, `done`. Every event is kept, so a
-//! page that (re)connects gets the whole task replayed.
-//!
-//! One task at a time: there is one phone. While a task runs and the user hasn't taken over, the viewer refuses the
-//! page's manual actions ([`Agents::manual_allowed`]), so the user and the agent don't tap at the same time.
+//! The task itself lives in the daemon (docs/task-control.md, D17): this opens it ([`protocol::open_task`]), keeps
+//! its lease while the agent runs, and runs the agent with the task's token, so the agent's MCP server takes part in
+//! the task. The daemon holds the agent while the user pauses or takes over, refuses anyone else's actions meanwhile,
+//! records the steps and waits for confirmations; the page follows the task's events and controls it through here.
+//! What this adds is the agent: its process (in its own process group, with only this program's MCP server and none
+//! of its built-in tools that touch the machine), what it says it is doing (sent as notes, shown with the next step)
+//! and its summary when it exits. When the task ends some other way (stopped on the page or with
+//! `iphone-control task stop`), the agent is stopped too.
use std::path::{Path, PathBuf};
-use std::sync::{Arc, Mutex};
-use std::time::{Duration, Instant};
+use std::sync::Arc;
+use std::time::Duration;
+use ictl_daemon::protocol::{self, Request, Response};
use serde_json::{Map, Value, json};
-use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
-use tokio::sync::{Notify, broadcast, oneshot};
+use tokio::io::{AsyncBufReadExt, BufReader};
/// Longest prompt accepted (the page limits the text box to the same)
pub const MAX_PROMPT: usize = 4000;
-/// Finished tasks kept for replay; each can hold dozens of screenshots
-const KEEP_FINISHED: usize = 4;
-/// A thought printed by the agent this soon after a step started belongs to that step (it reached the viewer
-/// through the agent's stdout, slightly after the tool call reached the gate)
-const LATE_THOUGHT: Duration = Duration::from_secs(2);
-/// Tools that look without acting: allowed right after the user hands control back
-const LOOKING: [&str; 3] = ["iphone_screenshot", "iphone_list_elements", "iphone_status"];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Backend {
@@ -78,180 +67,22 @@ pub fn backends() -> Value {
)
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum Status {
- Running,
- Paused,
- Takeover,
- Waiting,
- Done,
-}
-
-impl Status {
- fn name(self) -> &'static str {
- match self {
- Self::Running => "running",
- Self::Paused => "paused",
- Self::Takeover => "takeover",
- Self::Waiting => "waiting",
- Self::Done => "done",
- }
- }
-}
-
-/// One event for the page: SSE event name and its JSON data
-#[derive(Debug, Clone)]
-pub struct Event {
- pub name: &'static str,
- pub data: Value,
-}
-
-struct TaskState {
- status: Status,
- log: Vec<Event>,
- next_step: u64,
- /// What the agent said it is about to do, for the next step
- thought: Option<String>,
- /// The latest step: id, when it started, still running, has a thought
- last: Option<(u64, Instant, bool, bool)>,
- /// Steps by id whose tool taps by text: where it tapped comes with the result
- taps_by_text: Vec<u64>,
- /// The user handed control back: the agent looks at the screen again before acting
- recheck: bool,
- confirm: Option<(u64, oneshot::Sender<bool>)>,
- /// The agent's last words, the summary when it ends without a result line
- last_text: Option<String>,
- summary: Option<String>,
- failure: Option<String>,
- pid: Option<u32>,
- stopped: bool,
- /// The user turned down a step: the task ends as stopped, not as done
- rejected: bool,
-}
-
-pub struct Task {
- pub id: String,
- token: String,
- /// The page's language when the task started: its messages and the agent's tools use it
- lang: ictl_l10n::Lang,
- st: Mutex<TaskState>,
- tx: broadcast::Sender<Event>,
- /// Wakes calls held at the gate when the status changes
- changed: Notify,
-}
-
-impl Task {
- fn lock(&self) -> std::sync::MutexGuard<'_, TaskState> {
- self.st.lock().unwrap_or_else(|p| p.into_inner())
- }
-
- fn emit(&self, st: &mut TaskState, name: &'static str, data: Value) {
- let e = Event { name, data };
- st.log.push(e.clone());
- let _ = self.tx.send(e);
- }
-
- fn set_status(&self, st: &mut TaskState, s: Status) {
- if st.status != s && st.status != Status::Done {
- st.status = s;
- if s != Status::Done {
- self.emit(st, "state", json!({"state": s.name()}));
- }
- self.changed.notify_waiters();
- }
- }
-
- /// The whole task so far, and the events after it (taken together, so nothing falls between)
- pub fn subscribe(&self) -> (Vec<Event>, broadcast::Receiver<Event>, bool) {
- let st = self.lock();
- (st.log.clone(), self.tx.subscribe(), st.status == Status::Done)
- }
-
- fn thought(&self, text: &str) {
- let text = text.trim();
- if text.is_empty() {
- return;
- }
- let mut st = self.lock();
- st.last_text = Some(text.to_owned());
- match st.last {
- // arrived just after its step reached the gate
- Some((id, at, true, false)) if at.elapsed() < LATE_THOUGHT => {
- st.last = Some((id, at, true, true));
- self.emit(&mut st, "step", json!({"id": id, "thought": text}));
- }
- _ => st.thought = Some(text.to_owned()),
- }
- }
-
- fn finish(&self, ok: bool, stopped: bool, summary: String) {
- let mut st = self.lock();
- if st.status == Status::Done {
- return;
- }
- st.status = Status::Done;
- if let Some((_, tx)) = st.confirm.take() {
- let _ = tx.send(false);
- }
- self.emit(&mut st, "done", json!({"ok": ok, "stopped": stopped, "summary": summary}));
- self.changed.notify_waiters();
- }
-
- fn is_done(&self) -> bool {
- self.lock().status == Status::Done
- }
-}
-
-#[derive(Default)]
-struct Registry {
- tasks: Vec<Arc<Task>>,
-}
-
pub struct Agents {
- reg: Mutex<Registry>,
/// This program, for the agent's MCP server
exe: PathBuf,
socket: PathBuf,
- gate: PathBuf,
workdir: PathBuf,
}
impl Agents {
- pub fn new(socket: &Path, gate: PathBuf) -> anyhow::Result<Arc<Self>> {
+ pub fn new(socket: &Path) -> anyhow::Result<Arc<Self>> {
let workdir = std::env::temp_dir().join(format!("iphone-control-agent-{}", unsafe { libc::getuid() }));
std::fs::create_dir_all(&workdir)?;
- Ok(Arc::new(Self {
- reg: Mutex::default(),
- exe: std::env::current_exe()?,
- socket: socket.to_path_buf(),
- gate,
- workdir,
- }))
- }
-
- fn reg(&self) -> std::sync::MutexGuard<'_, Registry> {
- self.reg.lock().unwrap_or_else(|p| p.into_inner())
- }
-
- pub fn task(&self, id: &str) -> Option<Arc<Task>> {
- self.reg().tasks.iter().find(|t| t.id == id).cloned()
- }
-
- fn active(&self) -> Option<Arc<Task>> {
- self.reg().tasks.iter().find(|t| !t.is_done()).cloned()
- }
-
- /// The page may act on the phone itself: no task, or the user has taken over
- pub fn manual_allowed(&self) -> bool {
- self.active().is_none_or(|t| t.lock().status == Status::Takeover)
+ Ok(Arc::new(Self { exe: std::env::current_exe()?, socket: socket.to_path_buf(), workdir }))
}
- pub fn busy(&self) -> bool {
- self.active().is_some()
- }
-
- /// Starts a task; `Err` is a message for the page
- pub fn start(self: &Arc<Self>, prompt: &str, backend: &str) -> Result<String, String> {
+ /// Opens a task in the daemon and starts the agent on it; `Err` is a message for the page
+ pub async fn start(self: &Arc<Self>, prompt: &str, backend: &str) -> Result<String, String> {
let prompt = prompt.trim();
if prompt.is_empty() {
return Err(ictl_l10n::tr!("先写下要 AI 做的事", "Write what the AI should do first").into());
@@ -273,118 +104,63 @@ impl Agents {
backend.id()
));
};
- let task = {
- let mut reg = self.reg();
- if reg.tasks.iter().any(|t| !t.is_done()) {
- return Err(ictl_l10n::tr!(
- "已经有一个任务在执行,等它结束或先停止它",
- "A task is already running; wait for it to end or stop it first"
- )
- .into());
- }
- // all finished by now: keep the newest few for pages that reconnect
- while reg.tasks.len() >= KEEP_FINISHED {
- reg.tasks.remove(0);
- }
- let task = Arc::new(Task {
- id: uuid::Uuid::new_v4().simple().to_string()[..12].to_owned(),
- token: uuid::Uuid::new_v4().simple().to_string(),
- lang: ictl_l10n::lang(),
- st: Mutex::new(TaskState {
- status: Status::Running,
- log: Vec::new(),
- next_step: 1,
- thought: None,
- last: None,
- taps_by_text: Vec::new(),
- recheck: false,
- confirm: None,
- last_text: None,
- summary: None,
- failure: None,
- pid: None,
- stopped: false,
- rejected: false,
- }),
- tx: broadcast::channel(1024).0,
- changed: Notify::new(),
- });
- reg.tasks.push(task.clone());
- task
- };
+ let (opened, lease) = protocol::open_task(&self.socket, prompt, backend.id()).await?;
+ let id = opened.id.clone();
let me = self.clone();
- let (t, prompt) = (task.clone(), prompt.to_owned());
- let lang = task.lang;
+ let prompt = prompt.to_owned();
+ let lang = ictl_l10n::lang();
tokio::spawn(ictl_l10n::scope(lang, async move {
- if let Err(e) = me.run(&t, backend, &program, &prompt).await {
- t.finish(
- false,
- false,
- ictl_l10n::trf!("{} 没能启动或中途出错:{e}", "{} didn't start or failed: {e}", backend.name()),
- );
+ let mut lease = lease;
+ if let Err(e) = me.run(&opened.token, &mut lease, backend, &program, &prompt).await {
+ let summary =
+ ictl_l10n::trf!("{} 没能启动或中途出错:{e}", "{} didn't start or failed: {e}", backend.name());
+ me.finish(&opened.token, false, summary).await;
}
+ // only now: letting go of the lease first would end the task as abandoned instead
+ drop(lease);
}));
- Ok(task.id.clone())
+ Ok(id)
}
/// pause / resume / takeover / handback / stop / confirm from the page
- pub fn control(&self, id: &str, action: &str, body: &Value) -> Result<(), String> {
- let Some(task) = self.task(id) else { return Err(ictl_l10n::tr!("没有这个任务", "No such task").into()) };
- let mut st = task.lock();
- if st.status == Status::Done {
- return Err(ictl_l10n::tr!("任务已经结束", "The task has ended").into());
+ pub async fn control(&self, id: &str, action: &str, body: &Value) -> 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),
+ };
+ match protocol::call(&self.socket, &req, Some(Duration::from_secs(10))).await {
+ Ok(Response::Text { .. }) => Ok(()),
+ Ok(Response::Error { message, .. }) => Err(message),
+ Ok(Response::Image { caption, .. }) => Err(caption),
+ Err(e) => Err(e.to_string()),
}
- match (action, st.status) {
- ("pause", Status::Running) => task.set_status(&mut st, Status::Paused),
- ("resume", Status::Paused) => task.set_status(&mut st, Status::Running),
- ("takeover", Status::Running | Status::Paused) => task.set_status(&mut st, Status::Takeover),
- ("handback", Status::Takeover) => {
- st.recheck = true;
- task.set_status(&mut st, Status::Running);
- }
- ("confirm", Status::Waiting) => {
- let approve = body["approve"].as_bool().unwrap_or(false);
- let want = body["step"].as_u64();
- match st.confirm.take() {
- Some((step, tx)) if want.is_none_or(|w| w == step) => {
- let _ = tx.send(approve);
- }
- other => {
- st.confirm = other;
- return Err(ictl_l10n::tr!(
- "这一步已经不在等确认了",
- "That step is no longer waiting for confirmation"
- )
- .into());
- }
- }
- }
- ("stop", _) => {
- st.stopped = true;
- let pid = st.pid;
- let n = st.next_step - 1;
- drop(st);
- if let Some(pid) = pid {
- kill_group(pid);
- }
- task.finish(
- false,
- true,
- ictl_l10n::trf!(
- "在第 {n} 步停下了。已经做完的操作不会撤销。",
- "Stopped at step {n}. What was already done isn't undone."
- ),
- );
- return Ok(());
- }
- (a, s) => return Err(ictl_l10n::trf!("现在({})不能{a}", "Can't {a} now ({})", s.name())),
+ }
+
+ /// A request on behalf of the task (its token): a note or the end
+ async fn as_task(&self, token: &str, req: Request) {
+ let call = protocol::call(&self.socket, &req, Some(Duration::from_secs(10)));
+ if let Err(e) = protocol::as_task(Some(token.to_owned()), None, call).await {
+ tracing::warn!("task: {e}");
}
- Ok(())
}
- async fn run(&self, task: &Arc<Task>, backend: Backend, program: &Path, prompt: &str) -> anyhow::Result<()> {
+ async fn finish(&self, token: &str, ok: bool, summary: String) {
+ self.as_task(token, Request::TaskFinish { ok, summary }).await;
+ }
+
+ /// Runs the agent until it exits, holding the task's lease
+ async fn run(
+ &self,
+ token: &str,
+ lease: &mut protocol::TaskStream,
+ backend: Backend,
+ program: &Path,
+ prompt: &str,
+ ) -> anyhow::Result<()> {
let mut cmd = tokio::process::Command::new(program);
- cmd.args(self.agent_args(backend, &task.token, prompt))
+ cmd.args(self.agent_args(backend, token, prompt))
.current_dir(&self.workdir)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
@@ -394,7 +170,7 @@ impl Agents {
.process_group(0)
.kill_on_drop(true);
let mut child = cmd.spawn()?;
- task.lock().pid = child.id();
+ let pid = child.id();
let stdout = child.stdout.take().ok_or_else(|| anyhow::anyhow!("no stdout"))?;
let stderr = child.stderr.take().ok_or_else(|| anyhow::anyhow!("no stderr"))?;
let errs = tokio::spawn(async move {
@@ -408,43 +184,44 @@ impl Agents {
}
tail
});
+ let (mut summary, mut failure, mut last_text) = (None, None, None);
+ let mut ended = false;
let mut lines = BufReader::new(stdout).lines();
- while let Some(line) = lines.next_line().await? {
- let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };
- match parse_line(backend, &v) {
- Some(Out::Thought(t)) => task.thought(&t),
- Some(Out::Summary(t)) => task.lock().summary = Some(t),
- Some(Out::Failure(t)) => task.lock().failure = Some(t),
- None => {}
+ loop {
+ tokio::select! {
+ line = lines.next_line() => {
+ let Some(line) = line? else { break };
+ let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };
+ match parse_line(backend, &v) {
+ Some(Out::Thought(t)) => {
+ last_text = Some(t.clone());
+ self.as_task(token, Request::TaskNote { text: t }).await;
+ }
+ Some(Out::Summary(t)) => summary = Some(t),
+ Some(Out::Failure(t)) => failure = Some(t),
+ None => {}
+ }
+ }
+ // the task ended elsewhere (stopped, interrupted) or the daemon went away: stop the agent too
+ e = lease.next(), if !ended => {
+ if e.is_none_or(|e| e.event == "done") {
+ ended = true;
+ if let Some(pid) = pid {
+ kill_group(pid);
+ }
+ }
+ }
}
}
let status = child.wait().await?;
let tail = errs.await.unwrap_or_default();
- let (summary, failure, stopped, rejected) = {
- let st = task.lock();
- (st.summary.clone().or_else(|| st.last_text.clone()), st.failure.clone(), st.stopped, st.rejected)
- };
- if stopped {
- return Ok(());
- }
- if rejected && failure.is_none() {
- let s = summary.unwrap_or_else(|| {
- ictl_l10n::tr!(
- "你拒绝了一步操作,任务在那里停下了。",
- "You rejected a step, so the task stopped there."
- )
- .into()
- });
- task.finish(false, true, s);
+ if ended {
return Ok(());
}
let ok = status.success() && failure.is_none();
+ let summary = summary.or(last_text);
let summary = match (ok, summary, failure) {
- (true, Some(s), _) => s,
- (true, None, _) => {
- ictl_l10n::tr!("任务结束了,agent 没有给出总结。", "The task ended without a summary from the agent.")
- .into()
- }
+ (true, s, _) => s.unwrap_or_default(),
(false, s, f) => {
let why = f
.or_else(|| tail.iter().rev().find(|l| !l.trim().is_empty()).cloned())
@@ -455,17 +232,15 @@ impl Agents {
}
}
};
- task.finish(ok, false, summary);
+ self.finish(token, ok, summary).await;
Ok(())
}
fn agent_args(&self, backend: Backend, token: &str, prompt: &str) -> Vec<String> {
let exe = self.exe.to_string_lossy().into_owned();
let socket = self.socket.to_string_lossy().into_owned();
- let gate = self.gate.to_string_lossy().into_owned();
let mut env = Map::new();
- env.insert(ictl_mcp::gate::GATE_ENV.into(), gate.clone().into());
- env.insert(ictl_mcp::gate::TOKEN_ENV.into(), token.into());
+ env.insert(protocol::TASK_TOKEN_ENV.into(), token.into());
// the agent's tools answer in the task's language (this runs in its scope, see `start`)
env.insert("IPHONE_CONTROL_LANG".into(), ictl_l10n::lang().code().into());
let s = |v: &str| v.to_owned();
@@ -496,7 +271,7 @@ impl Agents {
Backend::Codex => {
// TOML values; a JSON string is a valid TOML basic string
let q = |v: &str| Value::from(v).to_string();
- let env_toml = env.iter().map(|(k, v)| format!("{k}={}", v)).collect::<Vec<_>>().join(",");
+ let env_toml = env.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join(",");
vec![
s("exec"),
s("--json"),
@@ -526,191 +301,6 @@ impl Agents {
}
}
}
-
- /// One gate message from the agent's MCP server; the reply line
- async fn gate(&self, msg: Value) -> Value {
- let token = msg["token"].as_str().unwrap_or_default();
- let task = self.reg().tasks.iter().find(|t| t.token == token).cloned();
- let Some(task) = task else {
- return refuse(ictl_l10n::tr!(
- "这个任务已经不在了:停下来,不要再操作手机",
- "This task no longer exists: stop and don't act on the phone any more"
- ));
- };
- ictl_l10n::scope(task.lang, async {
- match msg["op"].as_str() {
- Some("before") => task.before(msg["tool"].as_str().unwrap_or_default(), &msg["args"]).await,
- Some("after") => {
- task.after(&msg);
- json!({})
- }
- Some("confirm") => task.confirm(&msg).await,
- _ => refuse("bad gate message"),
- }
- })
- .await
- }
-}
-
-fn refuse(message: &str) -> Value {
- json!({"go": false, "approve": false, "message": message})
-}
-
-impl Task {
- /// Holds the call while the task is paused, taken over or waiting; then records it as a step
- async fn before(&self, tool: &str, args: &Value) -> Value {
- loop {
- let notified = self.changed.notified();
- {
- let mut st = self.lock();
- if st.status == Status::Done || st.stopped {
- return refuse(ictl_l10n::tr!(
- "用户停止了这个任务:不要再调用任何工具,直接结束",
- "The user stopped this task: don't call any more tools, just finish"
- ));
- }
- if st.status == Status::Running {
- if tool == "iphone_select_device" {
- return refuse(ictl_l10n::tr!(
- "网页上的任务不能切换设备,继续操作当前这台",
- "A task from the web page can't switch devices; keep using the current one"
- ));
- }
- if st.recheck && !LOOKING.contains(&tool) {
- st.recheck = false;
- return refuse(ictl_l10n::tr!(
- "用户刚才接管并操作过手机,界面可能已经变了:先用 iphone_screenshot 重新看一遍,再决定下一步",
- "The user took over and used the phone, so the screen may have changed: look again with iphone_screenshot before the next step"
- ));
- }
- st.recheck = false;
- let id = st.next_step;
- st.next_step += 1;
- let thought = st.thought.take();
- st.last = Some((id, Instant::now(), true, thought.is_some()));
- let mut d = json!({"id": id, "tool": tool, "args": args, "status": "running"});
- if let Some(t) = thought {
- d["thought"] = t.into();
- }
- if let Some(g) = gesture(tool, args, "") {
- d["gesture"] = g;
- }
- if tool == "iphone_tap_element" {
- st.taps_by_text.push(id);
- }
- self.emit(&mut st, "step", d);
- return json!({"go": true, "step": id});
- }
- }
- notified.await;
- }
- }
-
- fn after(&self, msg: &Value) {
- let mut st = self.lock();
- let Some(id) = msg["step"].as_u64() else { return };
- if let Some((last, at, _, th)) = st.last
- && last == id
- {
- st.last = Some((last, at, false, th));
- }
- let ok = msg["ok"].as_bool().unwrap_or(true);
- let text = msg["text"].as_str().unwrap_or_default();
- let mut d = json!({"id": id, "status": if ok { "ok" } else { "error" }, "ms": msg["ms"], "result": first_lines(text, 6)});
- // where iphone_tap_element tapped is only known now, from its result
- let by_text = st.taps_by_text.iter().position(|&s| s == id).map(|i| st.taps_by_text.swap_remove(i));
- if ok
- && by_text.is_some()
- && let Some(g) = gesture("iphone_tap_element", &Value::Null, text)
- {
- d["gesture"] = g;
- }
- self.emit(&mut st, "step", d);
- }
-
- async fn confirm(&self, msg: &Value) -> Value {
- let (rx, id) = {
- let mut st = self.lock();
- if st.status == Status::Done || st.stopped {
- return refuse(ictl_l10n::tr!("用户停止了这个任务", "The user stopped this task"));
- }
- let id = st.next_step;
- st.next_step += 1;
- let thought = st.thought.take();
- let (action, detail) =
- (msg["action"].as_str().unwrap_or_default(), msg["detail"].as_str().unwrap_or_default());
- let args = json!({"action": action, "detail": detail});
- let mut d = json!({"id": id, "tool": "iphone_confirm", "args": args, "status": "waiting"});
- if let Some(t) = thought {
- d["thought"] = t.into();
- }
- st.last = Some((id, Instant::now(), true, d.get("thought").is_some()));
- self.emit(&mut st, "step", d);
- self.emit(&mut st, "confirm", json!({"step": id, "action": action, "detail": detail}));
- let (tx, rx) = oneshot::channel();
- st.confirm = Some((id, tx));
- self.set_status(&mut st, Status::Waiting);
- (rx, id)
- };
- let approve = rx.await.unwrap_or(false);
- let mut st = self.lock();
- st.last = None;
- let stopped = st.status == Status::Done || st.stopped;
- st.rejected |= !approve && !stopped;
- let (status, result) = match (approve, stopped) {
- (true, false) => ("ok", ictl_l10n::tr!("你同意了,继续执行。", "You approved; carrying on.")),
- (_, true) => ("stopped", ictl_l10n::tr!("任务已停止。", "The task was stopped.")),
- (false, false) => {
- ("rejected", ictl_l10n::tr!("你拒绝了这一步,没有执行。", "You rejected this step; it wasn't done."))
- }
- };
- self.emit(&mut st, "step", json!({"id": id, "status": status, "result": result}));
- if !stopped {
- self.set_status(&mut st, Status::Running);
- }
- if approve && !stopped {
- json!({"approve": true, "message": ictl_l10n::tr!("用户同意了,继续执行这一步。", "The user approved; go ahead with this step.")})
- } else if stopped {
- refuse(ictl_l10n::tr!(
- "用户停止了这个任务:不要再调用任何工具,直接结束",
- "The user stopped this task: don't call any more tools, just finish"
- ))
- } else {
- refuse(ictl_l10n::tr!(
- "用户拒绝了这一步:不要执行,也不要换别的方式去做。停下来,说明没做这一步",
- "The user rejected this step: don't do it, and don't do it another way. Stop and say it wasn't done"
- ))
- }
- }
-}
-
-/// Where a step touches the screen, for the mark on the page: `{ kind, x, y, x2?, y2? }`.
-/// For `iphone_tap_element` it comes from the result text (`… @(x,y) WxH`)
-fn gesture(tool: &str, args: &Value, result: &str) -> Option<Value> {
- let f = |k: &str| args.get(k).and_then(Value::as_f64);
- match tool {
- "iphone_tap" => Some(json!({"kind": "tap", "x": f("x")?, "y": f("y")?})),
- "iphone_long_press" => Some(json!({"kind": "long_press", "x": f("x")?, "y": f("y")?})),
- "iphone_swipe" => {
- Some(json!({"kind": "swipe", "x": f("from_x")?, "y": f("from_y")?, "x2": f("to_x")?, "y2": f("to_y")?}))
- }
- "iphone_tap_element" if !result.is_empty() => {
- let first = result.lines().next()?;
- let at = &first[first.find(" @(")? + 3..];
- let (x, rest) = at.split_once(',')?;
- let y = rest.split(')').next()?;
- Some(json!({"kind": "tap", "x": x.trim().parse::<f64>().ok()?, "y": y.trim().parse::<f64>().ok()?}))
- }
- _ => None,
- }
-}
-
-fn first_lines(text: &str, n: usize) -> String {
- let mut out: Vec<&str> = text.lines().take(n).collect();
- if text.lines().count() > n {
- out.push("…");
- }
- out.join("\n")
}
#[derive(Debug, PartialEq)]
@@ -787,53 +377,6 @@ fn instructions() -> &'static str {
)
}
-/// The Unix socket the agents' MCP servers ask (see the module docs). Only this user can connect (the file is
-/// 0600 in the daemon's directory), and every message carries the task's token
-pub struct GateServer;
-
-impl GateServer {
- pub async fn serve(path: PathBuf, agents: Arc<Agents>) -> anyhow::Result<()> {
- use std::os::unix::fs::PermissionsExt;
- let _ = std::fs::remove_file(&path);
- let listener = tokio::net::UnixListener::bind(&path)?;
- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
- tokio::spawn(async move {
- while let Ok((s, _)) = listener.accept().await {
- let agents = agents.clone();
- tokio::spawn(async move {
- let (r, mut w) = s.into_split();
- let mut line = String::new();
- let mut r = BufReader::new(r);
- if r.read_line(&mut line).await.is_err() || line.len() > 4 * 1024 * 1024 {
- return;
- }
- let Ok(msg) = serde_json::from_str::<Value>(&line) else { return };
- // the MCP server gives up on a call (the agent cancelled it): stop waiting for the user
- let reply = tokio::select! {
- v = agents.gate(msg) => v,
- _ = closed(&mut r) => return,
- };
- let mut out = reply.to_string();
- out.push('\n');
- let _ = w.write_all(out.as_bytes()).await;
- });
- }
- });
- Ok(())
- }
-}
-
-/// Resolves when the other side closes the connection
-async fn closed(r: &mut BufReader<tokio::net::unix::OwnedReadHalf>) {
- let mut b = [0u8; 1];
- loop {
- match tokio::io::AsyncReadExt::read(r, &mut b).await {
- Ok(0) | Err(_) => return,
- Ok(_) => {}
- }
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -860,130 +403,4 @@ mod tests {
let f = json!({"type": "turn.failed", "error": {"message": "quota"}});
assert_eq!(parse_line(Backend::Codex, &f), Some(Out::Failure("quota".into())));
}
-
- #[test]
- fn gestures_for_the_marks() {
- assert_eq!(
- gesture("iphone_tap", &json!({"x": 10, "y": 20.5}), ""),
- Some(json!({"kind": "tap", "x": 10.0, "y": 20.5}))
- );
- assert_eq!(
- gesture("iphone_swipe", &json!({"from_x": 1, "from_y": 2, "to_x": 3, "to_y": 4}), ""),
- Some(json!({"kind": "swipe", "x": 1.0, "y": 2.0, "x2": 3.0, "y2": 4.0}))
- );
- let r = "已点击 Button \"通用\" id=\"com.apple.settings.general\" @(220,776) 400x52";
- assert_eq!(
- gesture("iphone_tap_element", &Value::Null, r),
- Some(json!({"kind": "tap", "x": 220.0, "y": 776.0}))
- );
- assert_eq!(gesture("iphone_tap_element", &Value::Null, "没找到包含 \"x\" 的元素"), None);
- assert_eq!(gesture("iphone_screenshot", &json!({}), ""), None);
- }
-
- fn task() -> Arc<Task> {
- Arc::new(Task {
- id: "t".into(),
- token: "k".into(),
- lang: ictl_l10n::Lang::Zh,
- st: Mutex::new(TaskState {
- status: Status::Running,
- log: Vec::new(),
- next_step: 1,
- thought: None,
- last: None,
- taps_by_text: Vec::new(),
- recheck: false,
- confirm: None,
- last_text: None,
- summary: None,
- failure: None,
- pid: None,
- stopped: false,
- rejected: false,
- }),
- tx: broadcast::channel(16).0,
- changed: Notify::new(),
- })
- }
-
- #[tokio::test]
- async fn a_paused_task_holds_the_call_until_resumed() {
- let t = task();
- t.thought("先看一下屏幕");
- t.set_status(&mut t.lock(), Status::Paused);
- let held = {
- let t = t.clone();
- tokio::spawn(async move { t.before("iphone_tap", &json!({"x": 1, "y": 2})).await })
- };
- tokio::time::sleep(Duration::from_millis(50)).await;
- assert!(!held.is_finished(), "paused: the call waits");
- t.set_status(&mut t.lock(), Status::Running);
- let v = held.await.unwrap();
- assert_eq!((v["go"].as_bool(), v["step"].as_u64()), (Some(true), Some(1)));
- let log = t.lock().log.clone();
- let step = log.iter().find(|e| e.name == "step").unwrap();
- assert_eq!(step.data["thought"], "先看一下屏幕");
- assert_eq!(step.data["gesture"]["kind"], "tap");
- }
-
- #[tokio::test]
- async fn only_a_tap_by_text_gets_a_mark_from_its_result() {
- let t = task();
- let listed = t.before("iphone_list_elements", &json!({})).await["step"].as_u64().unwrap();
- t.after(&json!({"step": listed, "ok": true, "text": "NavigationBar \"世界时钟\" @(220,115) 440x106"}));
- assert!(t.lock().log.last().unwrap().data.get("gesture").is_none());
- let tapped = t.before("iphone_tap_element", &json!({"text": "秒表"})).await["step"].as_u64().unwrap();
- t.after(&json!({"step": tapped, "ok": true, "text": "已点击 Button \"秒表\" @(267,904) 108x54"}));
- assert_eq!(t.lock().log.last().unwrap().data["gesture"], json!({"kind": "tap", "x": 267.0, "y": 904.0}));
- }
-
- #[tokio::test]
- async fn after_a_takeover_the_agent_looks_again_before_acting() {
- let t = task();
- t.lock().recheck = true;
- assert_eq!(t.before("iphone_tap", &json!({"x": 1, "y": 2})).await["go"], false);
- t.lock().recheck = true;
- assert_eq!(t.before("iphone_screenshot", &json!({})).await["go"], true);
- assert_eq!(t.before("iphone_tap", &json!({"x": 1, "y": 2})).await["go"], true, "only once");
- }
-
- #[tokio::test]
- async fn a_rejected_confirmation_tells_the_agent_not_to_do_it() {
- let t = task();
- let asked = {
- let t = t.clone();
- tokio::spawn(async move { t.confirm(&json!({"action": "发送消息", "detail": "给妈妈"})).await })
- };
- tokio::time::sleep(Duration::from_millis(50)).await;
- assert_eq!(t.lock().status, Status::Waiting);
- let (step, tx) = t.lock().confirm.take().unwrap();
- assert_eq!(step, 1);
- tx.send(false).unwrap();
- let v = asked.await.unwrap();
- assert_eq!(v["approve"], false);
- assert_eq!(t.lock().status, Status::Running);
- assert!(t.lock().rejected, "the task will end as stopped");
- assert!(t.lock().log.iter().any(|e| e.name == "confirm" && e.data["action"] == "发送消息"));
- }
-
- #[tokio::test]
- async fn a_stopped_task_refuses_everything() {
- let t = task();
- t.finish(false, true, "停了".into());
- assert_eq!(t.before("iphone_screenshot", &json!({})).await["go"], false);
- assert_eq!(t.confirm(&json!({"action": "a"})).await["approve"], false);
- assert_eq!(t.lock().log.last().unwrap().name, "done");
- }
-
- #[test]
- fn a_late_thought_joins_the_step_it_belongs_to() {
- let t = task();
- t.lock().last = Some((3, Instant::now(), true, false));
- t.thought("点「通用」");
- assert_eq!(t.lock().log.last().unwrap().data, json!({"id": 3, "thought": "点「通用」"}));
- // a finished step keeps it for the next one (the final summary doesn't land on the last step)
- t.lock().last = Some((4, Instant::now(), false, false));
- t.thought("都做完了");
- assert_eq!(t.lock().thought.as_deref(), Some("都做完了"));
- }
}
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index 5affff7..fc67fba 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -20,6 +20,7 @@ mod envfile;
mod guide;
mod schedule;
mod service;
+mod task;
mod update;
mod video;
mod viewer;
@@ -104,6 +105,11 @@ enum Command {
#[arg(long, default_value_t = 8200)]
port: u16,
},
+ #[command(about = ictl_l10n::tr!("AI 任务:在任务里运行外部 agent(task run),查看、暂停、接管、停止、确认任务", "AI tasks: run an external agent in a task (task run); list, pause, take over, stop and confirm tasks"))]
+ Task {
+ #[command(subcommand)]
+ action: task::TaskAction,
+ },
#[command(about = ictl_l10n::tr!("真机诊断(开发用,要用 `--features debug-cmds` 编译)。`wda`/`e2e`/`hid` 会和守护进程抢 XCTest、HID,先停掉守护进程", "Real-device diagnostics (for development, build with `--features debug-cmds`). `wda`/`e2e`/`hid` compete with the daemon for XCTest and HID, so stop the daemon first"))]
#[cfg(feature = "debug-cmds")]
#[command(hide = true)]
@@ -190,7 +196,7 @@ fn prints_and_exits(command: Option<&Command>) -> bool {
| Command::NotifyTest { .. }
| Command::Update { action: Some(UpdateAction::Check { .. }), .. }
)
- )
+ ) || matches!(command, Some(Command::Task { action }) if task::prints_and_exits(action))
}
/// Rust starts every program with SIGPIPE ignored, so once the reader of stdout has gone (`iphone-control status |
@@ -258,6 +264,7 @@ async fn run() -> anyhow::Result<()> {
Command::Select { device } => print_text(&cli.socket, Request::SelectDevice { device }).await,
Command::WdaBridge { port } => wda_bridge(&cli.socket, port).await,
Command::Viewer { port } => viewer::run(&cli.socket, &cli.data_dir, port).await,
+ Command::Task { action } => task::run(&cli.socket, action).await,
#[cfg(feature = "debug-cmds")]
Command::Debug(args) => debug::run(env_nonempty("IPHONE_UDID").as_deref(), args).await,
Command::NotifyTest { event } => notify_test(&cli.data_dir, event.as_deref()).await,
diff --git a/apps/iphone-control/src/task.rs b/apps/iphone-control/src/task.rs
new file mode 100644
index 0000000..0873728
--- /dev/null
+++ b/apps/iphone-control/src/task.rs
@@ -0,0 +1,218 @@
+//! `iphone-control task`: AI tasks from the command line, for agent platforms other than the control page
+//! (docs/task-control.md).
+//!
+//! `task run -- <command>` is the whole integration for most platforms: it opens a task on the controlled phone,
+//! holds its lease, and runs the command with the task's token in `IPHONE_CONTROL_TASK_TOKEN`, so an
+//! `iphone-control mcp` started anywhere below it takes part in the task (the page shows its steps, pausing and
+//! 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.
+
+use std::path::Path;
+use std::time::Duration;
+
+use anyhow::{Context, bail};
+use clap::Subcommand;
+use ictl_daemon::protocol::{self, Request, Response};
+
+#[derive(Subcommand)]
+pub enum TaskAction {
+ #[command(about = ictl_l10n::tr!("开一个任务并在其中运行命令:命令里启动的 iphone-control mcp 自动接入这个任务(控制台能看到每一步、暂停、接管、确认)。命令结束任务就结束;任务在别处被停止时命令也被停止", "Open a task and run a command in it: an iphone-control mcp started by the command takes part in the task (the control page shows every step and can pause, take over and confirm). The task ends when the command does; when the task is stopped elsewhere, so is the command"))]
+ Run {
+ #[arg(long, help = ictl_l10n::tr!("任务标题,显示在控制台上;默认是命令本身", "The task's title, shown on the control page; the command itself by default"))]
+ title: Option<String>,
+ #[arg(long, default_value = "external", help = ictl_l10n::tr!("谁在执行,显示在控制台上", "Who runs it, shown on the control page"))]
+ owner: String,
+ #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
+ command: Vec<String>,
+ },
+ #[command(about = ictl_l10n::tr!("最近的任务(--json 给程序读)", "Recent tasks (--json for programs)"))]
+ List {
+ #[arg(long)]
+ json: bool,
+ },
+ #[command(about = ictl_l10n::tr!("跟着一个任务的事件,每行一个 JSON,任务结束时退出", "Follow a task's events, one JSON per line, until it ends"))]
+ Events { id: String },
+ #[command(about = ictl_l10n::tr!("暂停:任务停在下一步之前", "Pause: the task holds before its next step"))]
+ Pause { id: String },
+ #[command(about = ictl_l10n::tr!("继续暂停的任务", "Resume a paused task"))]
+ Resume { id: String },
+ #[command(about = ictl_l10n::tr!("接管:任务停在下一步之前,你可以自己操作手机", "Take over: the task holds before its next step and you may act on the phone"))]
+ Takeover { id: String },
+ #[command(about = ictl_l10n::tr!("交还控制:任务先重新看界面再继续", "Hand back: the task looks at the screen again, then goes on"))]
+ Handback { id: String },
+ #[command(about = ictl_l10n::tr!("停止任务(task run 的命令也会被停止)", "Stop the task (and the command of a task run)"))]
+ Stop { id: String },
+ #[command(about = ictl_l10n::tr!("同意任务正在等确认的那一步", "Approve the step the task is waiting on"))]
+ Approve {
+ id: String,
+ #[arg(long)]
+ step: Option<u64>,
+ },
+ #[command(about = ictl_l10n::tr!("拒绝任务正在等确认的那一步", "Reject the step the task is waiting on"))]
+ Reject {
+ id: String,
+ #[arg(long)]
+ step: Option<u64>,
+ },
+ #[command(about = ictl_l10n::tr!("在任务里(IPHONE_CONTROL_TASK_TOKEN)给出结果并结束任务;task run 的命令可以用它写总结", "From inside a task (IPHONE_CONTROL_TASK_TOKEN): end it with a result; a command under task run can use it for its summary"))]
+ Finish {
+ #[arg(long)]
+ failed: bool,
+ summary: Vec<String>,
+ },
+}
+
+/// Commands that print and end (see `restore_sigpipe` in main)
+pub fn prints_and_exits(a: &TaskAction) -> bool {
+ matches!(a, TaskAction::List { .. } | TaskAction::Events { .. })
+}
+
+pub async fn run(socket: &Path, action: TaskAction) -> anyhow::Result<()> {
+ let control = |id: String, action: &str, step: Option<u64>, approve: bool| Request::TaskControl {
+ id,
+ action: action.into(),
+ step,
+ approve,
+ };
+ let req = match action {
+ TaskAction::Run { title, owner, command } => return run_command(socket, title, &owner, &command).await,
+ TaskAction::List { json } => return list(socket, json).await,
+ TaskAction::Events { id } => {
+ let mut s = protocol::task_events(socket, &id).await.map_err(anyhow::Error::msg)?;
+ while let Some(e) = s.next().await {
+ println!("{}", serde_json::to_string(&e)?);
+ }
+ return Ok(());
+ }
+ TaskAction::Finish { failed, summary } => {
+ 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)
+ })?;
+ let req = Request::TaskFinish { ok: !failed, summary: summary.join(" ") };
+ return expect_ok(protocol::as_task(Some(token), None, ask(socket, &req)).await);
+ }
+ TaskAction::Pause { id } => control(id, "pause", None, false),
+ TaskAction::Resume { id } => control(id, "resume", None, false),
+ TaskAction::Takeover { id } => control(id, "takeover", None, false),
+ TaskAction::Handback { id } => control(id, "handback", None, false),
+ TaskAction::Stop { id } => control(id, "stop", None, false),
+ TaskAction::Approve { id, step } => control(id, "confirm", step, true),
+ TaskAction::Reject { id, step } => control(id, "confirm", step, false),
+ };
+ expect_ok(ask(socket, &req).await)
+}
+
+async fn ask(socket: &Path, req: &Request) -> anyhow::Result<Response> {
+ protocol::call(socket, req, Some(Duration::from_secs(10))).await.with_context(|| {
+ ictl_l10n::trf!(
+ "连不上守护进程({});确认它在运行(iphone-control status)",
+ "Can't reach the daemon ({}); make sure it is running (iphone-control status)",
+ socket.display()
+ )
+ })
+}
+
+fn expect_ok(r: anyhow::Result<Response>) -> anyhow::Result<()> {
+ match r? {
+ Response::Error { message, .. } => bail!("{message}"),
+ _ => Ok(()),
+ }
+}
+
+async fn list(socket: &Path, json: bool) -> anyhow::Result<()> {
+ let tasks = protocol::task_list(socket).await.map_err(anyhow::Error::msg)?;
+ if json {
+ println!("{}", serde_json::to_string_pretty(&tasks)?);
+ return Ok(());
+ }
+ if tasks.is_empty() {
+ println!("{}", ictl_l10n::tr!("还没有任务", "No tasks yet"));
+ }
+ for t in &tasks {
+ let title: String = t.title.lines().next().unwrap_or_default().chars().take(60).collect();
+ println!("{} {:<11} {:>3} {} {:<10} {title}", t.id, t.state, t.steps, ictl_l10n::tr!("步", "steps"), t.owner);
+ }
+ Ok(())
+}
+
+/// `task run`: the task lives as long as the command
+async fn run_command(socket: &Path, title: Option<String>, owner: &str, command: &[String]) -> anyhow::Result<()> {
+ let title = title.unwrap_or_else(|| command.join(" "));
+ let (opened, mut lease) = protocol::open_task(socket, &title, owner).await.map_err(anyhow::Error::msg)?;
+ eprintln!("{}", ictl_l10n::trf!("任务 {} 已开始", "Task {} started", opened.id));
+ 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)
+ // its own group: stopping the task stops everything it started (an agent and its MCP server)
+ .process_group(0)
+ .kill_on_drop(true)
+ .spawn();
+ let mut child = match spawned {
+ Ok(c) => c,
+ 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;
+ drop(lease);
+ bail!("{why}");
+ }
+ };
+ let pid = child.id().map(|p| p as libc::pid_t);
+ let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
+ let mut outcome: Option<String> = None;
+ let mut ended = false;
+ let status = loop {
+ tokio::select! {
+ s = child.wait() => break s?,
+ e = lease.next(), if !ended => {
+ if let Some(e) = &e && e.event != "done" {
+ continue;
+ }
+ // ended elsewhere, or the daemon went away: the command can't go on
+ ended = true;
+ outcome = e.and_then(|e| e.data["outcome"].as_str().map(str::to_owned));
+ stop_group(pid);
+ }
+ _ = tokio::signal::ctrl_c() => stop_here(socket, &opened.id, pid).await,
+ _ = term.recv() => stop_here(socket, &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;
+ }
+ 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(),
+ };
+ eprintln!("{}", ictl_l10n::trf!("任务 {} 结束:{outcome}", "Task {} ended: {outcome}", opened.id));
+ drop(lease);
+ std::process::exit(status.code().unwrap_or(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 };
+ if !matches!(ask(socket, &req).await, Ok(Response::Text { .. })) {
+ stop_group(pid);
+ }
+}
+
+/// SIGTERM to the command's process group, SIGKILL a little later if still there
+fn stop_group(pid: Option<libc::pid_t>) {
+ let Some(pgid) = pid else { return };
+ unsafe { libc::kill(-pgid, libc::SIGTERM) };
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ unsafe { libc::kill(-pgid, libc::SIGKILL) };
+ });
+}
diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.html
index dbf3623..fbbb581 100644
--- a/apps/iphone-control/src/viewer.html
+++ b/apps/iphone-control/src/viewer.html
@@ -243,8 +243,8 @@ body.resizing .stage, body.resizing iframe { pointer-events: none; }
font: inherit; line-height: 1.5; text-align: left; overflow-wrap: anywhere; cursor: pointer;
transition: background-color var(--dur-fast) var(--ease-out);
}
-@media (hover: hover) { .bubble:hover:not(:disabled) { background: var(--accent-line); color: var(--text); } }
-.bubble:disabled { cursor: default; }
+@media (hover: hover) { button.bubble:hover:not(:disabled) { background: var(--accent-line); color: var(--text); } }
+.bubble:disabled, div.bubble { cursor: default; }
.msg-meta { display: flex; align-items: center; gap: 2px; flex-wrap: wrap; justify-content: flex-end; min-height: 28px; }
.msg-time { display: block; font-size: var(--fs-2xs); color: var(--muted); font-variant-numeric: tabular-nums; margin-right: var(--sp-1); }
.mini { display: inline-flex; align-items: center; gap: 4px; min-height: 28px; padding: 0 var(--sp-2); border: 0; border-radius: var(--r-sm); background: transparent; color: var(--muted); font-size: var(--fs-2xs); font-weight: 600; cursor: pointer; white-space: nowrap; --od-icon-size: 16px; transition: opacity var(--dur-fast) var(--ease-out), background-color var(--dur-fast) var(--ease-out); }
@@ -1085,7 +1085,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 = {"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."};
+const EN = {"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',
@@ -1152,18 +1152,20 @@ language.addEventListener('change', () => {
* GET /api/alert → { alert: null | { text, frame?: { x, y, width, height }, buttons: [{ label, x, y, width }] } } // 系统弹窗,单位点:弹窗的框(左上角)、按钮中心和宽;画面是手机自己的视频时页面定时问(2~6 秒,见 alertLoop)
* state 取值:Absent | NeedsTrust | DeveloperModeOff | NeedsSigning | WdaStarting | NeedsUnlock | NeedsAutomationPin | Ready
*
- * AI 任务:交给本机的 Claude Code 或 Codex,它只能用 iphone-control 的 MCP 工具;每一步都经 viewer 过一道闸,
- * 所以暂停、接管、确认在这里生效,和用哪个 agent 无关:
+ * AI 任务:交给本机的 Claude Code 或 Codex,它只能用 iphone-control 的 MCP 工具;每一步都经守护进程过一道闸,
+ * 所以暂停、接管、确认在那里生效,和用哪个 agent 无关:
* GET /api/agent/backends → { backends: [{ id, name, available }] }
+ * GET /api/agent/tasks → { tasks: [{ id, title, owner, udid, state, started, ended?, steps }] }
+ * 守护进程里的全部任务,含在别处开的(iphone-control task run);有正在进行的就接上它的事件
* POST /api/agent/tasks { prompt, agent } → { id }
* GET /api/agent/tasks/{id}/events SSE:step | confirm | state | done(连上时先重放已有的事件)
* step { id, thought?, tool?, args?, status: running|ok|error|waiting|rejected|stopped, ms?, result?, screenshot?, gesture? }
* confirm { step, action, detail }
* state { state: running|paused|takeover|waiting }
- * done { ok, stopped?, summary }
+ * done { ok, stopped?, outcome, summary } outcome:completed|failed|cancelled|rejected|abandoned|interrupted
* POST /api/agent/tasks/{id}/pause | resume | takeover | handback | stop
* POST /api/agent/tasks/{id}/confirm { step, approve }
- * 任务进行中(没有接管时)服务端也拒绝手动操作,返回 409 和原因。
+ * 任务在守护进程里(docs/task-control.md):任务进行中(没有接管时)守护进程拒绝别人的操作,结果里说明原因。
*
* 所有 POST 要求同源 Origin + JSON。打不开 /api/info 时(例如直接打开这个文件)进入演示模式,所有数据都在本地模拟。
* ================================================================ */
@@ -2784,18 +2786,47 @@ function upsertStep(task, d) {
async function runLive(task) {
try {
const v = await api('/api/agent/tasks', { prompt: task.prompt, agent: task.agent });
- task.remoteId = v.id;
- const es = new EventSource(`/api/agent/tasks/${encodeURIComponent(v.id)}/events`);
+ follow(task, v.id);
+ } catch (e) {
+ task.steps.push({ n: 1, tool: null, status: 'error', result: String(e.message || e) });
+ finish(task, 'failed', tr('任务没能交给 AI。手动操作和设备面板不受影响。'));
+ }
+}
+/* 任务在守护进程里:这个页面开的、页面刷新前开的、在别处开的(iphone-control task run)都一样跟着它的事件 */
+function follow(task, id) {
+ task.remoteId = id;
+ const es = new EventSource(`/api/agent/tasks/${encodeURIComponent(id)}/events`);
task.es = es;
es.addEventListener('step', e => { const d = JSON.parse(e.data); upsertStep(task, d); if (d.gesture) { const g = d.gesture; drawMark(g.kind, 'ai', { x: g.x, y: g.y }, g.x2 != null ? { x: g.x2, y: g.y2 } : null); } renderTurns(true); });
es.addEventListener('confirm', e => { const d = JSON.parse(e.data); upsertStep(task, { id: d.step, status: 'waiting', confirm: d }); task.status = 'waiting'; renderAll(); scrollConvo(); });
es.addEventListener('state', e => { const d = JSON.parse(e.data); if (ACTIVE.includes(task.status)) { task.status = d.state; renderAll(); } });
es.addEventListener('done', e => { const d = JSON.parse(e.data); finish(task, d.ok ? 'success' : d.stopped ? 'stopped' : 'failed', d.summary || ''); refreshStatusSoon(); });
es.onerror = () => { if (ACTIVE.includes(task.status)) show(tr('AI 任务的事件流断开了,正在重连…'), 'warn'); };
- } catch (e) {
- task.steps.push({ n: 1, tool: null, status: 'error', result: String(e.message || e) });
- finish(task, 'failed', tr('任务没能交给 AI。手动操作和设备面板不受影响。'));
- }
+}
+/* 页面已经跟不上的任务(守护进程不记得了,或者没连上服务) */
+function lostTask(t) {
+ t.reattach = false; t.status = 'stopped'; t.endedAt = t.endedAt || Date.now();
+ t.summary = tr('页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。');
+ t.steps.forEach(st => { if (st.status === 'running' || st.status === 'waiting') st.status = 'stopped'; });
+}
+/* 正在进行、但这个页面还没跟着的任务(页面刷新过,或者是在别处开的):接上,事件会从头重放 */
+let adopting = false;
+async function adoptTask() {
+ const pending = S.tasks.filter(t => t.reattach);
+ if (S.mode !== 'live' || adopting || (!pending.length && activeTask())) return;
+ adopting = true;
+ try {
+ const list = (await api('/api/agent/tasks')).tasks || [];
+ pending.forEach(t => { if (list.some(x => x.id === t.remoteId)) { t.reattach = false; follow(t, t.remoteId); } else lostTask(t); });
+ if (pending.length) renderAll();
+ const t = list.find(x => ACTIVE.includes(x.state));
+ if (!t || activeTask() || S.tasks.some(x => x.remoteId === t.id)) return;
+ const task = { id: 't' + (++S.seq), prompt: t.title, status: t.state, steps: [], startedAt: t.started || Date.now(), source: 'live', agent: t.owner };
+ S.tasks.push(task); S.expanded.add(task.id);
+ follow(task, t.id);
+ renderAll(); scrollConvo();
+ show(isExternal(task) ? tr('接上了一个正在进行的外部任务') : tr('接上了一个正在进行的 AI 任务'));
+ } catch { /* 下一轮再看 */ } finally { adopting = false; }
}
async function liveControl(task, action, body) {
if (!task.remoteId) return;
@@ -2845,7 +2876,7 @@ function startTask(text) {
}
function rerunTask(id) {
const t = S.tasks.find(x => x.id === id);
- if (!t || activeTask()) return;
+ if (!t || activeTask() || isExternal(t)) return;
if (startTask(t.prompt)) show(`${tr('重新执行:')}${t.prompt}`);
}
let delTimer = 0;
@@ -2959,21 +2990,32 @@ function stepHtml(s) {
return `<li class="step"><div class="step-rail"><span class="step-dot tone-${st.tone}" title="${st.label}">${icon(st.icon, st.icon === 'loader' ? 'spin' : '')}<span class="sr-only">${st.label}</span></span><span class="step-line"></span></div>
<div class="step-body"><p class="step-thought">${esc(text)}</p>${s.status === 'error' ? `<p class="step-result err">${tr('这一步没成功')}</p>` : ''}${confirm}</div></li>`;
}
+/* 谁在执行:本机的 Claude Code / Codex,或者在别处开任务的程序(iphone-control task run 的 --owner)。
+ * 外部任务不是这个页面交给 AI 的,所以不能「重新执行」,提示里也不说是 AI */
+const BUILTIN_AGENTS = { claude: 'Claude Code', codex: 'Codex' };
+function isExternal(t) {
+ return !!t && t.source === 'live' && !!t.agent && !(t.agent in BUILTIN_AGENTS) && !S.agents.some(a => a.id === t.agent);
+}
+function agentLabel(t) {
+ if (t.source !== 'live' || !t.agent) return `AI ${tr('助手')}`;
+ const name = (S.agents.find(a => a.id === t.agent) || {}).name || BUILTIN_AGENTS[t.agent] || t.agent;
+ return isExternal(t) ? `${name} · ${tr('外部任务')}` : name;
+}
function turnHtml(t) {
const st = TASK_STATUS[t.status], active = ACTIVE.includes(t.status), open = S.expanded.has(t.id) || active;
const busy = !!activeTask();
const actions = active ? '' : S.pendingDelete === t.id
? `<button type="button" class="mini confirm-del" data-action="del-yes" data-id="${t.id}" data-focus="dely-${t.id}">${icon('trash')}<span>${tr('确认删除')}</span></button><button type="button" class="mini" data-action="del-no" data-id="${t.id}" data-focus="deln-${t.id}">${tr('取消')}</button>`
- : `<button type="button" class="mini" data-action="rerun" data-id="${t.id}" data-focus="rerun-${t.id}" ${busy ? 'disabled' : ''}>${icon('refresh')}<span>${tr('重新执行')}</span></button><button type="button" class="mini danger" data-action="del-ask" data-id="${t.id}" data-focus="del-${t.id}" aria-label="${tr('删除这条记录')}" title="${tr('删除这条记录')}">${icon('trash')}<span>${tr('删除')}</span></button>`;
+ : `${isExternal(t) ? '' : `<button type="button" class="mini" data-action="rerun" data-id="${t.id}" data-focus="rerun-${t.id}" ${busy ? 'disabled' : ''}>${icon('refresh')}<span>${tr('重新执行')}</span></button>`}<button type="button" class="mini danger" data-action="del-ask" data-id="${t.id}" data-focus="del-${t.id}" aria-label="${tr('删除这条记录')}" title="${tr('删除这条记录')}">${icon('trash')}<span>${tr('删除')}</span></button>`;
const answer = !active && t.summary ? `<div class="answer tone-${st.tone}">${icon(st.icon)}<div class="answer-text"><span class="answer-title">${st.label}</span><div class="answer-body">${mdLite(t.summary)}</div></div></div>` : '';
const toggle = !active && t.steps.length ? `<button type="button" class="toggle-steps" data-action="toggle-steps" data-id="${t.id}" data-focus="ts-${t.id}" aria-expanded="${open}" aria-controls="steps-${t.id}"><span>${open ? tr('收起步骤') : `${tr('查看')} ${t.steps.length} ${tr('个步骤')}`}</span>${icon('chevron')}</button>` : '';
return `<li class="turn">
<div class="msg-user">
- <button type="button" class="bubble" data-action="rerun" data-id="${t.id}" data-focus="bubble-${t.id}" title="${busy ? tr('当前任务结束后可以重新执行') : tr('点击重新执行这条指令')}" aria-label="${tr('重新执行:')}${esc(t.prompt)}" ${busy ? 'disabled' : ''}>${esc(t.prompt)}</button>
+ ${isExternal(t) ? `<div class="bubble">${esc(t.prompt)}</div>` : `<button type="button" class="bubble" data-action="rerun" data-id="${t.id}" data-focus="bubble-${t.id}" title="${busy ? tr('当前任务结束后可以重新执行') : tr('点击重新执行这条指令')}" aria-label="${tr('重新执行:')}${esc(t.prompt)}" ${busy ? 'disabled' : ''}>${esc(t.prompt)}</button>`}
<div class="msg-meta"><span class="msg-time">${hhmm(new Date(t.startedAt))}</span>${actions}</div>
</div>
<div class="msg-agent">
- <div class="agent-line"><span class="avatar">${icon('bot')}</span><span class="agent-name">AI ${tr('助手')}</span><span class="agent-meta" data-elapsed="${t.id}">${t.steps.length} ${tr('步')} · ${mmss((t.endedAt || Date.now()) - t.startedAt)}</span>${badge(st)}</div>
+ <div class="agent-line"><span class="avatar">${icon('bot')}</span><span class="agent-name">${esc(agentLabel(t))}</span><span class="agent-meta" data-elapsed="${t.id}">${t.steps.length} ${tr('步')} · ${mmss((t.endedAt || Date.now()) - t.startedAt)}</span>${badge(st)}</div>
${answer}${toggle}
${t.steps.length ? `<ol class="steps" id="steps-${t.id}" aria-label="${tr('执行步骤')}"${open ? '' : ' hidden'}>${t.steps.map(stepHtml).join('')}</ol>` : ''}
</div></li>`;
@@ -3018,10 +3060,11 @@ function renderGuard() {
return;
}
dock.classList.add('is-covered'); dock.inert = true;
+ const ext = isExternal(t);
const cfg = {
- running: { tone: 'accent', ic: 'loader', title: tr('AI 正在操作这台设备'), sub: tr('手动操作已锁定,避免和 AI 同时点击。'), btns: [['takeover', tr('接管'), 'cursor']] },
- paused: { tone: 'warn', ic: 'pause', title: tr('AI 已暂停'), sub: tr('画面仍为 AI 保留,要自己操作先接管。'), btns: [['resume', tr('继续'), 'play'], ['takeover', tr('接管'), 'cursor']] },
- waiting: { tone: 'warn', ic: 'alert', title: tr('AI 在等你确认一步操作'), sub: tr('确认前画面保持锁定。'), btns: [['goto-confirm', tr('去确认'), 'arrow']] },
+ running: { tone: 'accent', ic: 'loader', title: ext ? tr('外部任务正在操作这台设备') : tr('AI 正在操作这台设备'), sub: ext ? tr('手动操作已锁定,避免和它同时点击。') : tr('手动操作已锁定,避免和 AI 同时点击。'), btns: [['takeover', tr('接管'), 'cursor']] },
+ paused: { tone: 'warn', ic: 'pause', title: ext ? tr('外部任务已暂停') : tr('AI 已暂停'), sub: ext ? tr('画面仍为这个任务保留,要自己操作先接管。') : tr('画面仍为 AI 保留,要自己操作先接管。'), btns: [['resume', tr('继续'), 'play'], ['takeover', tr('接管'), 'cursor']] },
+ waiting: { tone: 'warn', ic: 'alert', title: ext ? tr('外部任务在等你确认一步操作') : tr('AI 在等你确认一步操作'), sub: tr('确认前画面保持锁定。'), btns: [['goto-confirm', tr('去确认'), 'arrow']] },
takeover: { tone: 'user', ic: 'cursor', title: tr('你在接管'), sub: tr('AI 已暂停。交还后它会先重新看一遍屏幕。'), btns: [['handback', tr('交还 AI'), 'play']] }
}[t.status];
g.className = `guard glass tone-${cfg.tone}`;
@@ -3149,7 +3192,9 @@ document.addEventListener('click', ev => {
case 'pause': case 'resume': case 'takeover': case 'handback': control(a); break;
case 'approve': answerConfirm(true); break;
case 'reject': answerConfirm(false); break;
- case 'stop': stopDialog.showModal(); requestAnimationFrame(() => $('#stop-cancel').focus()); break;
+ case 'stop':
+ $('#stop-desc').textContent = isExternal(activeTask()) ? tr('发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。') : tr('AI 会立刻停下。已经在设备上做完的操作不会撤销。');
+ stopDialog.showModal(); requestAnimationFrame(() => $('#stop-cancel').focus()); break;
case 'clear': if (activeTask() || !S.tasks.length) return; clearDialog.showModal(); requestAnimationFrame(() => $('#clear-cancel').focus()); break;
case 'goto-confirm': gotoConfirm(); break;
case 'sign': signWda(); break;
@@ -3244,6 +3289,9 @@ async function detect() {
setTimeout(pollInfo, 2000);
alertLoop();
setInterval(loadDeviceState, 10000);
+ adoptTask(); setInterval(adoptTask, 3000);
+ } else {
+ S.tasks.filter(t => t.reattach).forEach(lostTask);
}
await loadDeviceState();
renderAll(); setDevTab(S.devTab);
@@ -3373,7 +3421,7 @@ fitPanes();
const TASKS_KEY = 'ictl.tasks', MAX_TASKS = 50;
function serializeTasks(withThumbs) {
return JSON.stringify(S.tasks.slice(-MAX_TASKS).map(t => ({
- id: t.id, prompt: t.prompt, status: t.status, source: t.source, startedAt: t.startedAt, endedAt: t.endedAt, summary: t.summary, remoteId: t.remoteId,
+ id: t.id, prompt: t.prompt, status: t.status, source: t.source, agent: t.agent, startedAt: t.startedAt, endedAt: t.endedAt, summary: t.summary, remoteId: t.remoteId,
steps: t.steps.map(st => ({ id: st.id, n: st.n, thought: st.thought, tool: st.tool, args: st.args, status: st.status, ms: st.ms, result: st.result, confirm: st.confirm }))
})));
}
@@ -3394,11 +3442,9 @@ function loadTasks() {
if (!Array.isArray(list)) return;
list = list.filter(t => t && t.id && Array.isArray(t.steps));
list.forEach(t => {
- // 刷新前还在执行的任务:页面已经不再跟踪它,如实标成已停止
+ // 刷新前还在执行的任务:任务在守护进程里,连上后接着跟(adoptTask);演示任务没有可接的,如实标成已停止
if (ACTIVE.includes(t.status)) {
- t.status = 'stopped'; t.endedAt = t.endedAt || Date.now();
- t.summary = tr('页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。');
- t.steps.forEach(st => { if (st.status === 'running' || st.status === 'waiting') st.status = 'stopped'; });
+ if (t.remoteId) t.reattach = true; else lostTask(t);
}
});
S.tasks = list;
diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs
index 10d540a..4f02318 100644
--- a/apps/iphone-control/src/viewer.rs
+++ b/apps/iphone-control/src/viewer.rs
@@ -115,10 +115,7 @@ pub async fn run(socket: &Path, data_dir: &Path, port: u16) -> anyhow::Result<()
};
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?;
let port = listener.local_addr()?.port();
- // next to the daemon's socket: a directory only this user can enter
- let gate = socket.parent().unwrap_or(Path::new("/tmp")).join(format!("viewer-{port}.sock"));
- let agents = Agents::new(socket, gate.clone())?;
- agent::GateServer::serve(gate, agents.clone()).await?;
+ let agents = Agents::new(socket)?;
println!(
"{}",
ictl_l10n::trf!(
@@ -247,12 +244,9 @@ async fn handle(mut client: TcpStream, ctx: &Ctx, head: Vec<u8>, req: Head, mut
}
("GET", p) if p.starts_with("/api/agent/tasks/") && p.ends_with("/events") => {
let id = &p["/api/agent/tasks/".len()..p.len() - "/events".len()];
- match ctx.agents.task(id) {
- Some(t) => events(&mut client, &t).await,
- None => {
- json_reply(&mut client, 404, &json!({"message": ictl_l10n::tr!("没有这个任务", "No such task")}))
- .await
- }
+ match protocol::task_events(&ctx.socket, id).await {
+ Ok(stream) => events(&mut client, stream).await,
+ Err(m) => json_reply(&mut client, 404, &json!({"message": m})).await,
}
}
("GET", p) if p.starts_with("/api/") => {
@@ -274,6 +268,8 @@ async fn handle(mut client: TcpStream, ctx: &Ctx, head: Vec<u8>, req: Head, mut
"elements" => elements(ctx, &req.query("filter").unwrap_or_default()).await,
"alert" => alert(ctx).await,
"agent/backends" => Ok(json!({"backends": agent::backends()})),
+ // every task the daemon knows, also those started elsewhere (`iphone-control task run`)
+ "agent/tasks" => protocol::task_list(&ctx.socket).await.map(|t| json!({"tasks": t})),
_ => return reply(&mut client, 404, "text/plain", b"not found").await,
};
match v {
@@ -408,7 +404,7 @@ async fn post(ctx: &Ctx, name: &str, b: &Value, device: Option<&str>) -> (u16, V
if name == "agent/tasks" {
let prompt = b["prompt"].as_str().unwrap_or_default();
let backend = b["agent"].as_str().unwrap_or("claude");
- return match ctx.agents.start(prompt, backend) {
+ return match ctx.agents.start(prompt, backend).await {
Ok(id) => (200, json!({"ok": true, "id": id})),
Err(m) => conflict(m),
};
@@ -416,18 +412,14 @@ async fn post(ctx: &Ctx, name: &str, b: &Value, device: Option<&str>) -> (u16, V
if let Some(rest) = name.strip_prefix("agent/tasks/")
&& let Some((id, action)) = rest.split_once('/')
{
- return match ctx.agents.control(id, action, b) {
+ return match ctx.agents.control(id, action, b).await {
Ok(()) => (200, json!({"ok": true})),
Err(m) => conflict(m),
};
}
+ // while a task runs the daemon refuses switching devices, signing and acting (unless the user took over), and
+ // says why; the page shows that message
if name == "select" {
- if ctx.agents.busy() {
- return conflict(
- ictl_l10n::tr!("AI 任务执行中,不能切换设备", "An AI task is running, so the device can't be switched")
- .into(),
- );
- }
let Some(device) = b["device"].as_str() else { return (400, json!({"ok": false, "message": "bad action"})) };
let v = run_action(&ctx.socket, &Request::SelectDevice { device: device.to_owned() }, None, SHORT).await;
// the page follows the device it picked
@@ -443,27 +435,10 @@ async fn post(ctx: &Ctx, name: &str, b: &Value, device: Option<&str>) -> (u16, V
// not known yet (the daemon wasn't up when this started): no device check rather than one that always fails
let udid = Some(udid.as_str()).filter(|u| !u.is_empty());
if name == "sign" {
- if !ctx.agents.manual_allowed() {
- return conflict(
- ictl_l10n::tr!("AI 任务执行中,不能签名安装", "An AI task is running; signing has to wait").into(),
- );
- }
// signing for the page's device: refused if the daemon has moved on to another one
return (200, run_action(&ctx.socket, &Request::Resign { force: true }, udid, SIGN).await);
}
let Some(req) = action(name, b) else { return (400, json!({"ok": false, "message": "bad action"})) };
- // reading is fine during a task, and so is lifting a finger that was down when it started; acting would compete
- // with the agent
- let harmless = matches!(req, Request::WaitFor { .. } | Request::Touch { phase: TouchPhase::Up, .. });
- if !harmless && !ctx.agents.manual_allowed() {
- return conflict(
- ictl_l10n::tr!(
- "AI 正在操作这台设备。要自己操作,先点「接管」。",
- "The AI is operating this device. To act yourself, click “Take over” first."
- )
- .into(),
- );
- }
if matches!(req, Request::TapElement { .. }) {
// The daemon resolves the name in a fresh accessibility tree on this device.
let Some(target) = device.filter(|id| !id.is_empty()) else {
@@ -490,32 +465,25 @@ async fn post(ctx: &Ctx, name: &str, b: &Value, device: Option<&str>) -> (u16, V
(200, run_action(&ctx.socket, &req, udid, SHORT).await)
}
-/// The task's events so far, then new ones as they come, as server-sent events, until it is done
-async fn events(client: &mut TcpStream, task: &agent::Task) -> anyhow::Result<()> {
+/// The task's events so far, then new ones as they come (from the daemon), as server-sent events, until it is done
+async fn events(client: &mut TcpStream, mut stream: protocol::TaskStream) -> anyhow::Result<()> {
client
.write_all(
b"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\n",
)
.await?;
- let (log, mut rx, done) = task.subscribe();
- for e in &log {
- client.write_all(sse(e).as_bytes()).await?;
- }
- if done {
- return Ok(());
- }
loop {
tokio::select! {
- r = rx.recv() => match r {
- Ok(e) => {
+ e = stream.next() => match e {
+ Some(e) => {
client.write_all(sse(&e).as_bytes()).await?;
- if e.name == "done" {
+ if e.event == "done" {
return Ok(());
}
}
- // fell behind (many screenshots at once): the page reconnects and gets everything again
- Err(_) => return Ok(()),
+ // the daemon went away (restarting): the page reconnects
+ None => return Ok(()),
},
// a comment now and then finds a page that went away
_ = tokio::time::sleep(Duration::from_secs(15)) => client.write_all(b": ping\n\n").await?,
@@ -523,8 +491,8 @@ async fn events(client: &mut TcpStream, task: &agent::Task) -> anyhow::Result<()
}
}
-fn sse(e: &agent::Event) -> String {
- format!("event: {}\ndata: {}\n\n", e.name, e.data)
+fn sse(e: &protocol::TaskEvent) -> String {
+ format!("event: {}\ndata: {}\n\n", e.event, e.data)
}
async fn json_reply(client: &mut TcpStream, status: u16, v: &Value) -> anyhow::Result<()> {
@@ -971,7 +939,7 @@ mod tests {
fn test_ctx(dir: &Path, socket: &Path) -> Ctx {
Ctx {
- agents: Agents::new(socket, dir.join("gate")).unwrap(),
+ agents: Agents::new(socket).unwrap(),
socket: socket.to_owned(),
data_dir: dir.into(),
port: 0,
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index b9685e8..d571104 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -199,6 +199,10 @@ pub struct CallCtx {
pub expect_udid: Option<String>,
/// Identity of the measured display used for this coordinate.
pub expect_view: Option<String>,
+ /// The token of the task this request belongs to ([`ictl_protocol::TASK`])
+ pub task: Option<String>,
+ /// The task's step it belongs to ([`ictl_protocol::TASK_STEP`])
+ pub task_step: Option<u64>,
}
/// Logical points measured on this connection. A different id invalidates queued coordinates.
@@ -339,6 +343,8 @@ pub struct Daemon {
/// taps and screenshots; see [`crate::web`]
pub(crate) web: Mutex<Option<crate::web::WebConn>>,
pub(crate) heartbeat: crate::watchdog::Heartbeat,
+ /// AI tasks: who may act on the phone while one runs (see [`crate::tasks`])
+ pub(crate) tasks: crate::tasks::Tasks,
}
/// 停掉 HID 会话(屏幕媒体流),隧道保留。媒体流不停的话手机一直以为「配对的电脑」在看屏幕:
@@ -454,7 +460,16 @@ impl Daemon {
log_tail: Vec::new(),
};
let (snap, _) = watch::channel(first);
- Arc::new(Self { cfg, log, inner: Mutex::new(inner), snap, web: Mutex::new(None), heartbeat: Heartbeat::new() })
+ let tasks = crate::tasks::Tasks::load(Some(cfg.data_dir.join("tasks")));
+ Arc::new(Self {
+ cfg,
+ log,
+ inner: Mutex::new(inner),
+ snap,
+ web: Mutex::new(None),
+ heartbeat: Heartbeat::new(),
+ tasks,
+ })
}
/// 自动解锁配置:用设备 `udid` 自己的密码。没接设备时密码文件不存在(自动解锁不可用)
@@ -606,9 +621,21 @@ impl Daemon {
ictl_sign::AccountDir { dir: self.cfg.account_dir(), anisette_url: self.cfg.anisette_url.clone() }
}
+ /// The device being controlled, from the last published snapshot (no lock)
+ pub(crate) fn controlled_udid(&self) -> Option<String> {
+ self.snap.borrow().device.as_ref().map(|d| d.udid.clone()).filter(|u| !u.is_empty())
+ }
+
+ /// Tests: pretend the daemon controls `udid`
+ #[cfg(test)]
+ pub(crate) fn fake_controlled(&self, udid: &str) {
+ self.snap.send_modify(|s| s.device = Some(DeviceInfo { udid: udid.into(), ..Default::default() }));
+ }
+
/// 发布快照给不拿锁的读者(`status`)。日志尾巴在读的时候再取
pub(crate) fn publish(&self, g: &Inner) {
self.heartbeat.beat();
+ self.tasks.device_is(g.device.as_ref().map(|d| d.udid.as_str()));
let unlock = self.unlock_cfg(g.device.as_ref().map(|d| d.udid.as_str()));
let pinned = self.pinned(g);
let devices = self.connected_infos(g);
@@ -656,11 +683,46 @@ 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 {
+ return r;
+ }
+ // while a task runs, only it acts on the phone (or the user, after taking over): see `crate::tasks`
+ let (admission, waited) =
+ match self.tasks.admit(&req, ctx.task.as_deref(), &mut ctx.expect_udid, &mut ctx.gone).await {
+ Ok(a) => a,
+ Err(r) => return r,
+ };
+ // held while the task was paused: the time in the queue starts now
+ let queued_at = if waited { Instant::now() } else { queued_at };
+ // an action of the task that no announced step covers is a step of its own
+ let auto = match &admission {
+ crate::tasks::Admission::Actor(t) if ctx.task_step.is_none() && req.is_device_action() => {
+ Some((t.clone(), self.tasks.auto_step(t, &req)))
+ }
+ _ => None,
+ };
+ let t0 = Instant::now();
+ // boxed: the request's state machine is large, and a connection's task shouldn't carry it on the stack
+ let resp = Box::pin(self.handle_admitted(req, queued_at, ctx)).await;
+ if let Some((t, step)) = auto {
+ self.tasks.auto_step_done(&t, step, &resp, t0.elapsed().as_millis() as u64);
+ }
+ resp
+ }
+
+ /// [`Self::handle`] once the tasks let the request through
+ async fn handle_admitted(self: &Arc<Self>, req: Request, queued_at: Instant, mut ctx: CallCtx) -> Response {
let text = |r: Result<String, String>| {
r.map(|t| Response::text_with(t, crate::protocol::Outcome::default())).unwrap_or_else(Response::error)
};
match lane(&req) {
Lane::Snapshot => unreachable!("handled above"),
+ Lane::Task => {
+ return Response::error(ictl_l10n::tr!(
+ "task_open、task_events 是流式请求,要用 open_task / task_events 打开",
+ "task_open and task_events are streaming requests: open them with open_task / task_events"
+ ));
+ }
// 重签自己分段持锁:签名、安装要几十秒,期间不挡住别的请求
Lane::Resign => {
let Request::Resign { force } = req else { unreachable!("lane") };
@@ -800,7 +862,16 @@ impl Daemon {
| Request::Resign { .. }
| Request::InstallApp { .. }
| Request::WebTargets
- | Request::WebEval { .. } => unreachable!("other lanes"),
+ | Request::WebEval { .. }
+ | Request::TaskOpen { .. }
+ | Request::TaskEvents { .. }
+ | Request::TaskList
+ | Request::TaskControl { .. }
+ | Request::TaskStep { .. }
+ | Request::TaskStepDone { .. }
+ | Request::TaskConfirm { .. }
+ | Request::TaskNote { .. }
+ | Request::TaskFinish { .. } => unreachable!("other lanes"),
};
r.map(|t| Response::text_with(t, outcome)).unwrap_or_else(Response::error)
}
@@ -828,6 +899,8 @@ enum Lane {
Install,
/// the device lock
Device,
+ /// tasks: the streams are served by the connection (`lib::serve_conn`), the rest before any lane
+ Task,
}
fn lane(req: &Request) -> Lane {
@@ -836,6 +909,15 @@ fn lane(req: &Request) -> Lane {
Request::Resign { .. } => Lane::Resign,
Request::WebTargets | Request::WebEval { .. } => Lane::Web,
Request::InstallApp { .. } => Lane::Install,
+ Request::TaskOpen { .. }
+ | Request::TaskEvents { .. }
+ | Request::TaskList
+ | Request::TaskControl { .. }
+ | Request::TaskStep { .. }
+ | Request::TaskStepDone { .. }
+ | Request::TaskConfirm { .. }
+ | Request::TaskNote { .. }
+ | Request::TaskFinish { .. } => Lane::Task,
Request::Status
| Request::ScreenStream
| Request::Screenshot { .. }
diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs
index 4052374..a1d1c34 100644
--- a/crates/ictl-daemon/src/lib.rs
+++ b/crates/ictl-daemon/src/lib.rs
@@ -4,6 +4,7 @@
//! - usbmuxd 用系统的(macOS 自带,Linux 是 usbmuxd 包,插上手机时由 udev 拉起)
//! - 控制接口:Unix socket,每行一个 JSON([`protocol`]),MCP 和 CLI 都通过它访问设备
//! - 并发模型见 [`core`]
+//! - AI 任务(谁能在任务进行中操作手机)见 [`tasks`]
pub mod config;
pub mod core;
@@ -17,6 +18,7 @@ pub mod maintenance;
pub mod notify;
mod screen;
mod supervise;
+pub mod tasks;
mod tools;
mod watchdog;
mod wda_pkg;
@@ -139,6 +141,15 @@ async fn serve_conn(daemon: Arc<Daemon>, stream: tokio::net::UnixStream) {
ictl_l10n::scope(lang, daemon.screen_stream(reader, w, ctx.expect_udid)).await;
return;
}
+ // also streams; an opened task's connection is its lease, so it isn't held against updates either
+ (
+ Ok((req @ (protocol::Request::TaskOpen { .. } | protocol::Request::TaskEvents { .. }), _, _, lang)),
+ Ok(lease),
+ ) => {
+ drop(lease);
+ ictl_l10n::scope(lang, task_stream(&daemon, reader, w, req)).await;
+ return;
+ }
(Ok((req, false, ctx, lang)), Ok(_lease)) => {
let handling = daemon.handle(req, queued_at, ctx);
ictl_l10n::scope(lang, handling).await
@@ -180,23 +191,105 @@ async fn serve_conn(daemon: Arc<Daemon>, stream: tokio::net::UnixStream) {
/// No language (an older client) means Chinese, which is what those clients expect and parse
fn parse_request(line: &[u8]) -> serde_json::Result<(protocol::Request, bool, core::CallCtx, ictl_l10n::Lang)> {
let mut v: serde_json::Value = serde_json::from_slice(line)?;
- let (cancel, udid, view, lang) = match v.as_object_mut() {
+ let (cancel, udid, view, lang, task, task_step) = match v.as_object_mut() {
Some(o) => (
o.remove(protocol::CANCEL_ON_CLOSE).is_some_and(|c| c == true),
o.remove(protocol::EXPECT_UDID).and_then(|u| u.as_str().map(str::to_owned)),
o.remove(protocol::EXPECT_VIEW).and_then(|v| v.as_str().map(str::to_owned)),
o.remove(protocol::LANG).and_then(|l| l.as_str().and_then(ictl_l10n::parse)),
+ o.remove(protocol::TASK).and_then(|t| t.as_str().map(str::to_owned)),
+ o.remove(protocol::TASK_STEP).and_then(|s| s.as_u64()),
),
- None => (false, None, None, None),
+ None => (false, None, None, None, None, None),
};
Ok((
serde_json::from_value(v)?,
cancel,
- core::CallCtx { gone: None, expect_udid: udid, expect_view: view },
+ core::CallCtx { gone: None, expect_udid: udid, expect_view: view, task, task_step },
lang.unwrap_or(ictl_l10n::Lang::Zh),
))
}
+/// Serves [`protocol::Request::TaskOpen`] (the connection is the task's lease) or [`protocol::Request::TaskEvents`]:
+/// one answer line, then the task's events, one JSON line each, until it ends or the client goes away
+async fn task_stream(
+ daemon: &Arc<Daemon>,
+ mut reader: BufReader<tokio::net::unix::OwnedReadHalf>,
+ mut w: tokio::net::unix::OwnedWriteHalf,
+ req: protocol::Request,
+) {
+ 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();
+ line.push('\n');
+ w.write_all(line.as_bytes()).await.is_ok()
+ }
+ let found = match req {
+ protocol::Request::TaskOpen { title, owner } => {
+ daemon.tasks.open(&title, &owner, daemon.controlled_udid().as_deref()).map(|t| {
+ daemon.log.log(&ictl_l10n::log_trf!(
+ "开始任务 {}({owner}):{title}",
+ "Task {} started ({owner}): {title}",
+ t.id
+ ));
+ let opened = protocol::TaskOpened { id: t.id.clone(), token: tasks::Tasks::token_of(&t).to_owned() };
+ (t, Some(opened))
+ })
+ }
+ protocol::Request::TaskEvents { id } => daemon
+ .tasks
+ .get(&id)
+ .map(|t| (t, None))
+ .ok_or_else(|| ictl_l10n::tr!("没有这个任务", "No such task").into()),
+ _ => Err("not a task stream".into()),
+ };
+ let (task, opened) = match found {
+ Ok(f) => f,
+ Err(m) => {
+ send(&mut w, &protocol::Response::error(m)).await;
+ return;
+ }
+ };
+ let lease = opened.is_some();
+ let first = match &opened {
+ Some(o) => serde_json::to_string(o).unwrap_or_default(),
+ None => "streaming".into(),
+ };
+ let (log, mut rx, ended) = task.subscribe();
+ let mut ok = send(&mut w, &protocol::Response::text(first)).await;
+ for e in &log {
+ ok = ok && send(&mut w, e).await;
+ }
+ if ok && !ended {
+ loop {
+ tokio::select! {
+ e = rx.recv() => match e {
+ Ok(e) => {
+ let done = e.event == "done";
+ if !send(&mut w, &e).await {
+ break;
+ }
+ if done {
+ return;
+ }
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
+ },
+ () = wait_closed(&mut reader) => break,
+ }
+ }
+ }
+ // the opener went away before the task ended
+ if lease && task.is_active() {
+ task.abandon();
+ daemon.log.log(&ictl_l10n::log_trf!(
+ "任务 {} 的发起方断开,任务中断",
+ "The opener of task {} went away; the task was interrupted",
+ task.id
+ ));
+ }
+}
+
/// 等到调用方关掉连接(读到 EOF 或出错)。带 cancel_on_close 的客户端一个连接只发一个请求,之后不会再写
async fn wait_closed<R: tokio::io::AsyncRead + Unpin>(reader: &mut R) {
let mut buf = [0u8; 64];
@@ -209,6 +302,58 @@ async fn wait_closed<R: tokio::io::AsyncRead + Unpin>(reader: &mut R) {
mod tests {
use super::*;
+ /// The whole way through the socket: a task opened by a client holds the phone until its connection closes
+ #[tokio::test]
+ async fn an_opened_task_holds_the_phone_until_its_lease_goes() {
+ use protocol::{Request, Response};
+ let local = tokio::task::LocalSet::new();
+ local
+ .run_until(async {
+ let (d, dir) = core::tests::test_daemon("lease");
+ d.fake_controlled("00008150-000A");
+ let socket = dir.join("ctl.sock");
+ let listener = tokio::net::UnixListener::bind(&socket).unwrap();
+ let daemon = d.clone();
+ tokio::task::spawn_local(async move {
+ while let Ok((s, _)) = listener.accept().await {
+ tokio::task::spawn_local(serve_conn(daemon.clone(), s));
+ }
+ });
+ let (opened, mut events) = protocol::open_task(&socket, "看看设置", "test").await.unwrap();
+ assert_eq!(events.next().await.unwrap().event, "task");
+ assert!(protocol::open_task(&socket, "又一个", "test").await.is_err(), "one at a time");
+
+ let tap = Request::Tap { x: 1.0, y: 2.0 };
+ let r = protocol::call(&socket, &tap, None).await.unwrap();
+ assert!(matches!(&r, Response::Error { message, .. } if message.contains(&opened.id)), "{r:?}");
+ // the task's own request gets past the task (and then finds no phone in this test)
+ let r = protocol::as_task(Some(opened.token.clone()), None, protocol::call(&socket, &tap, None))
+ .await
+ .unwrap();
+ assert!(matches!(&r, Response::Error { message, .. } if !message.contains(&opened.id)), "{r:?}");
+ let step = Request::TaskStep { tool: "iphone_tap".into(), args: serde_json::json!({"x": 1, "y": 2}) };
+ let r = protocol::as_task(Some(opened.token.clone()), None, protocol::call(&socket, &step, None))
+ .await
+ .unwrap();
+ assert_eq!(r, Response::text("2"), "step 1 was the tap above, recorded on its own");
+
+ let mut follower = protocol::task_events(&socket, &opened.id).await.unwrap();
+ drop(events);
+ let mut last = None;
+ while let Some(e) = follower.next().await {
+ last = Some(e);
+ }
+ let last = last.unwrap();
+ assert_eq!((last.event.as_str(), last.data["outcome"].as_str()), ("done", Some("abandoned")));
+ let list = protocol::task_list(&socket).await.unwrap();
+ assert_eq!(list.last().unwrap().state, "abandoned");
+ let r = protocol::call(&socket, &tap, None).await.unwrap();
+ assert!(matches!(&r, Response::Error { message, .. } if !message.contains(&opened.id)), "free again");
+ std::fs::remove_dir_all(dir).unwrap();
+ })
+ .await;
+ }
+
#[test]
fn request_options_are_taken_out_before_parsing() {
use ictl_l10n::Lang;
@@ -223,7 +368,9 @@ mod tests {
assert_eq!(lang, Lang::En);
// 旧版本客户端:没有这几个键;没说语言就是中文(它们按中文的固定写法认结果)
let (_, cancel, expect, lang) = parse_request(br#"{"op":"status"}"#).unwrap();
- assert!(!cancel && expect.expect_udid.is_none());
+ assert!(!cancel && expect.expect_udid.is_none() && expect.task.is_none() && expect.task_step.is_none());
+ let (_, _, ctx, _) = parse_request(br#"{"op":"tap","x":1.0,"y":2.0,"task":"T","task_step":3}"#).unwrap();
+ assert_eq!((ctx.task.as_deref(), ctx.task_step), (Some("T"), Some(3)));
assert_eq!(lang, Lang::Zh);
let (_, _, _, lang) = parse_request(br#"{"op":"status","lang":"klingon"}"#).unwrap();
assert_eq!(lang, Lang::Zh);
diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rs
new file mode 100644
index 0000000..3136d08
--- /dev/null
+++ b/crates/ictl-daemon/src/tasks.rs
@@ -0,0 +1,1085 @@
+//! Tasks: who may act on the phone while an AI task runs, enforced where the actions are carried out
+//! (docs/task-control.md, D17).
+//!
+//! A task is opened on a connection that stays open ([`crate::protocol::Request::TaskOpen`]); that connection is its
+//! lease, and when it closes before the task ended the task is abandoned. The opener gets a token and hands it to
+//! the agent (`IPHONE_CONTROL_TASK_TOKEN` for `iphone-control mcp`); every request with the token belongs to the task.
+//!
+//! While a task is active ([`Tasks::admit`]):
+//! - its requests wait while it is paused, taken over or waiting for a confirmation, and only go to the device it was
+//! opened on; after the user handed control back, or someone else acted on the phone, an action is refused until
+//! the agent has looked at the screen again;
+//! - requests without the token may look (screenshots, elements, status) but not act, unless the user has taken
+//! 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.
+//!
+//! 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
+//! are marked interrupted when it starts again.
+
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+use serde_json::{Value, json};
+use tokio::sync::{Notify, broadcast, oneshot};
+
+use crate::protocol::{Request, Response, TaskEvent, TaskInfo, TouchPhase};
+
+/// Task logs kept on disk (and in memory: a task's events are text only, a few KB)
+const KEEP: usize = 50;
+/// A thought sent this soon after a step started belongs to that step (it comes from the agent's output, which
+/// reaches its opener slightly after the tool call reached the daemon)
+const LATE_THOUGHT: Duration = Duration::from_secs(2);
+/// Lines of a step's result kept for the page
+const RESULT_LINES: usize = 6;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum End {
+ Completed,
+ Failed,
+ Cancelled,
+ Rejected,
+ Abandoned,
+ Interrupted,
+}
+
+impl End {
+ fn name(self) -> &'static str {
+ match self {
+ Self::Completed => "completed",
+ Self::Failed => "failed",
+ Self::Cancelled => "cancelled",
+ Self::Rejected => "rejected",
+ Self::Abandoned => "abandoned",
+ Self::Interrupted => "interrupted",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Status {
+ Running,
+ Paused,
+ Takeover,
+ Waiting,
+ Ended(End),
+}
+
+impl Status {
+ fn name(self) -> &'static str {
+ match self {
+ Self::Running => "running",
+ Self::Paused => "paused",
+ Self::Takeover => "takeover",
+ Self::Waiting => "waiting",
+ Self::Ended(e) => e.name(),
+ }
+ }
+ fn active(self) -> bool {
+ !matches!(self, Self::Ended(_))
+ }
+}
+
+struct TaskState {
+ status: Status,
+ log: Vec<TaskEvent>,
+ next_step: u64,
+ /// What the agent said it is about to do, for the next step
+ thought: Option<String>,
+ /// The latest step: id, when it started, still running, has a thought
+ last: Option<(u64, Instant, bool, bool)>,
+ /// Steps whose tool taps by text: where it tapped comes with the result
+ taps_by_text: Vec<u64>,
+ /// The screen may have changed under the agent (the user acted, or handed back): look before acting
+ recheck: bool,
+ confirm: Option<(u64, oneshot::Sender<bool>)>,
+ /// The user turned down a step: the task ends as rejected
+ rejected: bool,
+ ended: Option<u64>,
+}
+
+pub struct Task {
+ pub id: String,
+ token: String,
+ title: String,
+ owner: String,
+ udid: String,
+ started: u64,
+ file: Option<PathBuf>,
+ st: Mutex<TaskState>,
+ tx: broadcast::Sender<TaskEvent>,
+ /// Wakes requests held for the task when its status changes
+ changed: Notify,
+}
+
+/// How [`Tasks::admit`] lets a request through
+pub enum Admission {
+ /// No task is involved
+ Free,
+ /// Part of this task
+ Actor(Arc<Task>),
+ /// Someone other than the task acts while the user has taken over
+ Supervisor(Arc<Task>),
+}
+
+pub struct Tasks {
+ dir: Option<PathBuf>,
+ list: Mutex<Vec<Arc<Task>>>,
+}
+
+fn now_ms() -> u64 {
+ SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
+}
+
+fn refuse(msg: &str) -> Response {
+ Response::error(msg)
+}
+
+fn ended_message() -> &'static str {
+ ictl_l10n::tr!(
+ "这个任务已经结束(被停止、中断或不存在):不要再调用任何工具,直接结束",
+ "This task has ended (stopped, interrupted or unknown): don't call any more tools, just finish"
+ )
+}
+
+/// Requests that show the agent the screen: after one, it may act again ([`TaskState::recheck`])
+fn observes(req: &Request) -> bool {
+ matches!(req, Request::Screenshot { .. } | Request::ListElements { .. } | Request::WaitFor { .. })
+}
+
+/// Requests that change something on or about the phone, beyond [`Request::is_device_action`]
+fn acts(req: &Request) -> bool {
+ req.is_device_action() || matches!(req, Request::Resign { .. } | Request::UnlockReset)
+}
+
+impl Task {
+ fn lock(&self) -> std::sync::MutexGuard<'_, TaskState> {
+ self.st.lock().unwrap_or_else(|p| p.into_inner())
+ }
+
+ fn info(&self) -> TaskInfo {
+ let st = self.lock();
+ TaskInfo {
+ id: self.id.clone(),
+ title: self.title.clone(),
+ owner: self.owner.clone(),
+ udid: self.udid.clone(),
+ state: st.status.name().into(),
+ started: self.started,
+ ended: st.ended,
+ steps: st.next_step - 1,
+ }
+ }
+
+ pub fn is_active(&self) -> bool {
+ self.lock().status.active()
+ }
+
+ fn emit(&self, st: &mut TaskState, name: &str, data: Value) {
+ let e = TaskEvent { event: name.into(), data };
+ if let Some(f) = &self.file {
+ append(f, &e);
+ }
+ st.log.push(e.clone());
+ let _ = self.tx.send(e);
+ }
+
+ fn set_status(&self, st: &mut TaskState, s: Status) {
+ if st.status != s && st.status.active() {
+ st.status = s;
+ if s.active() {
+ self.emit(st, "state", json!({"state": s.name()}));
+ }
+ self.changed.notify_waiters();
+ }
+ }
+
+ /// The whole task so far and the events after it (taken together, so nothing falls between), and whether it ended
+ pub fn subscribe(&self) -> (Vec<TaskEvent>, broadcast::Receiver<TaskEvent>, bool) {
+ let st = self.lock();
+ (st.log.clone(), self.tx.subscribe(), !st.status.active())
+ }
+
+ /// Ends the task unless it already ended. Returns whether it did
+ pub fn end(&self, end: End, summary: &str) -> bool {
+ let mut st = self.lock();
+ if !st.status.active() {
+ return false;
+ }
+ st.status = Status::Ended(end);
+ st.ended = Some(now_ms());
+ if let Some((_, tx)) = st.confirm.take() {
+ let _ = tx.send(false);
+ }
+ let ok = end == End::Completed;
+ let stopped = matches!(end, End::Cancelled | End::Rejected);
+ self.emit(&mut st, "done", json!({"ok": ok, "stopped": stopped, "outcome": end.name(), "summary": summary}));
+ self.changed.notify_waiters();
+ true
+ }
+
+ /// The opener's lease went away
+ pub fn abandon(&self) {
+ self.end(
+ End::Abandoned,
+ ictl_l10n::tr!(
+ "开这个任务的程序断开了,任务中断。已经做完的操作不会撤销。",
+ "The program that opened this task went away, so the task was interrupted. What was already done isn't undone."
+ ),
+ );
+ }
+
+ /// Holds until the task runs; `Err` when it ended or the caller went away
+ async fn wait_running(&self, gone: &mut Option<oneshot::Receiver<()>>) -> Result<bool, Response> {
+ let mut waited = false;
+ loop {
+ let notified = self.changed.notified();
+ tokio::pin!(notified);
+ notified.as_mut().enable();
+ match self.lock().status {
+ Status::Running => return Ok(waited),
+ Status::Ended(_) => return Err(refuse(ended_message())),
+ _ => {}
+ }
+ waited = true;
+ match gone {
+ Some(g) => tokio::select! {
+ () = &mut notified => {}
+ _ = g => return Err(Response::error(ictl_l10n::tr!(
+ "调用方已取消,请求没有执行",
+ "The caller cancelled; the request was not carried out"
+ ))),
+ },
+ None => notified.await,
+ }
+ }
+ }
+
+ fn thought(&self, text: &str) {
+ let text = text.trim();
+ if text.is_empty() {
+ return;
+ }
+ let mut st = self.lock();
+ match st.last {
+ // arrived just after its step reached the daemon
+ Some((id, at, true, false)) if at.elapsed() < LATE_THOUGHT => {
+ st.last = Some((id, at, true, true));
+ self.emit(&mut st, "step", json!({"id": id, "thought": text}));
+ }
+ _ => st.thought = Some(text.to_owned()),
+ }
+ }
+
+ fn begin_step(&self, st: &mut TaskState, tool: &str, args: &Value, gesture: Option<Value>, status: &str) -> u64 {
+ let id = st.next_step;
+ st.next_step += 1;
+ let thought = st.thought.take();
+ st.last = Some((id, Instant::now(), true, thought.is_some()));
+ let mut d = json!({"id": id, "tool": tool, "args": args, "status": status});
+ if let Some(t) = thought {
+ d["thought"] = t.into();
+ }
+ if let Some(g) = gesture {
+ d["gesture"] = g;
+ }
+ self.emit(st, "step", d);
+ id
+ }
+
+ /// A tool call starts: waits while the task isn't running, then records it
+ async fn step(&self, tool: &str, args: &Value, gone: &mut Option<oneshot::Receiver<()>>) -> Response {
+ if let Err(r) = self.wait_running(gone).await {
+ return r;
+ }
+ let mut st = self.lock();
+ if !st.status.active() {
+ return refuse(ended_message());
+ }
+ let id = self.begin_step(&mut st, tool, args, gesture(tool, args, ""), "running");
+ if tool == "iphone_tap_element" {
+ st.taps_by_text.push(id);
+ }
+ Response::text(id.to_string())
+ }
+
+ /// A step's result
+ fn step_done(&self, id: u64, ok: bool, ms: u64, text: &str, gesture_now: Option<Value>) {
+ let mut st = self.lock();
+ if let Some((last, at, _, th)) = st.last
+ && last == id
+ {
+ st.last = Some((last, at, false, th));
+ }
+ let mut d = json!({"id": id, "status": if ok { "ok" } else { "error" }, "ms": ms, "result": first_lines(text)});
+ // where iphone_tap_element tapped is only known now, from its result
+ let by_text = st.taps_by_text.iter().position(|&s| s == id).map(|i| st.taps_by_text.swap_remove(i));
+ let g = gesture_now
+ .or_else(|| (ok && by_text.is_some()).then(|| gesture("iphone_tap_element", &Value::Null, text)).flatten());
+ if let Some(g) = g {
+ d["gesture"] = g;
+ }
+ self.emit(&mut st, "step", d);
+ }
+
+ async fn confirm(&self, action: &str, detail: &str) -> Response {
+ let action = action.trim();
+ if action.is_empty() {
+ return refuse(ictl_l10n::tr!("action 不能为空", "action can't be empty"));
+ }
+ let (rx, id) = {
+ let mut st = self.lock();
+ if !st.status.active() {
+ return refuse(ended_message());
+ }
+ let args = json!({"action": action, "detail": detail});
+ let id = self.begin_step(&mut st, "iphone_confirm", &args, None, "waiting");
+ self.emit(&mut st, "confirm", json!({"step": id, "action": action, "detail": detail}));
+ let (tx, rx) = oneshot::channel();
+ st.confirm = Some((id, tx));
+ self.set_status(&mut st, Status::Waiting);
+ (rx, id)
+ };
+ let approve = rx.await.unwrap_or(false);
+ let mut st = self.lock();
+ st.last = None;
+ let ended = !st.status.active();
+ st.rejected |= !approve && !ended;
+ let (status, result) = match (approve, ended) {
+ (true, false) => ("ok", ictl_l10n::tr!("你同意了,继续执行。", "You approved; carrying on.")),
+ (_, true) => ("stopped", ictl_l10n::tr!("任务已停止。", "The task was stopped.")),
+ (false, false) => {
+ ("rejected", ictl_l10n::tr!("你拒绝了这一步,没有执行。", "You rejected this step; it wasn't done."))
+ }
+ };
+ self.emit(&mut st, "step", json!({"id": id, "status": status, "result": result}));
+ if !ended {
+ self.set_status(&mut st, Status::Running);
+ }
+ match (approve, ended) {
+ (true, false) => Response::text(ictl_l10n::tr!(
+ "用户同意了,继续执行这一步。",
+ "The user approved; go ahead with this step."
+ )),
+ (_, true) => refuse(ended_message()),
+ (false, false) => refuse(ictl_l10n::tr!(
+ "用户拒绝了这一步:不要执行,也不要换别的方式去做。停下来,说明没做这一步",
+ "The user rejected this step: don't do it, and don't do it another way. Stop and say it wasn't done"
+ )),
+ }
+ }
+
+ fn finish(&self, ok: bool, summary: &str) {
+ let rejected = self.lock().rejected;
+ let summary = summary.trim();
+ let end = match (rejected, ok) {
+ (true, _) => End::Rejected,
+ (false, true) => End::Completed,
+ (false, false) => End::Failed,
+ };
+ let fallback = match end {
+ End::Rejected => {
+ ictl_l10n::tr!(
+ "你拒绝了一步操作,任务在那里停下了。",
+ "You rejected a step, so the task stopped there."
+ )
+ }
+ End::Completed => {
+ ictl_l10n::tr!("任务结束了,agent 没有给出总结。", "The task ended without a summary from the agent.")
+ }
+ _ => ictl_l10n::tr!("任务没有完成。", "The task didn't finish."),
+ };
+ self.end(end, if summary.is_empty() { fallback } else { summary });
+ }
+
+ fn control(&self, action: &str, step: Option<u64>, approve: bool) -> Result<(), String> {
+ let mut st = self.lock();
+ if !st.status.active() {
+ return Err(ictl_l10n::tr!("任务已经结束", "The task has ended").into());
+ }
+ match (action, st.status) {
+ ("pause", Status::Running) => self.set_status(&mut st, Status::Paused),
+ ("resume", Status::Paused) => self.set_status(&mut st, Status::Running),
+ ("takeover", Status::Running | Status::Paused) => self.set_status(&mut st, Status::Takeover),
+ ("handback", Status::Takeover) => {
+ st.recheck = true;
+ self.set_status(&mut st, Status::Running);
+ }
+ ("confirm", Status::Waiting) => match st.confirm.take() {
+ Some((waiting, tx)) if step.is_none_or(|s| s == waiting) => {
+ let _ = tx.send(approve);
+ }
+ other => {
+ st.confirm = other;
+ return Err(ictl_l10n::tr!(
+ "这一步已经不在等确认了",
+ "That step is no longer waiting for confirmation"
+ )
+ .into());
+ }
+ },
+ ("stop", _) => {
+ let n = st.next_step - 1;
+ drop(st);
+ self.end(
+ End::Cancelled,
+ &ictl_l10n::trf!(
+ "在第 {n} 步停下了。已经做完的操作不会撤销。",
+ "Stopped at step {n}. What was already done isn't undone."
+ ),
+ );
+ return Ok(());
+ }
+ (a, s) => return Err(ictl_l10n::trf!("现在({})不能{a}", "Can't {a} now ({})", s.name())),
+ }
+ Ok(())
+ }
+}
+
+impl Tasks {
+ /// Loads the task logs in `dir` (None: nothing on disk, for tests); tasks that hadn't ended are interrupted
+ pub fn load(dir: Option<PathBuf>) -> Self {
+ let mut list = Vec::new();
+ if let Some(dir) = &dir {
+ let _ = std::fs::create_dir_all(dir);
+ let mut files: Vec<(u64, PathBuf)> = std::fs::read_dir(dir)
+ .into_iter()
+ .flatten()
+ .flatten()
+ .map(|e| e.path())
+ .filter(|p| p.extension().is_some_and(|x| x == "jsonl"))
+ .filter_map(|p| Some((first_started(&p)?, p)))
+ .collect();
+ files.sort();
+ let extra = files.len().saturating_sub(KEEP);
+ for (_, p) in files.drain(..extra) {
+ let _ = std::fs::remove_file(p);
+ }
+ list.extend(files.into_iter().filter_map(|(_, p)| restore(&p)).map(Arc::new));
+ }
+ Self { dir, list: Mutex::new(list) }
+ }
+
+ fn list(&self) -> std::sync::MutexGuard<'_, Vec<Arc<Task>>> {
+ self.list.lock().unwrap_or_else(|p| p.into_inner())
+ }
+
+ pub fn active(&self) -> Option<Arc<Task>> {
+ self.list().iter().find(|t| t.is_active()).cloned()
+ }
+
+ pub fn get(&self, id: &str) -> Option<Arc<Task>> {
+ self.list().iter().find(|t| t.id == id).cloned()
+ }
+
+ fn by_token(&self, token: &str) -> Option<Arc<Task>> {
+ self.list().iter().find(|t| !t.token.is_empty() && t.token == token).cloned()
+ }
+
+ pub fn infos(&self) -> Vec<TaskInfo> {
+ self.list().iter().map(|t| t.info()).collect()
+ }
+
+ /// Opens a task on `udid` (the controlled device). `Err` is a message
+ pub fn open(&self, title: &str, owner: &str, udid: Option<&str>) -> Result<Arc<Task>, String> {
+ let title = title.trim();
+ if title.is_empty() {
+ return Err(ictl_l10n::tr!("任务要有标题", "A task needs a title").into());
+ }
+ let Some(udid) = udid.filter(|u| !u.is_empty()) else {
+ return Err(ictl_l10n::tr!(
+ "现在没有在控制的设备,开不了任务",
+ "No device is being controlled, so a task can't be opened"
+ )
+ .into());
+ };
+ let mut list = self.list();
+ if let Some(t) = list.iter().find(|t| t.is_active()) {
+ return Err(ictl_l10n::trf!(
+ "已经有一个任务在执行({},{}):等它结束或先停止它",
+ "A task is already running ({}, {}): wait for it to end or stop it first",
+ t.id,
+ t.title
+ ));
+ }
+ let id = uuid::Uuid::new_v4().simple().to_string()[..12].to_owned();
+ let task = Arc::new(Task {
+ file: self.dir.as_ref().map(|d| d.join(format!("{id}.jsonl"))),
+ id,
+ token: uuid::Uuid::new_v4().simple().to_string(),
+ title: title.chars().take(4000).collect(),
+ owner: owner.trim().chars().take(80).collect(),
+ udid: udid.to_owned(),
+ // after every task before it, even within the same millisecond: logs are ordered by it on the next start
+ started: now_ms().max(list.iter().map(|t| t.started + 1).max().unwrap_or(0)),
+ st: Mutex::new(TaskState {
+ status: Status::Running,
+ log: Vec::new(),
+ next_step: 1,
+ thought: None,
+ last: None,
+ taps_by_text: Vec::new(),
+ recheck: false,
+ confirm: None,
+ rejected: false,
+ ended: None,
+ }),
+ tx: broadcast::channel(4096).0,
+ changed: Notify::new(),
+ });
+ {
+ let mut st = task.lock();
+ let info = json!({"id": task.id, "title": task.title, "owner": task.owner, "udid": task.udid, "started": task.started});
+ task.emit(&mut st, "task", info);
+ }
+ if list.len() >= KEEP {
+ let old = list.remove(0);
+ if let Some(f) = &old.file {
+ let _ = std::fs::remove_file(f);
+ }
+ }
+ list.push(task.clone());
+ Ok(task)
+ }
+
+ pub fn token_of(task: &Task) -> &str {
+ &task.token
+ }
+
+ /// The task with this token, active: for the task's own requests (steps, notes, confirmations)
+ fn actor(&self, token: Option<&str>) -> Result<Arc<Task>, Response> {
+ let Some(token) = token else {
+ return Err(refuse(ictl_l10n::tr!("这个请求要带任务口令", "This request needs a task token")));
+ };
+ match self.by_token(token) {
+ Some(t) if t.is_active() => Ok(t),
+ _ => Err(refuse(ended_message())),
+ }
+ }
+
+ /// Decides whether a request may go on while tasks exist; holds a task's own requests while it isn't running.
+ /// `expect_udid` is set to the task's device for its requests. Returns whether it waited (the request's time in
+ /// the queue starts again)
+ pub async fn admit(
+ &self,
+ req: &Request,
+ token: Option<&str>,
+ expect_udid: &mut Option<String>,
+ gone: &mut Option<oneshot::Receiver<()>>,
+ ) -> Result<(Admission, bool), Response> {
+ if let Some(token) = token {
+ let task = self.by_token(token).filter(|t| t.is_active()).ok_or_else(|| refuse(ended_message()))?;
+ if matches!(req, Request::SelectDevice { .. }) {
+ return Err(refuse(ictl_l10n::tr!(
+ "任务进行中不能切换设备,继续操作当前这台",
+ "A task can't switch devices; keep using the current one"
+ )));
+ }
+ let waited = task.wait_running(gone).await?;
+ {
+ let mut st = task.lock();
+ if acts(req) && st.recheck {
+ return Err(refuse(ictl_l10n::tr!(
+ "用户刚才操作过手机,界面可能已经变了:先用 iphone_screenshot 或 iphone_list_elements 重新看一遍,再决定下一步",
+ "The user acted on the phone, so the screen may have changed: look again with iphone_screenshot or iphone_list_elements before the next step"
+ )));
+ }
+ if observes(req) {
+ st.recheck = false;
+ }
+ }
+ *expect_udid = Some(task.udid.clone());
+ return Ok((Admission::Actor(task), waited));
+ }
+ let Some(task) = self.active() else { return Ok((Admission::Free, false)) };
+ if matches!(req, Request::SelectDevice { .. }) {
+ return Err(refuse(&ictl_l10n::trf!(
+ "任务「{}」进行中,不能切换设备;先停止它",
+ "Task “{}” is running, so the device can't be switched; stop it first",
+ task.title
+ )));
+ }
+ if !acts(req) || matches!(req, Request::Touch { phase: TouchPhase::Up, .. }) {
+ return Ok((Admission::Free, false));
+ }
+ let mut st = task.lock();
+ if st.status == Status::Takeover {
+ // the agent looks again before its next action
+ st.recheck = true;
+ drop(st);
+ return Ok((Admission::Supervisor(task), false));
+ }
+ Err(refuse(&ictl_l10n::trf!(
+ "AI 任务「{}」正在操作这台设备({})。要自己操作,先接管或停止这个任务",
+ "AI task “{}” is operating this device ({}). To act yourself, take it over or stop it first",
+ task.title,
+ task.id
+ )))
+ }
+
+ /// An action of the task that no announced step covers: it becomes a step of its own. Returns the step
+ pub fn auto_step(&self, task: &Task, req: &Request) -> u64 {
+ let mut st = task.lock();
+ let mut args = serde_json::to_value(req).unwrap_or_default();
+ let op = args.as_object_mut().and_then(|o| o.remove("op")).and_then(|v| v.as_str().map(str::to_owned));
+ task.begin_step(&mut st, &op.unwrap_or_default(), &args, request_gesture(req), "running")
+ }
+
+ pub fn auto_step_done(&self, task: &Task, step: u64, resp: &Response, ms: u64) {
+ let (ok, text) = match resp {
+ Response::Text { text, .. } => (true, text.as_str()),
+ Response::Image { caption, .. } => (true, caption.as_str()),
+ Response::Error { message, .. } => (false, message.as_str()),
+ };
+ task.step_done(step, ok, ms, text, None);
+ }
+
+ /// The task requests that aren't about the device; `None` for any other request
+ pub async fn handle(
+ &self,
+ req: &Request,
+ token: Option<&str>,
+ 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),
+ },
+ None => Response::error(ictl_l10n::tr!("没有这个任务", "No such task")),
+ },
+ Request::TaskStep { tool, args } => match self.actor(token) {
+ Ok(t) => t.step(tool, args, gone).await,
+ Err(r) => r,
+ },
+ Request::TaskStepDone { step, ok, ms, text } => match self.actor(token) {
+ Ok(t) => {
+ t.step_done(*step, *ok, *ms, text, None);
+ Response::text("ok")
+ }
+ Err(r) => r,
+ },
+ Request::TaskConfirm { action, detail } => match self.actor(token) {
+ Ok(t) => t.confirm(action, detail).await,
+ Err(r) => r,
+ },
+ Request::TaskNote { text } => match self.actor(token) {
+ Ok(t) => {
+ t.thought(text);
+ Response::text("ok")
+ }
+ Err(r) => r,
+ },
+ Request::TaskFinish { ok, summary } => match self.actor(token) {
+ Ok(t) => {
+ t.finish(*ok, summary);
+ Response::text("ok")
+ }
+ Err(r) => r,
+ },
+ _ => return None,
+ })
+ }
+
+ /// The daemon now controls `udid`: a task on another device can't go on
+ pub fn device_is(&self, udid: Option<&str>) {
+ if let (Some(t), Some(u)) = (self.active(), udid)
+ && !t.udid.eq_ignore_ascii_case(u)
+ {
+ t.end(
+ End::Interrupted,
+ &ictl_l10n::log_trf!(
+ "正在控制的设备变成了 {u},任务中断(它是在 {} 上开的)",
+ "The controlled device changed to {u}, so the task was interrupted (it was opened on {})",
+ t.udid
+ ),
+ );
+ }
+ }
+}
+
+fn append(file: &Path, e: &TaskEvent) {
+ use std::io::Write;
+ let line = json!({"t": now_ms(), "event": e.event, "data": e.data});
+ let r = std::fs::OpenOptions::new().create(true).append(true).open(file).and_then(|mut f| writeln!(f, "{line}"));
+ if let Err(err) = r {
+ tracing::warn!("{}", ictl_l10n::log_trf!("写任务日志失败:{err}", "Writing the task log failed: {err}"));
+ }
+}
+
+fn read_events(file: &Path) -> Vec<TaskEvent> {
+ let Ok(text) = std::fs::read_to_string(file) else { return Vec::new() };
+ text.lines().filter_map(|l| serde_json::from_str::<TaskEvent>(l).ok()).collect()
+}
+
+fn first_started(file: &Path) -> Option<u64> {
+ use std::io::BufRead;
+ let f = std::fs::File::open(file).ok()?;
+ let line = std::io::BufReader::new(f).lines().next()?.ok()?;
+ serde_json::from_str::<Value>(&line).ok()?["data"]["started"].as_u64()
+}
+
+/// A task from its log; one that hadn't ended is interrupted now
+fn restore(file: &Path) -> Option<Task> {
+ let log = read_events(file);
+ let first = log.first().filter(|e| e.event == "task")?.data.clone();
+ let s = |k: &str| first[k].as_str().unwrap_or_default().to_owned();
+ let steps = log.iter().filter_map(|e| (e.event == "step").then(|| e.data["id"].as_u64()).flatten()).max();
+ let done = log.iter().rev().find(|e| e.event == "done").cloned();
+ let status = match done.as_ref().and_then(|d| d.data["outcome"].as_str()) {
+ Some("completed") => End::Completed,
+ Some("cancelled") => End::Cancelled,
+ Some("rejected") => End::Rejected,
+ Some("abandoned") => End::Abandoned,
+ Some("interrupted") => End::Interrupted,
+ _ if done.is_some() => End::Failed,
+ _ => End::Interrupted,
+ };
+ let task = Task {
+ id: s("id"),
+ // nobody holds a token for a task from before this daemon started
+ token: String::new(),
+ title: s("title"),
+ owner: s("owner"),
+ udid: s("udid"),
+ started: first["started"].as_u64().unwrap_or(0),
+ file: Some(file.to_owned()),
+ st: Mutex::new(TaskState {
+ status: Status::Running,
+ log,
+ next_step: steps.unwrap_or(0) + 1,
+ thought: None,
+ last: None,
+ taps_by_text: Vec::new(),
+ recheck: false,
+ confirm: None,
+ rejected: false,
+ ended: None,
+ }),
+ tx: broadcast::channel(16).0,
+ changed: Notify::new(),
+ };
+ if task.id.is_empty() {
+ return None;
+ }
+ if done.is_none() {
+ task.end(
+ End::Interrupted,
+ ictl_l10n::log_tr!(
+ "守护进程重启了,任务中断。已经做完的操作不会撤销。",
+ "The daemon restarted, so the task was interrupted. What was already done isn't undone."
+ ),
+ );
+ } else {
+ let mut st = task.lock();
+ st.status = Status::Ended(status);
+ st.ended = file
+ .metadata()
+ .ok()
+ .and_then(|m| m.modified().ok())
+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok().map(|d| d.as_millis() as u64));
+ }
+ Some(task)
+}
+
+/// Where a step touches the screen, for the mark on the page: `{ kind, x, y, x2?, y2? }`.
+/// For `iphone_tap_element` it comes from the result text (`… @(x,y) WxH`)
+fn gesture(tool: &str, args: &Value, result: &str) -> Option<Value> {
+ let f = |k: &str| args.get(k).and_then(Value::as_f64);
+ match tool {
+ "iphone_tap" => Some(json!({"kind": "tap", "x": f("x")?, "y": f("y")?})),
+ "iphone_long_press" => Some(json!({"kind": "long_press", "x": f("x")?, "y": f("y")?})),
+ "iphone_swipe" => {
+ Some(json!({"kind": "swipe", "x": f("from_x")?, "y": f("from_y")?, "x2": f("to_x")?, "y2": f("to_y")?}))
+ }
+ "iphone_tap_element" if !result.is_empty() => {
+ let first = result.lines().next()?;
+ let at = &first[first.find(" @(")? + 3..];
+ let (x, rest) = at.split_once(',')?;
+ let y = rest.split(')').next()?;
+ Some(json!({"kind": "tap", "x": x.trim().parse::<f64>().ok()?, "y": y.trim().parse::<f64>().ok()?}))
+ }
+ _ => None,
+ }
+}
+
+/// [`gesture`] for a request that no tool call announced
+fn request_gesture(req: &Request) -> Option<Value> {
+ match req {
+ Request::Tap { x, y } => Some(json!({"kind": "tap", "x": x, "y": y})),
+ Request::LongPress { x, y, .. } => Some(json!({"kind": "long_press", "x": x, "y": y})),
+ Request::Swipe { from, to, .. } => {
+ Some(json!({"kind": "swipe", "x": from.0, "y": from.1, "x2": to.0, "y2": to.1}))
+ }
+ _ => None,
+ }
+}
+
+fn first_lines(text: &str) -> String {
+ let mut out: Vec<&str> = text.lines().take(RESULT_LINES).collect();
+ if text.lines().count() > RESULT_LINES {
+ out.push("…");
+ }
+ out.join("\n")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const PHONE: &str = "00008150-000A";
+
+ fn tasks() -> Tasks {
+ Tasks::load(None)
+ }
+
+ fn open(ts: &Tasks) -> Arc<Task> {
+ ts.open("看看设置", "test", Some(PHONE)).unwrap()
+ }
+
+ fn tap() -> Request {
+ Request::Tap { x: 1.0, y: 2.0 }
+ }
+
+ async fn admit(ts: &Tasks, req: &Request, token: Option<&str>) -> Result<(Admission, bool), Response> {
+ ts.admit(req, token, &mut None, &mut None).await
+ }
+
+ fn message(r: Result<(Admission, bool), Response>) -> String {
+ match r {
+ Err(Response::Error { message, .. }) => message,
+ Err(other) => panic!("{other:?}"),
+ Ok(_) => panic!("admitted"),
+ }
+ }
+
+ #[tokio::test]
+ async fn without_a_task_everything_goes_as_before() {
+ let ts = tasks();
+ assert!(matches!(admit(&ts, &tap(), None).await, Ok((Admission::Free, false))));
+ let select = Request::SelectDevice { device: "auto".into() };
+ assert!(matches!(admit(&ts, &select, None).await, Ok((Admission::Free, _))));
+ }
+
+ #[tokio::test]
+ async fn only_one_task_and_only_on_a_device() {
+ let ts = tasks();
+ assert!(ts.open("x", "", None).is_err());
+ assert!(ts.open(" ", "", Some(PHONE)).is_err());
+ let t = open(&ts);
+ assert!(ts.open("another", "", Some(PHONE)).err().unwrap().contains(&t.id));
+ t.end(End::Completed, "");
+ assert!(ts.open("another", "", Some(PHONE)).is_ok());
+ }
+
+ /// The point of D17: while a task runs, a caller without its token can look but not act
+ #[tokio::test]
+ async fn others_may_look_but_not_act_until_the_user_takes_over() {
+ let ts = tasks();
+ let t = open(&ts);
+ assert!(message(admit(&ts, &tap(), None).await).contains(&t.id));
+ assert!(admit(&ts, &Request::Resign { force: true }, None).await.is_err());
+ let shot = Request::Screenshot { region: None };
+ assert!(matches!(admit(&ts, &shot, None).await, Ok((Admission::Free, _))));
+ let up = Request::Touch { phase: TouchPhase::Up, x: 0.0, y: 0.0 };
+ assert!(admit(&ts, &up, None).await.is_ok(), "a finger that was down can always be lifted");
+ let select = Request::SelectDevice { device: "auto".into() };
+ assert!(admit(&ts, &select, None).await.is_err());
+
+ t.control("takeover", None, false).unwrap();
+ assert!(matches!(admit(&ts, &tap(), None).await, Ok((Admission::Supervisor(_), _))));
+ assert!(admit(&ts, &select, None).await.is_err(), "not even while taken over");
+ }
+
+ #[tokio::test]
+ async fn the_task_goes_to_its_own_device() {
+ let ts = tasks();
+ let t = open(&ts);
+ let mut udid = Some("someone-else".to_owned());
+ let r = ts.admit(&tap(), Some(&t.token), &mut udid, &mut None).await;
+ assert!(matches!(r, Ok((Admission::Actor(_), false))));
+ assert_eq!(udid.as_deref(), Some(PHONE));
+ let select = Request::SelectDevice { device: "auto".into() };
+ assert!(admit(&ts, &select, Some(&t.token)).await.is_err());
+ }
+
+ #[tokio::test]
+ 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();
+ 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();
+ assert!(matches!(held.await.unwrap(), Ok(true)), "let through, and it says it waited");
+ }
+
+ #[tokio::test]
+ async fn a_held_request_whose_caller_left_is_dropped() {
+ let ts = tasks();
+ let t = open(&ts);
+ t.control("pause", None, false).unwrap();
+ let (tx, rx) = oneshot::channel();
+ tx.send(()).unwrap();
+ let r = ts.admit(&tap(), Some(&t.token), &mut None, &mut Some(rx)).await;
+ assert!(message(r).contains("取消"));
+ }
+
+ #[tokio::test]
+ async fn after_someone_else_acted_the_agent_looks_before_acting() {
+ let ts = tasks();
+ let t = open(&ts);
+ t.control("takeover", None, false).unwrap();
+ assert!(admit(&ts, &tap(), None).await.is_ok());
+ t.control("handback", None, false).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");
+ let look = Request::ListElements { filter: String::new(), limit: 10, max_age_ms: 0 };
+ assert!(admit(&ts, &look, Some(&t.token)).await.is_ok());
+ assert!(admit(&ts, &tap(), Some(&t.token)).await.is_ok());
+ }
+
+ #[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();
+ 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();
+ 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)
+ .await
+ .is_some_and(|r| matches!(r, Response::Error { .. }))
+ );
+ assert!(matches!(admit(&ts, &tap(), None).await, Ok((Admission::Free, _))), "the phone is free again");
+ }
+
+ #[tokio::test]
+ async fn a_rejected_confirmation_ends_the_task_as_rejected() {
+ let ts = Arc::new(tasks());
+ let t = open(&ts);
+ 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()
+ });
+ 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!(matches!(waiting.await.unwrap(), Response::Error { message, .. } if message.contains("拒绝")));
+ assert_eq!(t.info().state, "running");
+ t.finish(true, "done");
+ assert_eq!(t.info().state, "rejected");
+ }
+
+ #[tokio::test]
+ async fn steps_get_thoughts_results_and_marks() {
+ let ts = tasks();
+ 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;
+ 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;
+ 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 });
+ assert_eq!(n, 3);
+ let (log, _, _) = t.subscribe();
+ let steps: Vec<&Value> = log.iter().filter(|e| e.event == "step").map(|e| &e.data).collect();
+ assert_eq!(steps[0]["thought"], "先点「通用」");
+ assert_eq!(steps[1]["gesture"], json!({"kind": "tap", "x": 200.0, "y": 300.0}));
+ assert_eq!(steps[2]["gesture"]["kind"], "tap");
+ assert_eq!(steps[3]["thought"], "点一下");
+ assert_eq!(steps[4]["tool"], "swipe");
+ assert_eq!(steps[4]["gesture"]["x2"], 3.0);
+ }
+
+ #[tokio::test]
+ async fn another_device_interrupts_the_task() {
+ let ts = tasks();
+ let t = open(&ts);
+ ts.device_is(None);
+ ts.device_is(Some(&PHONE.to_lowercase()));
+ assert!(t.is_active(), "unplugged, or the same phone: the task waits");
+ ts.device_is(Some("00008150-000B"));
+ assert_eq!(t.info().state, "interrupted");
+ }
+
+ #[test]
+ fn logs_survive_a_restart_and_unfinished_tasks_are_interrupted() {
+ let dir = std::env::temp_dir().join(format!("ictl-tasks-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let ts = Tasks::load(Some(dir.clone()));
+ let done = open(&ts);
+ done.thought("看一下");
+ done.step_done(1, true, 5, "ok", None);
+ done.end(End::Completed, "好了");
+ let running = open(&ts);
+ drop(ts);
+
+ let ts = Tasks::load(Some(dir.clone()));
+ let infos = ts.infos();
+ assert_eq!(infos.len(), 2);
+ assert_eq!((infos[0].id.as_str(), infos[0].state.as_str()), (done.id.as_str(), "completed"));
+ assert_eq!((infos[1].id.as_str(), infos[1].state.as_str()), (running.id.as_str(), "interrupted"));
+ assert!(ts.active().is_none());
+ assert!(ts.by_token(&running.token).is_none(), "the old token means nothing now");
+ let (log, _, ended) = ts.get(&running.id).unwrap().subscribe();
+ assert!(ended && log.last().unwrap().data["outcome"] == "interrupted");
+ // and it stays that way on the next start
+ let ts = Tasks::load(Some(dir.clone()));
+ let (log, _, _) = ts.get(&running.id).unwrap().subscribe();
+ assert_eq!(log.iter().filter(|e| e.event == "done").count(), 1);
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
+ /// Tasks opened within the same millisecond (a fast machine, a test) still come back in the order they were opened
+ #[test]
+ fn tasks_keep_their_order_across_a_restart_even_within_a_millisecond() {
+ let dir = std::env::temp_dir().join(format!("ictl-tasks-order-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let ts = Tasks::load(Some(dir.clone()));
+ let ids: Vec<String> = (0..8)
+ .map(|_| {
+ let t = open(&ts);
+ t.end(End::Completed, "");
+ t.id.clone()
+ })
+ .collect();
+ let started: Vec<u64> = ts.infos().iter().map(|t| t.started).collect();
+ assert!(started.windows(2).all(|w| w[0] < w[1]), "{started:?}");
+ drop(ts);
+ let again: Vec<String> = Tasks::load(Some(dir.clone())).infos().into_iter().map(|t| t.id).collect();
+ assert_eq!(again, ids);
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
+ #[test]
+ fn only_the_newest_logs_are_kept() {
+ let dir = std::env::temp_dir().join(format!("ictl-tasks-keep-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let ts = Tasks::load(Some(dir.clone()));
+ for _ in 0..KEEP + 3 {
+ open(&ts).end(End::Completed, "");
+ }
+ assert_eq!(ts.infos().len(), KEEP);
+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), KEEP);
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+}
diff --git a/crates/ictl-mcp/src/gate.rs b/crates/ictl-mcp/src/gate.rs
deleted file mode 100644
index 2ae6fff..0000000
--- a/crates/ictl-mcp/src/gate.rs
+++ /dev/null
@@ -1,170 +0,0 @@
-//! The task gate: how a task started from the web viewer (`iphone-control viewer`) follows and steers the agent.
-//!
-//! The viewer runs an agent (Claude Code or Codex) with this MCP server and two environment variables:
-//! [`GATE_ENV`], the path of a Unix socket the viewer listens on, and [`TOKEN_ENV`], the task's secret. With them
-//! set, every tool call asks the viewer first (`before`): the viewer records it as a step of the task, holds it while
-//! the task is paused or the user has taken over, and can refuse it. After the call the result goes back (`after`)
-//! so the page shows it, screenshot included. [`CONFIRM_TOOL`] is listed too: the agent calls it before payments,
-//! deletions, sending messages and the like, and it waits until the user approves or rejects on the page.
-//!
-//! The steps come from here rather than from the agent's own output, so they look the same whichever agent runs.
-//! Without the variables nothing changes: the tool list and every call are as before.
-//!
-//! One JSON line each way per connection. Calls can wait as long as the user takes (a pause, a confirmation), so
-//! there is no timeout; when the viewer is gone the call is refused instead of acting unsupervised.
-
-use std::path::PathBuf;
-
-use serde_json::{Map, Value, json};
-use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
-
-pub const GATE_ENV: &str = "ICTL_AGENT_GATE";
-pub const TOKEN_ENV: &str = "ICTL_AGENT_TOKEN";
-/// Listed only under a gate: asks the user on the page before a sensitive action
-pub const CONFIRM_TOOL: &str = "iphone_confirm";
-/// Text results longer than this are cut before they go to the page (the agent still gets all of it)
-const MAX_TEXT: usize = 4000;
-
-#[derive(Debug, Clone)]
-pub struct Gate {
- path: PathBuf,
- token: String,
-}
-
-/// What the viewer says before a tool call
-#[derive(Debug, PartialEq)]
-pub enum Before {
- /// Go ahead; the call is step `step` of the task
- Go(u64),
- /// Don't run it; tell the agent why
- Refuse(String),
-}
-
-impl Gate {
- pub fn from_env() -> Option<Self> {
- let path = std::env::var_os(GATE_ENV).filter(|p| !p.is_empty())?;
- let token = std::env::var(TOKEN_ENV).ok().filter(|t| !t.is_empty())?;
- Some(Self { path: path.into(), token })
- }
-
- async fn ask(&self, mut msg: Value) -> std::io::Result<Value> {
- if let Some(o) = msg.as_object_mut() {
- o.insert("token".into(), self.token.clone().into());
- }
- let stream = tokio::net::UnixStream::connect(&self.path).await?;
- let (r, mut w) = stream.into_split();
- let mut line = msg.to_string();
- line.push('\n');
- w.write_all(line.as_bytes()).await?;
- let mut resp = String::new();
- BufReader::new(r).read_line(&mut resp).await?;
- serde_json::from_str(&resp).map_err(std::io::Error::other)
- }
-
- pub async fn before(&self, tool: &str, args: &Map<String, Value>) -> Before {
- match self.ask(json!({"op": "before", "tool": tool, "args": args})).await {
- Ok(v) if v["go"].as_bool() == Some(true) => Before::Go(v["step"].as_u64().unwrap_or(0)),
- Ok(v) => Before::Refuse(v["message"].as_str().unwrap_or_default().to_owned()),
- Err(e) => Before::Refuse(gone(&e)),
- }
- }
-
- /// Reports a finished call. `result` is the serialized tool result (`content`, `isError`)
- pub async fn after(&self, step: u64, result: &Value, ms: u64) {
- let text = summarize(result);
- let ok = result["isError"].as_bool() != Some(true);
- let msg = json!({"op": "after", "step": step, "ok": ok, "ms": ms, "text": text});
- if let Err(e) = self.ask(msg).await {
- // stdout is the MCP protocol: stderr only
- eprintln!("task gate: {e}");
- }
- }
-
- /// Waits for the user's answer. `Ok(message)` when approved, `Err(message)` when rejected or the task ended
- pub async fn confirm(&self, args: &Map<String, Value>) -> Result<String, String> {
- let s = |k: &str| args.get(k).and_then(Value::as_str).unwrap_or_default().trim().to_owned();
- let (action, detail) = (s("action"), s("detail"));
- if action.is_empty() {
- return Err(ictl_l10n::tr!("action 不能为空", "action can't be empty").into());
- }
- match self.ask(json!({"op": "confirm", "action": action, "detail": detail})).await {
- Ok(v) if v["approve"].as_bool() == Some(true) => Ok(v["message"].as_str().unwrap_or_default().to_owned()),
- Ok(v) => Err(v["message"].as_str().unwrap_or_default().to_owned()),
- Err(e) => Err(gone(&e)),
- }
- }
-}
-
-fn gone(e: &std::io::Error) -> String {
- ictl_l10n::trf!(
- "网页上的任务已经结束或页面服务已停止({e}),没有执行;停下来,不要再操作手机",
- "The task on the web page has ended or its server stopped ({e}); nothing was done. Stop and don't act on the phone any more"
- )
-}
-
-/// The text blocks joined, cut to [`MAX_TEXT`]. Screenshots stay with the agent: the page shows a sentence per step
-pub fn summarize(result: &Value) -> String {
- let mut text = String::new();
- for c in result["content"].as_array().into_iter().flatten() {
- if c["type"].as_str() == Some("text") {
- if !text.is_empty() {
- text.push('\n');
- }
- text += c["text"].as_str().unwrap_or_default();
- }
- }
- if let Some((i, _)) = text.char_indices().nth(MAX_TEXT) {
- text.truncate(i);
- text.push('…');
- }
- text
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn summary_joins_text_and_leaves_images_out() {
- let r = json!({"content": [
- {"type": "text", "text": "已点击"},
- {"type": "image", "data": "AAA", "mimeType": "image/jpeg"},
- {"type": "text", "text": "440x956"},
- {"type": "image", "data": "BBB", "mimeType": "image/jpeg"}
- ]});
- assert_eq!(summarize(&r), "已点击\n440x956");
- let long = json!({"content": [{"type": "text", "text": "字".repeat(MAX_TEXT + 10)}]});
- assert_eq!(summarize(&long).chars().count(), MAX_TEXT + 1);
- }
-
- #[tokio::test]
- async fn a_gate_nobody_listens_on_refuses() {
- let g = Gate { path: "/nonexistent/ictl-gate.sock".into(), token: "t".into() };
- assert!(matches!(g.before("iphone_tap", &Map::new()).await, Before::Refuse(_)));
- let args = json!({"action": "发送消息"}).as_object().cloned().unwrap();
- assert!(g.confirm(&args).await.is_err());
- }
-
- #[tokio::test]
- async fn talks_one_json_line_with_the_token() {
- let dir = std::env::temp_dir().join(format!("ictl-gate-test-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
- let path = dir.join("g.sock");
- let _ = std::fs::remove_file(&path);
- let listener = tokio::net::UnixListener::bind(&path).unwrap();
- let server = tokio::spawn(async move {
- let (s, _) = listener.accept().await.unwrap();
- let (r, mut w) = s.into_split();
- let mut line = String::new();
- BufReader::new(r).read_line(&mut line).await.unwrap();
- let v: Value = serde_json::from_str(&line).unwrap();
- w.write_all(b"{\"go\":true,\"step\":7}\n").await.unwrap();
- v
- });
- let g = Gate { path: path.clone(), token: "secret".into() };
- assert_eq!(g.before("iphone_tap", &Map::new()).await, Before::Go(7));
- let seen = server.await.unwrap();
- assert_eq!((seen["op"].as_str(), seen["token"].as_str()), (Some("before"), Some("secret")));
- let _ = std::fs::remove_dir_all(&dir);
- }
-}
diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs
index 76f80de..9b438a7 100644
--- a/crates/ictl-mcp/src/lib.rs
+++ b/crates/ictl-mcp/src/lib.rs
@@ -18,7 +18,7 @@ use rmcp::{
};
use serde_json::{Map, Value, json};
-pub mod gate;
+pub mod task;
/// 服务说明(发给客户端的 instructions):toolkit 的那段,加上自动解锁范围、多设备的说明
pub fn instructions() -> &'static str {
@@ -150,15 +150,15 @@ pub fn tools_with(dev: bool) -> Vec<Tool> {
v
}
-/// [`gate::CONFIRM_TOOL`], listed only for a task started from the web viewer
+/// [`task::CONFIRM_TOOL`], listed only while working for a task (see [`task`])
pub fn confirm_tool() -> Tool {
Tool::new(
- gate::CONFIRM_TOOL,
+ task::CONFIRM_TOOL,
ictl_l10n::tr!(
- "请用户在网页上确认一步操作,一直等到用户回答。\n\n何时用:付款、购买、下单、转账;删除或清空数据;发送消息、邮件、评论、帖子;\
+ "请用户确认一步操作(在控制台页面或发起任务的地方),一直等到用户回答。\n\n何时用:付款、购买、下单、转账;删除或清空数据;发送消息、邮件、评论、帖子;\
修改账号、密码、隐私或安全设置;其他不可撤销的操作。在真正点下那一步之前调用。\n\n\
返回:用户同意时是普通结果,接着执行;用户拒绝时是错误结果,这时不要执行这一步,也不要换个方式绕过,停下来说明情况。",
- "Ask the user on the web page to confirm one action, and wait for the answer.\n\nWhen to use: payments, purchases, orders, transfers; deleting or clearing data; sending messages, emails, comments, posts; changing account, password, privacy or security settings; anything else that can't be undone. Call it right before the step that does it.\n\nReturns: a normal result when the user approves, then go ahead; an error when the user rejects, then don't do that step or work around it: stop and explain."
+ "Ask the user to confirm one action (on the control page or wherever the task was started), and wait for the answer.\n\nWhen to use: payments, purchases, orders, transfers; deleting or clearing data; sending messages, emails, comments, posts; changing account, password, privacy or security settings; anything else that can't be undone. Call it right before the step that does it.\n\nReturns: a normal result when the user approves, then go ahead; an error when the user rejects, then don't do that step or work around it: stop and explain."
)
.to_owned(),
schema(
@@ -847,7 +847,17 @@ pub fn wants_alert_check(req: &Request) -> bool {
| Request::ListDevices
| Request::AppLogs { .. }
| Request::CrashReports { .. }
- | Request::WebTargets => false,
+ | Request::WebTargets
+ // tasks: not tools, nothing on the screen
+ | Request::TaskOpen { .. }
+ | Request::TaskEvents { .. }
+ | Request::TaskList
+ | Request::TaskControl { .. }
+ | Request::TaskStep { .. }
+ | Request::TaskStepDone { .. }
+ | Request::TaskConfirm { .. }
+ | Request::TaskNote { .. }
+ | Request::TaskFinish { .. } => false,
}
}
@@ -865,8 +875,8 @@ pub fn to_result(r: Response) -> CallToolResult {
#[derive(Debug, Clone)]
pub struct McpServer {
pub socket: PathBuf,
- /// Set for a task started from the web viewer (see [`gate`])
- pub gate: Option<gate::Gate>,
+ /// Working for a task (see [`task`])
+ pub task: bool,
}
impl ServerHandler for McpServer {
@@ -880,7 +890,7 @@ impl ServerHandler for McpServer {
_context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
let mut t = tools();
- if self.gate.is_some() {
+ if self.task {
t.push(confirm_tool());
}
Ok(ListToolsResult::with_all_items(t))
@@ -891,28 +901,30 @@ impl ServerHandler for McpServer {
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, ErrorData> {
- let Some(gate) = &self.gate else { return self.call_tool_cancellable(request, &context).await };
- // a task from the web viewer: the viewer sees every call and can hold or refuse it (see `gate`)
+ if !self.task {
+ return self.call_tool_cancellable(request, &context).await;
+ }
+ // working for a task: the daemon holds or refuses the calls; announce each so the page shows the tool
let args = request.arguments.clone().unwrap_or_default();
let work = async {
- if request.name == gate::CONFIRM_TOOL {
- let r = match gate.confirm(&args).await {
+ if request.name == task::CONFIRM_TOOL {
+ let r = match task::confirm(&self.socket, &args).await {
Ok(m) => CallToolResult::success(vec![ContentBlock::text(m)]),
Err(m) => CallToolResult::error(vec![ContentBlock::text(m)]),
};
return Ok(r.into());
}
- match gate.before(&request.name, &args).await {
- gate::Before::Go(step) => {
+ match task::before(&self.socket, &request.name, &args).await {
+ task::Before::Go(step) => {
let t0 = std::time::Instant::now();
- let r = self.call_tool_inner(request).await;
+ let r = protocol::as_task(None, Some(step), self.call_tool_inner(request)).await;
if let Ok(CallToolResponse::Complete(c)) = &r {
let v = serde_json::to_value(c).unwrap_or_default();
- gate.after(step, &v, t0.elapsed().as_millis() as u64).await;
+ task::after(&self.socket, step, &v, t0.elapsed().as_millis() as u64).await;
}
r
}
- gate::Before::Refuse(m) => Ok(CallToolResult::error(vec![ContentBlock::text(m)]).into()),
+ task::Before::Refuse(m) => Ok(CallToolResult::error(vec![ContentBlock::text(m)]).into()),
}
};
tokio::select! {
@@ -979,15 +991,15 @@ impl McpServer {
// 守护进程正忙(例如在自动解锁)时会排队;最多等 150 秒,免得 agent 一直挂着。An install uploads the package and
// can take several minutes on its own
let wait = if matches!(req, Request::InstallApp { .. }) { 660 } else { 150 };
- protocol::call_expecting(&self.socket, req, Some(Duration::from_secs(wait)), expect_udid).await.unwrap_or_else(
- |e| {
- Response::error(ictl_l10n::trf!(
- "连不上守护进程({}):{e};确认守护进程在运行(iphone-control status)",
- "Can't reach the daemon ({}): {e}; make sure the daemon is running (iphone-control status)",
- self.socket.display()
- ))
- },
- )
+ // in a task the daemon holds calls while the user has paused or taken over, as long as that takes
+ let wait = (!self.task).then(|| Duration::from_secs(wait));
+ protocol::call_expecting(&self.socket, req, wait, expect_udid).await.unwrap_or_else(|e| {
+ Response::error(ictl_l10n::trf!(
+ "连不上守护进程({}):{e};确认守护进程在运行(iphone-control status)",
+ "Can't reach the daemon ({}): {e}; make sure the daemon is running (iphone-control status)",
+ self.socket.display()
+ ))
+ })
}
/// 操作完成后:按 then 等界面稳定,再附上元素列表或截图(等稳定时顺带提醒弹窗)。
@@ -1109,7 +1121,7 @@ impl McpServer {
/// 在 stdin/stdout 上运行 MCP 服务直到客户端断开
pub async fn serve_stdio(socket: PathBuf) -> anyhow::Result<()> {
- let running = McpServer { socket, gate: gate::Gate::from_env() }.serve(rmcp::transport::stdio()).await?;
+ let running = McpServer { socket, task: task::join_from_env() }.serve(rmcp::transport::stdio()).await?;
running.waiting().await?;
Ok(())
}
diff --git a/crates/ictl-mcp/src/task.rs b/crates/ictl-mcp/src/task.rs
new file mode 100644
index 0000000..e9477c0
--- /dev/null
+++ b/crates/ictl-mcp/src/task.rs
@@ -0,0 +1,128 @@
+//! Taking part in a task (docs/task-control.md): with [`ictl_protocol::TASK_TOKEN_ENV`] set, this MCP server works
+//! for that task. Every request it sends carries the token, so the daemon holds them while the task is paused or
+//! taken over and refuses them once it ended; each tool call is announced as a step first (`task_step`) and its
+//! result reported after (`task_step_done`), so the control page shows the tool and its arguments.
+//! [`CONFIRM_TOOL`] is listed too: the agent calls it before payments, deletions, sending messages and the like,
+//! and it waits until the user approves or rejects.
+//!
+//! The daemon enforces all of it; this side only makes the steps readable. Without the variable nothing changes:
+//! the tool list and every call are as before.
+
+use ictl_protocol::{self as protocol, Request, Response};
+use serde_json::{Map, Value};
+
+/// Listed only in a task: asks the user before a sensitive action
+pub const CONFIRM_TOOL: &str = "iphone_confirm";
+/// Text results longer than this are cut before they go to the page (the agent still gets all of it)
+const MAX_TEXT: usize = 4000;
+
+/// Joins the task named by the environment, if any. Returns whether it did
+pub fn join_from_env() -> bool {
+ match std::env::var(protocol::TASK_TOKEN_ENV).ok().filter(|t| !t.trim().is_empty()) {
+ Some(t) => {
+ protocol::join_task(t.trim());
+ true
+ }
+ None => false,
+ }
+}
+
+/// Whether this process works for a task
+pub fn joined() -> bool {
+ protocol::process_task().is_some()
+}
+
+/// What the daemon says before a tool call
+#[derive(Debug, PartialEq)]
+pub enum Before {
+ /// Go ahead; the call is step `n` of the task
+ Go(u64),
+ /// Don't run it; tell the agent why
+ Refuse(String),
+}
+
+/// Announces a tool call; waits while the task is paused or taken over
+pub async fn before(socket: &std::path::Path, tool: &str, args: &Map<String, Value>) -> Before {
+ let req = Request::TaskStep { tool: tool.to_owned(), args: Value::Object(args.clone()) };
+ match protocol::call(socket, &req, None).await {
+ Ok(Response::Text { text, .. }) => Before::Go(text.trim().parse().unwrap_or(0)),
+ Ok(Response::Error { message, .. }) => Before::Refuse(message),
+ Ok(Response::Image { caption, .. }) => Before::Refuse(caption),
+ Err(e) => Before::Refuse(gone(&e)),
+ }
+}
+
+/// Reports a finished call. `result` is the serialized tool result (`content`, `isError`)
+pub async fn after(socket: &std::path::Path, step: u64, result: &Value, ms: u64) {
+ let ok = result["isError"].as_bool() != Some(true);
+ let req = Request::TaskStepDone { step, ok, ms, text: summarize(result) };
+ if let Err(e) = protocol::call(socket, &req, Some(std::time::Duration::from_secs(10))).await {
+ // stdout is the MCP protocol: stderr only
+ eprintln!("task: {e}");
+ }
+}
+
+/// Waits for the user's answer. `Ok(message)` when approved, `Err(message)` when rejected or the task ended
+pub async fn confirm(socket: &std::path::Path, args: &Map<String, Value>) -> Result<String, String> {
+ let s = |k: &str| args.get(k).and_then(Value::as_str).unwrap_or_default().trim().to_owned();
+ let req = Request::TaskConfirm { action: s("action"), detail: s("detail") };
+ match protocol::call(socket, &req, None).await {
+ Ok(Response::Text { text, .. }) => Ok(text),
+ Ok(Response::Error { message, .. }) => Err(message),
+ Ok(Response::Image { caption, .. }) => Err(caption),
+ Err(e) => Err(gone(&e)),
+ }
+}
+
+fn gone(e: &std::io::Error) -> String {
+ ictl_l10n::trf!(
+ "连不上守护进程({e}),没有执行;停下来,不要再操作手机",
+ "Can't reach the daemon ({e}); nothing was done. Stop and don't act on the phone any more"
+ )
+}
+
+/// The text blocks joined, cut to [`MAX_TEXT`]. Screenshots stay with the agent: the page shows a sentence per step
+pub fn summarize(result: &Value) -> String {
+ let mut text = String::new();
+ for c in result["content"].as_array().into_iter().flatten() {
+ if c["type"].as_str() == Some("text") {
+ if !text.is_empty() {
+ text.push('\n');
+ }
+ text += c["text"].as_str().unwrap_or_default();
+ }
+ }
+ if let Some((i, _)) = text.char_indices().nth(MAX_TEXT) {
+ text.truncate(i);
+ text.push('…');
+ }
+ text
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn summary_joins_text_and_leaves_images_out() {
+ let r = json!({"content": [
+ {"type": "text", "text": "已点击"},
+ {"type": "image", "data": "AAA", "mimeType": "image/jpeg"},
+ {"type": "text", "text": "440x956"},
+ {"type": "image", "data": "BBB", "mimeType": "image/jpeg"}
+ ]});
+ assert_eq!(summarize(&r), "已点击\n440x956");
+ let long = json!({"content": [{"type": "text", "text": "字".repeat(MAX_TEXT + 10)}]});
+ assert_eq!(summarize(&long).chars().count(), MAX_TEXT + 1);
+ }
+
+ /// No daemon: refused, never run unsupervised
+ #[tokio::test]
+ async fn without_the_daemon_a_task_call_is_refused() {
+ let socket = std::path::Path::new("/nonexistent/ictl-task-test.sock");
+ assert!(matches!(before(socket, "iphone_tap", &Map::new()).await, Before::Refuse(_)));
+ let args = json!({"action": "发送消息"}).as_object().cloned().unwrap();
+ assert!(confirm(socket, &args).await.is_err());
+ }
+}
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index 24db5fb..36b56e1 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -183,6 +183,96 @@ pub enum Request {
expression: String,
timeout_ms: u64,
},
+ /// Tasks (docs/task-control.md): opens a task bound to the controlled device. Streaming: the daemon answers one
+ /// line ([`Response::Text`] whose text is `{"id","token"}`, or [`Response::Error`]), then sends the task's
+ /// events (one JSON [`TaskEvent`] per line) until it ends. The connection is the task's lease: when it closes
+ /// before the task ended, the task is abandoned. Use [`open_task`]
+ TaskOpen {
+ title: String,
+ /// Who runs it, shown on the control page (`claude`, `codex`, the name of an external platform…)
+ #[serde(default)]
+ owner: String,
+ },
+ /// Streaming like [`Request::TaskOpen`]: the task's events so far, then new ones, until it ends
+ TaskEvents {
+ id: String,
+ },
+ /// Recent tasks, newest last, as a JSON array of [`TaskInfo`]
+ TaskList,
+ /// `pause` / `resume` / `takeover` / `handback` / `stop` / `confirm` (with `approve` and the waiting `step`)
+ TaskControl {
+ id: String,
+ action: String,
+ #[serde(default)]
+ step: Option<u64>,
+ #[serde(default)]
+ approve: bool,
+ },
+ /// 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 {
+ tool: String,
+ #[serde(default)]
+ args: serde_json::Value,
+ },
+ /// With the task's token: the tool call's result, shown on the page
+ TaskStepDone {
+ step: u64,
+ ok: bool,
+ #[serde(default)]
+ ms: u64,
+ #[serde(default)]
+ text: String,
+ },
+ /// With the task's token: waits until the user approves (text) or rejects (error) a sensitive action
+ TaskConfirm {
+ action: String,
+ #[serde(default)]
+ detail: String,
+ },
+ /// With the task's token: what the agent says it is doing, shown with the next step
+ TaskNote {
+ text: String,
+ },
+ /// With the task's token: the task ended on its own
+ TaskFinish {
+ ok: bool,
+ #[serde(default)]
+ summary: String,
+ },
+}
+
+/// One event of a task, as the daemon streams it and the control page shows it: `step`, `confirm`, `state`, `done`
+/// (and `task`, the first one, with the task's [`TaskInfo`])
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct TaskEvent {
+ pub event: String,
+ pub data: serde_json::Value,
+}
+
+/// A task as [`Request::TaskList`] lists it
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct TaskInfo {
+ pub id: String,
+ pub title: String,
+ pub owner: String,
+ pub udid: String,
+ /// `running` / `paused` / `takeover` / `waiting`, or how it ended: `completed` / `failed` / `cancelled` /
+ /// `rejected` / `abandoned` / `interrupted`
+ pub state: String,
+ /// Unix milliseconds
+ pub started: u64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ended: Option<u64>,
+ /// Steps so far
+ #[serde(default)]
+ pub steps: u64,
+}
+
+impl TaskInfo {
+ pub fn active(&self) -> bool {
+ matches!(self.state.as_str(), "running" | "paused" | "takeover" | "waiting")
+ }
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -263,7 +353,16 @@ impl Request {
| Self::ListDevices
| Self::AppLogs { .. }
| Self::CrashReports { .. }
- | Self::WebTargets => false,
+ | Self::WebTargets
+ | Self::TaskOpen { .. }
+ | Self::TaskEvents { .. }
+ | Self::TaskList
+ | Self::TaskControl { .. }
+ | Self::TaskStep { .. }
+ | Self::TaskStepDone { .. }
+ | Self::TaskConfirm { .. }
+ | Self::TaskNote { .. }
+ | Self::TaskFinish { .. } => false,
}
}
}
@@ -374,6 +473,44 @@ pub const EXPECT_UDID: &str = "expect_udid";
/// The live view whose geometry was used to calculate a coordinate.
pub const EXPECT_VIEW: &str = "expect_view";
+/// Request key carrying a task's token (docs/task-control.md): the request is part of that task. While a task is
+/// active the daemon only lets requests with its token act on the phone (and holds them while the task is paused or
+/// taken over); a token of a task that ended refuses everything. Set it with [`join_task`] or [`as_task`]
+pub const TASK: &str = "task";
+/// Request key with the step (from [`Request::TaskStep`]) a request belongs to; see [`as_task`]
+pub const TASK_STEP: &str = "task_step";
+/// The environment variable that hands a task's token to `iphone-control mcp` (and anything else using this crate)
+pub const TASK_TOKEN_ENV: &str = "IPHONE_CONTROL_TASK_TOKEN";
+
+static PROCESS_TASK: std::sync::OnceLock<String> = std::sync::OnceLock::new();
+
+tokio::task_local! {
+ static CALL_TASK: (Option<String>, Option<u64>);
+}
+
+/// Every request this process sends from now on belongs to the task with `token` (the MCP server of an agent
+/// started for a task). Only the first call counts
+pub fn join_task(token: &str) {
+ let _ = PROCESS_TASK.set(token.to_owned());
+}
+
+/// The task this process joined ([`join_task`]), if any
+pub fn process_task() -> Option<&'static str> {
+ PROCESS_TASK.get().map(String::as_str)
+}
+
+/// Runs `f` with its requests sent as part of a task: `token` overrides the process's ([`join_task`]), `step` says
+/// which step they belong to
+pub async fn as_task<F: std::future::Future>(token: Option<String>, step: Option<u64>, f: F) -> F::Output {
+ let token = token.or_else(|| current_task().0);
+ CALL_TASK.scope((token, step), f).await
+}
+
+fn current_task() -> (Option<String>, Option<u64>) {
+ let (token, step) = CALL_TASK.try_with(Clone::clone).unwrap_or_default();
+ (token.or_else(|| process_task().map(str::to_owned)), step)
+}
+
/// Request key carrying the client's language (`zh` / `en`). The daemon answers in it; requests without it
/// (older clients) get Chinese, as before. Older daemons ignore the extra key
pub const LANG: &str = "lang";
@@ -430,6 +567,7 @@ async fn exchange_on(
if let Some(u) = expect_udid {
o.insert(EXPECT_UDID.into(), u.into());
}
+ add_task_keys(o);
}
let mut line = v.to_string();
line.push('\n');
@@ -449,6 +587,88 @@ async fn exchange_on(
}
}
+fn add_task_keys(o: &mut serde_json::Map<String, serde_json::Value>) {
+ let (token, step) = current_task();
+ if let Some(t) = token {
+ o.insert(TASK.into(), t.into());
+ }
+ if let Some(s) = step {
+ o.insert(TASK_STEP.into(), s.into());
+ }
+}
+
+/// What [`open_task`] got back
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct TaskOpened {
+ pub id: String,
+ pub token: String,
+}
+
+/// A task's events as the daemon streams them ([`Request::TaskOpen`], [`Request::TaskEvents`]). For an opened task
+/// this is also its lease: dropping it ends the task as abandoned unless it ended before
+pub struct TaskStream {
+ lines: tokio::io::Lines<tokio::io::BufReader<tokio::net::unix::OwnedReadHalf>>,
+ _w: tokio::net::unix::OwnedWriteHalf,
+}
+
+impl TaskStream {
+ /// The next event; `None` when the task ended (after its `done`) or the daemon went away
+ pub async fn next(&mut self) -> Option<TaskEvent> {
+ loop {
+ let line = self.lines.next_line().await.ok()??;
+ if let Ok(e) = serde_json::from_str(&line) {
+ return Some(e);
+ }
+ }
+ }
+}
+
+async fn open_stream(socket: &std::path::Path, req: &Request) -> std::io::Result<(Response, TaskStream)> {
+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+ let stream = tokio::net::UnixStream::connect(socket).await?;
+ let (r, mut w) = stream.into_split();
+ let mut v = serde_json::to_value(req)?;
+ if let Some(o) = v.as_object_mut() {
+ o.insert(LANG.into(), ictl_l10n::lang().code().into());
+ add_task_keys(o);
+ }
+ let mut line = v.to_string();
+ line.push('\n');
+ w.write_all(line.as_bytes()).await?;
+ let mut lines = BufReader::new(r).lines();
+ let first = lines.next_line().await?.ok_or_else(|| std::io::Error::other("the daemon closed the connection"))?;
+ let resp = serde_json::from_str(&first).map_err(std::io::Error::other)?;
+ Ok((resp, TaskStream { lines, _w: w }))
+}
+
+/// Opens a task bound to the device the daemon controls now ([`Request::TaskOpen`]). `Err` is a message
+pub async fn open_task(socket: &std::path::Path, title: &str, owner: &str) -> Result<(TaskOpened, TaskStream), String> {
+ let req = Request::TaskOpen { title: title.to_owned(), owner: owner.to_owned() };
+ match open_stream(socket, &req).await.map_err(|e| e.to_string())? {
+ (Response::Text { text, .. }, s) => Ok((serde_json::from_str(&text).map_err(|e| e.to_string())?, s)),
+ (Response::Error { message, .. }, _) => Err(message),
+ (Response::Image { caption, .. }, _) => Err(caption),
+ }
+}
+
+/// Follows a task's events ([`Request::TaskEvents`]). `Err` is a message
+pub async fn task_events(socket: &std::path::Path, id: &str) -> Result<TaskStream, String> {
+ match open_stream(socket, &Request::TaskEvents { id: id.to_owned() }).await.map_err(|e| e.to_string())? {
+ (Response::Text { .. }, s) => Ok(s),
+ (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())? {
+ Response::Text { text, .. } => serde_json::from_str(&text).map_err(|e| e.to_string()),
+ Response::Error { message, .. } => Err(message),
+ Response::Image { caption, .. } => Err(caption),
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/docs/architecture.md b/docs/architecture.md
index d5588cc..8802979 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -48,7 +48,8 @@
- viewer 的画面像触摸屏:iOS 27 起按下、移动、松开各发一个 `Request::Touch`(`prepare`/`down`/`move`/`up`),守护进程在已开的 HID 会话上发一个 touchscreen 报告(约 2 毫秒);解锁、核对方向只在 `down` 时做一次。页面一次只发一个请求,没发出去的移动只留最新的一个,按住不动时每 100 毫秒再报一次位置。滚轮、触控板换成同样的手指拖动。iOS 27 以下松开后发整段手势(WDA)。画面的 MJPEG 流在 `WdaClient::fast_stream` 下最多每秒 60 帧、原尺寸、不转正:缩放或转正时 WDA 要逐帧解码、处理、重新编码,CPU 超过 iOS 的上限(60 秒内平均 80%)会被杀掉;这样设置时它直接转发 testmanagerd 用硬件编好的 JPEG。iPhone 横屏时这些帧仍是竖的:JPEG 带 EXIF 方向,浏览器显示 MJPEG 的 img 时自己转正;本机编码的 H.264 不带方向,页面按界面方向(`/api/info` 的 `display.rotation`)在 canvas 上转正,和手机自己的视频一样。页面的文字中英两套,请求带 `X-Ictl-Lang`,viewer 在这种语言下处理,AI 任务记下开始时的语言。
- viewer 的画面编码(`video/`):macOS 上和装了 ffmpeg 时页面拉 `/video`,是 H.264。每个连接读手机的 MJPEG,丢掉和上一帧相同的(静止时 WDA 每秒重复约 25 次),交给一个 ffmpeg 子进程(`mpjpeg` 进,FLV 出;FLV 每帧带长度,收完最后一个字节就能发,裸 H.264 要等下一帧开头才知道这一帧结束),再按「1 字节类型 + 4 字节长度 + 内容」发给页面,页面用 WebCodecs 解码画到 canvas。发出去的解码配置先改写 SPS,写明不重排帧(`video/sps.rs`):没写的话 Chrome 的硬件解码器按级别的最坏情况扣着几帧不出(990×2151 时 4 帧),画面滞后,静止后停在动作中间。macOS 上先用本程序直接调的 VideoToolbox(`video/vt.rs`,每个连接一个线程:VideoToolbox 的 JPEG 解码器把 JPEG 解成 NV12,奇数尺寸顺带拉成偶数,直接交给 H.264 编码器;不重排、不扣帧,每帧编完才取下一帧,不用补帧;输出本来就是 avcC 格式,avcC 取自格式描述;qp 用 `MinAllowedFrameQP`/`MaxAllowedFrameQP` 定住,macOS 12 以前的系统按 `Quality` 近似;macOS 11 以后才有的键运行时用 `dlsym` 找,免得在旧系统上起不来),不需要 ffmpeg。其余编码器在 `viewer` 启动时按顺序试(NVENC、各渲染节点上的 VAAPI(先显卡解 JPEG,再 CPU 解)、QSV、V4L2 M2M、ffmpeg 的 VideoToolbox(原生的备用)、x264),处理真实画面失败就换下一个。ffmpeg 会扣住最新的一帧等下一帧来(AMD 780M 的 VAAPI 是 1 帧),画面静止时最后一次变化就出不来,所以每帧后面紧跟着把它再写 K 遍,K 在探测时测出(写入的帧数减去出来的帧数),这几份副本各编成约 100 字节。流量控制:系统和 SSH 隧道的缓冲能吞下几 MB,光看队列满不满判断不了页面跟不跟得上(每秒读 30 KB 的客户端曾落后 40 秒),所以页面每 100 毫秒 `POST /api/video/ack` 报告收到多少字节;最早一个没确认的消息比平常的往返时间晚 300 毫秒以上,或者在路上的字节超过「链路速度 ×(往返时间 + 300 毫秒)」时,新画面先不交给编码器,追上后只交最新一张。编好的帧一个不丢,帧链完整,不需要关键帧。没有 ffmpeg 或浏览器不支持 WebCodecs 时用 `/stream`:同样丢掉重复帧、只发最新一张,每帧后面紧跟下一部分的分隔线和头部(Chrome 要看到这些才显示上一帧)。
- 手机自己的视频(iOS 27 及以上,页面优先用它):CoreDevice 屏幕媒体流本来就由 HID 会话持有(HID 事件要它在才生效)。`ictl-device` 的 `media.rs` 不再丢掉 RTP:用上游的 `HevcDepacketizer` 还原成 Annex-B,按 RTP marker 组成一帧,记下 VPS/SPS/PPS 补到手机按请求发来、不带参数集的关键帧前面,经 broadcast 发给订阅者(`ScreenFeed`);并照 Device Hub 回传 RTCP(每帧一个帧确认、每 50 毫秒一个 RCTL、每秒一个接收报告),按需发 PLI+FIR 要关键帧(最多每 300 毫秒一次)。守护进程的 `screen.rs` 处理流式请求 `ScreenStream`:先回一行 JSON,之后在同一连接上发「类型 + 长度 + 内容」的消息(0 解码配置、1 关键帧、2 其他帧、3 界面方向),客户端写 `K` 要关键帧;还没收到关键帧时每 250 毫秒再要一次(刚开流时要的那次手机可能不理);界面方向每秒问一次 WDA。有页面在看时(`screen_viewers`),HID 会话不因空闲关闭。viewer 的 `video/device.rs` 转发到 `/video?src=device`,流量控制沿用页面的回报:落后时丢掉非关键帧、再要一个关键帧。页面不带 description 配置 HEVC 解码器(Annex-B),按 `/api/info` 的屏幕尺寸裁掉宽高补到 16 倍数的边(1320×2868 编成 1328×2896),按方向转正;`isConfigSupported` 不支持或从没出过画面就退回 H.264,再退回 MJPEG。
-- viewer 的 AI 任务(`agent.rs`):页面上写的任务交给本机的 Claude Code(`claude -p --output-format stream-json`,`--tools ""`、`--strict-mcp-config`,只有 iphone 的 MCP 工具)或 Codex(`codex exec --json`,只读沙箱,`-c` 挂上 iphone 的 MCP 服务),作为子进程(单独的进程组,停止时整组结束)。它的 MCP 服务带上环境变量 `ICTL_AGENT_GATE`(viewer 在控制接口旁边监听的 Unix socket `viewer-<端口>.sock`,0600)和 `ICTL_AGENT_TOKEN`(这个任务的口令),于是每次工具调用前先问 viewer(`ictl_mcp::gate`):记成任务的一步、暂停或用户接管时挂住、任务停了就拒绝;调用后把结果和截图报回去;另外多列一个 `iphone_confirm`,等用户在页面上同意或拒绝。所以步骤、暂停、接管、确认都在 iphone-control 这一层,和用哪种 agent 无关;agent 自己的输出只取它说的话(挂到下一步上)和最后的总结。Codex 对标了 destructive 的 MCP 工具默认要审批,非交互运行时会全部拒绝,所以给这个服务设 `default_tools_approval_mode="approve"`,由 `iphone_confirm` 把关。页面按 SSE 收任务事件(`step`/`confirm`/`state`/`done`),重连时先重放;同一时间只有一个任务,任务执行中(没有接管时)viewer 拒绝页面的手动操作。
+- AI 任务(守护进程的 `tasks.rs`,设计见 [task-control.md](task-control.md),D17):任务由守护进程管理,`Daemon::handle` 在排队拿锁之前先过 `Tasks::admit`。开任务(`task_open`)的连接就是租约,连接断了任务就是 abandoned;任务绑定开任务时控制的设备。有任务在进行时,带它口令(请求键 `task`)的请求固定发往那台设备,任务暂停、接管、等确认时在守护进程里等着,用户交还或别人动过手机后要先看一次屏幕才能再操作;不带口令的请求可以看,但操作一律拒绝(用户接管时除外,抬起手指总是可以);切换设备一律拒绝;已结束任务的口令什么都做不了。工具调用先报一步(`task_step`,它的请求带上步骤号 `task_step`),没报的操作也自己记成一步。事件逐条写进 `tasks/<id>.jsonl`(最多 50 个),重启后没结束的记成 interrupted。控制台、命令行(`iphone-control task …`)和外部平台用的是同一套请求。
+- viewer 的 AI 任务(`agent.rs`):页面上写的任务交给本机的 Claude Code(`claude -p --output-format stream-json`,`--tools ""`、`--strict-mcp-config`,只有 iphone 的 MCP 工具)或 Codex(`codex exec --json`,只读沙箱,`-c` 挂上 iphone 的 MCP 服务),作为子进程(单独的进程组,停止时整组结束)。viewer 先在守护进程里开任务、拿住租约,再带着 `IPHONE_CONTROL_TASK_TOKEN` 启动 agent,它的 MCP 服务就加入了这个任务(`ictl_mcp::task`),并多列出一个 `iphone_confirm`。agent 自己的输出只取它说的话(作为 `task_note` 挂到下一步上)和最后的总结(`task_finish`);任务在别处结束(页面上停止、`task stop`、换了设备)时,viewer 结束 agent 的进程组。Codex 对标了 destructive 的 MCP 工具默认要审批,非交互运行时会全部拒绝,所以给这个服务设 `default_tools_approval_mode="approve"`,由 `iphone_confirm` 把关。页面按 SSE 收任务事件(viewer 转发守护进程的 `task_events`:`step`/`confirm`/`state`/`done`),重连时先重放;页面每 3 秒问一次 `/api/agent/tasks`,刷新前在跟的任务和在别处开的任务都会接上。
### 并发模型
diff --git a/docs/decisions.md b/docs/decisions.md
index cdc90c1..bfeff33 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -137,3 +137,15 @@
- 依赖苹果没公开的协议:RTCP 反馈照上游对 Device Hub 的抓包;上游提醒不回 RCTL 时剧烈运动会花屏,回了之后的长时间表现还没测过。
- **重新评估**:长时间运行出现花屏或断流时;浏览器普遍能软解 HEVC 时,可以去掉对硬件解码的依赖。
- **补充(2026-11-13)**:背景里说“改缩放没有明显改善”,指的是缩小。WDA 的截图由 testmanagerd 用硬件编成 JPEG(质量 0.25)交给它;缩放不是 100% 时,WDA 要逐帧解码、用 CoreGraphics 缩放、再重新编码,这正是 CPU 超限的来源(`cpu_resource_fatal` 报告里 13 个采样有 11 个在这条调用栈上)。改成原尺寸后 WDA 直接转发那张 JPEG:iPhone 15 Pro Max(iOS 27.0.1)上帧率不变(约 34 fps),每帧更小(约 80 KB 对 104 KB);拉本机编码的画面时,原来每 1.5~2.5 分钟被杀一次,改后竖屏连拉 15 分钟没再被杀。横屏同理:`mjpegFixOrientation` 让 WDA 逐帧旋转、重新编码,横屏 2 分钟就被杀(92%),所以也关掉,改由页面转正(MJPEG 的 img 由浏览器按 EXIF 方向转正)。所以 D15 那条路(浏览器解不了 HEVC、设备低于 iOS 27)不再需要“不看就关页面”。手机自己的视频仍是 iOS 27 上的首选:帧率更高,主机不用编码。
+
+## D17:任务和租约放进守护进程(2026-11-12)
+
+- **背景**:控制台的 AI 任务(暂停、接管、确认、步骤记录)原来放在 viewer 进程里:viewer 启动 Agent,Agent 的 MCP 每次调用前经一个 Unix socket 来问 viewer。守护进程不知道有任务这回事。结果是:普通 MCP、命令行在任务进行中照样能操作手机;不开控制台就没有任务;外部 Agent 平台没有接入点([#50](https://github.com/Derrors/iphone-control/issues/50))。目标架构和差距见 [task-control.md](task-control.md)。
+- **决定**:任务、租约和确认放进守护进程,在准入检查(`admit` 之前)时强制执行:有任务在进行时,只有带任务口令的请求能操作手机,人接管时人可以;任务不在 running 时,带口令的请求在守护进程里等着;请求固定发往任务绑定的设备。开任务的连接就是租约,连接断了任务就是 abandoned。任务按事件落盘,重启后没结束的记成 interrupted。控制台的内建 runner 和外部平台(`iphone-control task run`)用同一套请求;MCP 凭 `IPHONE_CONTROL_TASK_TOKEN` 接入任务,原来 viewer 的 gate socket 删掉。
+- **理由**:
+ - 监管只有放在执行点才拦得住所有调用方。守护进程本来就是唯一的排队点,准入检查也已经在这里(设备、排队时长、调用方是否已经走了),加上任务状态只是多一项检查。
+ - 一套接口同时服务内建和外部:外部平台用的就是内建功能自己在用的那套,不会出现只有内建能用的捷径。
+ - 用连接表示租约,比心跳简单,没有超时误判;守护进程本来就靠连接断开来判断调用方走了(`cancel_on_close`)。
+- **对 D2、D13 的修改**:D2 里「MCP 是薄客户端」不变,但守护进程从此管任务这层语义,不再只是设备驱动。D13「socket 权限才是边界」不变:任务口令用来区分调用方、让出错的调用方停下来,不是权限控制。同一用户的进程能拿到口令,也能直接发控制请求。要真正隔离,需要让 Agent 换 uid 运行或进沙箱,并用 `SO_PEERCRED` 认调用方(task-control.md 阶段三、四)。
+- **代价**:守护进程多了一个模块和几种请求。有任务时,不带口令的动作会被拒绝:这正是要的效果,但以前「任务进行中用命令行点一下」的做法不能用了,要先接管。任务日志写在数据目录(`tasks/`,最多 50 个)。
+- **重新评估**:需要无人值守、Agent 跑在沙箱里时,再做口令分开、任务范围和 `SO_PEERCRED`;需要跨主机时,再做带认证的 HTTP 控制面。
diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md
index 7126855..7c4ec08 100644
--- a/docs/dev/regression-cases.md
+++ b/docs/dev/regression-cases.md
@@ -68,9 +68,9 @@
| 62 | 网页检查器没开时手机直接断开 Web Inspector 连接,工具只报一句 TLS 错误 | 连接被手机断开时提示打开 设置 → Safari → 高级 → 网页检查器 | 单测(`a_closed_connection_points_at_the_web_inspector_setting`)+ 真机(开关关着时调 `iphone_web_targets`) |
| 63 | 不带调试消息的日志流里仍有 Info 级别的条目,和 `iphone_app_logs` 的说明不符 | 采集时丢掉 Info、Debug | 单测(`info_and_debug_entries_are_not_kept`)+ 真机 |
| 64 | Codex 对标了 destructiveHint 的 MCP 工具默认要审批,`codex exec` 非交互运行时直接拒绝(「requires approval, but approval policy is never」),点击、滑动全都做不了 | 给 iphone 这个 MCP 服务设 `default_tools_approval_mode="approve"`,由 `iphone_confirm` 把关 | 真机(Codex 任务里点击、按名字点都执行了) |
-| 65 | viewer 已经停了、任务已经停了,agent 的 MCP 服务还在继续操作手机 | 闸门连不上或任务已结束一律拒绝,并告诉 agent 停下 | 单测(`a_gate_nobody_listens_on_refuses`、`a_stopped_task_refuses_everything`)+ 真机(任务中途停止,之后没有新步骤,agent 进程组已结束) |
-| 66 | 暂停只挡住了界面上的按钮,agent 照样继续点 | 暂停、接管、等确认时,下一个工具调用在闸门处挂住,恢复后才放行 | 单测(`a_paused_task_holds_the_call_until_resumed`)+ 真机(暂停 8 秒没有新步骤) |
-| 67 | 用户接管时动过手机,交还后 agent 按旧的界面接着点 | 交还后第一个不是看屏幕的调用被拒,让它先截图 | 单测(`after_a_takeover_the_agent_looks_again_before_acting`)+ 真机(交还后先截图) |
+| 65 | viewer 已经停了、任务已经停了,agent 的 MCP 服务还在继续操作手机 | 连不上守护进程或任务已结束一律拒绝,并告诉 agent 停下;开任务的程序断开,任务就结束(abandoned) | 单测(`without_the_daemon_a_task_call_is_refused`、`an_ended_or_unknown_token_is_refused_for_everything`、`an_opened_task_holds_the_phone_until_its_lease_goes`)+ 真机(任务中途停止,之后没有新步骤,agent 进程组已结束) |
+| 66 | 暂停只挡住了界面上的按钮,agent 照样继续点 | 暂停、接管、等确认时,任务的请求在守护进程里挂住(包括一个工具调用中间的请求,如 `iphone_batch` 的下一步),恢复后才放行 | 单测(`a_paused_task_holds_its_requests_until_resumed`、`a_held_request_whose_caller_left_is_dropped`)+ 真机(暂停 8 秒没有新步骤) |
+| 67 | 用户接管时动过手机,交还后 agent 按旧的界面接着点 | 交还后、或别人动过手机后,任务的操作一直被拒,直到它截图或读过元素 | 单测(`after_someone_else_acted_the_agent_looks_before_acting`)+ 真机(交还后先截图) |
| 68 | 用户拒绝确认后 agent 正常结束,页面显示「已完成」 | 有被拒绝的一步就按「已停止」结束 | 单测(`a_rejected_confirmation_tells_the_agent_not_to_do_it`)+ 真机(拒绝删除世界时钟城市,没有删) |
| 69 | 按结果文字里的 `@(x,y)` 给所有步骤画点击标记,读元素的一步也被标成点击 | 只给 `iphone_tap_element` 的结果解析点击位置 | 单测(`only_a_tap_by_text_gets_a_mark_from_its_result`) |
| 70 | 其他网站用 `<img src="http://127.0.0.1:8200/api/elements">` 触发读元素,顺带自动解锁手机 | 浏览器标明 `Sec-Fetch-Site` 不是 same-origin / none 的读请求一律 403 | 单测(`reads_from_other_sites_are_refused`)+ curl |
@@ -109,6 +109,10 @@
| 103 | WDA 半死:`/status` 照常 200,前台 App、截图、读元素、`/wda/locked` 全部超时(iPad mini 5,iPadOS 26.7.3,后台启动的 WDA 跑 20~40 分钟后)。守护进程只看 `/status`,一直显示「就绪」,不重启;后台模式下守护进程重启还会把它接回来。只靠巡检探测也不够:卡死时工具调用一个接一个等满超时(每个 10~30 秒),设备被占好几分钟,巡检抢不到锁 | WDA 客户端数经 XCTest 的请求(`/status` 之外都是,工具调用和巡检探测 `/wda/activeAppInfo` 一样算)连续几次送到了却没有应答,有应答(哪怕是错误)就清零;连续 3 次就算卡死:之后经 XCTest 的请求直接报不可用,巡检和每个设备请求开头都会忘掉记下的后台 WDA、丢掉会话重新启动 | 单测 three_unanswered_requests_mean_stalled、xctest_probe_counts_only_missing_answers;真机:绕过守护进程让 WDA 长按(期间 `/status` 5 毫秒 200,`/wda/activeAppInfo` 超时)。空闲时 0.2.3 一直「就绪」,修复后约 28 秒判定卡死、34 秒恢复;同时经守护进程背靠背发工具调用时,main(#60)180 秒里 8 次调用各等 10~30 秒、不重启,修复后第 3 次超时(约 50 秒)就重启,13 秒后就绪,其间的调用立即返回;经守护进程连续长按 6×10 秒不误判 |
| 104 | iOS 27 以下(iPad mini 5,iPadOS 26.7.3)锁屏没锁上:经 IOHID 按电源键 3 秒后未锁、`/wda/lock` 报「Timed out while waiting until the screen gets locked」,之后退到 HID 后备路线,而低版本没有 HID,报的是「WDA 不可用(刚掉线)」,WDA 其实正常 | WDA 在、两种办法都没锁上、又没有 HID 后备时,报「没锁上屏」和两种办法各自的原因;有 HID 后备时照旧退到 HID | 单测 a_failed_lock_says_why_not_that_wda_is_down;真机:见 PR |
| 105 | iPad mini 5(iPadOS 26.7.3)一直锁不上屏:经 IOHID 按电源键 0.1 秒调用卡约 5.4 秒、不锁;`/wda/lock`(iOS 27 以下是 XCTest 的 `pressLockButton`)10 秒后报「Timed out while waiting until the screen gets locked」。iPhone 15 Pro Max(iOS 27.0.1)上 0.1 秒同样不认,每台第一次锁屏要退到 `/wda/lock`,约 10 秒 | 电源键按 0.15 秒(`POWER_PRESS_SECS`):iPad mini 5、iPhone 15 Pro Max 上 0.15~0.3 秒都能锁,iPhone 18 Pro Max(iOS 27.2.1)上 0.05~0.15 秒能锁、0.5 秒不行 | 单测 hid_buttons_send_consumer_page_events;真机:经 `wda-bridge` 每次先解锁再按不同时长,看 `/wda/locked`;经守护进程连续锁屏 3 次 |
+| 106 | AI 任务进行中,另一个 MCP 客户端或命令行照样能点手机,和 agent 抢着操作(监管只在 viewer 里) | 任务由守护进程管:不带任务口令的请求可以看,操作一律拒绝并说明是哪个任务,用户接管后才放行;切换设备一律拒绝 | 单测(`others_may_look_but_not_act_until_the_user_takes_over`、`an_opened_task_holds_the_phone_until_its_lease_goes`)+ 真机(任务进行中用 `iphone-control` 另开的 MCP 点击被拒,截图照常) |
+| 107 | 任务进行中在别处 `select` 或自动选设备换了一台,任务接着操作另一台手机 | 任务的请求固定发往开任务时的设备;控制的设备变成另一台时任务中断(interrupted) | 单测(`the_task_goes_to_its_own_device`、`another_device_interrupts_the_task`) |
+| 108 | 守护进程重启后任务和步骤记录都没了,也说不清任务怎么结束的 | 任务事件逐条落盘(`tasks/<id>.jsonl`,最多 50 个),重启后没结束的记成 interrupted,旧口令失效 | 单测(`logs_survive_a_restart_and_unfinished_tasks_are_interrupted`、`tasks_keep_their_order_across_a_restart_even_within_a_millisecond`、`only_the_newest_logs_are_kept`) |
+| 109 | 控制台刷新后不再跟踪正在进行的任务;在别处开的任务页面上看不到 | 页面接着跟刷新前的任务(事件从头重放),也接上在别处开的任务;守护进程不记得的才标成已停止 | 单测(`tests/viewer/tasks.test.mjs`)+ 无头 Chrome 或手动(任务进行中刷新页面) |
| 111 | 控制台上 AI 任务的总结直接显示 Markdown 原文(`**iOS 27.0.1**`、`- **设置**:…`),换行也被合并成一行 | 总结先整体转义,再按一小部分 Markdown 显示(粗体、斜体、行内代码、列表、标题、分隔线、换行、http(s) 链接),原始 HTML 一律当文字 | 页面测试(`tests/viewer/summary.test.mjs`)+ 真机(Claude Code、Codex 任务的总结) |
| 112 | iOS 27 上控制台用手机自己的视频时,系统权限弹窗(「允许“日历”使用你的位置?」)在画面里只剩变暗的屏幕,看不到弹窗本身,接管的人不知道该点哪里;agent 的截图里有 | 画面是手机自己的视频时,页面问守护进程有没有系统弹窗(`AlertCheck`;在 App 里每 2 秒,主屏幕上查一次约 0.6 秒,没弹窗时放慢到 6 秒,刚触摸后 3 秒内不问),有就照 iOS 弹窗的样子把它画在画面里它所在的位置(文字、按钮);按钮按坐标点(按名字点「允许」会点到「不允许」);AI 任务进行中按钮要先接管 | 单测(`a_system_alert_with_its_own_buttons`)+ 页面测试(`tests/viewer/alert.test.mjs`)+ 真机(弹出权限请求时页面显示弹窗和按钮,点按钮生效) |
| 113 | 在控制台画面上拖动、滑动时,触控板双指一碰就变成了缩放画面(双指捏合在浏览器里是按住 Ctrl 的滚轮) | 画面只用上方的加减号缩放;画面区域里的 Ctrl/⌘ + 滚轮、Safari 的 gesture 事件都拦下,既不缩放画面也不缩放整页;触屏上画面周围不允许双指缩放(`touch-action: pan-x pan-y`) | 页面测试(`tests/viewer/zoom.test.mjs`)+ 真机(在画面上双指捏合,缩放比例不变) |
diff --git a/docs/task-control.md b/docs/task-control.md
new file mode 100644
index 0000000..a5586dd
--- /dev/null
+++ b/docs/task-control.md
@@ -0,0 +1,206 @@
+# 任务控制:多个调用方共用一台手机
+
+这份文档记录「AI 任务怎么被人和程序监管」的目标架构、它和现状的差距,以及分步落地的顺序。为什么要把任务放进守护进程见 [D17](decisions.md#d17任务和租约放进守护进程2026-11-12)。缘起是 [#50](https://github.com/Derrors/iphone-control/issues/50):外部 Agent 平台想用控制台的步骤显示、暂停、接管和确认。
+
+## 1. 要解决的问题
+
+一台手机同一时间只能有一个操控者(D11),想用它的却很多:控制台里的 AI 任务、外部 Agent 平台、看着页面的人、命令行、定时任务。要做到:
+
+1. **独占**:同一时刻只有一方在操作手机。这一点要**强制**执行,不能靠各方自觉。
+2. **归属**:每个动作都能追到是哪个任务、哪个调用方做的,基于的是哪次观察。
+3. **监管**:暂停、接管、确认、取消在执行点生效,谁也绕不过去。
+4. **出错就停**:调用方不见了、设备变了、服务重启了,任务都停下来,不能没人看着继续操作。
+
+## 2. 目标架构
+
+```
+ 控制台(人) 命令行 外部平台适配层 内建 runner(Claude/Codex)
+ │ │ │ │
+ └─────────┴─── 控制面:任务 · 租约 · 确认 · 事件 ───┘
+ │
+ MCP 适配层(凭任务口令绑定到某个任务)
+ │ 数据面:设备动作
+ ┌─────────────────┴─────────────────┐
+ │ 守护进程:唯一的执行点 │
+ │ 租约 · 任务状态机 · 策略 · 确认 │
+ │ 步骤日志(落盘) · 事件流 │
+ └─────────────────┬─────────────────┘
+ 设备(WDA / HID)
+```
+
+### 2.1 原则:监管和执行在同一个地方
+
+守护进程本来就是唯一持有手机的进程(D2),所有动作都要在它那里排队拿锁。监管也应该放在这里:动作要经过准入检查(有没有租约、任务处于什么状态、设备对不对、策略允不允许)才执行。控制台、命令行、MCP 都只是客户端,谁都不能自己决定「现在可以操作」。
+
+如果监管放在某个客户端里(比如控制台),不经过它的调用方照样能操作手机。这种监管只拦得住愿意配合的调用方。
+
+### 2.2 概念
+
+| 概念 | 含义 |
+|---|---|
+| 主体(principal) | 调用方:人、外部平台、内建 runner |
+| 租约(lease) | 谁正在占用哪台设备。可以转移:接管时转给人,交还时还回来 |
+| 任务(task) | 一件事从开始到结束的全过程。属于某个主体,绑定一台设备 |
+| 步骤(step) | 一次动作:提出、准入、执行、结果,归在某个任务名下 |
+| 确认(approval) | 一个单独的待决定事项,有自己的编号和决定权 |
+
+### 2.3 状态机
+
+```
+Running ⇄ Paused
+Running / Paused → TakenOver → Running(交还后先重新看界面)
+Running → Waiting(等确认)→ Running
+终态:completed · failed · cancelled · rejected · abandoned(租约断了) · interrupted(设备变了或服务重启)
+```
+
+每次状态变化都追加写入任务日志。守护进程重启后,没结束的任务记成 interrupted,不会悄悄消失。审计记录也一直在。
+
+### 2.4 租约:用连接是否还在判断调用方是否还在
+
+开任务的调用方保持一条连接,这条连接就是租约。连接断了(进程退出、崩溃、被杀),任务就变成 abandoned,之后这个任务的动作一律拒绝。不用心跳和超时,也就没有心跳超时的误判。
+
+### 2.5 口令
+
+- **执行口令**(actor):交给 Agent。凭它操作手机、报告步骤、请求确认。
+- **控制口令**(controller):给任务的所有者,用来暂停、取消、确认。
+- **人**:对任何任务都能接管、停止。
+
+口令还可以限定范围:哪台设备、哪些 App、最多几步、最长多久。
+
+**边界要说清楚**:同一个系统用户下,进程能读到彼此的文件和环境,口令只是约定,不构成安全边界(和 D13 同理)。要让「只有所有者能确认」真正成立,必须让 Agent 换一个 uid 运行或者放进沙箱,同时守护进程用 `SO_PEERCRED` 认调用方。
+
+### 2.6 敏感动作:由策略拦截,不靠 Agent 自觉
+
+只看点击坐标,没法识别所有敏感操作。最有效的办法是**给任务划定范围**:开任务时声明它只在哪些 App 里操作。守护进程知道前台是哪个 App,任务越界就停下来等人。`iphone_confirm`(Agent 主动请求确认)作为补充。
+
+### 2.7 观察版本:人和 Agent 都动过手机时,动作建立在旧画面上怎么办
+
+每次观察(截图、读元素)都对应一个版本。别人(人或者其他调用方)动过手机之后,再来的动作如果不是基于新的观察,就拒绝执行,让 Agent 先重新看一遍。
+
+### 2.8 子步骤
+
+`iphone_batch` 这类一次发多个动作的请求,在每个动作之间都检查暂停和接管,而不是把整批当成一步。
+
+### 2.9 设备绑定
+
+开任务时绑定 UDID,之后每个动作都带上它。切换设备或拔掉设备时,任务停下(interrupted),需要人重新开始。
+
+### 2.10 只有一套接口
+
+- 控制面只有一套接口:本机用 Unix socket,以后需要远程时再加带认证的 HTTP。事件带编号,断线后能从断点接着收。
+- 内建的 Claude/Codex runner 也走这套接口。外部平台用的就是内建功能自己在用的那套,不另开一条路。
+- MCP 只是一层适配:靠任务口令绑定到某个任务。
+
+### 2.11 兼容
+
+不带任务口令的普通 MCP 调用,没有任务在跑时和以前完全一样。有任务在跑时,看界面(截图、读元素、状态)照常可以,操作手机会被拒绝,并说明原因。
+
+## 3. 现状与差距(2026-11-12,0.2.2 之后的 main)
+
+做对了、不用动的:
+
+- 守护进程独占设备,是唯一的排队点(D2)。准入时检查期望的设备(`expect_udid`),排队太久的动作丢掉,调用方走了的请求也丢掉(`core.rs` 的 `admit`)。
+- 任务只要出问题就拒绝:gate 不在、任务不在,一律拒绝。
+- 步骤由 gate 记录,不解析 Agent 的输出,所以和用哪个 Agent 无关。
+- 接管后要求先重新看界面(`recheck`),是观察版本的雏形。
+- socket 权限 0600;每个请求自带语言。
+
+差距(越靠前越根本):
+
+| # | 差距 | 现状 | 后果 |
+|---|---|---|---|
+| 1 | 监管不在执行点 | 任务、暂停、确认都在 viewer 进程里,MCP 主动来问 gate;守护进程不知道有任务这回事 | 普通 MCP、命令行在任务进行中照样能操作;不开控制台就没有任务 |
+| 2 | 没有租约 | 独占只靠 viewer 里的 `start()` 和 `manual_allowed()` 检查 | 互斥只在控制台里有效 |
+| 3 | 任务不落盘 | 只在内存里,保留最近 4 个 | 一重启就没了,没有审计记录 |
+| 4 | 状态不全 | `Running/Paused/Takeover/Waiting/Done`,再加 `ok`、`stopped` 两个标志 | 分不清放弃、中断和失败 |
+| 5 | 只有一个口令 | 每个任务一个口令,交给 Agent;控制靠「能访问本机 HTTP」 | 执行方和控制方分不开 |
+| 6 | 敏感动作靠 Agent 自觉 | 只有 `iphone_confirm` | Agent 不主动报,就拦不住 |
+| 7 | 设备绑定只做了一半 | 页面上的动作带 `expect_udid`,gate 下 MCP 的调用不带 | 任务进行中在命令行 `select`,任务就去操作另一台设备 |
+| 8 | 观察版本只覆盖一种情况 | `recheck` 只在控制台接管时触发 | 别人从命令行或其他 MCP 动过手机,Agent 不知道 |
+| 9 | 批量算一步 | `iphone_batch` 只过一次 gate | 暂停要等整批跑完才生效 |
+| 10 | 没有公共控制面 | 任务接口只有面向浏览器的 HTTP;内建 runner 的参数写死在 `agent_args` | 外部平台没有接入点 |
+| 11 | 只能靠子进程判断存活 | 只适用于 viewer 自己启动的 Agent | 外部 Agent 无法判断是否还活着 |
+| 12 | 单设备 | 和 D11 一致 | 有同时驱动多台的需求时再说 |
+
+## 4. 落地顺序
+
+差距 1 是根本:租约和任务状态机放进守护进程以后,2、3、4、7、8、9、10、11 都自然解决,或者变成小改动。差距 5、6 要等 Agent 在沙箱里运行、需要无人值守时才有实际意义,单用户本机部署时只会增加复杂度。
+
+| 阶段 | 内容 | 状态 |
+|---|---|---|
+| 一 | 任务和租约放进守护进程:控制面请求、准入检查、状态机、落盘、设备绑定、观察版本(简化版)、子步骤;内建 runner 和 MCP 改走守护进程;`iphone-control task` 命令给外部平台用 | 已完成(2026-11-12) |
+| 二 | 控制台接上正在进行的任务(刷新后、在别处开的);命令行查看事件 | 已完成(2026-11-12) |
+| 三 | 任务范围(App 白名单)和越界确认;执行口令与控制口令分开 | 等需要时 |
+| 四 | 带认证的 HTTP 控制面、HTTP MCP;局域网访问控制台(第 7 节);`SO_PEERCRED`;多设备租约 | 等需要时 |
+
+## 5. 阶段一的具体设计
+
+### 5.1 请求
+
+都是控制接口上的普通请求(每行一个 JSON),任务口令用请求键 `task` 传递,和 `lang`、`expect_udid` 一样:
+
+| 请求 | 谁发 | 作用 |
+|---|---|---|
+| `task_open { title, owner }` | 开任务的一方 | 绑定当前控制的设备,开一个任务。先回一行 `{id, token}`,然后这条连接就是租约,持续推送任务事件,直到任务结束;连接断了,任务就是 abandoned |
+| `task_events { id }` | 任何人 | 先重放已有事件,再接着推送新事件,任务结束时连接关闭 |
+| `task_list` | 任何人 | 最近的任务(含正在进行的) |
+| `task_control { id, action, step?, approve? }` | 人、所有者 | `pause`、`resume`、`takeover`、`handback`、`stop`、`confirm` |
+| `task_step { tool, args }` | 执行方(带口令) | 一个工具调用开始:任务不在 running 时一直等,然后记一步,返回步骤号 |
+| `task_step_done { step, ok, ms, text }` | 执行方 | 一个工具调用的结果 |
+| `task_confirm { action, detail }` | 执行方 | 等人确认 |
+| `task_note { text }` | 执行方、所有者 | Agent 说的话,归到下一步 |
+| `task_finish { ok, summary }` | 执行方、所有者 | 任务结束 |
+
+### 5.2 准入规则(`Daemon::handle`)
+
+有任务在进行(不在终态)时:
+
+- **带这个任务口令的请求**:任务不在 running 就一直等,调用方走了就放弃;等完后排队时间重新计算。请求固定发往任务绑定的设备。不能切换设备。交还控制或者别人动过手机之后,先要有一次观察,才接受下一个动作。
+- **不带口令的请求**:查看类(截图、读元素、状态、列 App 等)照常执行。动作类只在 takeover(人接管)时接受,接受后给任务记上「需要重新观察」;其他状态下一律拒绝并说明原因(抬起手指除外)。切换设备、手动重签同样拒绝。
+- **带的口令属于已结束或不存在的任务**:任何请求都拒绝,提示「任务已结束,停下来」。
+
+没有任务在进行时,和以前完全一样。
+
+### 5.3 落盘
+
+每个任务一个 `tasks/<id>.jsonl`,每行一个事件,最多保留 50 个。守护进程启动时把没有 `done` 的任务补成 interrupted。
+
+### 5.4 给外部平台用
+
+`iphone-control task run --title … -- <命令>`:开任务、保持租约,带着 `IPHONE_CONTROL_TASK_TOKEN`(以及 `IPHONE_CONTROL_TASK_ID`)启动命令,命令里的 `iphone-control mcp` 会自动加入任务。命令结束时任务随之结束,结果取命令的退出码;命令想写总结时自己调 `iphone-control task finish …`。任务在别处被停止时,结束这个命令的整个进程组。Ctrl-C 或 SIGTERM 等于停止任务。适配层只需要包一层,不用自己实现协议。
+
+## 6. 阶段一、二之后还差什么
+
+和第 2 节的目标架构相比:
+
+- **口令只有一种**(2.5):开任务的一方拿到的口令同时交给 Agent,控制请求(暂停、确认)不验口令。在同一个用户下这本来就不是边界(D13、D17),等 Agent 跑进沙箱时再分开,届时加上 `SO_PEERCRED`。
+- **没有策略和任务范围**(2.6):敏感动作仍然靠 Agent 调 `iphone_confirm`。
+- **观察版本是简化版**(2.7):只有一个「需要重新看」的标记,在交还、或别人在接管期间动过手机后置上,Agent 截图、读元素或等文字之后清掉。动作不带「基于哪次观察」,所以 Agent 自己连续操作时不做这项检查。
+- **事件不带编号**(2.10):重连时从头重放,没有从断点继续。任务事件全是文字,从头重放代价不大。
+- **设备拔掉时**(2.9):任务不中断,它的请求会被拒绝(找不到绑定的设备),插回同一台手机后可以继续;只有换成另一台设备才中断。
+- **单设备**(D11)、**只在本机**(没有 HTTP 控制面):按原计划留给阶段四。
+
+## 7. 阶段四的需求
+
+### 7.1 局域网访问控制台(2026-11-13 提出)
+
+**场景**:守护进程和手机在一台机器上(比如 NAS),人在局域网里另一台电脑的浏览器上看控制台、操作手机、开 AI 任务,不想每次先建 SSH 隧道。
+
+**现状**:控制台只绑 `127.0.0.1`,没有改的参数;请求的 `Host` 必须是 `127.0.0.1`/`localhost`/`[::1]`(防 DNS rebinding),操作的 `Origin` 必须是页面自己的这几个地址;没有登录(D3)。局域网里用 SSH 隧道:`ssh -L 8202:127.0.0.1:8202 <用户>@<主机>`,浏览器开 `http://127.0.0.1:8202/`。在做之前,这是推荐的办法。
+
+**要求**:
+
+1. **显式开启,默认不变**:默认仍然只监听本机(D3)。开局域网要明确配置监听地址(例如 `viewer --listen 0.0.0.0:8202`,或设置文件里的一项),启动时提示谁能连上。
+2. **必须认证**:开了局域网监听就必须配访问令牌(或密码),没配就拒绝启动,不能退回「谁都能连」。令牌存在设置文件里(0600);浏览器登录一次后用 `HttpOnly`、`SameSite=Strict` 的 cookie;输错限速。MCP、命令行等非浏览器客户端用 `Authorization: Bearer`。
+3. **Host / Origin 检查照样做**:认可的从「只认回环」改成「回环 + 配置的主机名或 IP」;不在名单里的 `Host` 一律拒绝(DNS rebinding 依然要防),操作的 `Origin` 必须是这些地址之一。
+4. **HTTPS**:WebCodecs 只在安全上下文(HTTPS,或 `127.0.0.1`/`localhost`)里可用,用普通 HTTP 从局域网 IP 打开时,H.264 / 手机自己的 HEVC 画面都解不了,只能退回每秒 4~10 MB 的 MJPEG。所以局域网访问要支持 HTTPS:用户提供证书,或者自动生成自签证书并显示指纹供第一次核对。令牌在 HTTP 上明文传输也是一个理由。
+5. **能做什么分开**:至少区分「只看画面和状态」和「操作手机、开 AI 任务、确认」两种令牌(对应 2.5 的口令分开);任务事件里记下是哪个令牌(哪个人)暂停、接管、确认的。
+6. **和控制面是同一件事**:局域网里的控制台用的就是第 2.10 节的 HTTP 控制面,外部 Agent 平台跨主机接入(HTTP MCP)用同一套认证,不另做一套。
+
+**验收**:
+
+- 默认安装不监听任何网卡(和现在一样)。
+- 开了局域网监听、没配令牌:拒绝启动并说明原因。
+- 局域网另一台电脑:用令牌登录后能看画面(H.264 或 HEVC,不退回 MJPEG)、操作、开 AI 任务、暂停、确认。
+- 没有令牌、令牌错误、`Host` 不在名单里、来自别的网页的 `Origin`:一律拒绝。
+- 只读令牌:能看画面和状态,操作、开任务、确认都被拒绝。
diff --git a/docs/tools.md b/docs/tools.md
index 8839a8a..9a271a3 100644
--- a/docs/tools.md
+++ b/docs/tools.md
@@ -59,15 +59,15 @@ How `iphone_app_logs` records:
See [SECURITY.md](../SECURITY.md#developer-tools) before turning these tools on.
-## Tasks from the web viewer
+## Tasks
-When `iphone-control viewer` runs an AI task, it starts the agent with this MCP server and two environment variables, `ICTL_AGENT_GATE` and `ICTL_AGENT_TOKEN`. With them set, every tool call is first reported to the viewer, which shows it as a step, holds it while the task is paused or the user has taken over, and refuses it once the task is stopped; the result (and the screenshot, if any) is reported back afterwards. One more tool is listed:
+An AI task (docs/task-control.md) is kept by the daemon. While one runs, only requests carrying its token act on the phone; anyone else may look (screenshots, elements, status) but is refused for actions until the user takes over. `iphone-control viewer` starts its agents in a task, and `iphone-control task run -- <command>` does the same for any other agent platform. Both hand the token to this MCP server in `IPHONE_CONTROL_TASK_TOKEN`. With it set, every tool call is first announced to the daemon, which records it as a step for the control page, holds it while the task is paused, taken over or waiting for a confirmation, and refuses it once the task ended; the result is reported back afterwards. One more tool is listed:
| Tool | Parameters | Notes |
|---|---|---|
-| `iphone_confirm` | `action`, `detail` | Asks the user on the page to confirm one step (paying, deleting, sending a message, changing account settings…) and waits for the answer. A normal result means approved; an error means rejected or the task ended, and the agent must not do the step |
+| `iphone_confirm` | `action`, `detail` | Asks the user to confirm one step (paying, deleting, sending a message, changing account settings…) and waits for the answer, given on the control page or with `iphone-control task approve` / `reject`. A normal result means approved; an error means rejected or the task ended, and the agent must not do the step |
-Without the variables, the tool list and every call are unchanged.
+Without the variable, the tool list and every call are unchanged; while a task runs, a plain MCP server's actions are refused with a message that says which task holds the phone.
## Auto-unlock and "read-only" tools
diff --git a/tests/device/tasks.py b/tests/device/tasks.py
new file mode 100644
index 0000000..6d59029
--- /dev/null
+++ b/tests/device/tasks.py
@@ -0,0 +1,486 @@
+"""Real-device scenarios for AI tasks kept by the daemon (docs/task-control.md; regression cases #65–67, #106–110).
+
+ pip install -r tests/device/requirements.txt
+ python tests/device/tasks.py # every scenario except `restart`
+ python tests/device/tasks.py pause scope # only these
+ python tests/device/tasks.py restart --restart 'systemctl --user restart iphone-control'
+
+It plays an agent platform: opens tasks on the daemon's control socket (holding the lease the way `task run` does),
+starts one MCP server with the task's token (the agent) and one without (anyone else), steers the task with the
+`iphone-control task …` commands and checks what the daemon lets through. Every check prints a PASS / FAIL line with
+what came back; the last line sums up, and the exit code is 1 if anything failed. Paste the output into the pull
+request (CONTRIBUTING.md, "Required tests", part 4).
+
+Harmless by design: it presses Home, opens Settings and Clock, takes screenshots, and refuses the two links it tries
+to 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`).
+"""
+
+import argparse
+import asyncio
+import json
+import os
+import shlex
+import sys
+import tempfile
+import time
+from contextlib import AsyncExitStack
+
+from mcp import ClientSession
+from mcp.client.stdio import StdioServerParameters, stdio_client
+
+BIN = shlex.split(os.environ.get("ICTL_BIN", "iphone-control"))
+MCP_CMD = shlex.split(os.environ.get("MCP_CMD", "")) or [*BIN, "mcp"]
+SOCKET = os.environ.get("ICTL_SOCKET") or os.path.join(
+ os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"), "iphone-control", "ctl.sock"
+)
+TOKEN_ENV = "IPHONE_CONTROL_TASK_TOKEN"
+OWNER = "device-test"
+HERE = os.path.dirname(os.path.abspath(__file__))
+
+results: list[bool] = []
+
+
+def short(text: str, n: int = 160) -> str:
+ one = " ".join(text.split())
+ return one if len(one) <= n else one[: n - 1] + "…"
+
+
+def check(case: str, what: str, ok: bool, got: str = "") -> bool:
+ results.append(ok)
+ print(f"{'PASS' if ok else 'FAIL'} [{case}] {what}" + (f" ← {short(got)}" if got else ""), flush=True)
+ return ok
+
+
+# ---------------------------------------------------------------- the daemon's control socket
+
+
+async def ask(req: dict, timeout: float = 15) -> dict:
+ r, w = await asyncio.open_unix_connection(SOCKET)
+ try:
+ w.write((json.dumps(req, ensure_ascii=False) + "\n").encode())
+ await w.drain()
+ return json.loads(await asyncio.wait_for(r.readline(), timeout))
+ finally:
+ w.close()
+
+
+async def tasks() -> list[dict]:
+ r = await ask({"op": "task_list"})
+ if r.get("kind") != "text":
+ raise RuntimeError(f"task_list: {r}")
+ return json.loads(r["text"])
+
+
+async def info(task_id: str) -> dict:
+ return next((t for t in await tasks() if t["id"] == task_id), {})
+
+
+async def wait_for(cond, timeout: float = 15, every: float = 0.2):
+ """Polls the async `cond()` until it returns something truthy; returns that, or None on timeout"""
+ end = time.time() + timeout
+ while time.time() < end:
+ v = await cond()
+ if v:
+ return v
+ await asyncio.sleep(every)
+ return None
+
+
+async def state_is(task_id: str, state: str, timeout: float = 15) -> bool:
+ async def ok():
+ return (await info(task_id)).get("state") == state
+
+ return bool(await wait_for(ok, timeout))
+
+
+class Lease:
+ """An opened task: the connection is its lease, and its events are collected as they come"""
+
+ def __init__(self):
+ self.id = self.token = ""
+ self.events: list[dict] = []
+ self._w = None
+ self._reader = None
+
+ @classmethod
+ async def open(cls, title: str, apps=()):
+ self = cls()
+ r, self._w = await asyncio.open_unix_connection(SOCKET)
+ req = {"op": "task_open", "title": title, "owner": OWNER, "apps": list(apps)}
+ self._w.write((json.dumps(req, ensure_ascii=False) + "\n").encode())
+ await self._w.drain()
+ first = json.loads(await asyncio.wait_for(r.readline(), 60))
+ if first.get("kind") != "text":
+ self._w.close()
+ raise RuntimeError(first.get("message", first))
+ opened = json.loads(first["text"])
+ self.id, self.token = opened["id"], opened["token"]
+ self._reader = asyncio.create_task(self._read(r))
+ return self
+
+ async def _read(self, r):
+ while line := await r.readline():
+ try:
+ self.events.append(json.loads(line))
+ except ValueError:
+ pass
+
+ def of(self, kind: str) -> list[dict]:
+ return [e["data"] for e in self.events if e["event"] == kind]
+
+ def done(self):
+ return next(iter(self.of("done")), None)
+
+ async def finish(self, ok: bool = True, summary: str = "device test"):
+ return await ask({"op": "task_finish", "ok": ok, "summary": summary, "task": self.token})
+
+ def close(self):
+ if self._w:
+ self._w.close()
+ self._w = None
+
+
+# ---------------------------------------------------------------- MCP servers and the CLI
+
+
+async def mcp(stack: AsyncExitStack, token: str | None) -> ClientSession:
+ env = dict(os.environ)
+ env.pop(TOKEN_ENV, None)
+ if token:
+ env[TOKEN_ENV] = token
+ params = StdioServerParameters(command=MCP_CMD[0], args=MCP_CMD[1:], env=env)
+ r, w = await stack.enter_async_context(stdio_client(params))
+ s = await stack.enter_async_context(ClientSession(r, w))
+ await s.initialize()
+ return s
+
+
+async def call(s: ClientSession, name: str, args: dict | None = None, timeout: float = 90):
+ """(is_error, text, seconds)"""
+ t = time.time()
+ res = await asyncio.wait_for(s.call_tool(name, args or {}), timeout)
+ text = "\n".join(c.text for c in res.content if c.type == "text")
+ return bool(res.is_error), text, time.time() - t
+
+
+async def cli(*args: str, timeout: float = 30):
+ """`iphone-control task …`: (exit code, output)"""
+ p = await asyncio.create_subprocess_exec(
+ *BIN, "task", *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT
+ )
+ out, _ = await asyncio.wait_for(p.communicate(), timeout)
+ return p.returncode, out.decode(errors="replace").strip()
+
+
+async def confirm_asked(lease: Lease, before: int, timeout: float = 30):
+ """Waits until the task waits for a confirmation it didn't have before; returns the confirmation"""
+
+ async def asked():
+ c = lease.of("confirm")
+ return c[-1] if len(c) > before and (await info(lease.id)).get("state") == "waiting" else None
+
+ return await wait_for(asked, timeout)
+
+
+# ---------------------------------------------------------------- scenarios
+
+
+async def others(stack):
+ """#106: while a task runs, anyone else may look but not act; the task's agent may"""
+ c = "others"
+ lease = await Lease.open("真机回归:任务进行中别人只能看")
+ stack.callback(lease.close)
+ agent, other = await mcp(stack, lease.token), await mcp(stack, None)
+ names = lambda r: {t.name for t in r.tools} # noqa: E731
+ check(c, "the agent's MCP server lists iphone_confirm", "iphone_confirm" in names(await agent.list_tools()))
+ check(c, "a plain MCP server doesn't", "iphone_confirm" not in names(await other.list_tools()))
+ err, text, dt = await call(other, "iphone_screenshot")
+ check(c, f"another caller may take a screenshot ({dt:.2f}s)", not err, text)
+ err, text, dt = await call(other, "iphone_press_button", {"button": "home"})
+ check(c, f"another caller's Home is refused, naming the task ({dt:.2f}s)", err and lease.id in text, text)
+ # the device it already controls: harmless even if it went through (`auto` would undo a pinned choice)
+ udid = (await info(lease.id)).get("udid", "")
+ err, text, _ = await call(other, "iphone_select_device", {"device": udid})
+ check(c, "selecting a device is refused", err, text)
+ err, text, dt = await call(agent, "iphone_press_button", {"button": "home"})
+ check(c, f"the agent's Home goes through ({dt:.2f}s)", not err, text)
+ steps = [s for s in lease.of("step") if s.get("tool") == "iphone_press_button"]
+ check(c, "the agent's call is a step of the task", bool(steps), json.dumps(steps[:1], ensure_ascii=False))
+ await lease.finish()
+ check(c, "finished as completed", await state_is(lease.id, "completed"))
+ err, text, dt = await call(other, "iphone_press_button", {"button": "home"})
+ check(c, f"after the task, anyone may act again ({dt:.2f}s)", not err, text)
+
+
+async def pause(stack):
+ """#66: a paused task's calls wait in the daemon, also between the steps of iphone_batch"""
+ c = "pause"
+ lease = await Lease.open("真机回归:暂停")
+ stack.callback(lease.close)
+ agent = await mcp(stack, lease.token)
+ code, out = await cli("pause", lease.id)
+ check(c, "`task pause` works", code == 0, out)
+ began = lambda: len([s for s in lease.of("step") if "tool" in s]) # noqa: E731
+ n = began()
+ held = asyncio.create_task(call(agent, "iphone_screenshot"))
+ await asyncio.sleep(5)
+ check(c, "a call while paused is held (5 s, no result)", not held.done())
+ check(c, "and no new step shows up", began() == n)
+ code, out = await cli("resume", lease.id)
+ check(c, "`task resume` works", code == 0, out)
+ err, text, dt = await asyncio.wait_for(held, 60)
+ check(c, f"after resuming it runs ({dt:.1f}s in all)", not err and dt >= 5, text)
+
+ steps = [{"tool": "iphone_press_button", "button": "home"}, {"tool": "wait", "seconds": 3}, {"tool": "iphone_press_button", "button": "home"}]
+ batch = asyncio.create_task(call(agent, "iphone_batch", {"steps": steps}))
+ await asyncio.sleep(1.5)
+ await cli("pause", lease.id)
+ await asyncio.sleep(5)
+ check(c, "a batch paused in its wait doesn't take its next step (held 5 s after a 3 s wait)", not batch.done())
+ await cli("resume", lease.id)
+ err, text, dt = await asyncio.wait_for(batch, 60)
+ check(c, f"after resuming the batch finishes ({dt:.1f}s in all)", not err and dt >= 6, text)
+ await lease.finish()
+
+
+async def handback(stack):
+ """#67: the user may act while the task is taken over; after handing back, the agent looks before acting"""
+ c = "handback"
+ lease = await Lease.open("真机回归:接管和交还")
+ stack.callback(lease.close)
+ agent, other = await mcp(stack, lease.token), await mcp(stack, None)
+ code, out = await cli("takeover", lease.id)
+ check(c, "`task takeover` works", code == 0 and await state_is(lease.id, "takeover"), out)
+ err, text, dt = await call(other, "iphone_press_button", {"button": "home"})
+ check(c, f"while taken over, the user's Home goes through ({dt:.2f}s)", not err, text)
+ code, out = await cli("handback", lease.id)
+ check(c, "`task handback` works", code == 0 and await state_is(lease.id, "running"), out)
+ err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
+ check(c, "the agent's first action is refused: look first", err and "iphone_screenshot" in text, text)
+ err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
+ check(c, "and the next one too, until it has looked", err, text)
+ err, text, _ = await call(agent, "iphone_screenshot")
+ check(c, "a screenshot goes through", not err, text)
+ err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
+ check(c, "after it, the agent acts again", not err, text)
+ await lease.finish()
+
+
+async def confirm(stack):
+ """iphone_confirm waits for `task approve` / `task reject`; a rejection ends the task as rejected"""
+ c = "confirm"
+ lease = await Lease.open("真机回归:确认")
+ stack.callback(lease.close)
+ agent = await mcp(stack, lease.token)
+ code, out = await cli("approve", lease.id)
+ check(c, "`task approve` with nothing waiting fails", code != 0, out)
+ args = {"action": "真机回归:测试确认", "detail": "只是测试,同意或拒绝都不会在手机上做任何事"}
+ for approve in (True, False):
+ before = len(lease.of("confirm"))
+ asking = asyncio.create_task(call(agent, "iphone_confirm", args))
+ shown = await confirm_asked(lease, before)
+ check(c, "the task waits, with the confirmation shown", bool(shown), json.dumps(shown, ensure_ascii=False))
+ code, out = await cli("approve" if approve else "reject", lease.id)
+ err, text, dt = await asyncio.wait_for(asking, 30)
+ what = "approved: a normal result" if approve else "rejected: an error the agent must stop on"
+ check(c, f"{what} ({dt:.1f}s)", code == 0 and err != approve, text)
+ await lease.finish(ok=True)
+ check(c, "the task ends as rejected though the agent said ok", await state_is(lease.id, "rejected"))
+
+
+async def stop(stack):
+ """#65: once stopped, the task's token is refused for everything"""
+ c = "stop"
+ lease = await Lease.open("真机回归:停止")
+ stack.callback(lease.close)
+ agent = await mcp(stack, lease.token)
+ err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
+ check(c, "the agent acts", not err, text)
+ code, out = await cli("stop", lease.id)
+ check(c, "`task stop` works", code == 0, out)
+ done = await wait_for(lambda: asyncio.sleep(0, lease.done()), 10)
+ check(c, "the opener hears it ended (cancelled)", bool(done) and done.get("outcome") == "cancelled", json.dumps(done, ensure_ascii=False))
+ for tool in ("iphone_press_button", "iphone_screenshot"):
+ err, text, _ = await call(agent, tool, {"button": "home"} if tool == "iphone_press_button" else {})
+ check(c, f"afterwards the agent's {tool} is refused", err, text)
+
+
+async def lease(stack):
+ """#65: the opener going away ends the task as abandoned; the agent stops, others may act again"""
+ c = "lease"
+ t = await Lease.open("真机回归:发起方断开")
+ agent, other = await mcp(stack, t.token), await mcp(stack, None)
+ t.close()
+ check(c, "closing the lease ends the task as abandoned", await state_is(t.id, "abandoned", 10))
+ err, text, _ = await call(agent, "iphone_screenshot")
+ check(c, "the agent is refused", err, text)
+ err, text, _ = await call(other, "iphone_press_button", {"button": "home"})
+ check(c, "others may act again", not err, text)
+
+
+async def run_cmd(stack):
+ """`task run`: the integration for agent platforms (#50), end to end and when stopped from elsewhere"""
+ c = "run"
+ title = f"真机回归:task run {int(time.time())}"
+ steps = [
+ ["iphone_status", {}],
+ ["iphone_press_button", {"button": "home"}],
+ ["iphone_launch_app", {"app": "时钟"}],
+ ["iphone_list_elements", {"limit": 5}],
+ ["iphone_press_button", {"button": "home"}],
+ ]
+ env = {**os.environ, "MCP_CMD": shlex.join(MCP_CMD), "SHOTS_DIR": tempfile.mkdtemp(prefix="ictl-shots-")}
+ env.pop(TOKEN_ENV, None)
+ p = await asyncio.create_subprocess_exec(
+ *BIN, "task", "run", "--title", title, "--owner", OWNER, "--",
+ sys.executable, os.path.join(HERE, "run.py"), json.dumps(steps, ensure_ascii=False),
+ 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("---")]
+ check(c, "run.py under `task run` passes (exit 0)", p.returncode == 0, last[-1] if last else out[-300:])
+ t = next((t for t in reversed(await tasks()) if t["title"] == title), {})
+ 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 被停止 {int(time.time())}"
+ p = await asyncio.create_subprocess_exec(
+ *BIN, "task", "run", "--title", title, "--owner", OWNER, "--", "sleep", "600",
+ stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
+ )
+
+ async def running():
+ return next((t for t in await tasks() if t["title"] == title and t["state"] == "running"), None)
+
+ t = await wait_for(running, 20)
+ check(c, "`task run -- sleep 600` opens a task", bool(t))
+ if t:
+ t0 = time.time()
+ await cli("stop", t["id"])
+ code = await asyncio.wait_for(p.wait(), 15)
+ check(c, f"`task stop` ends the command too ({time.time() - t0:.1f}s, exit {code})", code != 0)
+ check(c, "and the task is cancelled", await state_is(t["id"], "cancelled"))
+ elif p.returncode is None:
+ p.kill()
+
+
+async def scope(stack):
+ """#110: a task limited to Settings asks before going elsewhere; approving lets it in, rejecting refuses one step"""
+ c = "scope"
+ lease = await Lease.open("真机回归:只在设置里", apps=["设置"])
+ stack.callback(lease.close)
+ apps = (await info(lease.id)).get("apps", [])
+ if not apps:
+ print(f"SKIP [{c}] this daemon has no app scope (feat/task-scope)", flush=True)
+ await lease.finish()
+ return
+ check(c, "「设置」 resolved to its bundle ID", "com.apple.Preferences" in apps, ", ".join(apps))
+ agent = await mcp(stack, lease.token)
+ asked = lambda: len(lease.of("confirm")) # noqa: E731
+
+ n = asked()
+ err, text, _ = await call(agent, "iphone_launch_app", {"app": "设置"})
+ check(c, "launching Settings doesn't ask", not err and asked() == n, text)
+
+ async def outside(name, args, approve):
+ n = asked()
+ doing = asyncio.create_task(call(agent, name, args))
+ shown = await confirm_asked(lease, n)
+ check(c, f"{name} {json.dumps(args, ensure_ascii=False)} waits for the user", bool(shown), json.dumps(shown, ensure_ascii=False))
+ await cli("approve" if approve else "reject", lease.id)
+ err, text, dt = await asyncio.wait_for(doing, 60)
+ check(c, f"…{'approved: done' if approve else 'rejected: refused, the task goes on'} ({dt:.1f}s)", err != approve, text)
+ return shown
+
+ shown = await outside("iphone_launch_app", {"app": "时钟"}, False)
+ check(c, "the question names the app", bool(shown) and "mobiletimer" in json.dumps(shown))
+ check(c, "the task is still running", (await info(lease.id)).get("state") == "running")
+ err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
+ check(c, "Home (the way back) isn't checked", not err, text)
+ await outside("iphone_launch_app", {"app": "时钟"}, True)
+ check(c, "Clock joined the scope", "com.apple.mobiletimer" in (await info(lease.id)).get("apps", []))
+ n = asked()
+ err, text, _ = await call(agent, "iphone_tap_element", {"text": "不存在的按钮xyz"})
+ check(c, "acting in Clock no longer asks (and taps nothing)", asked() == n, text)
+ await outside("iphone_open_url", {"url": "ictl-device-test://nothing"}, False)
+ await outside("iphone_open_url", {"url": "https://example.com"}, False)
+ err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
+ await lease.finish()
+ check(c, "the task completes (refusals don't make it rejected)", await state_is(lease.id, "completed"))
+
+
+async def restart(stack, cmd: str):
+ """#108: the daemon restarting interrupts the task; its old token means nothing afterwards"""
+ c = "restart"
+ lease = await Lease.open("真机回归:守护进程重启")
+ agent = await mcp(stack, lease.token)
+ err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
+ check(c, "the agent acts", not err, text)
+ p = await asyncio.create_subprocess_shell(cmd)
+ check(c, f"restart command `{cmd}`", await p.wait() == 0)
+
+ async def answers():
+ try:
+ return await info(lease.id)
+ except OSError:
+ return None
+
+ t = await wait_for(answers, 120, 1)
+ check(c, "after the restart the task is interrupted", (t or {}).get("state") == "interrupted", json.dumps(t, ensure_ascii=False))
+ err, text, _ = await call(agent, "iphone_screenshot", timeout=180)
+ check(c, "the old token is refused", err, text)
+ lease.close()
+
+
+SCENARIOS = {
+ "others": others,
+ "pause": pause,
+ "handback": handback,
+ "confirm": confirm,
+ "stop": stop,
+ "lease": lease,
+ "run": run_cmd,
+ "scope": scope,
+}
+
+
+async def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ ap.add_argument("only", nargs="*", help=f"scenarios ({', '.join([*SCENARIOS, 'restart'])}); all but restart if none")
+ ap.add_argument("--restart", metavar="CMD", help="shell command that restarts the daemon, for `restart`")
+ a = ap.parse_args()
+ names = a.only or list(SCENARIOS)
+ unknown = [n for n in names if n not in SCENARIOS and n != "restart"]
+ if unknown or ("restart" in names and not a.restart):
+ ap.error(f"unknown {unknown}" if unknown else "restart needs --restart CMD")
+ print(f"=== {shlex.join(BIN)} ({SOCKET}), MCP: {shlex.join(MCP_CMD)}", flush=True)
+ t0 = time.time()
+ for name in names:
+ busy = [t for t in await tasks() if t["state"] in ("running", "paused", "takeover", "waiting")]
+ if busy:
+ print(f"FAIL [{name}] another task is active ({busy[0]['id']}, {busy[0]['title']}); not run", flush=True)
+ results.append(False)
+ continue
+ print(f"--- {name}", flush=True)
+ t = time.time()
+ async with AsyncExitStack() as stack:
+ 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
+ check(name, f"scenario raised {type(e).__name__}", False, str(e))
+ finally:
+ # never leave a task holding the phone
+ for t_ in await tasks():
+ if t_["state"] in ("running", "paused", "takeover", "waiting") and t_["owner"] == OWNER:
+ await ask({"op": "task_control", "id": t_["id"], "action": "stop"})
+ print(f" ({time.time() - t:.1f}s)", flush=True)
+ failed = results.count(False)
+ print(f"--- {len(results)} checks, {failed} failed, {time.time() - t0:.1f}s in all", flush=True)
+ return 1 if failed else 0
+
+
+if __name__ == "__main__":
+ sys.exit(asyncio.run(main()))
diff --git a/tests/viewer/tasks.test.mjs b/tests/viewer/tasks.test.mjs
new file mode 100644
index 0000000..841b053
--- /dev/null
+++ b/tests/viewer/tasks.test.mjs
@@ -0,0 +1,101 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { test } from 'node:test';
+import { runInNewContext } from 'node:vm';
+
+const html = readFileSync(new URL('../../apps/iphone-control/src/viewer.html', import.meta.url), 'utf8');
+
+// The page's task handlers, with the network and rendering replaced (same approach as actions.test.mjs)
+function handlers(names, context) {
+ const functions = names.map(name => {
+ const match = html.match(new RegExp(`^(?:async )?function ${name}\\([^]*?^}`, 'm'));
+ assert.ok(match, name);
+ return match[0];
+ });
+ return runInNewContext(functions.join('\n') + '\n({' + names.join(', ') + '})', context);
+}
+
+const ACTIVE = ['running', 'paused', 'takeover', 'waiting'];
+const noop = () => {};
+
+function page(tasks, serverTasks) {
+ const S = { mode: 'live', tasks, seq: tasks.length, expanded: new Set(), agents: [] };
+ const followed = [], shown = [];
+ const context = {
+ S, ACTIVE, adopting: false, tr: String, show: m => shown.push(m), renderAll: noop, scrollConvo: noop,
+ BUILTIN_AGENTS: { claude: 'Claude Code', codex: 'Codex' },
+ activeTask: () => S.tasks.find(t => ACTIVE.includes(t.status)),
+ follow: (task, id) => { task.remoteId = id; followed.push([task, id]); },
+ calls: 0,
+ async api(path) { context.calls++; assert.equal(path, '/api/agent/tasks'); return { tasks: serverTasks }; },
+ };
+ return { S, followed, shown, context, ...handlers(['isExternal', 'lostTask', 'adoptTask'], context) };
+}
+
+test('a task that was running before the reload is followed again', async () => {
+ const mine = { id: 't1', status: 'running', steps: [{ id: 1, status: 'running' }], remoteId: 'abc', reattach: true };
+ const { followed, adoptTask } = page([mine], [{ id: 'abc', state: 'paused', title: 'x', owner: 'claude' }]);
+ await adoptTask();
+ assert.deepEqual(followed.map(([t, id]) => [t.id, id]), [['t1', 'abc']]);
+ assert.equal(mine.reattach, false);
+ assert.equal(mine.status, 'running', 'the replayed events set the state');
+});
+
+test('a task the daemon no longer knows is marked stopped', async () => {
+ const mine = { id: 't1', status: 'waiting', steps: [{ id: 1, status: 'waiting' }], remoteId: 'gone', reattach: true };
+ const { followed, adoptTask } = page([mine], []);
+ await adoptTask();
+ assert.equal(followed.length, 0);
+ assert.equal(mine.status, 'stopped');
+ assert.equal(mine.steps[0].status, 'stopped');
+});
+
+test('a task started elsewhere shows up with its title and who runs it', async () => {
+ const done = { id: 't1', status: 'success', steps: [], remoteId: 'old' };
+ const server = [{ id: 'old', state: 'completed' }, { id: 'ext', state: 'running', title: '查天气', owner: 'happyclaw', started: 5 }];
+ const { S, followed, shown, adoptTask } = page([done], server);
+ await adoptTask();
+ assert.equal(S.tasks.length, 2);
+ assert.deepEqual(shown, ['接上了一个正在进行的外部任务'], 'not called an AI task');
+ const t = S.tasks[1];
+ assert.deepEqual([t.prompt, t.agent, t.status, t.startedAt], ['查天气', 'happyclaw', 'running', 5]);
+ assert.deepEqual(followed.map(([, id]) => id), ['ext']);
+ await adoptTask();
+ assert.equal(S.tasks.length, 2, 'only once');
+});
+
+test('nothing to ask while this page follows its own task', async () => {
+ const mine = { id: 't1', status: 'running', steps: [], remoteId: 'abc' };
+ const { context, adoptTask } = page([mine], []);
+ await adoptTask();
+ assert.equal(context.calls, 0);
+});
+
+function who(agents = []) {
+ const S = { agents, tasks: [] };
+ const context = { S, tr: String };
+ runInNewContext(html.match(/^const BUILTIN_AGENTS = .*$/m)[0] + '\nthis.BUILTIN_AGENTS = BUILTIN_AGENTS;', context);
+ return { S, ...handlers(['isExternal', 'agentLabel'], context) };
+}
+
+test('each task shows who runs it; a task opened elsewhere is marked external', () => {
+ const { isExternal, agentLabel } = who([{ id: 'claude', name: 'Claude Code', available: true }]);
+ const live = agent => ({ source: 'live', agent });
+ assert.equal(agentLabel(live('claude')), 'Claude Code');
+ assert.equal(agentLabel(live('codex')), 'Codex', 'known even before the backends are read');
+ assert.equal(agentLabel(live('happyclaw')), 'happyclaw · 外部任务');
+ assert.equal(agentLabel({ source: 'demo', agent: 'claude' }), 'AI 助手');
+ assert.equal(agentLabel({ source: 'live' }), 'AI 助手', 'records saved before the agent was kept');
+ assert.deepEqual([live('claude'), live('codex'), live('external'), { source: 'live' }].map(isExternal), [false, false, true, false]);
+});
+
+test('a task opened elsewhere is never run again as a prompt', () => {
+ const { S } = who();
+ const started = [];
+ const context = { S, tr: String, show: () => {}, BUILTIN_AGENTS: { claude: 'Claude Code', codex: 'Codex' }, activeTask: () => null, startTask: p => { started.push(p); return true; } };
+ const { rerunTask } = handlers(['isExternal', 'rerunTask'], context);
+ S.tasks = [{ id: 't1', source: 'live', agent: 'external', prompt: '外部任务测试' }, { id: 't2', source: 'live', agent: 'claude', prompt: '打开设置' }];
+ rerunTask('t1');
+ rerunTask('t2');
+ assert.deepEqual(started, ['打开设置']);
+});
diff --git a/website/en/guide/cli.md b/website/en/guide/cli.md
index 69f8865..4a52758 100644
--- a/website/en/guide/cli.md
+++ b/website/en/guide/cli.md
@@ -102,12 +102,15 @@ 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>]` | Control page in the browser at `http://127.0.0.1:8200/` (default port), 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). 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>] -- <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 |
+| `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 |
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).
## Notes
-- **Need the daemon running:** the phone part of `setup`, `status`, `doctor`, `sign`, `resign`, `devices`, `select`, `unlock-reset`, `wda-bridge`, `viewer`, and MCP tool calls.
+- **Need the daemon running:** the phone part of `setup`, `status`, `doctor`, `sign`, `resign`, `devices`, `select`, `unlock-reset`, `wda-bridge`, `viewer`, `task`, and MCP tool calls.
- **Need an interactive terminal:** `iphone-control` with no command (the first time), `setup`, `login`, `passcode set`.
- **Settings:** every command reads `~/.config/iphone-control/env` when it starts; a variable already in the environment wins. See [Configuration](./configuration#settings-file).
diff --git a/website/guide/cli.md b/website/guide/cli.md
index c8c1863..8ddfc96 100644
--- a/website/guide/cli.md
+++ b/website/guide/cli.md
@@ -102,12 +102,15 @@ Viewer 只监听本机回环地址。同机其他用户也能查看安装信息
| `notify-test [事件]` | 发测试通知:每类事件各一条,或只发一类(`resign`、`session`、`pin`、`pin-recovered`、`unlock`、`offline`、`online`) |
| `wda-bridge [--port <端口>]` | 把 WDA 桥接到 `127.0.0.1`,端口默认 8100,给别的工具用。WDA 没有认证,本机任何用户都能连上,用完就停 |
| `viewer [--port <端口>]` | 浏览器里的控制台,地址 `http://127.0.0.1:8200/`(默认端口),中英文(默认跟着 `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,在页面上选)。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。本机任何用户都能连上这个端口,用完就停 |
+| `task run [--title <标题>] -- <命令>` | 给别的 agent 平台用的 AI 任务:在当前控制的设备上开一个任务,再运行这条命令。命令启动的 `iphone-control mcp` 自动加入任务(经环境变量 `IPHONE_CONTROL_TASK_TOKEN`),控制台上能看到每一步,可以暂停、接管、停止,付款、发消息之前会等你确认。命令结束,任务就结束;任务在别处被停止,命令也会被停止;按 Ctrl-C 等于停止任务。任务进行中,其他客户端只能看,不能操作手机 |
+| `task list` / `task events <id>` | 最近的任务(`--json` 给程序读);跟着一个任务的事件,每行一个 JSON |
+| `task pause\|resume\|takeover\|handback\|stop <id>`、`task approve\|reject <id>` | 在命令行里控制任务,和控制台上的按钮一样 |
调试用的 `debug` 子命令默认不编译,见[贡献指南](https://github.com/Derrors/iphone-control/blob/main/CONTRIBUTING.md#testing-on-a-real-phone)。
## 使用说明
-- **要守护进程在运行的:** `setup` 的手机部分、`status`、`doctor`、`sign`、`resign`、`devices`、`select`、`unlock-reset`、`wda-bridge`、`viewer`,以及 MCP 工具调用。
+- **要守护进程在运行的:** `setup` 的手机部分、`status`、`doctor`、`sign`、`resign`、`devices`、`select`、`unlock-reset`、`wda-bridge`、`viewer`、`task`,以及 MCP 工具调用。
- **要在终端里交互运行的:** 不带命令的 `iphone-control`(首次运行时)、`setup`、`login`、`passcode set`。
- **设置:** 每个命令启动时都会读 `~/.config/iphone-control/env`,环境里已经有的变量优先,见[配置](./configuration#settings-file)。