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): limit a task to some apps; elsewhere each step waits for the user (#69)

Qinghe Lib64b90c34dba
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a9dbdca..e68a90c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ All notable changes to this project are documented here. The format is based on
- 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.
+- A task can be limited to some apps (`task run --app Settings`): in any other app, launching it, or opening a link that isn't a web page, each step waits for you to confirm; approving lets the task into that app.
### Changed
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 545cb4c..4139a52 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -10,6 +10,7 @@
- 任何 agent 平台都能用 AI 任务:`iphone-control task run -- <命令>` 在任务里运行命令,它启动的 `iphone-control mcp` 自动加入任务(控制台能看到每一步,可以暂停、接管、停止、确认)。`task list`、`task events`、`task pause`/`resume`/`takeover`/`handback`/`stop`、`task approve`/`reject` 在命令行里查看和控制任务。
- 控制台会接上正在进行的任务:页面刷新后,以及在别处开的任务。
+- 任务可以限定 App(`task run --app 设置`):在别的 App 里操作、启动别的 App、打开网页以外的链接,每一步都先等你确认;同意后这个 App 就加入任务范围。
### 变更
diff --git a/apps/iphone-control/src/agent.rs b/apps/iphone-control/src/agent.rs
index 8226a2d..1b247fe 100644
--- a/apps/iphone-control/src/agent.rs
+++ b/apps/iphone-control/src/agent.rs
@@ -104,7 +104,7 @@ impl Agents {
backend.id()
));
};
- let (opened, lease) = protocol::open_task(&self.socket, prompt, backend.id()).await?;
+ let (opened, lease) = protocol::open_task(&self.socket, prompt, backend.id(), &[]).await?;
let id = opened.id.clone();
let me = self.clone();
let prompt = prompt.to_owned();
diff --git a/apps/iphone-control/src/task.rs b/apps/iphone-control/src/task.rs
index 0873728..dfffdd2 100644
--- a/apps/iphone-control/src/task.rs
+++ b/apps/iphone-control/src/task.rs
@@ -23,6 +23,8 @@ pub enum TaskAction {
title: Option<String>,
#[arg(long, default_value = "external", help = ictl_l10n::tr!("谁在执行,显示在控制台上", "Who runs it, shown on the control page"))]
owner: String,
+ #[arg(long = "app", value_name = "APP", help = ictl_l10n::tr!("任务只在这些 App 里操作(App 名或 Bundle ID,可以写多次);到了别的 App 每一步都先等你确认。不写就不限制", "Limit the task to these apps (name or bundle ID, repeatable); in any other app each step waits for you first. No limit if not given"))]
+ apps: Vec<String>,
#[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
command: Vec<String>,
},
@@ -76,7 +78,9 @@ pub async fn run(socket: &Path, action: TaskAction) -> anyhow::Result<()> {
approve,
};
let req = match action {
- TaskAction::Run { title, owner, command } => return run_command(socket, title, &owner, &command).await,
+ TaskAction::Run { title, owner, apps, command } => {
+ return run_command(socket, title, &owner, &apps, &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)?;
@@ -137,10 +141,19 @@ async fn list(socket: &Path, json: bool) -> anyhow::Result<()> {
}
/// `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<()> {
+async fn run_command(
+ socket: &Path,
+ title: Option<String>,
+ owner: &str,
+ apps: &[String],
+ command: &[String],
+) -> anyhow::Result<()> {
let title = title.unwrap_or_else(|| command.join(" "));
- let (opened, mut lease) = protocol::open_task(socket, &title, owner).await.map_err(anyhow::Error::msg)?;
+ let (opened, mut lease) = protocol::open_task(socket, &title, owner, apps).await.map_err(anyhow::Error::msg)?;
eprintln!("{}", ictl_l10n::trf!("任务 {} 已开始", "Task {} started", opened.id));
+ if !apps.is_empty() {
+ eprintln!("{}", ictl_l10n::trf!("只在这些 App 里操作:{}", "Limited to these apps: {}", apps.join(", ")));
+ }
let spawned = tokio::process::Command::new(&command[0])
.args(&command[1..])
.env(protocol::TASK_TOKEN_ENV, &opened.token)
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index d571104..ca95278 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -692,8 +692,18 @@ impl Daemon {
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 };
+ // a task limited to some apps: outside them, the action waits for the user (docs/task-control.md §2.6)
+ let mut asked = false;
+ if let crate::tasks::Admission::Actor(t) = &admission
+ && t.scoped()
+ {
+ match self.scope_gate(t, &req, &mut ctx.gone).await {
+ Ok(a) => asked = a,
+ Err(r) => return r,
+ }
+ }
+ // held while the task was paused or waiting for the user: the time in the queue starts now
+ let queued_at = if waited || asked { 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() => {
@@ -710,6 +720,58 @@ impl Daemon {
resp
}
+ /// What an action of a scoped task touches, then [`crate::tasks::Task::check_scope`]. The device lock is only held
+ /// to look it up, not while the user decides (the user may take over meanwhile). Returns whether it waited
+ async fn scope_gate(
+ &self,
+ task: &crate::tasks::Task,
+ req: &Request,
+ gone: &mut Option<tokio::sync::oneshot::Receiver<()>>,
+ ) -> Result<bool, Response> {
+ use crate::tasks::{Check, Target};
+ let Some(check) = crate::tasks::scope_check(req) else { return Ok(false) };
+ let target = match check {
+ Check::Url(u) => Target::Url(u),
+ Check::Always { action, detail } => Target::Always { action, detail },
+ Check::Launch(app) => {
+ let mut g = acquire(&self.inner, gone).await?;
+ Target::Launch(self.resolve_app(&mut g, &app).await.map_err(Response::error)?)
+ }
+ Check::Foreground => {
+ let mut g = acquire(&self.inner, gone).await?;
+ // can't tell which app is in front: a scoped task doesn't act blind
+ let unknown = |why: String| {
+ Response::error(ictl_l10n::trf!(
+ "看不出前台是哪个 App({why});这个任务限定了 App 范围,所以没有操作。稍后截图再试",
+ "Can't tell which app is in front ({why}); this task is limited to some apps, so nothing was done. Take a screenshot and try again shortly"
+ ))
+ };
+ let Some(w) = self.wda(&mut g) else {
+ return Err(unknown(ictl_l10n::tr!("WDA 不可用", "WDA unavailable").into()));
+ };
+ Target::Foreground(w.active_app().await.map_err(|e| unknown(e.to_string()))?)
+ }
+ };
+ task.check_scope(&target, gone).await
+ }
+
+ /// A task's scope from names or bundle IDs: the bundle IDs, each once. `Err` names the app that isn't there
+ pub(crate) async fn resolve_scope(&self, apps: &[String]) -> Result<Vec<String>, String> {
+ let apps: Vec<&str> = apps.iter().map(|a| a.trim()).filter(|a| !a.is_empty()).collect();
+ if apps.is_empty() {
+ return Ok(Vec::new());
+ }
+ let mut g = self.inner.lock().await;
+ let mut out: Vec<String> = Vec::new();
+ for a in apps {
+ let b = self.resolve_app(&mut g, a).await?;
+ if !out.iter().any(|x| x.eq_ignore_ascii_case(&b)) {
+ out.push(b);
+ }
+ }
+ Ok(out)
+ }
+
/// [`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>| {
diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs
index a1d1c34..0af62c0 100644
--- a/crates/ictl-daemon/src/lib.rs
+++ b/crates/ictl-daemon/src/lib.rs
@@ -224,8 +224,9 @@ async fn task_stream(
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| {
+ protocol::Request::TaskOpen { title, owner, apps } => match daemon.resolve_scope(&apps).await {
+ Err(m) => Err(m),
+ Ok(apps) => daemon.tasks.open(&title, &owner, daemon.controlled_udid().as_deref(), apps).map(|t| {
daemon.log.log(&ictl_l10n::log_trf!(
"开始任务 {}({owner}):{title}",
"Task {} started ({owner}): {title}",
@@ -233,8 +234,8 @@ async fn task_stream(
));
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)
@@ -319,9 +320,9 @@ mod tests {
tokio::task::spawn_local(serve_conn(daemon.clone(), s));
}
});
- let (opened, mut events) = protocol::open_task(&socket, "看看设置", "test").await.unwrap();
+ 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");
+ 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();
@@ -349,6 +350,19 @@ mod tests {
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");
+
+ // a scope is resolved when the task opens: bundle IDs as they are, names need the phone's app list
+ // (the tap above published a snapshot without the pretend device)
+ d.fake_controlled("00008150-000A");
+ let prefs = vec!["com.apple.Preferences".to_owned()];
+ let (scoped, _lease) = protocol::open_task(&socket, "改设置", "test", &prefs).await.unwrap();
+ let list = protocol::task_list(&socket).await.unwrap();
+ let info = list.iter().find(|t| t.id == scoped.id).unwrap();
+ assert_eq!(info.apps, prefs);
+ drop(_lease);
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ let named = vec!["没有这个 App".to_owned()];
+ assert!(protocol::open_task(&socket, "改设置", "test", &named).await.is_err());
std::fs::remove_dir_all(dir).unwrap();
})
.await;
diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rs
index 3136d08..469f940 100644
--- a/crates/ictl-daemon/src/tasks.rs
+++ b/crates/ictl-daemon/src/tasks.rs
@@ -98,6 +98,8 @@ struct TaskState {
/// The user turned down a step: the task ends as rejected
rejected: bool,
ended: Option<u64>,
+ /// Bundle IDs the task may act in ([`Target`]); empty: anywhere. Grows when the user lets it go further
+ scope: Vec<String>,
}
pub struct Task {
@@ -149,6 +151,162 @@ fn observes(req: &Request) -> bool {
matches!(req, Request::Screenshot { .. } | Request::ListElements { .. } | Request::WaitFor { .. })
}
+/// The home screen, the lock screen and notifications: always in a task's scope (getting back from elsewhere)
+const SPRINGBOARD: &str = "com.apple.springboard";
+/// Where http(s) links open
+const SAFARI: &str = "com.apple.mobilesafari";
+
+/// What a request of a scoped task needs looked up before it may run ([`scope_check`])
+#[derive(Debug, PartialEq)]
+pub enum Check {
+ /// Launches this app (a name or a bundle ID, to resolve)
+ Launch(String),
+ /// Opens this URL
+ Url(String),
+ /// Acts on whatever app is in front
+ Foreground,
+ /// Always asks, whatever the scope
+ Always { action: String, detail: String },
+}
+
+/// What a scoped task's action touches, once looked up
+#[derive(Debug, PartialEq)]
+pub enum Target {
+ Launch(String),
+ Url(String),
+ /// The foreground app's bundle ID; empty when WDA didn't say
+ Foreground(String),
+ Always {
+ action: String,
+ detail: String,
+ },
+}
+
+/// What a request does to the app scope. Pressing buttons and quitting apps aren't checked: they are how an agent
+/// gets back after the user said no. Every variant is listed (no `_`), so a new request type has to be decided here
+pub fn scope_check(req: &Request) -> Option<Check> {
+ match req {
+ Request::LaunchApp { app } => Some(Check::Launch(app.clone())),
+ Request::OpenUrl { url } => Some(Check::Url(url.clone())),
+ Request::Tap { .. }
+ | Request::TapElement { .. }
+ | Request::LongPress { .. }
+ | Request::Swipe { .. }
+ | Request::TypeText { .. }
+ | Request::WebEval { .. }
+ | Request::Touch { phase: TouchPhase::Down | TouchPhase::Move, .. } => Some(Check::Foreground),
+ Request::InstallApp { path } => {
+ Some(Check::Always { action: ictl_l10n::tr!("安装 App", "Install an app").into(), detail: path.clone() })
+ }
+ Request::UninstallApp { app } => Some(Check::Always {
+ action: ictl_l10n::tr!("卸载 App(连同它的数据)", "Uninstall an app (with its data)").into(),
+ detail: app.clone(),
+ }),
+ Request::Touch { phase: TouchPhase::Prepare | TouchPhase::Up, .. }
+ | Request::PressButton { .. }
+ | Request::TerminateApp { .. }
+ | Request::SelectDevice { .. }
+ | Request::Status
+ | Request::ScreenStream
+ | Request::Screenshot { .. }
+ | Request::ListElements { .. }
+ | Request::ListApps { .. }
+ | Request::Settle { .. }
+ | Request::AlertCheck
+ | Request::WaitFor { .. }
+ | Request::Daemon
+ | Request::Doctor
+ | Request::Resign { .. }
+ | Request::UnlockReset
+ | Request::ListDevices
+ | Request::AppLogs { .. }
+ | Request::CrashReports { .. }
+ | Request::WebTargets
+ | Request::TaskOpen { .. }
+ | Request::TaskEvents { .. }
+ | Request::TaskList
+ | Request::TaskControl { .. }
+ | Request::TaskStep { .. }
+ | Request::TaskStepDone { .. }
+ | Request::TaskConfirm { .. }
+ | Request::TaskNote { .. }
+ | Request::TaskFinish { .. } => None,
+ }
+}
+
+fn in_scope(scope: &[String], bundle: &str) -> bool {
+ bundle.eq_ignore_ascii_case(SPRINGBOARD) || scope.iter().any(|s| s.eq_ignore_ascii_case(bundle))
+}
+
+/// `None` when `target` is within `scope` (empty: no limit); otherwise what to ask the user (action, detail) and
+/// the app that approving lets the task into for the rest of it
+fn out_of_scope(scope: &[String], target: &Target) -> Option<(String, String, Option<String>)> {
+ if scope.is_empty() {
+ return None;
+ }
+ let within = || ictl_l10n::trf!("任务范围:{}", "Task scope: {}", scope.join(", "));
+ match target {
+ Target::Launch(b) if !in_scope(scope, b) => Some((
+ ictl_l10n::trf!("打开任务范围以外的 App:{b}", "Open an app outside the task's scope: {b}"),
+ within(),
+ Some(b.clone()),
+ )),
+ Target::Foreground(b) if b.is_empty() => Some((
+ ictl_l10n::tr!("在不知道是哪个 App 的界面上操作", "Act on a screen whose app is unknown").into(),
+ within(),
+ None,
+ )),
+ Target::Foreground(b) if !in_scope(scope, b) => Some((
+ ictl_l10n::trf!("在任务范围以外的 App 里操作:{b}", "Act in an app outside the task's scope: {b}"),
+ within(),
+ Some(b.clone()),
+ )),
+ Target::Url(u) => {
+ let web = u
+ .split_once(':')
+ .is_some_and(|(s, _)| s.eq_ignore_ascii_case("http") || s.eq_ignore_ascii_case("https"));
+ match (web, in_scope(scope, SAFARI)) {
+ (true, true) => None,
+ (true, false) => Some((
+ ictl_l10n::trf!("在 Safari 里打开链接:{u}", "Open a link in Safari: {u}"),
+ within(),
+ Some(SAFARI.into()),
+ )),
+ // tel:, sms:, an app's own scheme…: which app it opens, and what it starts there, isn't known
+ (false, _) => Some((
+ ictl_l10n::trf!("打开链接:{u}", "Open the link {u}"),
+ ictl_l10n::trf!(
+ "不知道它会打开哪个 App、在那里做什么。{}",
+ "Which app it opens, and what it does there, isn't known. {}",
+ within()
+ ),
+ None,
+ )),
+ }
+ }
+ Target::Always { action, detail } => Some((action.clone(), detail.clone(), None)),
+ Target::Launch(_) | Target::Foreground(_) => None,
+ }
+}
+
+/// How the user answered [`Task::ask_user`]
+#[derive(Debug, PartialEq)]
+enum Asked {
+ Approved,
+ Rejected,
+ /// The task ended meanwhile
+ Ended,
+ /// The caller went away before the answer
+ Gone,
+}
+
+fn cancelled() -> Response {
+ Response::error(ictl_l10n::tr!(
+ "调用方已取消,请求没有执行",
+ "The caller cancelled; the request was not carried out"
+ ))
+}
+
/// 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)
@@ -170,6 +328,7 @@ impl Task {
started: self.started,
ended: st.ended,
steps: st.next_step - 1,
+ apps: st.scope.clone(),
}
}
@@ -247,10 +406,7 @@ impl Task {
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"
- ))),
+ _ = g => return Err(cancelled()),
},
None => notified.await,
}
@@ -324,15 +480,12 @@ impl Task {
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) = {
+ /// Shows a confirmation on the page and holds until the user answers, the task ends or the caller goes away
+ async fn ask_user(&self, action: &str, detail: &str, gone: &mut Option<oneshot::Receiver<()>>) -> Asked {
+ let (mut rx, id) = {
let mut st = self.lock();
if !st.status.active() {
- return refuse(ended_message());
+ return Asked::Ended;
}
let args = json!({"action": action, "detail": detail});
let id = self.begin_step(&mut st, "iphone_confirm", &args, None, "waiting");
@@ -342,32 +495,98 @@ impl Task {
self.set_status(&mut st, Status::Waiting);
(rx, id)
};
- let approve = rx.await.unwrap_or(false);
+ let answer = match gone {
+ Some(g) => tokio::select! {
+ a = &mut rx => Some(a.unwrap_or(false)),
+ _ = g => None,
+ },
+ None => Some(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."))
+ let (asked, status, result) = match (answer, ended) {
+ (_, true) => (Asked::Ended, "stopped", ictl_l10n::tr!("任务已停止。", "The task was stopped.")),
+ (None, false) => {
+ // nobody waits for the answer any more: take the question off the page
+ if st.confirm.as_ref().is_some_and(|(waiting, _)| *waiting == id) {
+ st.confirm = None;
+ }
+ (Asked::Gone, "stopped", ictl_l10n::tr!("调用方已取消,没有执行。", "The caller cancelled; not done."))
}
+ (Some(true), false) => {
+ (Asked::Approved, "ok", ictl_l10n::tr!("你同意了,继续执行。", "You approved; carrying on."))
+ }
+ (Some(false), false) => (
+ Asked::Rejected,
+ "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!(
+ asked
+ }
+
+ /// The agent asks before a sensitive action ([`crate::protocol::Request::TaskConfirm`])
+ async fn confirm(&self, action: &str, detail: &str, gone: &mut Option<oneshot::Receiver<()>>) -> Response {
+ let action = action.trim();
+ if action.is_empty() {
+ return refuse(ictl_l10n::tr!("action 不能为空", "action can't be empty"));
+ }
+ match self.ask_user(action, detail, gone).await {
+ Asked::Approved => 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"
- )),
+ Asked::Ended => refuse(ended_message()),
+ Asked::Gone => cancelled(),
+ Asked::Rejected => {
+ self.lock().rejected = true;
+ 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"
+ ))
+ }
+ }
+ }
+
+ /// Whether the task is limited to some apps
+ pub fn scoped(&self) -> bool {
+ !self.lock().scope.is_empty()
+ }
+
+ /// Before an action of a scoped task: within its scope it goes on; outside it waits for the user. Approving lets
+ /// the task into that app for the rest of it; rejecting refuses this action only, so the agent can go back
+ /// (unlike a rejected [`Self::confirm`], the task doesn't end as rejected). Returns whether it waited
+ pub async fn check_scope(
+ &self,
+ target: &Target,
+ gone: &mut Option<oneshot::Receiver<()>>,
+ ) -> Result<bool, Response> {
+ let ask = {
+ let st = self.lock();
+ out_of_scope(&st.scope, target).map(|a| (a, st.scope.join(", ")))
+ };
+ let Some(((action, detail, adds), scope)) = ask else { return Ok(false) };
+ match self.ask_user(&action, &detail, gone).await {
+ Asked::Approved => {
+ if let Some(a) = adds {
+ let mut st = self.lock();
+ if !in_scope(&st.scope, &a) {
+ st.scope.push(a);
+ }
+ }
+ Ok(true)
+ }
+ Asked::Rejected => Err(refuse(&ictl_l10n::trf!(
+ "用户不同意超出任务范围({action}),这一步没有执行。回到任务范围内的 App({scope})再继续,做不到就结束任务并说明原因",
+ "The user didn't allow going outside the task's scope ({action}); this step wasn't done. Go back to an app within the scope ({scope}) and carry on there, or if you can't, finish and say why"
+ ))),
+ Asked::Ended => Err(refuse(ended_message())),
+ Asked::Gone => Err(cancelled()),
}
}
@@ -483,7 +702,8 @@ impl Tasks {
}
/// 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> {
+ /// `apps`: bundle IDs it may act in, empty for no limit (see [`Task::check_scope`])
+ pub fn open(&self, title: &str, owner: &str, udid: Option<&str>, apps: Vec<String>) -> Result<Arc<Task>, String> {
let title = title.trim();
if title.is_empty() {
return Err(ictl_l10n::tr!("任务要有标题", "A task needs a title").into());
@@ -525,13 +745,14 @@ impl Tasks {
confirm: None,
rejected: false,
ended: None,
+ scope: apps,
}),
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});
+ let info = json!({"id": task.id, "title": task.title, "owner": task.owner, "udid": task.udid, "started": task.started, "apps": st.scope});
task.emit(&mut st, "task", info);
}
if list.len() >= KEEP {
@@ -664,7 +885,7 @@ impl Tasks {
Err(r) => r,
},
Request::TaskConfirm { action, detail } => match self.actor(token) {
- Ok(t) => t.confirm(action, detail).await,
+ Ok(t) => t.confirm(action, detail, gone).await,
Err(r) => r,
},
Request::TaskNote { text } => match self.actor(token) {
@@ -759,6 +980,10 @@ fn restore(file: &Path) -> Option<Task> {
confirm: None,
rejected: false,
ended: None,
+ scope: first["apps"]
+ .as_array()
+ .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect())
+ .unwrap_or_default(),
}),
tx: broadcast::channel(16).0,
changed: Notify::new(),
@@ -838,7 +1063,7 @@ mod tests {
}
fn open(ts: &Tasks) -> Arc<Task> {
- ts.open("看看设置", "test", Some(PHONE)).unwrap()
+ ts.open("看看设置", "test", Some(PHONE), Vec::new()).unwrap()
}
fn tap() -> Request {
@@ -868,12 +1093,12 @@ mod tests {
#[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());
+ assert!(ts.open("x", "", None, Vec::new()).is_err());
+ assert!(ts.open(" ", "", Some(PHONE), Vec::new()).is_err());
let t = open(&ts);
- assert!(ts.open("another", "", Some(PHONE)).err().unwrap().contains(&t.id));
+ assert!(ts.open("another", "", Some(PHONE), Vec::new()).err().unwrap().contains(&t.id));
t.end(End::Completed, "");
- assert!(ts.open("another", "", Some(PHONE)).is_ok());
+ assert!(ts.open("another", "", Some(PHONE), Vec::new()).is_ok());
}
/// The point of D17: while a task runs, a caller without its token can look but not act
@@ -1070,6 +1295,113 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
+ fn scope(apps: &[&str]) -> Vec<String> {
+ apps.iter().map(|a| a.to_string()).collect()
+ }
+
+ #[test]
+ fn what_each_request_checks_against_the_scope() {
+ assert_eq!(scope_check(&tap()), Some(Check::Foreground));
+ assert_eq!(scope_check(&Request::LaunchApp { app: "设置".into() }), Some(Check::Launch("设置".into())));
+ assert_eq!(scope_check(&Request::OpenUrl { url: "tel:10086".into() }), Some(Check::Url("tel:10086".into())));
+ assert!(matches!(scope_check(&Request::UninstallApp { app: "x".into() }), Some(Check::Always { .. })));
+ // the ways back after a refusal, and looking, are never held
+ assert_eq!(scope_check(&Request::PressButton { button: "home".into() }), None);
+ assert_eq!(scope_check(&Request::TerminateApp { app: "x".into() }), None);
+ assert_eq!(scope_check(&Request::Screenshot { region: None }), None);
+ assert_eq!(scope_check(&Request::Touch { phase: TouchPhase::Up, x: 0.0, y: 0.0 }), None);
+ }
+
+ #[test]
+ fn what_is_outside_the_scope() {
+ let prefs = scope(&["com.apple.Preferences"]);
+ let fg = |b: &str| Target::Foreground(b.into());
+ assert_eq!(out_of_scope(&[], &fg("com.tencent.xin")), None, "no scope: no limit");
+ assert_eq!(out_of_scope(&prefs, &fg("com.apple.preferences")), None, "bundle IDs ignore case");
+ assert_eq!(out_of_scope(&prefs, &fg(SPRINGBOARD)), None, "the home screen is always fine");
+ let (_, _, adds) = out_of_scope(&prefs, &fg("com.tencent.xin")).unwrap();
+ assert_eq!(adds.as_deref(), Some("com.tencent.xin"));
+ let (_, _, adds) = out_of_scope(&prefs, &fg("")).unwrap();
+ assert_eq!(adds, None, "an unknown app is asked about, never let in");
+ assert_eq!(out_of_scope(&prefs, &Target::Launch("com.apple.Preferences".into())), None);
+ assert!(out_of_scope(&prefs, &Target::Launch("com.apple.MobileSMS".into())).is_some());
+ // links: http(s) is Safari; other schemes open who knows what
+ let web = Target::Url("https://example.com".into());
+ assert_eq!(out_of_scope(&prefs, &web).unwrap().2.as_deref(), Some(SAFARI));
+ assert_eq!(out_of_scope(&scope(&["com.apple.Preferences", SAFARI]), &web), None);
+ let tel = Target::Url("tel:10086".into());
+ assert_eq!(out_of_scope(&scope(&[SAFARI]), &tel).unwrap().2, None);
+ let always = Target::Always { action: "卸载".into(), detail: "x".into() };
+ assert!(out_of_scope(&prefs, &always).is_some());
+ }
+
+ async fn answer_soon(t: &Arc<Task>, approve: bool) {
+ let t = t.clone();
+ tokio::spawn(async move {
+ while t.info().state != "waiting" {
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ t.control("confirm", None, approve).unwrap();
+ });
+ }
+
+ #[tokio::test]
+ async fn an_approved_app_joins_the_scope_for_the_rest_of_the_task() {
+ let ts = tasks();
+ let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"])).unwrap();
+ assert!(t.scoped());
+ let wechat = Target::Foreground("com.tencent.xin".into());
+ answer_soon(&t, true).await;
+ assert_eq!(t.check_scope(&wechat, &mut None).await.ok(), Some(true), "asked, then let through");
+ assert_eq!(t.check_scope(&wechat, &mut None).await.ok(), Some(false), "not asked again");
+ assert_eq!(t.info().apps, scope(&["com.apple.Preferences", "com.tencent.xin"]));
+ assert_eq!(t.info().state, "running");
+ }
+
+ #[tokio::test]
+ async fn a_rejected_app_refuses_that_step_but_the_task_can_go_back() {
+ let ts = tasks();
+ let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"])).unwrap();
+ answer_soon(&t, false).await;
+ let r = t.check_scope(&Target::Launch("com.apple.MobileSMS".into()), &mut None).await;
+ assert!(matches!(r, Err(Response::Error { message, .. }) if message.contains("com.apple.Preferences")));
+ assert_eq!(t.info().state, "running");
+ assert_eq!(t.info().apps, scope(&["com.apple.Preferences"]));
+ t.finish(true, "改好了");
+ assert_eq!(t.info().state, "completed", "a scope refusal isn't a rejected task");
+ }
+
+ #[tokio::test]
+ async fn a_question_nobody_waits_for_leaves_the_page() {
+ let ts = tasks();
+ let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"])).unwrap();
+ let (tx, rx) = oneshot::channel();
+ let t2 = t.clone();
+ let asking =
+ tokio::spawn(
+ async move { t2.check_scope(&Target::Foreground("com.tencent.xin".into()), &mut Some(rx)).await },
+ );
+ while t.info().state != "waiting" {
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ tx.send(()).unwrap();
+ assert!(matches!(asking.await.unwrap(), Err(Response::Error { message, .. }) if message.contains("取消")));
+ assert_eq!(t.info().state, "running");
+ assert!(t.control("confirm", None, true).is_err(), "nothing waits for an answer any more");
+ }
+
+ #[test]
+ fn the_scope_survives_a_restart() {
+ let dir = std::env::temp_dir().join(format!("ictl-tasks-scope-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let ts = Tasks::load(Some(dir.clone()));
+ let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"])).unwrap();
+ t.end(End::Completed, "");
+ let ts = Tasks::load(Some(dir.clone()));
+ assert_eq!(ts.get(&t.id).unwrap().info().apps, scope(&["com.apple.Preferences"]));
+ 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()));
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index 36b56e1..5734921 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -192,6 +192,10 @@ pub enum Request {
/// Who runs it, shown on the control page (`claude`, `codex`, the name of an external platform…)
#[serde(default)]
owner: String,
+ /// Apps (names or bundle IDs) the task may act in; outside them each action waits for the user. Empty: no
+ /// limit
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ apps: Vec<String>,
},
/// Streaming like [`Request::TaskOpen`]: the task's events so far, then new ones, until it ends
TaskEvents {
@@ -267,6 +271,9 @@ pub struct TaskInfo {
/// Steps so far
#[serde(default)]
pub steps: u64,
+ /// Bundle IDs the task may act in (empty: no limit), including those the user let it into
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub apps: Vec<String>,
}
impl TaskInfo {
@@ -642,8 +649,14 @@ async fn open_stream(socket: &std::path::Path, req: &Request) -> std::io::Result
}
/// 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() };
+/// `apps`: the task's scope (see [`Request::TaskOpen`]), empty for none
+pub async fn open_task(
+ socket: &std::path::Path,
+ title: &str,
+ owner: &str,
+ apps: &[String],
+) -> Result<(TaskOpened, TaskStream), String> {
+ let req = Request::TaskOpen { title: title.to_owned(), owner: owner.to_owned(), apps: apps.to_vec() };
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),
diff --git a/docs/architecture.md b/docs/architecture.md
index 8802979..5251089 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -48,7 +48,7 @@
- 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。
-- 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 …`)和外部平台用的是同一套请求。
+- 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。开任务时可以限定 App(`apps`,开任务时解析成 Bundle ID):有范围的任务每个操作前先查它碰到哪个 App(启动的目标、链接、或问 WDA 当时的前台),超出范围就像 `iphone_confirm` 一样等人确认,同意后那个 App 加入范围,看不出前台时不操作(task-control.md 5.5)。控制台、命令行(`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 bfeff33..1a36053 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -148,4 +148,5 @@
- 用连接表示租约,比心跳简单,没有超时误判;守护进程本来就靠连接断开来判断调用方走了(`cancel_on_close`)。
- **对 D2、D13 的修改**:D2 里「MCP 是薄客户端」不变,但守护进程从此管任务这层语义,不再只是设备驱动。D13「socket 权限才是边界」不变:任务口令用来区分调用方、让出错的调用方停下来,不是权限控制。同一用户的进程能拿到口令,也能直接发控制请求。要真正隔离,需要让 Agent 换 uid 运行或进沙箱,并用 `SO_PEERCRED` 认调用方(task-control.md 阶段三、四)。
- **代价**:守护进程多了一个模块和几种请求。有任务时,不带口令的动作会被拒绝:这正是要的效果,但以前「任务进行中用命令行点一下」的做法不能用了,要先接管。任务日志写在数据目录(`tasks/`,最多 50 个)。
-- **重新评估**:需要无人值守、Agent 跑在沙箱里时,再做口令分开、任务范围和 `SO_PEERCRED`;需要跨主机时,再做带认证的 HTTP 控制面。
+- **重新评估**:需要无人值守、Agent 跑在沙箱里时,再做口令分开和 `SO_PEERCRED`;需要跨主机时,再做带认证的 HTTP 控制面。
+- **补充(2026-11-13)**:任务范围先做了(task-control.md 5.5):开任务时限定 App,越界的操作停下来问人。和口令不同,它在同一个用户下也有用:防的是走错路的 Agent,不是有意绕过的程序。拒绝只拒这一步而不结束任务,是因为越界多半是 Agent 误点进了别的 App,让它退回来比整个任务作废更合用;看不出前台 App 时不操作,是和整个任务机制一样出错就停。
diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md
index 7c4ec08..8bac4fa 100644
--- a/docs/dev/regression-cases.md
+++ b/docs/dev/regression-cases.md
@@ -113,6 +113,7 @@
| 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 或手动(任务进行中刷新页面) |
+| 110 | AI 任务只该改设置,却点进了微信、打开了 `tel:` 链接或别的 App,没人拦 | 限定了 App 范围的任务,每个操作前看它碰到哪个 App(启动目标、链接、当时的前台),超出范围就停下来等人确认;`tel:` 这类链接、安装和卸载一律先问;看不出前台时不操作;拒绝只拒这一步,任务可以回到范围内继续 | 单测(`what_is_outside_the_scope`、`what_each_request_checks_against_the_scope`、`an_approved_app_joins_the_scope_for_the_rest_of_the_task`、`a_rejected_app_refuses_that_step_but_the_task_can_go_back`、`a_question_nobody_waits_for_leaves_the_page`、`the_scope_survives_a_restart`)+ 真机(`task run --app 设置` 的任务启动「信息」时页面出现确认) |
| 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
index a5586dd..36f1c50 100644
--- a/docs/task-control.md
+++ b/docs/task-control.md
@@ -130,7 +130,8 @@ Running → Waiting(等确认)→ Running
|---|---|---|
| 一 | 任务和租约放进守护进程:控制面请求、准入检查、状态机、落盘、设备绑定、观察版本(简化版)、子步骤;内建 runner 和 MCP 改走守护进程;`iphone-control task` 命令给外部平台用 | 已完成(2026-11-12) |
| 二 | 控制台接上正在进行的任务(刷新后、在别处开的);命令行查看事件 | 已完成(2026-11-12) |
-| 三 | 任务范围(App 白名单)和越界确认;执行口令与控制口令分开 | 等需要时 |
+| 三 | 任务范围(App 白名单)和越界确认 | 已完成(2026-11-13,见 5.5) |
+| 三 | 执行口令与控制口令分开 | 等需要时 |
| 四 | 带认证的 HTTP 控制面、HTTP MCP;局域网访问控制台(第 7 节);`SO_PEERCRED`;多设备租约 | 等需要时 |
## 5. 阶段一的具体设计
@@ -169,12 +170,32 @@ Running → Waiting(等确认)→ Running
`iphone-control task run --title … -- <命令>`:开任务、保持租约,带着 `IPHONE_CONTROL_TASK_TOKEN`(以及 `IPHONE_CONTROL_TASK_ID`)启动命令,命令里的 `iphone-control mcp` 会自动加入任务。命令结束时任务随之结束,结果取命令的退出码;命令想写总结时自己调 `iphone-control task finish …`。任务在别处被停止时,结束这个命令的整个进程组。Ctrl-C 或 SIGTERM 等于停止任务。适配层只需要包一层,不用自己实现协议。
+### 5.5 任务范围(阶段三的前一半)
+
+开任务时可以带 `apps`(App 名或 Bundle ID;`iphone-control task run --app …` 可以写多次)。开任务时就解析成 Bundle ID,名字写错直接开不了任务。不带就是不限制,和以前一样。
+
+有范围的任务,每个操作执行之前守护进程检查它会碰到哪个 App(`tasks::scope_check`):
+
+| 操作 | 看什么 |
+|---|---|
+| 启动 App | 要启动的那个 |
+| 打开链接 | http(s) 算 Safari;别的 scheme(`tel:`、`sms:`、App 自己的)不知道会打开什么、做什么,一律先问,同意也只放行这一次 |
+| 点击、按名字点、长按、滑动、输入、按下和移动手指、在网页里执行 JS | 当时的前台 App(问 WDA 的 `activeAppInfo`) |
+| 安装、卸载 App | 不管范围,一律先问 |
+| 按键、结束 App、看屏幕 | 不检查:被拒绝之后靠它们回到范围内 |
+
+- 主屏幕(SpringBoard,含锁屏和通知中心)总在范围内。
+- 超出范围时任务进入 waiting,和 `iphone_confirm` 用同一套确认:页面和 `task approve`/`reject` 都能回答。同意后这个 App 加入本任务的范围,之后不再问;拒绝只拒这一步,Agent 收到「回到范围内的 App 再继续」,任务不会因此记成 rejected。
+- 看不出前台是哪个 App(WDA 不可用、读失败)时不操作,返回错误让 Agent 稍后再试,不在不知道是哪个 App 的界面上盲点。
+- 查前台只短暂拿设备锁,等人回答时不持锁(人可以先接管);调用方中途断开,问题从页面上撤掉。
+- 局限:检查的是动作之前的前台。在范围内的 App 里点一下跳进了别的 App,这一下本身不会被拦,进去之后的下一步才会。
+
## 6. 阶段一、二之后还差什么
和第 2 节的目标架构相比:
- **口令只有一种**(2.5):开任务的一方拿到的口令同时交给 Agent,控制请求(暂停、确认)不验口令。在同一个用户下这本来就不是边界(D13、D17),等 Agent 跑进沙箱时再分开,届时加上 `SO_PEERCRED`。
-- **没有策略和任务范围**(2.6):敏感动作仍然靠 Agent 调 `iphone_confirm`。
+- **任务范围已有,策略还没有**(2.6):限定 App 后越界会停下来问人(5.5);但范围内的敏感动作(在微信里发消息)仍然靠 Agent 调 `iphone_confirm`。控制台上开的任务还不能设范围。
- **观察版本是简化版**(2.7):只有一个「需要重新看」的标记,在交还、或别人在接管期间动过手机后置上,Agent 截图、读元素或等文字之后清掉。动作不带「基于哪次观察」,所以 Agent 自己连续操作时不做这项检查。
- **事件不带编号**(2.10):重连时从头重放,没有从断点继续。任务事件全是文字,从头重放代价不大。
- **设备拔掉时**(2.9):任务不中断,它的请求会被拒绝(找不到绑定的设备),插回同一台手机后可以继续;只有换成另一台设备才中断。
diff --git a/docs/tools.md b/docs/tools.md
index 9a271a3..c7ae63c 100644
--- a/docs/tools.md
+++ b/docs/tools.md
@@ -61,7 +61,7 @@ See [SECURITY.md](../SECURITY.md#developer-tools) before turning these tools on.
## Tasks
-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:
+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`. A task can be limited to some apps (`task run --app …`): outside them, each action waits for the user to confirm, the same way as `iphone_confirm`; a rejection refuses that step and tells the agent to go back. With the token 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 |
|---|---|---|
diff --git a/website/en/guide/cli.md b/website/en/guide/cli.md
index 4a52758..2a51fb9 100644
--- a/website/en/guide/cli.md
+++ b/website/en/guide/cli.md
@@ -102,7 +102,7 @@ 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 run [--title <title>] [--app <app>…] -- <command>` | AI tasks for other agent platforms: opens a task on the controlled device and runs the command in it. An `iphone-control mcp` the command starts takes part (through `IPHONE_CONTROL_TASK_TOKEN`): the control page shows every step and can pause, take over and stop it, and it waits for you before paying or sending a message. The task ends when the command does; when the task is stopped elsewhere, so is the command; Ctrl-C stops the task. While a task runs, other clients can look but not act on the phone. `--app` (repeatable, name or bundle ID) limits the task to those apps: in any other app, or to open a link that isn't a web page, each step waits for you first |
| `task list` / `task events <id>` | Recent tasks (`--json` for programs); follow a task's events, one JSON per line |
| `task pause\|resume\|takeover\|handback\|stop <id>`, `task approve\|reject <id>` | Control a task from the command line, like the buttons on the control page |
diff --git a/website/guide/cli.md b/website/guide/cli.md
index 8ddfc96..00791e1 100644
--- a/website/guide/cli.md
+++ b/website/guide/cli.md
@@ -102,7 +102,7 @@ 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 run [--title <标题>] [--app <App>…] -- <命令>` | 给别的 agent 平台用的 AI 任务:在当前控制的设备上开一个任务,再运行这条命令。命令启动的 `iphone-control mcp` 自动加入任务(经环境变量 `IPHONE_CONTROL_TASK_TOKEN`),控制台上能看到每一步,可以暂停、接管、停止,付款、发消息之前会等你确认。命令结束,任务就结束;任务在别处被停止,命令也会被停止;按 Ctrl-C 等于停止任务。任务进行中,其他客户端只能看,不能操作手机。`--app`(可写多次,App 名或 Bundle ID)把任务限定在这些 App 里:到了别的 App、或者要打开网页以外的链接,每一步都先等你确认 |
| `task list` / `task events <id>` | 最近的任务(`--json` 给程序读);跟着一个任务的事件,每行一个 JSON |
| `task pause\|resume\|takeover\|handback\|stop <id>`、`task approve\|reject <id>` | 在命令行里控制任务,和控制台上的按钮一样 |