Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

feat(viewer): limit a task to some apps when starting it on the control page (#70)

Qinghe Lie6b1ca5bcf21
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e68a90c..323c7d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ All notable changes to this project are documented here. The format is based on
### Added
+- On the control page, a task can be limited to some apps before it starts (the App button next to the agent): in any other app each step waits for you, as with `task run --app`. The task card shows the scope, and running a task again keeps it.
- 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.
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 4139a52..09ccbfd 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -8,6 +8,7 @@
### 新增
+- 控制台上开任务前可以限定 App 范围(Agent 旁边的 App 按钮):到了别的 App,每一步都先等你确认,和 `task run --app` 一样。任务卡片上显示范围,重新执行时沿用。
- 任何 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 1b247fe..30e0e6d 100644
--- a/apps/iphone-control/src/agent.rs
+++ b/apps/iphone-control/src/agent.rs
@@ -20,6 +20,10 @@ use tokio::io::{AsyncBufReadExt, BufReader};
/// Longest prompt accepted (the page limits the text box to the same)
pub const MAX_PROMPT: usize = 4000;
+/// Most apps a task from the page may be limited to (docs/task-control.md 5.5); a name or bundle ID is at most
+/// [`MAX_APP_LEN`] characters
+pub const MAX_SCOPE_APPS: usize = 30;
+const MAX_APP_LEN: usize = 200;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Backend {
@@ -81,8 +85,9 @@ impl Agents {
Ok(Arc::new(Self { exe: std::env::current_exe()?, socket: socket.to_path_buf(), workdir }))
}
- /// 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> {
+ /// Opens a task in the daemon and starts the agent on it; `Err` is a message for the page. `apps` limits the
+ /// task to those apps (names or bundle IDs, resolved by the daemon); empty for no limit
+ pub async fn start(self: &Arc<Self>, prompt: &str, backend: &str, apps: &[String]) -> 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());
@@ -93,6 +98,7 @@ impl Agents {
"The task is too long, at most {MAX_PROMPT} characters"
));
}
+ let apps = scope_apps(apps)?;
let Some(backend) = Backend::parse(backend) else {
return Err(ictl_l10n::trf!("不认识的 agent「{backend}」", "Unknown agent “{backend}”"));
};
@@ -104,14 +110,15 @@ impl Agents {
backend.id()
));
};
- let (opened, lease) = protocol::open_task(&self.socket, prompt, backend.id(), &[]).await?;
+ // the daemon resolves names and refuses an app the phone doesn't have
+ let (opened, lease) = protocol::open_task(&self.socket, prompt, backend.id(), &apps).await?;
let id = opened.id.clone();
let me = self.clone();
let prompt = prompt.to_owned();
let lang = ictl_l10n::lang();
tokio::spawn(ictl_l10n::scope(lang, async move {
let mut lease = lease;
- if let Err(e) = me.run(&opened.token, &mut lease, backend, &program, &prompt).await {
+ if let Err(e) = me.run(&opened.token, &mut lease, backend, &program, &prompt, &apps).await {
let summary =
ictl_l10n::trf!("{} 没能启动或中途出错:{e}", "{} didn't start or failed: {e}", backend.name());
me.finish(&opened.token, false, summary).await;
@@ -158,9 +165,10 @@ impl Agents {
backend: Backend,
program: &Path,
prompt: &str,
+ apps: &[String],
) -> anyhow::Result<()> {
let mut cmd = tokio::process::Command::new(program);
- cmd.args(self.agent_args(backend, token, prompt))
+ cmd.args(self.agent_args(backend, token, prompt, apps))
.current_dir(&self.workdir)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
@@ -236,7 +244,8 @@ impl Agents {
Ok(())
}
- fn agent_args(&self, backend: Backend, token: &str, prompt: &str) -> Vec<String> {
+ fn agent_args(&self, backend: Backend, token: &str, prompt: &str, apps: &[String]) -> Vec<String> {
+ let guide = guidance(apps);
let exe = self.exe.to_string_lossy().into_owned();
let socket = self.socket.to_string_lossy().into_owned();
let mut env = Map::new();
@@ -265,7 +274,7 @@ impl Agents {
s("dontAsk"),
s("--no-session-persistence"),
s("--append-system-prompt"),
- s(instructions()),
+ guide.clone(),
]
}
Backend::Codex => {
@@ -296,7 +305,7 @@ impl Agents {
s("mcp_servers.iphone.default_tools_approval_mode=\"approve\""),
s("-c"),
s("suppress_unstable_features_warning=true"),
- format!("{}\n\n{}{prompt}", instructions(), ictl_l10n::tr!("任务:", "Task: ")),
+ format!("{guide}\n\n{}{prompt}", ictl_l10n::tr!("任务:", "Task: ")),
]
}
}
@@ -377,10 +386,68 @@ fn instructions() -> &'static str {
)
}
+/// The apps a task from the page is limited to: trimmed, each once, at most [`MAX_SCOPE_APPS`]. `Err` is a message
+fn scope_apps(apps: &[String]) -> Result<Vec<String>, String> {
+ let mut out: Vec<String> = Vec::new();
+ for a in apps.iter().map(|a| a.trim()).filter(|a| !a.is_empty()) {
+ if a.chars().count() > MAX_APP_LEN {
+ return Err(ictl_l10n::tr!("App 名太长", "An app name is too long").into());
+ }
+ if !out.iter().any(|o| o.eq_ignore_ascii_case(a)) {
+ out.push(a.to_owned());
+ }
+ }
+ if out.len() > MAX_SCOPE_APPS {
+ return Err(ictl_l10n::trf!(
+ "最多限定 {MAX_SCOPE_APPS} 个 App",
+ "A task can be limited to at most {MAX_SCOPE_APPS} apps"
+ ));
+ }
+ Ok(out)
+}
+
+/// [`instructions`], and the task's app scope when it has one: the agent plans within it from the start (the daemon
+/// holds anything outside it for the user either way)
+fn guidance(apps: &[String]) -> String {
+ if apps.is_empty() {
+ return instructions().to_owned();
+ }
+ let list = apps.join(ictl_l10n::tr!("、", ", "));
+ format!(
+ "{}\n{}",
+ instructions(),
+ ictl_l10n::trf!(
+ "- 这个任务限定在这些 App 里:{list}(主屏幕总是可以)。在别的 App 里操作、打开别的 App 或网页以外的链接时,那一步会先等用户确认;用户不同意,就回到这些 App 里继续,做不到就结束并说明原因。",
+ "- This task is limited to these apps: {list} (the home screen is always fine). Acting in another app, opening one, or opening a link that isn't a web page waits for the user to confirm first; if the user says no, go back to these apps and carry on, or if you can't, finish and say why."
+ )
+ )
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn a_scope_from_the_page_is_checked_and_told_to_the_agent() {
+ let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
+ assert_eq!(
+ scope_apps(&v(&[" 设置 ", "", "com.apple.mobiletimer", "设置"])).unwrap(),
+ v(&["设置", "com.apple.mobiletimer"])
+ );
+ assert_eq!(scope_apps(&v(&["com.apple.Preferences", "COM.APPLE.PREFERENCES"])).unwrap().len(), 1);
+ assert!(scope_apps(&["x".repeat(MAX_APP_LEN + 1)]).is_err());
+ assert!(scope_apps(&(0..=MAX_SCOPE_APPS).map(|i| format!("app{i}")).collect::<Vec<_>>()).is_err());
+
+ let agents = Agents::new(Path::new("/nonexistent/ctl.sock")).unwrap();
+ let scoped = v(&["com.apple.Preferences", "com.apple.mobiletimer"]);
+ for backend in Backend::ALL {
+ let plain = agents.agent_args(backend, "t", "看看设置", &[]).join("\n");
+ let limited = agents.agent_args(backend, "t", "看看设置", &scoped).join("\n");
+ assert!(!plain.contains("com.apple.Preferences"), "{backend:?}: no scope, nothing about one");
+ assert!(limited.contains("com.apple.Preferences、com.apple.mobiletimer"), "{backend:?}");
+ }
+ }
+
#[test]
fn claude_lines() {
let a = json!({"type": "assistant", "message": {"content": [{"type": "text", "text": "先看屏幕"}, {"type": "tool_use", "name": "x"}]}});
diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.html
index fbbb581..40bfb9d 100644
--- a/apps/iphone-control/src/viewer.html
+++ b/apps/iphone-control/src/viewer.html
@@ -310,6 +310,25 @@ body.resizing .stage, body.resizing iframe { pointer-events: none; }
.textarea:focus-visible { outline: none; }
.textarea:disabled { color: var(--muted); cursor: not-allowed; }
.composer-row { display: flex; align-items: center; justify-content: flex-end; min-width: 0; gap: 6px; padding: 0 8px 8px; }
+.scope-pick { flex: 0 1 auto; min-width: 0; max-width: min(12rem, 45%); margin-right: auto; }
+.scope-trigger .ic:first-child { color: var(--text-2); --od-icon-size: 14px; }
+.scope-trigger[data-scoped] { color: var(--accent); }
+.scope-trigger[data-scoped] .ic:first-child { color: var(--accent); }
+.scope-menu { width: min(22rem, calc(100vw - 16px)); display: flex; flex-direction: column; gap: 8px; padding: 12px; }
+.scope-menu:not(:popover-open) { display: none; }
+.scope-title { margin: 0; font-weight: 600; font-size: var(--fs-sm); }
+.scope-desc { margin: -4px 0 0; color: var(--muted); font-size: var(--fs-2xs); line-height: 1.4; }
+.scope-list { flex: 1 1 auto; min-height: 3rem; max-height: 18rem; overflow: auto; margin: 0 -4px; }
+.scope-row { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; column-gap: 10px; min-height: 36px; padding: 4px 8px; border-radius: 8px; cursor: pointer; }
+.scope-row:hover { background: var(--hover); }
+.scope-row input { margin: 0; accent-color: var(--accent); }
+.scope-row .scope-app { min-width: 0; display: grid; }
+.scope-row .scope-app b { font-weight: 500; overflow-wrap: anywhere; }
+.scope-row .scope-app small { color: var(--muted); font-family: var(--font-mono); font-size: var(--fs-2xs); overflow-wrap: anywhere; }
+.scope-list .empty-note { margin: 8px; }
+.scope-foot { display: flex; align-items: center; gap: 6px; }
+.scope-count { margin-right: auto; color: var(--muted); font-size: var(--fs-2xs); }
+.msg-scope { display: inline-flex; align-items: center; gap: 3px; min-width: 0; color: var(--muted); font-size: var(--fs-2xs); --od-icon-size: 12px; }
.agent-pick { flex: 0 1 auto; min-width: 0; max-width: min(11rem, calc(100% - 52px)); }
.picker-trigger { display: flex; align-items: center; gap: 4px; max-width: 100%; min-height: 32px; padding: 0 6px; border: 0; border-radius: 7px; background: transparent; color: var(--text-2); font-size: var(--fs-xs); font-weight: 500; cursor: pointer; }
.picker-trigger .ic { flex: none; color: var(--muted); --od-icon-size: 12px; }
@@ -882,6 +901,17 @@ button.nav-device:disabled { cursor: default; }
<label class="sr-only" for="prompt">交给 AI 的任务</label>
<textarea class="textarea" id="prompt" rows="1" maxlength="4000" aria-describedby="composer-hint prompt-error" placeholder="想让设备做什么?"></textarea>
<div class="composer-row">
+ <div class="scope-pick" id="scope-pick" hidden>
+ <span class="sr-only" id="scope-label">任务范围</span>
+ <button type="button" class="picker-trigger scope-trigger" id="scope-btn" popovertarget="scope-menu" aria-haspopup="dialog" aria-controls="scope-menu" aria-expanded="false" aria-labelledby="scope-label scope-name"><span class="ic" data-icon="grid"></span><span class="od-truncate" id="scope-name">所有 App</span><span class="ic" data-icon="chevron"></span></button>
+ <div id="scope-menu" class="picker-menu scope-menu glass" role="dialog" aria-labelledby="scope-title" aria-describedby="scope-desc" popover="auto" tabindex="-1">
+ <p class="scope-title" id="scope-title">任务只在这些 App 里操作</p>
+ <p class="scope-desc" id="scope-desc">到了别的 App,每一步都先等你确认。不选就不限制。</p>
+ <div class="search"><label class="sr-only" for="scope-q">搜索 App</label><input class="input" id="scope-q" type="search" autocomplete="off" placeholder="按名称或 bundle id 搜索"><span class="search-ic" data-icon="search"></span></div>
+ <div class="scope-list" id="scope-list" role="group" aria-label="App"></div>
+ <div class="scope-foot"><span class="scope-count" id="scope-count"></span><button type="button" class="btn btn-sm" id="scope-clear">清空</button><button type="button" class="btn btn-sm btn-primary" id="scope-done">完成</button></div>
+ </div>
+ </div>
<div class="agent-pick" id="agent-pick" hidden>
<span class="sr-only" id="agent-label">执行任务的 AI</span>
<select id="agent-value" data-picker="agent" data-open-above hidden></select>
@@ -1085,7 +1115,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.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress"};
+const EN = {"任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","<div class=\"ph-kb\" data-type=\"Keyboard\">键盘</div>":"<div class=\"ph-kb\" data-type=\"Keyboard\">Keyboard</div>","<li class=\"empty-note\">打开这一页时会读取已安装的 App。</li>":"<li class=\"empty-note\">The installed apps are read when this tab opens.</li>","<li class=\"sr-only\">正在读取 App 列表…</li>":"<li class=\"sr-only\">Reading the app list…</li>","<li class=\"sr-only\">正在读取元素…</li>":"<li class=\"sr-only\">Reading elements…</li>","<option>没有可用的 AI</option>":"<option>No AI available</option>","<p class=\"empty-note\">正在连接 iphone-control 服务…</p>":"<p class=\"empty-note\">Connecting to the iphone-control service…</p>","<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>演示模式</span></span>":"<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>Demo</span></span>","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。":"Run <code>iphone-control sign</code> to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 <code>iphone-control setup --reconfigure</code> 选「手机」,在设备上点「信任」。":"Run <code>iphone-control setup --reconfigure</code>, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress"};
Object.assign(EN, {
'未连接设备':'No device connected', '用数据线连接 iPhone 或 iPad。':'Connect an iPhone or iPad with a USB cable.', '等待设备连接':'Waiting for a device',
'外观':'Appearance', '界面字号':'Text size', '标准':'Standard', '大':'Large', '特大':'Extra large',
@@ -1415,6 +1445,7 @@ const S = {
daemon: null, dstatus: null, statusErr: '',
devices: [], devicesErr: '',
apps: [], appsState: 'idle', appsErr: '',
+ scope: [], scopeApps: null, scopeAppsFor: '', scopeErr: '',
elements: [], elState: 'idle', elErr: '',
tasks: [], expanded: new Set(), seq: 0,
udid: null, deviceName: '', switching: false, signing: false, // 本页显示的设备:画面、操作、面板都跟着它
@@ -2785,7 +2816,7 @@ function upsertStep(task, d) {
}
async function runLive(task) {
try {
- const v = await api('/api/agent/tasks', { prompt: task.prompt, agent: task.agent });
+ const v = await api('/api/agent/tasks', { prompt: task.prompt, agent: task.agent, apps: task.apps || [] });
follow(task, v.id);
} catch (e) {
task.steps.push({ n: 1, tool: null, status: 'error', result: String(e.message || e) });
@@ -2821,7 +2852,7 @@ async function adoptTask() {
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 };
+ const task = { id: 't' + (++S.seq), prompt: t.title, status: t.state, steps: [], startedAt: t.started || Date.now(), source: 'live', agent: t.owner, apps: t.apps || [] };
S.tasks.push(task); S.expanded.add(task.id);
follow(task, t.id);
renderAll(); scrollConvo();
@@ -2862,11 +2893,11 @@ function sendPrompt() {
clearPromptError();
if (startTask(text)) { promptEl.value = ''; autosize(); }
}
-function startTask(text) {
+function startTask(text, apps = S.scope) {
if (activeTask()) return false;
if (S.mode === 'detecting') { show(tr('还在连接服务,稍等一下再开始'), 'warn'); return false; }
S.pendingDelete = null;
- const task = { id: 't' + (++S.seq), prompt: text, status: 'running', steps: [], startedAt: Date.now(), source: S.mode, agent: S.agent };
+ const task = { id: 't' + (++S.seq), prompt: text, status: 'running', steps: [], startedAt: Date.now(), source: S.mode, agent: S.agent, apps: S.mode === 'live' ? [...apps] : [] };
S.tasks.push(task); S.expanded.add(task.id);
renderAll(); scrollConvo();
($('[data-focus="rc-pause"]') || $('#intro-title')).focus({ preventScroll: true });
@@ -2877,7 +2908,8 @@ function startTask(text) {
function rerunTask(id) {
const t = S.tasks.find(x => x.id === id);
if (!t || activeTask() || isExternal(t)) return;
- if (startTask(t.prompt)) show(`${tr('重新执行:')}${t.prompt}`);
+ // 重新执行沿用原来的范围
+ if (startTask(t.prompt, t.apps || [])) show(`${tr('重新执行:')}${t.prompt}`);
}
let delTimer = 0;
function askDelete(id) {
@@ -3012,7 +3044,7 @@ function turnHtml(t) {
return `<li class="turn">
<div class="msg-user">
${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 class="msg-meta"><span class="msg-time">${hhmm(new Date(t.startedAt))}</span>${t.apps?.length ? `<span class="msg-scope" title="${esc(tr('任务只在这些 App 里操作:'))}${esc(scopeText(t.apps))}">${icon('grid')}<span class="od-truncate">${esc(tr('只在') + ' ' + scopeText(t.apps))}</span></span>` : ''}${actions}</div>
</div>
<div class="msg-agent">
<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>
@@ -3136,8 +3168,74 @@ async function tapSysAlert(i) {
S.sysAlert = null; renderSysAlert();
setTimeout(pollAlert, 800);
}
+/* ---------- 任务的 App 范围:开任务时可以限定只在哪些 App 里操作(守护进程强制,见 docs/task-control.md 5.5)。
+ * 选择在本次页面里一直保留,按钮上始终显示;刷新后不保留,免得忘了而让任务被悄悄限制。演示模式里没有 ---------- */
+const scopeMenu = $('#scope-menu'), scopeBtn = $('#scope-btn');
+function scopeName(bundle) {
+ const a = (S.scopeApps || []).find(x => x.bundle_id === bundle);
+ return a ? a.name : appLabel(bundle);
+}
+function scopeText(apps) { return apps.map(scopeName).join(tr('、')); }
+/* 按钮在输入框左边:面板的左边对齐按钮(共用的 positionPopover 是右对齐) */
+function placeScopeMenu() {
+ positionPopover(scopeBtn, scopeMenu, true);
+ if (!scopeMenu.matches(':popover-open')) return;
+ const r = scopeBtn.getBoundingClientRect();
+ scopeMenu.style.left = Math.max(8, Math.min(r.left, innerWidth - scopeMenu.offsetWidth - 8)) + 'px';
+}
+function renderScopePick() {
+ $('#scope-pick').hidden = S.mode !== 'live';
+ const n = S.scope.length;
+ $('#scope-name').textContent = n ? scopeText(S.scope) : tr('所有 App');
+ scopeBtn.toggleAttribute('data-scoped', n > 0);
+ scopeBtn.disabled = !!activeTask() || !S.udid;
+ scopeBtn.title = n ? `${tr('任务只在这些 App 里操作:')}${scopeText(S.scope)}` : tr('任务可以操作所有 App;点这里限定范围');
+ if (scopeBtn.disabled && scopeMenu.matches(':popover-open')) scopeMenu.hidePopover();
+}
+async function loadScopeApps() {
+ if (S.scopeApps && S.scopeAppsFor === S.udid) return;
+ const target = S.udid;
+ S.scopeErr = ''; S.scopeApps = null; renderScopeList();
+ try {
+ const apps = ((await api('/api/apps?system=1')).apps || []).slice().sort((a, b) => a.name.localeCompare(b.name));
+ if (target !== S.udid) return;
+ S.scopeApps = apps; S.scopeAppsFor = target;
+ } catch (e) { S.scopeErr = String(e.message || e); }
+ renderScopeList(); renderScopePick(); placeScopeMenu();
+}
+function renderScopeList() {
+ const list = $('#scope-list'), q = $('#scope-q').value.trim().toLowerCase();
+ const picked = new Set(S.scope);
+ $('#scope-count').textContent = picked.size ? `${tr('已选')} ${picked.size}` : tr('不限制');
+ if (S.scopeErr) { list.innerHTML = `<p class="empty-note">${esc(tr('读不到 App 列表:'))}${esc(S.scopeErr)}</p>`; return; }
+ if (!S.scopeApps) { list.innerHTML = `<p class="empty-note">${esc(tr('正在读取 App…'))}</p>`; return; }
+ // 选中的排在前面(包括列表里没有的,例如换了设备后),其余按名字
+ const known = new Set(S.scopeApps.map(a => a.bundle_id));
+ const rows = [...S.scope.filter(b => !known.has(b)).map(b => ({ name: scopeName(b), bundle_id: b })), ...S.scopeApps]
+ .filter(a => !q || a.name.toLowerCase().includes(q) || a.bundle_id.toLowerCase().includes(q))
+ .sort((a, b) => Number(picked.has(b.bundle_id)) - Number(picked.has(a.bundle_id)));
+ list.innerHTML = rows.length ? rows.map(a => `<label class="scope-row"><input type="checkbox" value="${esc(a.bundle_id)}"${picked.has(a.bundle_id) ? ' checked' : ''}><span class="scope-app"><b>${esc(a.name)}</b><small>${esc(a.bundle_id)}</small></span></label>`).join('')
+ : `<p class="empty-note">${esc(tr('没有名称或 bundle id 含「'))}${esc(q)}${esc(tr('」的 App。'))}</p>`;
+}
+function toggleScope(bundle, on) {
+ S.scope = on ? [...new Set([...S.scope, bundle])] : S.scope.filter(b => b !== bundle);
+ $('#scope-count').textContent = S.scope.length ? `${tr('已选')} ${S.scope.length}` : tr('不限制');
+ renderScopePick();
+}
+scopeMenu.addEventListener('beforetoggle', ev => {
+ const opening = ev.newState === 'open';
+ scopeBtn.setAttribute('aria-expanded', String(opening));
+ if (opening) { $('#scope-q').value = ''; renderScopeList(); loadScopeApps(); requestAnimationFrame(placeScopeMenu); }
+ else renderScopeList();
+});
+scopeMenu.addEventListener('toggle', ev => { if (ev.newState === 'open') { placeScopeMenu(); $('#scope-q').focus(); } });
+addEventListener('resize', placeScopeMenu);
+$('#scope-list').addEventListener('change', ev => { if (ev.target.matches('input[type="checkbox"]')) toggleScope(ev.target.value, ev.target.checked); });
+$('#scope-q').addEventListener('input', renderScopeList);
+$('#scope-clear').addEventListener('click', () => { S.scope = []; renderScopeList(); renderScopePick(); });
+$('#scope-done').addEventListener('click', () => { scopeMenu.hidePopover(); scopeBtn.focus(); });
function renderAll() {
- keepFocus(() => { renderRunbar(); renderGuard(); renderManual(); renderTurns(); renderChips(); renderFeed(); renderAgentPick(); renderSysAlert(); });
+ keepFocus(() => { renderRunbar(); renderGuard(); renderManual(); renderTurns(); renderChips(); renderFeed(); renderAgentPick(); renderScopePick(); renderSysAlert(); });
if (S.devTab === 'apps') renderApps();
if (S.devTab === 'elements') renderElements();
}
@@ -3421,7 +3519,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, agent: t.agent, 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, apps: t.apps, 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 }))
})));
}
diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs
index 4f02318..642369a 100644
--- a/apps/iphone-control/src/viewer.rs
+++ b/apps/iphone-control/src/viewer.rs
@@ -9,7 +9,7 @@
//! - `POST /api/{tap,swipe,long_press,type,button,launch_app,terminate_app,open_url,tap_element,wait_for,select}`
//! turn into ordinary daemon requests, so they queue with an agent's calls, get auto-unlock and follow the
//! controlled device, exactly like an MCP tool call.
-//! - `/api/agent/…`: available agents, starting a task, its events (server-sent events), and pause / resume /
+//! - `/api/agent/…`: available agents, starting a task (optionally limited to some apps), its events (server-sent events), and pause / resume /
//! take over / hand back / stop / confirm.
//!
//! Protections, same model as `wda-bridge`: it binds to the loopback address only, every request needs a
@@ -404,7 +404,15 @@ 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).await {
+ // the apps the task is limited to (bundle IDs from the page's picker); absent or empty: no limit
+ let apps: Vec<String> = match &b["apps"] {
+ Value::Null => Vec::new(),
+ Value::Array(a) if a.iter().all(Value::is_string) => {
+ a.iter().filter_map(Value::as_str).map(str::to_owned).collect()
+ }
+ _ => return (400, json!({"ok": false, "message": "apps must be a list of strings"})),
+ };
+ return match ctx.agents.start(prompt, backend, &apps).await {
Ok(id) => (200, json!({"ok": true, "id": id})),
Err(m) => conflict(m),
};
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index ca95278..c9cc601 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -697,7 +697,7 @@ impl Daemon {
if let crate::tasks::Admission::Actor(t) = &admission
&& t.scoped()
{
- match self.scope_gate(t, &req, &mut ctx.gone).await {
+ match self.scope_gate(t, &req, ctx.task_step, &mut ctx.gone).await {
Ok(a) => asked = a,
Err(r) => return r,
}
@@ -726,6 +726,7 @@ impl Daemon {
&self,
task: &crate::tasks::Task,
req: &Request,
+ step: Option<u64>,
gone: &mut Option<tokio::sync::oneshot::Receiver<()>>,
) -> Result<bool, Response> {
use crate::tasks::{Check, Target};
@@ -752,7 +753,7 @@ impl Daemon {
Target::Foreground(w.active_app().await.map_err(|e| unknown(e.to_string()))?)
}
};
- task.check_scope(&target, gone).await
+ task.check_scope(&target, step, gone).await
}
/// A task's scope from names or bundle IDs: the bundle IDs, each once. `Err` names the app that isn't there
diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rs
index 469f940..b4edb3d 100644
--- a/crates/ictl-daemon/src/tasks.rs
+++ b/crates/ictl-daemon/src/tasks.rs
@@ -100,6 +100,8 @@ struct TaskState {
ended: Option<u64>,
/// Bundle IDs the task may act in ([`Target`]); empty: anywhere. Grows when the user lets it go further
scope: Vec<String>,
+ /// Steps whose action the user kept out of the task's scope: shown as rejected, not as failed
+ declined: Vec<u64>,
}
pub struct Task {
@@ -469,7 +471,14 @@ impl Task {
{
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)});
+ // the user said no to going outside the scope: that's a choice, not something that went wrong
+ let declined = st.declined.iter().position(|&s| s == id).map(|i| st.declined.swap_remove(i)).is_some();
+ let status = match (ok, declined) {
+ (true, _) => "ok",
+ (false, true) => "rejected",
+ (false, false) => "error",
+ };
+ let mut d = json!({"id": id, "status": status, "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
@@ -560,10 +569,12 @@ impl Task {
/// 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
+ /// (unlike a rejected [`Self::confirm`], the task doesn't end as rejected). `step`: the tool call the action
+ /// belongs to, shown as rejected when the user says no. Returns whether it waited
pub async fn check_scope(
&self,
target: &Target,
+ step: Option<u64>,
gone: &mut Option<oneshot::Receiver<()>>,
) -> Result<bool, Response> {
let ask = {
@@ -581,10 +592,15 @@ impl Task {
}
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::Rejected => Err({
+ if let Some(s) = step {
+ self.lock().declined.push(s);
+ }
+ 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()),
}
@@ -746,6 +762,7 @@ impl Tasks {
rejected: false,
ended: None,
scope: apps,
+ declined: Vec::new(),
}),
tx: broadcast::channel(4096).0,
changed: Notify::new(),
@@ -980,6 +997,7 @@ fn restore(file: &Path) -> Option<Task> {
confirm: None,
rejected: false,
ended: None,
+ declined: Vec::new(),
scope: first["apps"]
.as_array()
.map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect())
@@ -1352,8 +1370,8 @@ mod tests {
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.check_scope(&wechat, None, &mut None).await.ok(), Some(true), "asked, then let through");
+ assert_eq!(t.check_scope(&wechat, None, &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");
}
@@ -1363,8 +1381,19 @@ mod tests {
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;
+ // the tool call that tried it (step 7) shows as rejected, not failed; another failing call stays an error
+ let r = t.check_scope(&Target::Launch("com.apple.MobileSMS".into()), Some(7), &mut None).await;
assert!(matches!(r, Err(Response::Error { message, .. }) if message.contains("com.apple.Preferences")));
+ t.step_done(7, false, 5, "refused", None);
+ t.step_done(8, false, 5, "WDA unavailable", None);
+ let (log, _, _) = t.subscribe();
+ let status = |id: u64| {
+ log.iter()
+ .rev()
+ .find(|e| e.event == "step" && e.data["id"] == id && e.data.get("ms").is_some())
+ .map(|e| e.data["status"].clone())
+ };
+ assert_eq!((status(7), status(8)), (Some(json!("rejected")), Some(json!("error"))));
assert_eq!(t.info().state, "running");
assert_eq!(t.info().apps, scope(&["com.apple.Preferences"]));
t.finish(true, "改好了");
@@ -1377,10 +1406,9 @@ mod tests {
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 },
- );
+ let asking = tokio::spawn(async move {
+ t2.check_scope(&Target::Foreground("com.tencent.xin".into()), None, &mut Some(rx)).await
+ });
while t.info().state != "waiting" {
tokio::time::sleep(Duration::from_millis(5)).await;
}
diff --git a/docs/architecture.md b/docs/architecture.md
index 5251089..306d3a6 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -49,7 +49,7 @@
- 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。开任务时可以限定 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`,刷新前在跟的任务和在别处开的任务都会接上。
+- 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 先在守护进程里开任务(带上页面选的 App 范围 `apps`,并在给 agent 的说明里写明范围)、拿住租约,再带着 `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/task-control.md b/docs/task-control.md
index 36f1c50..cd0ff8a 100644
--- a/docs/task-control.md
+++ b/docs/task-control.md
@@ -172,7 +172,7 @@ Running → Waiting(等确认)→ Running
### 5.5 任务范围(阶段三的前一半)
-开任务时可以带 `apps`(App 名或 Bundle ID;`iphone-control task run --app …` 可以写多次)。开任务时就解析成 Bundle ID,名字写错直接开不了任务。不带就是不限制,和以前一样。
+开任务时可以带 `apps`(App 名或 Bundle ID;`iphone-control task run --app …` 可以写多次;控制台上是 Agent 旁边的 App 按钮,传 Bundle ID)。开任务时就解析成 Bundle ID,名字写错直接开不了任务。不带就是不限制,和以前一样。
有范围的任务,每个操作执行之前守护进程检查它会碰到哪个 App(`tasks::scope_check`):
@@ -195,7 +195,7 @@ Running → Waiting(等确认)→ Running
和第 2 节的目标架构相比:
- **口令只有一种**(2.5):开任务的一方拿到的口令同时交给 Agent,控制请求(暂停、确认)不验口令。在同一个用户下这本来就不是边界(D13、D17),等 Agent 跑进沙箱时再分开,届时加上 `SO_PEERCRED`。
-- **任务范围已有,策略还没有**(2.6):限定 App 后越界会停下来问人(5.5);但范围内的敏感动作(在微信里发消息)仍然靠 Agent 调 `iphone_confirm`。控制台上开的任务还不能设范围。
+- **任务范围已有,策略还没有**(2.6):限定 App 后越界会停下来问人(5.5);但范围内的敏感动作(在微信里发消息)仍然靠 Agent 调 `iphone_confirm`。控制台上开任务时也能设范围(Agent 旁边的 App 按钮,2026-11-13)。
- **观察版本是简化版**(2.7):只有一个「需要重新看」的标记,在交还、或别人在接管期间动过手机后置上,Agent 截图、读元素或等文字之后清掉。动作不带「基于哪次观察」,所以 Agent 自己连续操作时不做这项检查。
- **事件不带编号**(2.10):重连时从头重放,没有从断点继续。任务事件全是文字,从头重放代价不大。
- **设备拔掉时**(2.9):任务不中断,它的请求会被拒绝(找不到绑定的设备),插回同一台手机后可以继续;只有换成另一台设备才中断。
diff --git a/tests/device/tasks.py b/tests/device/tasks.py
index 6d59029..b15e118 100644
--- a/tests/device/tasks.py
+++ b/tests/device/tasks.py
@@ -393,6 +393,10 @@ async def scope(stack):
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)
+ if not approve:
+ # the tool call the user kept out of scope shows as rejected on the page, not as failed
+ done = [e for e in lease.of("step") if "ms" in e and e.get("status") in ("rejected", "error")]
+ check(c, "…and its step is shown as rejected, not failed", bool(done) and done[-1]["status"] == "rejected", json.dumps(done[-1:], ensure_ascii=False))
return shown
shown = await outside("iphone_launch_app", {"app": "时钟"}, False)
diff --git a/tests/viewer/scope.test.mjs b/tests/viewer/scope.test.mjs
new file mode 100644
index 0000000..a834ece
--- /dev/null
+++ b/tests/viewer/scope.test.mjs
@@ -0,0 +1,98 @@
+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 handlers with the network and DOM replaced (same approach as actions.test.mjs)
+function handlers(names, context) {
+ const fns = names.map(n => {
+ const m = html.match(new RegExp(`^(?:async )?function ${n}\\([^]*?^}`, 'm'));
+ assert.ok(m, n);
+ return m[0];
+ });
+ return runInNewContext(fns.join('\n') + `\n({${names}})`, context);
+}
+// through JSON: values made inside the vm have that realm's prototypes
+const plain = v => JSON.parse(JSON.stringify(v));
+const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+const APPS = [{ name: '时钟', bundle_id: 'com.apple.mobiletimer' }, { name: '设置', bundle_id: 'com.apple.Preferences' }, { name: '照片', bundle_id: 'com.apple.mobileslideshow' }];
+
+function dom() {
+ const els = {};
+ const el = id => (els[id] ??= { id, hidden: false, disabled: false, textContent: '', innerHTML: '', title: '', value: '', attrs: new Set(),
+ toggleAttribute(a, on) { on ? this.attrs.add(a) : this.attrs.delete(a); }, matches: () => false, hidePopover() {} });
+ return { els, $: sel => el(sel.replace('#', '')) };
+}
+
+test('a task from the page carries its app scope to the viewer', async () => {
+ const sent = [];
+ const context = { tr: String, finish() {}, follow() {}, async api(path, body) { sent.push([path, body]); return { id: 'abc' }; } };
+ const { runLive } = handlers(['runLive'], context);
+ await runLive({ prompt: '把亮度调到一半', agent: 'claude', apps: ['com.apple.Preferences'], steps: [] });
+ await runLive({ prompt: '看看时间', agent: 'claude', steps: [] });
+ assert.deepEqual(plain(sent), [
+ ['/api/agent/tasks', { prompt: '把亮度调到一半', agent: 'claude', apps: ['com.apple.Preferences'] }],
+ ['/api/agent/tasks', { prompt: '看看时间', agent: 'claude', apps: [] }],
+ ]);
+});
+
+test('running a task again keeps the scope it had, not the one picked now', () => {
+ const started = [];
+ const S = { agents: [], scope: ['com.apple.mobiletimer'], tasks: [
+ { id: 't1', source: 'live', agent: 'claude', prompt: '改设置', apps: ['com.apple.Preferences'] },
+ { id: 't2', source: 'live', agent: 'claude', prompt: '看看', apps: undefined },
+ ] };
+ const context = { S, tr: String, show() {}, BUILTIN_AGENTS: { claude: 'Claude Code', codex: 'Codex' }, activeTask: () => null,
+ startTask: (p, apps) => { started.push([p, apps]); return true; } };
+ const { rerunTask } = handlers(['isExternal', 'rerunTask'], context);
+ rerunTask('t1'); rerunTask('t2');
+ assert.deepEqual(plain(started), [['改设置', ['com.apple.Preferences']], ['看看', []]], 'an old record without a scope runs without one');
+});
+
+test('the picker lists picked apps first, searches, and toggles', () => {
+ const { els, $ } = dom();
+ const S = { scope: ['com.apple.Preferences', 'com.example.gone'], scopeApps: APPS, scopeErr: '', mode: 'live', udid: 'U' };
+ const context = { S, $, tr: String, esc, appLabel: b => b, activeTask: () => null, scopeMenu: { matches: () => false }, scopeBtn: $('#scope-btn') };
+ const { renderScopeList, toggleScope } = handlers(['scopeName', 'scopeText', 'renderScopePick', 'renderScopeList', 'toggleScope'], context);
+ renderScopeList();
+ const order = [...els['scope-list'].innerHTML.matchAll(/value="([^"]+)"/g)].map(m => m[1]);
+ assert.deepEqual(order.slice(0, 2), ['com.example.gone', 'com.apple.Preferences'], 'picked first, even one the list lacks');
+ assert.equal((els['scope-list'].innerHTML.match(/ checked/g) || []).length, 2);
+ assert.equal(els['scope-count'].textContent, '已选 2');
+ $('#scope-q').value = 'timer';
+ renderScopeList();
+ assert.deepEqual([...els['scope-list'].innerHTML.matchAll(/value="([^"]+)"/g)].map(m => m[1]), ['com.apple.mobiletimer']);
+ toggleScope('com.apple.mobiletimer', true); toggleScope('com.apple.mobiletimer', true);
+ toggleScope('com.example.gone', false);
+ assert.deepEqual(plain(S.scope), ['com.apple.Preferences', 'com.apple.mobiletimer'], 'each once, removed when unticked');
+});
+
+test('the button says what the task is limited to, and waits while a task runs', () => {
+ const { els, $ } = dom();
+ const S = { scope: [], scopeApps: APPS, mode: 'live', udid: 'U' };
+ let active = null;
+ const context = { S, $, tr: String, esc, appLabel: b => b, activeTask: () => active, scopeMenu: { matches: () => false, hidePopover() {} }, scopeBtn: $('#scope-btn') };
+ const { renderScopePick } = handlers(['scopeName', 'scopeText', 'renderScopePick'], context);
+ renderScopePick();
+ assert.equal(els['scope-name'].textContent, '所有 App');
+ assert.equal(els['scope-btn'].attrs.has('data-scoped'), false);
+ S.scope = ['com.apple.Preferences', 'com.apple.mobiletimer'];
+ renderScopePick();
+ assert.equal(els['scope-name'].textContent, '设置、时钟');
+ assert.equal(els['scope-btn'].attrs.has('data-scoped'), true);
+ assert.equal(els['scope-btn'].disabled, false);
+ active = { status: 'running' };
+ renderScopePick();
+ assert.equal(els['scope-btn'].disabled, true, 'a running task keeps its scope');
+ S.mode = 'demo';
+ renderScopePick();
+ assert.equal(els['scope-pick'].hidden, true, 'nothing enforces it in the demo');
+});
+
+test('the button is announced as the task scope, not just an app name', () => {
+ const btn = html.match(/<button[^>]*id="scope-btn"[^>]*>/)[0];
+ assert.match(btn, /aria-labelledby="scope-label scope-name"/);
+ assert.match(html, /<span class="sr-only" id="scope-label">任务范围<\/span>/);
+});
diff --git a/website/en/guide/cli.md b/website/en/guide/cli.md
index 2a51fb9..0d9d25f 100644
--- a/website/en/guide/cli.md
+++ b/website/en/guide/cli.md
@@ -101,7 +101,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 |
+| `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). Before it starts you can limit it to some apps with the App button next to the agent; in any other app each step waits for you. You can pause, take over and hand back, or stop it, and it asks on the page before paying, deleting or sending messages. Every local user can reach the port, so stop it when done |
| `task run [--title <title>] [--app <app>…] -- <command>` | AI tasks for other agent platforms: opens a task on the controlled device and runs the command in it. An `iphone-control mcp` the command starts takes part (through `IPHONE_CONTROL_TASK_TOKEN`): the control page shows every step and can pause, take over and stop it, and it waits for you before paying or sending a message. The task ends when the command does; when the task is stopped elsewhere, so is the command; Ctrl-C stops the task. While a task runs, other clients can look but not act on the phone. `--app` (repeatable, name or bundle ID) limits the task to those apps: in any other app, or to open a link that isn't a web page, each step waits for you first |
| `task list` / `task events <id>` | Recent tasks (`--json` for programs); follow a task's events, one JSON per line |
| `task pause\|resume\|takeover\|handback\|stop <id>`, `task approve\|reject <id>` | Control a task from the command line, like the buttons on the control page |
diff --git a/website/guide/cli.md b/website/guide/cli.md
index 00791e1..e05bf3a 100644
--- a/website/guide/cli.md
+++ b/website/guide/cli.md
@@ -101,7 +101,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,在页面上选)。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。本机任何用户都能连上这个端口,用完就停 |
+| `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,在页面上选)。开任务前可以用 Agent 旁边的 App 按钮限定范围,到了别的 App 每一步都先等你确认。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。本机任何用户都能连上这个端口,用完就停 |
| `task run [--title <标题>] [--app <App>…] -- <命令>` | 给别的 agent 平台用的 AI 任务:在当前控制的设备上开一个任务,再运行这条命令。命令启动的 `iphone-control mcp` 自动加入任务(经环境变量 `IPHONE_CONTROL_TASK_TOKEN`),控制台上能看到每一步,可以暂停、接管、停止,付款、发消息之前会等你确认。命令结束,任务就结束;任务在别处被停止,命令也会被停止;按 Ctrl-C 等于停止任务。任务进行中,其他客户端只能看,不能操作手机。`--app`(可写多次,App 名或 Bundle ID)把任务限定在这些 App 里:到了别的 App、或者要打开网页以外的链接,每一步都先等你确认 |
| `task list` / `task events <id>` | 最近的任务(`--json` 给程序读);跟着一个任务的事件,每行一个 JSON |
| `task pause\|resume\|takeover\|handback\|stop <id>`、`task approve\|reject <id>` | 在命令行里控制任务,和控制台上的按钮一样 |