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

refactor: the viewer reads the daemon's data, not its text; client and process-group code in one place (#92)

Qinghe Li991864e9ecdf
diff --git a/apps/iphone-control/src/agent.rs b/apps/iphone-control/src/agent.rs
index 334a56b..af9fce6 100644
--- a/apps/iphone-control/src/agent.rs
+++ b/apps/iphone-control/src/agent.rs
@@ -262,7 +262,7 @@ impl Agents {
if e.is_none_or(|e| e.event == "done") {
ended = true;
if let Some(pid) = pid {
- kill_group(pid);
+ crate::procgroup::stop(pid);
}
}
}
@@ -405,16 +405,6 @@ fn parse_line(backend: Backend, v: &Value) -> Option<Out> {
}
}
-/// SIGTERM to the agent and everything it started (its MCP server), SIGKILL a little later if still there
-fn kill_group(pid: u32) {
- let pgid = pid as libc::pid_t;
- unsafe { libc::kill(-pgid, libc::SIGTERM) };
- tokio::spawn(async move {
- tokio::time::sleep(Duration::from_secs(3)).await;
- unsafe { libc::kill(-pgid, libc::SIGKILL) };
- });
-}
-
/// What the agent is told, besides the task, in the task's language
fn instructions() -> &'static str {
ictl_l10n::tr!(
diff --git a/apps/iphone-control/src/client.rs b/apps/iphone-control/src/client.rs
new file mode 100644
index 0000000..6514911
--- /dev/null
+++ b/apps/iphone-control/src/client.rs
@@ -0,0 +1,106 @@
+//! Talking to the daemon from this program: the CLI's commands, the setup guide, the viewer and the updater ask
+//! through these, not through the CLI's entry point
+
+use std::path::Path;
+use std::time::Duration;
+
+use anyhow::{Context, bail};
+use ictl_daemon::config::env as env_nonempty;
+use ictl_daemon::protocol::{self, Request, Response};
+
+pub async fn ask(socket: &Path, req: Request) -> anyhow::Result<Response> {
+ // 签名要等装完,不设时限;其余命令守护进程忙也最多等 3 分钟
+ let timeout = match req {
+ Request::Resign { .. } => None,
+ _ => Some(Duration::from_secs(180)),
+ };
+ protocol::call(socket, &req, timeout).await.with_context(|| {
+ ictl_l10n::trf!("连不上守护进程({}):先启动它(iphone-control service start;没装后台服务的,运行 iphone-control 按引导装,或在另一个终端运行 iphone-control daemon);\
+ 守护进程以别的用户运行时,用 --socket 或 ICTL_SOCKET 指到它的控制接口", "Can't reach the daemon ({}): start it first (iphone-control service start; without a background service, run iphone-control and let the guide set one up, or run iphone-control daemon in another terminal); if the daemon runs as another user, point --socket or ICTL_SOCKET at its control socket",
+ socket.display()
+ )
+ })
+}
+
+pub async fn print_text(socket: &Path, req: Request) -> anyhow::Result<()> {
+ match ask(socket, req).await? {
+ Response::Text { text, .. } => {
+ println!("{text}");
+ Ok(())
+ }
+ Response::Error { message, .. } => bail!("{message}"),
+ Response::Image { caption, .. } => {
+ println!("{caption}");
+ Ok(())
+ }
+ }
+}
+
+pub async fn snapshot(socket: &Path) -> anyhow::Result<ictl_daemon::Snapshot> {
+ match ask(socket, Request::Daemon).await? {
+ Response::Text { text, .. } => Ok(serde_json::from_str(&text)?),
+ Response::Error { message, .. } => bail!("{message}"),
+ Response::Image { .. } => {
+ bail!("{}", ictl_l10n::tr!("守护进程返回了意外的响应", "The daemon sent an unexpected response"))
+ }
+ }
+}
+
+/// 账号目录和 anisette 地址:与守护进程同一份配置(路径、环境变量的读法都在 Config 里)
+pub fn account_dir(data_dir: &Path) -> ictl_sign::AccountDir {
+ let cfg = ictl_daemon::Config::from_env(data_dir);
+ ictl_sign::AccountDir { dir: cfg.account_dir(), anisette_url: cfg.anisette_url }
+}
+
+/// 命令要针对哪台设备:`IPHONE_UDID` > 守护进程正在控制的(或选定的)> USB 上唯一的一台。
+/// 给了 `query`(UDID 或设备名)就在接着的设备里找
+pub async fn target_device(socket: &Path, query: Option<&str>) -> anyhow::Result<ictl_device::DeviceInfo> {
+ let snap = snapshot(socket).await.ok();
+ let mut infos = snap.as_ref().map(|s| s.devices.clone()).unwrap_or_default();
+ if infos.is_empty() {
+ for d in ictl_device::list_devices().await.unwrap_or_default() {
+ let i = ictl_device::Device::from_usb(&d).info().await.unwrap_or_default();
+ infos.push(ictl_device::DeviceInfo { udid: d.udid, ..i });
+ }
+ }
+ let pick = |u: &str| {
+ infos
+ .iter()
+ .find(|d| d.udid.eq_ignore_ascii_case(u))
+ .cloned()
+ .unwrap_or_else(|| ictl_device::DeviceInfo { udid: u.to_owned(), ..Default::default() })
+ };
+ if let Some(q) = query {
+ let i = ictl_daemon::devices::resolve_device(&infos, q).map_err(anyhow::Error::msg)?;
+ return Ok(infos[i].clone());
+ }
+ if let Some(u) = env_nonempty("IPHONE_UDID") {
+ return Ok(pick(&u));
+ }
+ if let Some(s) = &snap {
+ if let Some(d) = &s.device {
+ return Ok(d.clone());
+ }
+ if let Some(p) = &s.pinned {
+ return Ok(pick(p));
+ }
+ }
+ match &infos[..] {
+ [one] => Ok(one.clone()),
+ [] => bail!(
+ "{}",
+ ictl_l10n::tr!(
+ "没接设备:用数据线接好并解锁",
+ "No device connected: plug it in with a data cable and unlock it"
+ )
+ ),
+ _ => bail!(
+ "{}",
+ ictl_l10n::trf!(
+ "接着 {} 台设备,不知道是哪台:先用 iphone-control select 选一台,或加 --device 指定",
+ "{} devices connected, not sure which one: choose one with iphone-control select, or pass --device",
+ infos.len()
+ )
+ ),
+ }
+}
diff --git a/apps/iphone-control/src/guide.rs b/apps/iphone-control/src/guide.rs
index 9a4f858..810665b 100644
--- a/apps/iphone-control/src/guide.rs
+++ b/apps/iphone-control/src/guide.rs
@@ -138,7 +138,7 @@ async fn setup_inner(cli: &Cli, reconfigure: bool) -> anyhow::Result<()> {
daemon(cli, false).await?;
crate::login(&cli.data_dir, None).await?;
println!("{}", ictl_l10n::tr!("用新的账号重签 WDA…", "Re-signing WDA with the account…"));
- crate::print_text(&cli.socket, ictl_daemon::protocol::Request::Resign { force: true }).await?;
+ crate::client::print_text(&cli.socket, ictl_daemon::protocol::Request::Resign { force: true }).await?;
}
5 => {
daemon(cli, false).await?;
@@ -211,7 +211,7 @@ async fn full_with(cli: &Cli, force: bool) -> anyhow::Result<()> {
/// Already set up: make sure the daemon runs, then show where things stand
async fn already_set_up(cli: &Cli) -> anyhow::Result<()> {
- if crate::snapshot(&cli.socket).await.is_err()
+ if crate::client::snapshot(&cli.socket).await.is_err()
&& let Some(s) = service::find()
{
println!("{}", ictl_l10n::tr!("守护进程没在运行,正在启动…", "The daemon isn't running, starting it…"));
@@ -278,12 +278,12 @@ fn proxy(env: &mut EnvFile, force: bool) -> anyhow::Result<bool> {
}
async fn wait_daemon(socket: &Path, timeout: Duration) -> bool {
- crate::wait_until(timeout, Duration::from_secs(1), || async { crate::snapshot(socket).await.is_ok() }).await
+ crate::wait_until(timeout, Duration::from_secs(1), || async { crate::client::snapshot(socket).await.is_ok() }).await
}
/// Makes sure the daemon runs (as a service if the user agrees); `restart` reloads changed settings
async fn daemon(cli: &Cli, restart: bool) -> anyhow::Result<()> {
- let running = crate::snapshot(&cli.socket).await.is_ok();
+ let running = crate::client::snapshot(&cli.socket).await.is_ok();
match (running, service::find()) {
(true, Some(s)) if restart => {
println!(
@@ -385,7 +385,7 @@ async fn reinstall_service(cli: &Cli) -> anyhow::Result<()> {
async fn passcode(cli: &Cli, force: bool) -> anyhow::Result<()> {
let cfg = ictl_daemon::Config::from_env(&cli.data_dir);
- let device = crate::target_device(&cli.socket, None).await?;
+ let device = crate::client::target_device(&cli.socket, None).await?;
let set = cfg.passcode_file_for(&device.udid).is_file();
println!(
"{}",
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index d61e8e1..780dcab 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -8,18 +8,21 @@ use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;
-use anyhow::{Context, bail};
+use anyhow::bail;
use clap::{Parser, Subcommand};
+use client::{account_dir, print_text, snapshot, target_device};
use ictl_daemon::config::env as env_nonempty;
-use ictl_daemon::protocol::{self, Request, Response};
+use ictl_daemon::protocol::{self, Request};
mod agent;
+mod client;
mod completions;
#[cfg(feature = "debug-cmds")]
mod debug;
mod envfile;
mod guide;
mod mcp_bridge;
+mod procgroup;
mod remote;
mod schedule;
mod service;
@@ -722,44 +725,6 @@ fn shell_quote(s: &str) -> String {
}
}
-async fn ask(socket: &Path, req: Request) -> anyhow::Result<Response> {
- // 签名要等装完,不设时限;其余命令守护进程忙也最多等 3 分钟
- let timeout = match req {
- Request::Resign { .. } => None,
- _ => Some(Duration::from_secs(180)),
- };
- protocol::call(socket, &req, timeout).await.with_context(|| {
- ictl_l10n::trf!("连不上守护进程({}):先启动它(iphone-control service start;没装后台服务的,运行 iphone-control 按引导装,或在另一个终端运行 iphone-control daemon);\
- 守护进程以别的用户运行时,用 --socket 或 ICTL_SOCKET 指到它的控制接口", "Can't reach the daemon ({}): start it first (iphone-control service start; without a background service, run iphone-control and let the guide set one up, or run iphone-control daemon in another terminal); if the daemon runs as another user, point --socket or ICTL_SOCKET at its control socket",
- socket.display()
- )
- })
-}
-
-async fn print_text(socket: &Path, req: Request) -> anyhow::Result<()> {
- match ask(socket, req).await? {
- Response::Text { text, .. } => {
- println!("{text}");
- Ok(())
- }
- Response::Error { message, .. } => bail!("{message}"),
- Response::Image { caption, .. } => {
- println!("{caption}");
- Ok(())
- }
- }
-}
-
-async fn snapshot(socket: &Path) -> anyhow::Result<ictl_daemon::Snapshot> {
- match ask(socket, Request::Daemon).await? {
- Response::Text { text, .. } => Ok(serde_json::from_str(&text)?),
- Response::Error { message, .. } => bail!("{message}"),
- Response::Image { .. } => {
- bail!("{}", ictl_l10n::tr!("守护进程返回了意外的响应", "The daemon sent an unexpected response"))
- }
- }
-}
-
async fn status(socket: &Path) -> anyhow::Result<()> {
let s = snapshot(socket).await?;
println!("{}", ictl_l10n::trf!("状态 {}", "State {}", s.state.describe()));
@@ -928,12 +893,6 @@ fn read_secret(prompt: &str) -> anyhow::Result<String> {
r
}
-/// 账号目录和 anisette 地址:与守护进程同一份配置(路径、环境变量的读法都在 Config 里)
-fn account_dir(data_dir: &Path) -> ictl_sign::AccountDir {
- let cfg = ictl_daemon::Config::from_env(data_dir);
- ictl_sign::AccountDir { dir: cfg.account_dir(), anisette_url: cfg.anisette_url }
-}
-
async fn login(data_dir: &Path, email: Option<String>) -> anyhow::Result<()> {
println!(
"{}",
@@ -988,59 +947,6 @@ async fn login(data_dir: &Path, email: Option<String>) -> anyhow::Result<()> {
Ok(())
}
-/// 命令要针对哪台设备:`IPHONE_UDID` > 守护进程正在控制的(或选定的)> USB 上唯一的一台。
-/// 给了 `query`(UDID 或设备名)就在接着的设备里找
-async fn target_device(socket: &Path, query: Option<&str>) -> anyhow::Result<ictl_device::DeviceInfo> {
- let snap = snapshot(socket).await.ok();
- let mut infos = snap.as_ref().map(|s| s.devices.clone()).unwrap_or_default();
- if infos.is_empty() {
- for d in ictl_device::list_devices().await.unwrap_or_default() {
- let i = ictl_device::Device::from_usb(&d).info().await.unwrap_or_default();
- infos.push(ictl_device::DeviceInfo { udid: d.udid, ..i });
- }
- }
- let pick = |u: &str| {
- infos
- .iter()
- .find(|d| d.udid.eq_ignore_ascii_case(u))
- .cloned()
- .unwrap_or_else(|| ictl_device::DeviceInfo { udid: u.to_owned(), ..Default::default() })
- };
- if let Some(q) = query {
- let i = ictl_daemon::devices::resolve_device(&infos, q).map_err(anyhow::Error::msg)?;
- return Ok(infos[i].clone());
- }
- if let Some(u) = env_nonempty("IPHONE_UDID") {
- return Ok(pick(&u));
- }
- if let Some(s) = &snap {
- if let Some(d) = &s.device {
- return Ok(d.clone());
- }
- if let Some(p) = &s.pinned {
- return Ok(pick(p));
- }
- }
- match &infos[..] {
- [one] => Ok(one.clone()),
- [] => bail!(
- "{}",
- ictl_l10n::tr!(
- "没接设备:用数据线接好并解锁",
- "No device connected: plug it in with a data cable and unlock it"
- )
- ),
- _ => bail!(
- "{}",
- ictl_l10n::trf!(
- "接着 {} 台设备,不知道是哪台:先用 iphone-control select 选一台,或加 --device 指定",
- "{} devices connected, not sure which one: choose one with iphone-control select, or pass --device",
- infos.len()
- )
- ),
- }
-}
-
async fn passcode(data_dir: &Path, socket: &Path, action: PasscodeAction) -> anyhow::Result<()> {
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
let cfg = ictl_daemon::Config::from_env(data_dir);
diff --git a/apps/iphone-control/src/procgroup.rs b/apps/iphone-control/src/procgroup.rs
new file mode 100644
index 0000000..1b0c38d
--- /dev/null
+++ b/apps/iphone-control/src/procgroup.rs
@@ -0,0 +1,45 @@
+//! A command run in a process group of its own (`Command::process_group(0)`): an AI task's agent from the control
+//! page ([`crate::agent`]) or the command of `task run` ([`crate::task`]). Stopping the task stops the whole group,
+//! so the agent's MCP server and anything else it started go too.
+
+use std::time::Duration;
+
+/// How long a group has after SIGTERM before SIGKILL
+const GRACE: Duration = Duration::from_secs(3);
+
+/// SIGTERM to the group led by `pid`, SIGKILL [`GRACE`] later if it is still there
+pub fn stop(pid: u32) {
+ let Ok(pgid) = libc::pid_t::try_from(pid) else { return };
+ if pgid <= 1 {
+ // -0 and -1 would signal this process's own group, or every process
+ return;
+ }
+ unsafe { libc::kill(-pgid, libc::SIGTERM) };
+ tokio::spawn(async move {
+ tokio::time::sleep(GRACE).await;
+ unsafe { libc::kill(-pgid, libc::SIGKILL) };
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ #[tokio::test]
+ async fn stopping_the_group_stops_what_it_started() {
+ use std::os::unix::process::CommandExt;
+ // a shell (the group's leader) and a child of its own
+ let mut leader =
+ std::process::Command::new("sh").args(["-c", "sleep 30 & wait"]).process_group(0).spawn().unwrap();
+ std::thread::sleep(Duration::from_millis(200));
+ super::stop(leader.id());
+ let started = std::time::Instant::now();
+ while leader.try_wait().unwrap().is_none() {
+ assert!(started.elapsed() < Duration::from_secs(5), "still running");
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ // the group is gone too: no process with that group id is left
+ let r = unsafe { libc::kill(-(leader.id() as libc::pid_t), 0) };
+ assert!(r != 0, "a process of the group is still there");
+ }
+
+ use std::time::Duration;
+}
diff --git a/apps/iphone-control/src/task.rs b/apps/iphone-control/src/task.rs
index bc182b0..513f6af 100644
--- a/apps/iphone-control/src/task.rs
+++ b/apps/iphone-control/src/task.rs
@@ -393,14 +393,11 @@ async fn stop_here(backend: &Backend<'_>, id: &str, pid: Option<libc::pid_t>) {
}
}
-/// SIGTERM to the command's process group, SIGKILL a little later if still there
+/// The command's process group ([`crate::procgroup::stop`])
fn stop_group(pid: Option<libc::pid_t>) {
- let Some(pgid) = pid else { return };
- unsafe { libc::kill(-pgid, libc::SIGTERM) };
- tokio::spawn(async move {
- tokio::time::sleep(Duration::from_secs(3)).await;
- unsafe { libc::kill(-pgid, libc::SIGKILL) };
- });
+ if let Some(pid) = pid.and_then(|p| u32::try_from(p).ok()) {
+ crate::procgroup::stop(pid);
+ }
}
#[cfg(test)]
diff --git a/apps/iphone-control/src/update/channel.rs b/apps/iphone-control/src/update/channel.rs
index a927975..ae5e127 100644
--- a/apps/iphone-control/src/update/channel.rs
+++ b/apps/iphone-control/src/update/channel.rs
@@ -138,7 +138,7 @@ async fn restart_daemon(socket: &Path, version: &str, running: bool, cmd: &[&std
async fn wait_for_daemon(socket: &Path, version: &str, within: Duration) -> bool {
let end = tokio::time::Instant::now() + within;
while tokio::time::Instant::now() < end {
- if let Ok(Ok(s)) = tokio::time::timeout(Duration::from_secs(2), crate::snapshot(socket)).await
+ if let Ok(Ok(s)) = tokio::time::timeout(Duration::from_secs(2), crate::client::snapshot(socket)).await
&& s.version.as_deref() == Some(version)
{
return true;
diff --git a/apps/iphone-control/src/update/transaction.rs b/apps/iphone-control/src/update/transaction.rs
index aba5c06..70928fc 100644
--- a/apps/iphone-control/src/update/transaction.rs
+++ b/apps/iphone-control/src/update/transaction.rs
@@ -240,7 +240,7 @@ impl Host<'_> {
if !self.owns_pid(pid) {
return false;
}
- matches!(tokio::time::timeout(Duration::from_secs(2), crate::snapshot(self.socket)).await, Ok(Ok(s)) if s.maintenance == Some(true) && s.pid == Some(pid) && s.version.as_deref() == Some(version))
+ matches!(tokio::time::timeout(Duration::from_secs(2), crate::client::snapshot(self.socket)).await, Ok(Ok(s)) if s.maintenance == Some(true) && s.pid == Some(pid) && s.version.as_deref() == Some(version))
}
}
diff --git a/apps/iphone-control/src/update/transaction/tests.rs b/apps/iphone-control/src/update/transaction/tests.rs
index e314983..53353f5 100644
--- a/apps/iphone-control/src/update/transaction/tests.rs
+++ b/apps/iphone-control/src/update/transaction/tests.rs
@@ -117,7 +117,7 @@ impl Services for TestService {
for _ in 0..2 {
let snap = tokio::time::timeout(Duration::from_secs(5), async {
loop {
- if let Ok(s) = crate::snapshot(&self.socket).await {
+ if let Ok(s) = crate::client::snapshot(&self.socket).await {
break s;
}
tokio::time::sleep(Duration::from_millis(20)).await;
@@ -180,7 +180,7 @@ async fn busy_then_replace_while_daemon_is_running() {
f.host.busy.set(false);
f.apply().await.unwrap();
f.assert_installed(&f.new);
- assert_eq!(crate::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.new.version);
+ assert_eq!(crate::client::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.new.version);
assert_eq!(outcome(&f.store.binary).unwrap().unwrap().status, "installed");
assert_eq!(fs::read_to_string(&state).unwrap(), "untouched device state");
}
@@ -194,7 +194,7 @@ async fn unhealthy_daemon_restores_last_verified_executable_and_service() {
f.host.start_healthy(&f.old.version).await.unwrap();
assert!(f.apply().await.is_err());
f.assert_installed(&f.old);
- assert_eq!(crate::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.old.version);
+ assert_eq!(crate::client::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.old.version);
let result = outcome(&f.store.binary).unwrap().unwrap();
assert_eq!(result.status, "restored");
assert_eq!(result.suppressed_version.unwrap(), f.new.version);
@@ -296,12 +296,12 @@ async fn recovers_after_process_death_using_only_durable_records() {
write_json(&store.journal(), &tx).unwrap();
}
if phase == "starting" {
- assert_eq!(crate::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.new.version);
+ assert_eq!(crate::client::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.new.version);
}
resume(&store, &f.host, &tx).await.unwrap();
assert_eq!(digest(&store.binary).unwrap(), f.old.sha256);
assert!(!store.journal().exists());
- assert_eq!(crate::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.old.version);
+ assert_eq!(crate::client::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.old.version);
}
}
diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs
index d010cce..e1dc9c3 100644
--- a/apps/iphone-control/src/viewer.rs
+++ b/apps/iphone-control/src/viewer.rs
@@ -25,6 +25,7 @@
//! instead of tapping a phone the user isn't looking at. The device handle is looked up again for each stream, so a
//! replug (new usbmuxd id) doesn't break the picture.
+mod api;
pub mod auth;
mod lan;
mod mcp;
@@ -37,6 +38,7 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use anyhow::bail;
+use api::*;
use ictl_daemon::machine::DeviceState;
use ictl_daemon::protocol::{self, Request, Response, TouchPhase};
use serde_json::{Value, json};
@@ -125,7 +127,7 @@ pub async fn run(
// only a first guess: the page follows whichever device the daemon controls (see `info`). Not knowing yet is
// fine: the daemon may still be starting (started together with this at login), and with several devices
// connected it is the one that picks
- let udid = match crate::target_device(socket, None).await {
+ let udid = match crate::client::target_device(socket, None).await {
Ok(d) => d.udid,
Err(e) => {
eprintln!(
@@ -516,17 +518,7 @@ async fn route(
}
}
("POST", "/api/agent/tasks/open" | "/api/agent/tasks/finish") => {
- if !action_allowed(&req, &ctx.access, ctx.port, pass.program()) {
- return reply(&mut client, 403, "text/plain", b"forbidden").await;
- }
- let len = req.content_length.unwrap_or(0);
- if len > MAX_BODY {
- return reply(&mut client, 413, "text/plain", b"too large").await;
- }
- read_body(&mut client, &mut body, len).await?;
- let Ok(b) = serde_json::from_slice::<Value>(&body) else {
- return json_reply(&mut client, 400, &json!({"ok": false, "message": "bad request"})).await;
- };
+ let Some(b) = action_body(&mut client, ctx, &req, pass, &mut body).await? else { return Ok(()) };
if req.path == "/api/agent/tasks/open" {
let who = pass.who.as_ref().map_or("remote", |w| w.name.as_str());
return open_task(&mut client, ctx, &b, who).await;
@@ -565,17 +557,7 @@ async fn route(
mcp::serve(svc, &mut client, &head, body).await
}
("POST", p) if p.starts_with("/api/") => {
- if !action_allowed(&req, &ctx.access, ctx.port, pass.program()) {
- return reply(&mut client, 403, "text/plain", b"forbidden").await;
- }
- let len = req.content_length.unwrap_or(0);
- if len > MAX_BODY {
- return reply(&mut client, 413, "text/plain", b"too large").await;
- }
- read_body(&mut client, &mut body, len).await?;
- let Ok(b) = serde_json::from_slice::<Value>(&body) else {
- return json_reply(&mut client, 400, &json!({"ok": false, "message": "bad request"})).await;
- };
+ let Some(b) = action_body(&mut client, ctx, &req, pass, &mut body).await? else { return Ok(()) };
// controlling a task: who, for its log, and which local process (the daemon refuses the task's agent)
let caller = if p.starts_with("/api/agent/tasks/") {
Caller::of(&client, pass.who.as_ref()).await
@@ -741,7 +723,7 @@ async fn post(ctx: &Ctx, name: &str, b: &Value, device: Option<&str>, caller: Ca
let v = run_action(&ctx.socket, &Request::SelectDevice { device: device.to_owned() }, None, SHORT).await;
// the page follows the device it picked
if v["ok"] == true
- && let Ok(s) = crate::snapshot(&ctx.socket).await
+ && let Ok(s) = crate::client::snapshot(&ctx.socket).await
&& let Some(d) = s.device
{
*ctx.udid.lock().unwrap_or_else(|p| p.into_inner()) = d.udid;
@@ -872,6 +854,34 @@ fn sse(e: &protocol::TaskEvent) -> String {
format!("event: {}\ndata: {}\n\n", e.event, e.data)
}
+/// An action's JSON body (`POST /api/…`), once it may be sent from where it comes ([`action_allowed`]); `None` when
+/// the request was answered already (refused, too large, not JSON)
+async fn action_body(
+ client: &mut Conn,
+ ctx: &Ctx,
+ req: &Head,
+ pass: &Pass,
+ body: &mut Vec<u8>,
+) -> anyhow::Result<Option<Value>> {
+ if !action_allowed(req, &ctx.access, ctx.port, pass.program()) {
+ reply(client, 403, "text/plain", b"forbidden").await?;
+ return Ok(None);
+ }
+ let len = req.content_length.unwrap_or(0);
+ if len > MAX_BODY {
+ reply(client, 413, "text/plain", b"too large").await?;
+ return Ok(None);
+ }
+ read_body(client, body, len).await?;
+ match serde_json::from_slice::<Value>(body) {
+ Ok(b) => Ok(Some(b)),
+ Err(_) => {
+ json_reply(client, 400, &json!({"ok": false, "message": "bad request"})).await?;
+ Ok(None)
+ }
+ }
+}
+
/// `/api/agent/tasks/<id>/events`: the task's id
fn task_events_id(path: &str) -> Option<&str> {
path.strip_prefix("/api/agent/tasks/")?.strip_suffix("/events").filter(|id| !id.is_empty() && !id.contains('/'))
@@ -1257,7 +1267,7 @@ async fn run_action(socket: &Path, req: &Request, udid: Option<&str>, timeout: D
fn action_result(req: &Request, result: Result<Response, impl std::fmt::Display>) -> Value {
match result {
// tapping by text that found nothing is an ordinary answer for the agent, a failure for the page
- Ok(Response::Text { text, outcome }) => {
+ Ok(Response::Text { text, outcome, .. }) => {
let missed = matches!(req, Request::TapElement { .. }) && protocol::tapped_nothing(&text, outcome);
json!({"ok": !missed, "message": text})
}
@@ -1268,255 +1278,6 @@ fn action_result(req: &Request, result: Result<Response, impl std::fmt::Display>
}
}
-/// One daemon request whose text the page needs as data. `en`: ask in English, whose wording the parsers expect
-async fn text_of(socket: &Path, req: Request, en: bool) -> Result<String, String> {
- let call = protocol::call(socket, &req, Some(Duration::from_secs(60)));
- let r = if en { ictl_l10n::scope(ictl_l10n::Lang::En, call).await } else { call.await };
- match r {
- Ok(Response::Text { text, .. }) => Ok(text),
- Ok(Response::Error { message, .. }) => Err(message),
- Ok(Response::Image { caption, .. }) => Ok(caption),
- Err(e) => Err(e.to_string()),
- }
-}
-
-/// Screen size in points (portrait) for turning a click on the picture into a tap, and the device the viewer follows.
-/// It follows the device the daemon controls: switched on this page, on another page, with `iphone-control select`,
-/// or automatically after an unplug. The page notices `udid` changing and moves its picture and panels over; until
-/// then its actions carry the old UDID and are refused, never sent to a phone the user isn't looking at
-async fn info(ctx: &Ctx) -> Result<Value, String> {
- let s = crate::snapshot(&ctx.socket).await.map_err(|e| e.to_string())?;
- let udid = s.device.as_ref().map(|d| d.udid.as_str()).unwrap_or_default();
- *ctx.udid.lock().unwrap_or_else(|p| p.into_inner()) = udid.to_owned();
- let screen = screen_of(&s.persisted, udid);
- let live_touch = s.device.as_ref().is_some_and(|d| d.major_version() >= 27);
- Ok(json!({
- "display": s.display,
- "width": screen.map(|s| s.width),
- "height": screen.map(|s| s.height),
- "udid": udid,
- // the picture's pointer drives a finger over CoreDevice HID (iOS 27 and later); older phones get whole gestures
- "live_touch": live_touch,
- "device": s.device.as_ref().map(|d| &d.name),
- "model": s.device.as_ref().map(|d| &d.product_type),
- "model_name": s.device.as_ref().and_then(|d| d.model_name()),
- "family": s.device.as_ref().map_or("unknown", |d| d.family()),
- "state": state_of(&s.state).0,
- // the picture as H.264 (`/video`) and with which encoder; null: MJPEG only
- "video": ctx.video.as_ref().and_then(|e| e.label()),
- // the phone's own screen video can be tried (`/video?src=device`): iOS 27 and later, not turned off
- "device_video": ctx.device_video_allowed && live_touch,
- }))
-}
-
-fn state_of(s: &DeviceState) -> (&'static str, Option<String>) {
- match s {
- DeviceState::Absent => ("Absent", None),
- DeviceState::NeedsTrust => ("NeedsTrust", None),
- DeviceState::DeveloperModeOff => ("DeveloperModeOff", None),
- DeviceState::NeedsUnlock => ("NeedsUnlock", None),
- DeviceState::NeedsSigning => ("NeedsSigning", None),
- DeviceState::WdaStarting { last_error } => ("WdaStarting", last_error.clone()),
- DeviceState::NeedsAutomationPin => ("NeedsAutomationPin", None),
- DeviceState::Ready => ("Ready", None),
- }
-}
-
-fn device_json(d: &ictl_device::DeviceInfo) -> Value {
- json!({
- "udid": d.udid, "name": d.name, "model": d.product_type, "ios": d.product_version,
- "model_name": d.model_name(), "family": d.family(),
- })
-}
-
-/// `{ state, last_error?, device: { name, model, model_name, family, ios, udid }, auto_unlock }`
-async fn daemon(ctx: &Ctx) -> Result<Value, String> {
- let s = crate::snapshot(&ctx.socket).await.map_err(|e| e.to_string())?;
- let (state, last_error) = state_of(&s.state);
- Ok(json!({
- "state": state,
- "state_text": s.state.describe(),
- "last_error": last_error,
- "device": s.device.as_ref().map(device_json),
- "auto_unlock": s.auto_unlock && !s.unlock_disabled,
- // the page offers to sign and install WDA (NeedsSigning) only with an Apple ID to sign with
- "signed_in": crate::account_dir(&ctx.data_dir).selected_email().await.is_ok(),
- }))
-}
-
-/// `{ devices: [{ udid, name, model, model_name, family, ios, controlled }], fixed }`
-async fn devices(ctx: &Ctx) -> Result<Value, String> {
- let s = crate::snapshot(&ctx.socket).await.map_err(|e| e.to_string())?;
- let cur = s.device.as_ref().map(|d| d.udid.to_ascii_lowercase());
- let list: Vec<Value> = s
- .devices
- .iter()
- .map(|d| {
- let mut v = device_json(d);
- v["controlled"] = (cur.as_deref() == Some(d.udid.to_ascii_lowercase().as_str())).into();
- v
- })
- .collect();
- Ok(json!({"devices": list, "fixed": s.pinned_by_env, "auto": s.pinned.is_none()}))
-}
-
-/// `{ wda_ready, locked, foreground, foreground_id, width, height, route }`, from the English status text
-async fn status(ctx: &Ctx) -> Result<Value, String> {
- let text = text_of(&ctx.socket, Request::Status, true).await?;
- // the HID fallback needs iOS 27; an older device without WDA can't be operated at all
- let hid = crate::snapshot(&ctx.socket).await.ok().and_then(|s| s.device).is_some_and(|d| d.major_version() >= 27);
- let mut v = parse_status(&text, hid);
- if let Some(id) = v["foreground_id"].as_str().map(str::to_owned) {
- v["foreground"] = app_name(ctx, &id).await.into();
- }
- Ok(v)
-}
-
-fn parse_status(text: &str, hid: bool) -> Value {
- let field = |k: &str| text.lines().find_map(|l| l.strip_prefix(k)).map(str::trim);
- let ready = field("WDA ready:") == Some("True");
- let lock = field("Locked:");
- let locked = lock.map(|l| !l.starts_with("unlocked"));
- let fg = field("Foreground app:").filter(|s| !s.is_empty());
- let (w, h) = field("Screen:")
- .and_then(|s| s.split_whitespace().next())
- .and_then(|s| s.split_once('x'))
- .and_then(|(w, h)| Some((w.parse::<f64>().ok()?, h.parse::<f64>().ok()?)))
- .unzip();
- json!({
- "wda_ready": ready,
- "locked": locked,
- "possibly_locked": lock.is_some_and(|l| l.starts_with("possibly")),
- "foreground_id": fg,
- "foreground": fg,
- "width": w,
- "height": h,
- // without WDA, screenshots, taps and keys go over CoreDevice HID (iOS 27 and later); otherwise nothing works
- "route": if ready { "wda" } else if hid { "hid" } else { "none" },
- })
-}
-
-/// The display name of an installed app (the home screen for SpringBoard); the bundle id when unknown
-async fn app_name(ctx: &Ctx, bundle: &str) -> String {
- if bundle == SPRINGBOARD {
- return ictl_l10n::tr!("主屏幕", "Home Screen").into();
- }
- let mut names = ctx.names.lock().await;
- if !names.contains_key(bundle) {
- for system in [false, true] {
- if let Ok(list) = list_apps(ctx, system).await {
- for (n, b) in list {
- names.insert(b, n);
- }
- }
- }
- }
- names.get(bundle).cloned().unwrap_or_else(|| bundle.to_owned())
-}
-
-async fn list_apps(ctx: &Ctx, system: bool) -> Result<Vec<(String, String)>, String> {
- let text = text_of(&ctx.socket, Request::ListApps { include_system: system }, false).await?;
- Ok(text
- .lines()
- .filter_map(|l| l.split_once('\t'))
- .map(|(n, b)| (n.trim().to_owned(), b.trim().to_owned()))
- .collect())
-}
-
-/// `{ apps: [{ name, bundle_id }] }`: the user's apps, and with `system` the system's too
-async fn apps(ctx: &Ctx, system: bool) -> Result<Value, String> {
- let mut all = list_apps(ctx, false).await?;
- if system {
- all.extend(list_apps(ctx, true).await?);
- }
- let mut seen = std::collections::HashSet::new();
- all.retain(|(_, b)| seen.insert(b.clone()));
- Ok(json!({"apps": all.iter().map(|(n, b)| json!({"name": n, "bundle_id": b})).collect::<Vec<_>>()}))
-}
-
-/// `{ elements: [{ type, label, x, y, width, height }] }`, `x`/`y` the top-left corner in points
-/// `keep_locked`: a read-only visitor, for whom a locked phone isn't unlocked
-async fn elements(ctx: &Ctx, filter: &str, keep_locked: bool) -> Result<Value, String> {
- let req = Request::ListElements { filter: filter.to_owned(), limit: ELEMENT_LIMIT, max_age_ms: 0, keep_locked };
- let text = text_of(&ctx.socket, req, true).await?;
- Ok(json!({"elements": text.lines().filter_map(parse_element).collect::<Vec<_>>()}))
-}
-
-/// A system alert on the phone (a permission prompt and the like): `{ alert: null }` or
-/// `{ alert: { text, frame?: { x, y, width, height }, buttons: [{ label, x, y, width }] } }` in points: the alert's
-/// box (top left), each button's center and width. The page draws it where the real one is. The phone's own video
-/// (iOS 27, D16) can leave such an alert out: a location prompt showed there only as the dimmed screen behind it,
-/// while WDA's screenshot had it. The page asks while it shows that video and puts the alert next to the picture.
-/// `AlertCheck` is two quick WDA calls (the foreground app; the alert's text only when SpringBoard is in front); the
-/// element tree is only read when there is an alert
-async fn alert(ctx: &Ctx, keep_locked: bool) -> Result<Value, String> {
- let check = text_of(&ctx.socket, Request::AlertCheck, true).await?;
- let Some(text) = alert_text(&check) else { return Ok(json!({"alert": null})) };
- let req = Request::ListElements { filter: String::new(), limit: ELEMENT_LIMIT, max_age_ms: 0, keep_locked };
- // without its buttons the page still says there is an alert
- let els: Vec<Value> = text_of(&ctx.socket, req, true)
- .await
- .map(|t| t.lines().filter_map(parse_element).collect())
- .unwrap_or_default();
- let (frame, buttons) = alert_parts(&els);
- Ok(json!({"alert": {"text": text, "frame": frame, "buttons": buttons}}))
-}
-
-/// The alert's own text from `AlertCheck`'s English answer (`…a system alert is on screen: “text”, taps…`); `None`
-/// when it reports none
-fn alert_text(check: &str) -> Option<String> {
- let start = check.find('“')? + '“'.len_utf8();
- let end = check.rfind('”')?;
- (end > start).then(|| check[start..end].trim().to_owned()).filter(|t| !t.is_empty())
-}
-
-/// The tree's alert box, and the buttons on it (whose center lies inside it) as `{ label, x, y, width }`
-fn alert_parts(els: &[Value]) -> (Value, Vec<Value>) {
- let f = |e: &Value, k: &str| e[k].as_f64().unwrap_or(0.0);
- let Some(a) = els.iter().find(|e| e["type"] == "Alert") else { return (Value::Null, Vec::new()) };
- let frame = json!({"x": f(a, "x"), "y": f(a, "y"), "width": f(a, "width"), "height": f(a, "height")});
- let inside = |x: f64, y: f64| {
- x >= f(a, "x") && x <= f(a, "x") + f(a, "width") && y >= f(a, "y") && y <= f(a, "y") + f(a, "height")
- };
- let buttons = els
- .iter()
- .filter(|e| e["type"] == "Button")
- .map(|e| (e, f(e, "x") + f(e, "width") / 2.0, f(e, "y") + f(e, "height") / 2.0))
- .filter(|&(_, x, y)| inside(x, y))
- .map(|(e, x, y)| json!({"label": e["label"], "x": x, "y": y, "width": f(e, "width")}))
- .collect();
- (frame, buttons)
-}
-
-/// One line of `iphone_list_elements`: `Type "label" [id="…"] [value="…"] @(cx,cy) WxH`. Other lines (a note
-/// that more were left out) are skipped
-fn parse_element(line: &str) -> Option<Value> {
- let (kind, rest) = line.split_once(" \"")?;
- if kind.is_empty() || kind.contains(' ') {
- return None;
- }
- let at = rest.rfind(" @(")?;
- let (desc, geom) = (&rest[..at], &rest[at + 3..]);
- let label_end =
- [desc.find("\" id=\""), desc.find("\" value=\"")].into_iter().flatten().min().unwrap_or_else(|| {
- // no id or value: the label runs to the last quote
- desc.rfind('"').unwrap_or(desc.len())
- });
- let label = &desc[..label_end];
- let (center, size) = geom.split_once(") ")?;
- let (cx, cy) = center.split_once(',')?;
- let (w, h) = size.trim().split_once('x')?;
- let n = |s: &str| s.trim().parse::<f64>().ok();
- let (cx, cy, w, h) = (n(cx)?, n(cy)?, n(w)?, n(h)?);
- Some(json!({"type": kind, "label": label, "x": cx - w / 2.0, "y": cy - h / 2.0, "width": w, "height": h}))
-}
-
-/// The recorded screen size, only if it belongs to `udid` (a size recorded by an older version, without
-/// a device, is used as is, like the daemon does)
-fn screen_of(p: &ictl_daemon::core::Persisted, udid: &str) -> Option<ictl_device::ScreenSize> {
- p.screen_for(Some(udid)).map(|s| s.portrait())
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -2110,61 +1871,56 @@ mod tests {
}
#[test]
- fn status_text_becomes_fields() {
- let v = parse_status(
- "WDA ready: True\nLocked: locked (actions unlock automatically)\nForeground app: com.apple.Preferences\nScreen: 440x956 points\nDaemon: Ready",
- true,
- );
+ fn the_daemon_s_status_becomes_the_page_s() {
+ let s = protocol::StatusData {
+ wda_ready: true,
+ locked: Some(true),
+ possibly_locked: false,
+ foreground: Some("com.apple.Preferences".into()),
+ width: Some(440.0),
+ height: Some(956.0),
+ };
+ let v = status_json(&s, true);
assert_eq!(v["wda_ready"], true);
assert_eq!(v["locked"], true);
assert_eq!(v["foreground_id"], "com.apple.Preferences");
assert_eq!((v["width"].as_f64(), v["height"].as_f64()), (Some(440.0), Some(956.0)));
assert_eq!(v["route"], "wda");
- assert_eq!(parse_status("WDA ready: True\nLocked: unlocked\n", false)["locked"], false);
- let down = "WDA is starting\nreading elements … wait until WDA is back\nDaemon: Starting WDA";
- assert_eq!(parse_status(down, true)["route"], "hid", "iOS 27 and later");
- assert_eq!(parse_status(down, false)["route"], "none", "older: no HID fallback");
- let down = parse_status(down, true);
- assert_eq!(down["wda_ready"], false);
- assert!(down["locked"].is_null());
- }
-
- #[test]
- fn element_lines_become_boxes() {
- let e = parse_element("Button \"通用\" id=\"com.apple.settings.general\" @(220,776) 400x52").unwrap();
- assert_eq!(
- e,
- json!({"type": "Button", "label": "通用", "x": 20.0, "y": 750.0, "width": 400.0, "height": 52.0})
- );
- let v = parse_element("Button \"秒表\" value=\"1\" @(267,904) 108x54").unwrap();
- assert_eq!((v["label"].as_str(), v["x"].as_f64()), (Some("秒表"), Some(213.0)));
- let plain = parse_element("StaticText \"世界时钟\" @(83,140) 126x41").unwrap();
- assert_eq!(plain["label"], "世界时钟");
- let quoted = parse_element("StaticText \"say \"hi\"\" @(10,10) 4x4").unwrap();
- assert_eq!(quoted["label"], "say \"hi\"");
- assert!(parse_element("……另有 4 个未列出,可用 filter 缩小范围").is_none());
- assert!(parse_element("4 more not listed; narrow it down with filter").is_none());
+ let down = protocol::StatusData::default();
+ assert_eq!(status_json(&down, true)["route"], "hid", "iOS 27 and later");
+ assert_eq!(status_json(&down, false)["route"], "none", "older: no HID fallback");
+ assert!(status_json(&down, true)["locked"].is_null());
}
/// The location prompt that the phone's own video didn't show (iPhone 15 Pro Max, iOS 27.0.1)
#[test]
fn a_system_alert_with_its_own_buttons() {
- let check = "\nNote: a system alert is on screen: “Allow “Calendar” to use your location?\nYour location is used for travel time alerts.”, taps and swipes land on the alert; first tap a button on the alert with iphone_tap_element";
- assert_eq!(
- alert_text(check).as_deref(),
- Some("Allow “Calendar” to use your location?\nYour location is used for travel time alerts.")
- );
- assert_eq!(alert_text(""), None, "no alert");
- assert_eq!(alert_text("Launched x"), None);
+ // (type, label, center, size), as the daemon reads them
let tree = [
- "Button \"今天\" id=\"today-button\" @(61,880) 56x38",
- "Alert \"允许“日历”使用你的位置?\" @(215,466) 270x320",
- "StaticText \"允许“日历”使用你的位置?\" @(215,350) 230x44",
- "Button \"允许一次\" @(215,520) 270x44",
- "Button \"使用 App 时允许\" @(215,564) 270x44",
- "Button \"不允许\" @(215,608) 270x44",
+ ("Button", "今天", (61.0, 880.0), (56.0, 38.0)),
+ ("Alert", "允许“日历”使用你的位置?", (215.0, 466.0), (270.0, 320.0)),
+ ("StaticText", "允许“日历”使用你的位置?", (215.0, 350.0), (230.0, 44.0)),
+ ("Button", "允许一次", (215.0, 520.0), (270.0, 44.0)),
+ ("Button", "使用 App 时允许", (215.0, 564.0), (270.0, 44.0)),
+ ("Button", "不允许", (215.0, 608.0), (270.0, 44.0)),
];
- let els: Vec<Value> = tree.iter().filter_map(|l| parse_element(l)).collect();
+ let elements = tree
+ .iter()
+ .map(|&(kind, label, (cx, cy), (w, h))| protocol::ElementData {
+ kind: kind.into(),
+ label: label.into(),
+ x: cx - w / 2.0,
+ y: cy - h / 2.0,
+ width: w,
+ height: h,
+ })
+ .collect();
+ let els = element_list(Some(protocol::Data::Elements { elements }));
+ assert_eq!(
+ els[0],
+ json!({"type": "Button", "label": "今天", "x": 33.0, "y": 861.0, "width": 56.0, "height": 38.0})
+ );
+ assert!(element_list(Some(protocol::Data::Alert { text: None })).is_empty());
let (frame, b) = alert_parts(&els);
assert_eq!(frame, json!({"x": 80.0, "y": 306.0, "width": 270.0, "height": 320.0}));
let labels: Vec<&str> = b.iter().filter_map(|v| v["label"].as_str()).collect();
diff --git a/apps/iphone-control/src/viewer/api.rs b/apps/iphone-control/src/viewer/api.rs
new file mode 100644
index 0000000..ea3d4bf
--- /dev/null
+++ b/apps/iphone-control/src/viewer/api.rs
@@ -0,0 +1,220 @@
+//! The page's JSON (`GET /api/…`) from the daemon's answers: its snapshot and the facts it reports as data
+//! ([`protocol::Data`]), never its text, which is worded for people and agents
+
+use super::*;
+
+/// One daemon request whose answer the page needs as data ([`protocol::Data`], not the text: that is worded for
+/// people and agents and may change)
+pub(super) async fn data_of(socket: &Path, req: Request) -> Result<Option<protocol::Data>, String> {
+ match protocol::call(socket, &req, Some(Duration::from_secs(60))).await {
+ Ok(Response::Text { data, .. }) => Ok(data),
+ Ok(Response::Error { message, .. }) => Err(message),
+ Ok(Response::Image { caption, .. }) => Err(caption),
+ Err(e) => Err(e.to_string()),
+ }
+}
+
+/// Screen size in points (portrait) for turning a click on the picture into a tap, and the device the viewer follows.
+/// It follows the device the daemon controls: switched on this page, on another page, with `iphone-control select`,
+/// or automatically after an unplug. The page notices `udid` changing and moves its picture and panels over; until
+/// then its actions carry the old UDID and are refused, never sent to a phone the user isn't looking at
+pub(super) async fn info(ctx: &Ctx) -> Result<Value, String> {
+ let s = crate::client::snapshot(&ctx.socket).await.map_err(|e| e.to_string())?;
+ let udid = s.device.as_ref().map(|d| d.udid.as_str()).unwrap_or_default();
+ *ctx.udid.lock().unwrap_or_else(|p| p.into_inner()) = udid.to_owned();
+ let screen = screen_of(&s.persisted, udid);
+ let live_touch = s.device.as_ref().is_some_and(|d| d.major_version() >= 27);
+ Ok(json!({
+ "display": s.display,
+ "width": screen.map(|s| s.width),
+ "height": screen.map(|s| s.height),
+ "udid": udid,
+ // the picture's pointer drives a finger over CoreDevice HID (iOS 27 and later); older phones get whole gestures
+ "live_touch": live_touch,
+ "device": s.device.as_ref().map(|d| &d.name),
+ "model": s.device.as_ref().map(|d| &d.product_type),
+ "model_name": s.device.as_ref().and_then(|d| d.model_name()),
+ "family": s.device.as_ref().map_or("unknown", |d| d.family()),
+ "state": state_of(&s.state).0,
+ // the picture as H.264 (`/video`) and with which encoder; null: MJPEG only
+ "video": ctx.video.as_ref().and_then(|e| e.label()),
+ // the phone's own screen video can be tried (`/video?src=device`): iOS 27 and later, not turned off
+ "device_video": ctx.device_video_allowed && live_touch,
+ }))
+}
+
+pub(super) fn state_of(s: &DeviceState) -> (&'static str, Option<String>) {
+ match s {
+ DeviceState::Absent => ("Absent", None),
+ DeviceState::NeedsTrust => ("NeedsTrust", None),
+ DeviceState::DeveloperModeOff => ("DeveloperModeOff", None),
+ DeviceState::NeedsUnlock => ("NeedsUnlock", None),
+ DeviceState::NeedsSigning => ("NeedsSigning", None),
+ DeviceState::WdaStarting { last_error } => ("WdaStarting", last_error.clone()),
+ DeviceState::NeedsAutomationPin => ("NeedsAutomationPin", None),
+ DeviceState::Ready => ("Ready", None),
+ }
+}
+
+pub(super) fn device_json(d: &ictl_device::DeviceInfo) -> Value {
+ json!({
+ "udid": d.udid, "name": d.name, "model": d.product_type, "ios": d.product_version,
+ "model_name": d.model_name(), "family": d.family(),
+ })
+}
+
+/// `{ state, last_error?, device: { name, model, model_name, family, ios, udid }, auto_unlock }`
+pub(super) async fn daemon(ctx: &Ctx) -> Result<Value, String> {
+ let s = crate::client::snapshot(&ctx.socket).await.map_err(|e| e.to_string())?;
+ let (state, last_error) = state_of(&s.state);
+ Ok(json!({
+ "state": state,
+ "state_text": s.state.describe(),
+ "last_error": last_error,
+ "device": s.device.as_ref().map(device_json),
+ "auto_unlock": s.auto_unlock && !s.unlock_disabled,
+ // the page offers to sign and install WDA (NeedsSigning) only with an Apple ID to sign with
+ "signed_in": crate::client::account_dir(&ctx.data_dir).selected_email().await.is_ok(),
+ }))
+}
+
+/// `{ devices: [{ udid, name, model, model_name, family, ios, controlled }], fixed }`
+pub(super) async fn devices(ctx: &Ctx) -> Result<Value, String> {
+ let s = crate::client::snapshot(&ctx.socket).await.map_err(|e| e.to_string())?;
+ let cur = s.device.as_ref().map(|d| d.udid.to_ascii_lowercase());
+ let list: Vec<Value> = s
+ .devices
+ .iter()
+ .map(|d| {
+ let mut v = device_json(d);
+ v["controlled"] = (cur.as_deref() == Some(d.udid.to_ascii_lowercase().as_str())).into();
+ v
+ })
+ .collect();
+ Ok(json!({"devices": list, "fixed": s.pinned_by_env, "auto": s.pinned.is_none()}))
+}
+
+/// `{ wda_ready, locked, foreground, foreground_id, width, height, route }`
+pub(super) async fn status(ctx: &Ctx) -> Result<Value, String> {
+ let status = match data_of(&ctx.socket, Request::Status).await? {
+ Some(protocol::Data::Status(s)) => s,
+ _ => protocol::StatusData::default(),
+ };
+ // the HID fallback needs iOS 27; an older device without WDA can't be operated at all
+ let hid =
+ crate::client::snapshot(&ctx.socket).await.ok().and_then(|s| s.device).is_some_and(|d| d.major_version() >= 27);
+ let mut v = status_json(&status, hid);
+ if let Some(id) = v["foreground_id"].as_str().map(str::to_owned) {
+ v["foreground"] = app_name(ctx, &id).await.into();
+ }
+ Ok(v)
+}
+
+pub(super) fn status_json(s: &protocol::StatusData, hid: bool) -> Value {
+ json!({
+ "wda_ready": s.wda_ready,
+ "locked": s.locked,
+ "possibly_locked": s.possibly_locked,
+ "foreground_id": s.foreground,
+ "foreground": s.foreground,
+ "width": s.width,
+ "height": s.height,
+ // without WDA, screenshots, taps and keys go over CoreDevice HID (iOS 27 and later); otherwise nothing works
+ "route": if s.wda_ready { "wda" } else if hid { "hid" } else { "none" },
+ })
+}
+
+/// The display name of an installed app (the home screen for SpringBoard); the bundle id when unknown
+pub(super) async fn app_name(ctx: &Ctx, bundle: &str) -> String {
+ if bundle == SPRINGBOARD {
+ return ictl_l10n::tr!("主屏幕", "Home Screen").into();
+ }
+ let mut names = ctx.names.lock().await;
+ if !names.contains_key(bundle) {
+ for system in [false, true] {
+ if let Ok(list) = list_apps(ctx, system).await {
+ for (n, b) in list {
+ names.insert(b, n);
+ }
+ }
+ }
+ }
+ names.get(bundle).cloned().unwrap_or_else(|| bundle.to_owned())
+}
+
+pub(super) async fn list_apps(ctx: &Ctx, system: bool) -> Result<Vec<(String, String)>, String> {
+ Ok(match data_of(&ctx.socket, Request::ListApps { include_system: system }).await? {
+ Some(protocol::Data::Apps { apps }) => apps.into_iter().map(|a| (a.name, a.bundle_id)).collect(),
+ _ => Vec::new(),
+ })
+}
+
+/// `{ apps: [{ name, bundle_id }] }`: the user's apps, and with `system` the system's too
+pub(super) async fn apps(ctx: &Ctx, system: bool) -> Result<Value, String> {
+ let mut all = list_apps(ctx, false).await?;
+ if system {
+ all.extend(list_apps(ctx, true).await?);
+ }
+ let mut seen = std::collections::HashSet::new();
+ all.retain(|(_, b)| seen.insert(b.clone()));
+ Ok(json!({"apps": all.iter().map(|(n, b)| json!({"name": n, "bundle_id": b})).collect::<Vec<_>>()}))
+}
+
+/// `{ elements: [{ type, label, x, y, width, height }] }`, `x`/`y` the top-left corner in points
+/// `keep_locked`: a read-only visitor, for whom a locked phone isn't unlocked
+pub(super) async fn elements(ctx: &Ctx, filter: &str, keep_locked: bool) -> Result<Value, String> {
+ let req = Request::ListElements { filter: filter.to_owned(), limit: ELEMENT_LIMIT, max_age_ms: 0, keep_locked };
+ Ok(json!({"elements": element_list(data_of(&ctx.socket, req).await?)}))
+}
+
+/// A system alert on the phone (a permission prompt and the like): `{ alert: null }` or
+/// `{ alert: { text, frame?: { x, y, width, height }, buttons: [{ label, x, y, width }] } }` in points: the alert's
+/// box (top left), each button's center and width. The page draws it where the real one is. The phone's own video
+/// (iOS 27, D16) can leave such an alert out: a location prompt showed there only as the dimmed screen behind it,
+/// while WDA's screenshot had it. The page asks while it shows that video and puts the alert next to the picture.
+/// `AlertCheck` is two quick WDA calls (the foreground app; the alert's text only when SpringBoard is in front); the
+/// element tree is only read when there is an alert
+pub(super) async fn alert(ctx: &Ctx, keep_locked: bool) -> Result<Value, String> {
+ let Some(protocol::Data::Alert { text: Some(text) }) = data_of(&ctx.socket, Request::AlertCheck).await? else {
+ return Ok(json!({"alert": null}));
+ };
+ let req = Request::ListElements { filter: String::new(), limit: ELEMENT_LIMIT, max_age_ms: 0, keep_locked };
+ // without its buttons the page still says there is an alert
+ let els = data_of(&ctx.socket, req).await.map(element_list).unwrap_or_default();
+ let (frame, buttons) = alert_parts(&els);
+ Ok(json!({"alert": {"text": text, "frame": frame, "buttons": buttons}}))
+}
+
+/// The elements in a [`protocol::Data::Elements`] as the page's JSON: `{ type, label, x, y, width, height }`
+pub(super) fn element_list(data: Option<protocol::Data>) -> Vec<Value> {
+ match data {
+ Some(protocol::Data::Elements { elements }) => {
+ elements.iter().filter_map(|e| serde_json::to_value(e).ok()).collect()
+ }
+ _ => Vec::new(),
+ }
+}
+
+/// The tree's alert box, and the buttons on it (whose center lies inside it) as `{ label, x, y, width }`
+pub(super) fn alert_parts(els: &[Value]) -> (Value, Vec<Value>) {
+ let f = |e: &Value, k: &str| e[k].as_f64().unwrap_or(0.0);
+ let Some(a) = els.iter().find(|e| e["type"] == "Alert") else { return (Value::Null, Vec::new()) };
+ let frame = json!({"x": f(a, "x"), "y": f(a, "y"), "width": f(a, "width"), "height": f(a, "height")});
+ let inside = |x: f64, y: f64| {
+ x >= f(a, "x") && x <= f(a, "x") + f(a, "width") && y >= f(a, "y") && y <= f(a, "y") + f(a, "height")
+ };
+ let buttons = els
+ .iter()
+ .filter(|e| e["type"] == "Button")
+ .map(|e| (e, f(e, "x") + f(e, "width") / 2.0, f(e, "y") + f(e, "height") / 2.0))
+ .filter(|&(_, x, y)| inside(x, y))
+ .map(|(e, x, y)| json!({"label": e["label"], "x": x, "y": y, "width": f(e, "width")}))
+ .collect();
+ (frame, buttons)
+}
+
+/// The recorded screen size, only if it belongs to `udid` (a size recorded by an older version, without
+/// a device, is used as is, like the daemon does)
+pub(super) fn screen_of(p: &ictl_daemon::core::Persisted, udid: &str) -> Option<ictl_device::ScreenSize> {
+ p.screen_for(Some(udid)).map(|s| s.portrait())
+}
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index 99d2cb8..06a5cc5 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -961,8 +961,14 @@ impl Daemon {
async fn dispatch(&self, g: &mut Inner, req: Request, view: Option<&str>) -> Response {
// what the text reports, for clients that act on it (Response::Text.outcome)
let mut outcome = crate::protocol::Outcome::default();
+ // the same facts as data, for programs (Response::Text.data)
+ let mut data = None;
let r = match req {
- Request::Status => Ok(self.status_text(g).await),
+ Request::Status => {
+ let (text, status) = self.status(g).await;
+ data = Some(crate::protocol::Data::Status(status));
+ Ok(text)
+ }
// streams on its own connection (`lib::serve_conn` hands it to `screen::stream`); never queued here
Request::ScreenStream => {
Err("screen_stream is a streaming request: open it with open_screen_stream".into())
@@ -970,9 +976,13 @@ impl Daemon {
Request::Screenshot { region } => {
return self.screenshot(g, region).await.unwrap_or_else(Response::error);
}
- Request::ListElements { filter, limit, max_age_ms, keep_locked } => {
- self.list_elements(g, &filter, limit, Duration::from_millis(max_age_ms), keep_locked).await
- }
+ Request::ListElements { filter, limit, max_age_ms, keep_locked } => self
+ .list_elements(g, &filter, limit, Duration::from_millis(max_age_ms), keep_locked)
+ .await
+ .map(|(text, elements)| {
+ data = Some(crate::protocol::Data::Elements { elements });
+ text
+ }),
Request::Tap { x, y } => self.tap(g, x, y, view).await,
Request::TapElement { text, index, max_age_ms } => {
self.tap_element(g, &text, index, Duration::from_millis(max_age_ms)).await.map(|(t, missed)| {
@@ -991,10 +1001,14 @@ impl Daemon {
.map(|()| Response::text_with("", outcome))
.unwrap_or_else(|e| e);
}
- Request::ListApps { include_system } => self
- .list_apps(g, include_system)
- .await
- .map(|a| a.iter().map(|a| format!("{}\t{}", a.name, a.bundle_id)).collect::<Vec<_>>().join("\n")),
+ Request::ListApps { include_system } => self.list_apps(g, include_system).await.map(|a| {
+ let apps = a
+ .iter()
+ .map(|a| crate::protocol::AppData { name: a.name.clone(), bundle_id: a.bundle_id.clone() })
+ .collect();
+ data = Some(crate::protocol::Data::Apps { apps });
+ a.iter().map(|a| format!("{}\t{}", a.name, a.bundle_id)).collect::<Vec<_>>().join("\n")
+ }),
Request::LaunchApp { app } => self.launch_app(g, &app).await.map(|(t, alert)| {
outcome.alert_reported = alert;
t
@@ -1005,7 +1019,10 @@ impl Daemon {
t
}),
Request::Settle { max_ms } => self.settle(g, Duration::from_millis(max_ms)).await,
- Request::AlertCheck => self.alert_check(g).await,
+ Request::AlertCheck => self.alert_check(g).await.map(|(text, alert)| {
+ data = Some(crate::protocol::Data::Alert { text: alert });
+ text
+ }),
Request::WaitFor { text, timeout_ms } => self.wait_for(g, &text, Duration::from_millis(timeout_ms)).await,
Request::Doctor => Ok(self.doctor(g).await),
Request::UnlockReset => {
@@ -1037,7 +1054,7 @@ impl Daemon {
| Request::TaskNote { .. }
| Request::TaskFinish { .. } => unreachable!("other lanes"),
};
- r.map(|t| Response::text_with(t, outcome)).unwrap_or_else(Response::error)
+ r.map(|t| Response::text_data(t, outcome, data)).unwrap_or_else(Response::error)
}
pub async fn shutdown(&self) {
diff --git a/crates/ictl-daemon/src/tools.rs b/crates/ictl-daemon/src/tools.rs
index d3b011a..e174d9a 100644
--- a/crates/ictl-daemon/src/tools.rs
+++ b/crates/ictl-daemon/src/tools.rs
@@ -14,6 +14,7 @@ use crate::core::{Daemon, Inner, drop_tunnel, hid_supported, wda_down};
use crate::imaging::{self, fmt_g};
use crate::notify::Event;
use crate::protocol::{ALERT_BLOCKING, Response, TAP_MISSED, TouchPhase};
+use crate::protocol::{ElementData, StatusData};
/// 锁屏后至少等这么久再自动解锁:锁屏过渡没走完就唤醒,WDA 第一下上滑卡约 16 秒后报 `point.x != INFINITY`
pub(crate) const LOCK_SETTLE: Duration = Duration::from_secs(3);
@@ -194,16 +195,18 @@ impl Daemon {
}
}
- pub(crate) async fn status_text(&self, g: &mut Inner) -> String {
+ /// The status for people and agents, and the same as data for programs (the control page)
+ pub(crate) async fn status(&self, g: &mut Inner) -> (String, StatusData) {
let mut daemon_line = ictl_l10n::trf!("守护进程: {}", "Daemon: {}", g.state.describe());
if let Some(l) = self.devices_line(g) {
daemon_line = format!("{l}\n{daemon_line}");
}
let unlock = self.unlock_cfg(g.device.as_ref().map(|d| d.udid.as_str()));
let Some(w) = self.wda(g) else {
- return format!("{}\n{}\n{daemon_line}", wda_down(&g.state, g.info.as_ref()), needs_wda());
+ let text = format!("{}\n{}\n{daemon_line}", wda_down(&g.state, g.info.as_ref()), needs_wda());
+ return (text, StatusData::default());
};
- let r: Result<String, WdaError> = async {
+ let r: Result<(String, StatusData), WdaError> = async {
let ready = w.ready().await?;
let app = w.active_app().await?;
let s = w.screen_size().await?;
@@ -223,16 +226,25 @@ impl Daemon {
if !locked && unlock.disabled_by_failure() {
lock += ictl_l10n::tr!(";自动解锁已停用", "; auto-unlock disabled");
}
+ let data = StatusData {
+ wda_ready: ready,
+ locked: Some(locked || check.uncertain),
+ possibly_locked: check.uncertain,
+ foreground: Some(app.clone()).filter(|a| !a.is_empty()),
+ width: Some(s.width),
+ height: Some(s.height),
+ };
let ready = if ready { "True" } else { "False" };
- Ok(ictl_l10n::trf!("WDA 就绪: {ready}\n锁屏: {lock}\n前台 App: {app}\n屏幕: {}x{} 点", "WDA ready: {ready}\nLocked: {lock}\nForeground app: {app}\nScreen: {}x{} points",
+ let text = ictl_l10n::trf!("WDA 就绪: {ready}\n锁屏: {lock}\n前台 App: {app}\n屏幕: {}x{} 点", "WDA ready: {ready}\nLocked: {lock}\nForeground app: {app}\nScreen: {}x{} points",
fmt_g(s.width),
fmt_g(s.height)
- ))
+ );
+ Ok((text, data))
}
.await;
match r {
- Ok(t) => format!("{t}\n{daemon_line}"),
- Err(e) => format!("{e}\n{}\n{daemon_line}", needs_wda()),
+ Ok((t, data)) => (format!("{t}\n{daemon_line}"), data),
+ Err(e) => (format!("{e}\n{}\n{daemon_line}", needs_wda()), StatusData::default()),
}
}
@@ -299,7 +311,7 @@ impl Daemon {
limit: usize,
max_age: Duration,
keep_locked: bool,
- ) -> Result<String, String> {
+ ) -> Result<(String, Vec<ElementData>), String> {
if keep_locked {
// only looking (a read-only viewer): the passcode isn't typed for it
if let Some(w) = self.wda(g)
@@ -318,6 +330,7 @@ impl Daemon {
let shown: Vec<&elements::Element> =
if filter.is_empty() { els.iter().collect() } else { elements::filter(&els, filter) };
let lines: Vec<_> = shown.iter().take(limit).map(|e| e.describe()).collect();
+ let data = shown.iter().take(limit).map(|e| element_data(e)).collect();
let more = if shown.len() > limit {
ictl_l10n::trf!(
"\n……另有 {} 个未列出,可用 filter 缩小范围",
@@ -327,7 +340,7 @@ impl Daemon {
} else {
String::new()
};
- Ok(if lines.is_empty() { no_elements_text(filter, els.len()) } else { lines.join("\n") } + &more)
+ Ok((if lines.is_empty() { no_elements_text(filter, els.len()) } else { lines.join("\n") } + &more, data))
}
/// 等界面稳定,最多等 `max`:
@@ -427,14 +440,15 @@ impl Daemon {
/// 前台是 SpringBoard 时查有没有系统弹窗(权限请求等),有就返回提醒,没有返回空串。
/// 不带 then 的操作做完后调:弹窗挡着时点击、滑动都会落在弹窗上,WDA 却照样报成功。
/// 前台是 App 时只多一次约 0.13 秒的查询;在主屏上再多约 0.4 秒
- pub(crate) async fn alert_check(&self, g: &mut Inner) -> Result<String, String> {
- let Some(w) = self.wda(g) else { return Ok(String::new()) };
+ /// A system alert in front: the note for the agent, and the alert's own text
+ pub(crate) async fn alert_check(&self, g: &mut Inner) -> Result<(String, Option<String>), String> {
+ let Some(w) = self.wda(g) else { return Ok((String::new(), None)) };
if w.active_app().await.map_err(|e| e.to_string())? != SPRINGBOARD {
- return Ok(String::new());
+ return Ok((String::new(), None));
}
Ok(match w.alert_text().await {
- Ok(Some(text)) => alert_msg(&text),
- _ => String::new(),
+ Ok(Some(text)) => (alert_msg(&text), Some(text)),
+ _ => (String::new(), None),
})
}
@@ -1253,6 +1267,20 @@ fn no_elements_text(filter: &str, total: usize) -> String {
}
}
+/// An element as data: the text it shows (its label, else its name, else its value) and its box
+fn element_data(e: &elements::Element) -> ElementData {
+ let text = [&e.label, &e.name, &e.value].into_iter().find(|s| !s.is_empty()).cloned().unwrap_or_default();
+ let (w, h) = (e.size.0 as f64, e.size.1 as f64);
+ ElementData {
+ kind: e.kind.clone(),
+ label: text.chars().take(200).collect(),
+ x: e.center.0 as f64 - w / 2.0,
+ y: e.center.1 as f64 - h / 2.0,
+ width: w,
+ height: h,
+ }
+}
+
fn alert_msg(text: &str) -> String {
ictl_l10n::trf!(
"\n注意:{},点击、滑动都会落在弹窗上;{TAP_ALERT}",
diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs
index a2f5354..c3339e0 100644
--- a/crates/ictl-mcp/src/lib.rs
+++ b/crates/ictl-mcp/src/lib.rs
@@ -1013,7 +1013,7 @@ impl McpServer {
// then 只对操作类工具有意义;看界面的工具本身就是返回界面
let resp = self.call(&req).await;
Ok(match resp {
- Response::Text { text, outcome } if req.is_device_action() => {
+ Response::Text { text, outcome, .. } if req.is_device_action() => {
// 结果里已经说了有弹窗(启动 App 被挡)就不再查
let check = wants_alert_check(&req) && !protocol::alert_reported(&text, outcome);
self.finish(text, false, then, check).await
@@ -1133,7 +1133,9 @@ impl McpServer {
}
Step::Request { tool, req } => match self.call_on(&req, udid.as_deref()).await {
// 按名字没点到(toolkit 兼容:单独调用时是普通结果)在批量里要停下:后面的步骤都建立在它点中的前提上
- Response::Text { text, outcome } if tool == "iphone_tap_element" && tap_missed(&text, outcome) => {
+ Response::Text { text, outcome, .. }
+ if tool == "iphone_tap_element" && tap_missed(&text, outcome) =>
+ {
lines.push(format!("{n}. {tool} → {text}"));
if n < total {
lines.push(ictl_l10n::trf!(
@@ -1144,7 +1146,7 @@ impl McpServer {
}
return self.finish(lines.join("\n"), true, then, false).await;
}
- Response::Text { text, outcome } => {
+ Response::Text { text, outcome, .. } => {
check = wants_alert_check(&req) && !protocol::alert_reported(&text, outcome);
lines.push(format!("{n}. {tool} → {text}"));
}
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index 729621a..fac52c5 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -310,6 +310,10 @@ pub enum Response {
/// language). Daemons before this field existed don't send it; their text is always Chinese
#[serde(default, skip_serializing_if = "Option::is_none")]
outcome: Option<Outcome>,
+ /// The same facts as data, for programs such as the control page ([`Data`]): the text is worded for people
+ /// and agents, in their language, and may change. Only some requests have it
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ data: Option<Data>,
},
/// JPEG base64 + 说明文字(尺寸、放大倍数、坐标换算式)
Image { jpeg_base64: String, caption: String },
@@ -332,13 +336,67 @@ pub struct Outcome {
pub alert_reported: bool,
}
+/// What [`Request::Status`], [`Request::ListElements`], [`Request::ListApps`] and [`Request::AlertCheck`] report, as
+/// data ([`Response::Text`]'s `data`)
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum Data {
+ Status(StatusData),
+ Elements {
+ elements: Vec<ElementData>,
+ },
+ Apps {
+ apps: Vec<AppData>,
+ },
+ /// A system alert in front (its text), or none
+ Alert {
+ text: Option<String>,
+ },
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct StatusData {
+ pub wda_ready: bool,
+ /// `None` when WDA couldn't say (it isn't running)
+ pub locked: Option<bool>,
+ /// Looks like the lock screen though WDA says unlocked (`locked` is then true too)
+ pub possibly_locked: bool,
+ /// The foreground app's bundle ID
+ pub foreground: Option<String>,
+ /// The screen in points, as it is turned now
+ pub width: Option<f64>,
+ pub height: Option<f64>,
+}
+
+/// An element on screen: its type, the text it shows, and its box in points (top left, size)
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct ElementData {
+ #[serde(rename = "type")]
+ pub kind: String,
+ pub label: String,
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct AppData {
+ pub name: String,
+ pub bundle_id: String,
+}
+
impl Response {
pub fn text(s: impl Into<String>) -> Self {
- Self::Text { text: s.into(), outcome: None }
+ Self::Text { text: s.into(), outcome: None, data: None }
}
/// Text with its [`Outcome`] (the daemon answers every text request this way)
pub fn text_with(s: impl Into<String>, outcome: Outcome) -> Self {
- Self::Text { text: s.into(), outcome: Some(outcome) }
+ Self::Text { text: s.into(), outcome: Some(outcome), data: None }
+ }
+ /// Text with its [`Outcome`] and the same facts as [`Data`]
+ pub fn text_data(s: impl Into<String>, outcome: Outcome, data: Option<Data>) -> Self {
+ Self::Text { text: s.into(), outcome: Some(outcome), data }
}
pub fn error(s: impl Into<String>) -> Self {
Self::Error { message: s.into(), retry_as_gesture: false }
@@ -820,6 +878,27 @@ mod tests {
assert_eq!(text, "Not found");
}
+ /// Data travels tagged by its type, and only when there is some
+ #[test]
+ fn data_travels_with_the_text() {
+ let status = Data::Status(StatusData {
+ wda_ready: true,
+ locked: Some(false),
+ foreground: Some("com.apple.springboard".into()),
+ width: Some(430.0),
+ height: Some(932.0),
+ ..Default::default()
+ });
+ let r = Response::text_data("WDA ready: True", Outcome::default(), Some(status));
+ let s = serde_json::to_string(&r).unwrap();
+ assert!(s.contains(r#""data":{"type":"status","wda_ready":true"#), "{s}");
+ assert_eq!(serde_json::from_str::<Response>(&s).unwrap(), r);
+ let el = ElementData { kind: "Button".into(), label: "OK".into(), x: 1.0, y: 2.0, width: 3.0, height: 4.0 };
+ let v = serde_json::to_value(Data::Elements { elements: vec![el] }).unwrap();
+ assert_eq!(v["elements"][0]["type"], "Button", "the page reads `type`");
+ assert!(!serde_json::to_string(&Response::text_with("x", Outcome::default())).unwrap().contains("data"));
+ }
+
/// The field decides; without it (older daemon) the Chinese text is read
#[test]
fn outcome_wins_over_text() {
diff --git a/docs/architecture.md b/docs/architecture.md
index c03aeca..c1619c7 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -37,8 +37,8 @@
|---|---|---|
| `iphone-control daemon` | 常驻,作为用户服务运行(macOS 是 launchd,Linux 是 systemd 用户服务;由 `install.sh`、`iphone-control service install`、`brew services` 或 .deb 的 unit 装好),也可以在终端里前台运行 | 唯一和设备通信的进程。维护设备状态机,对外提供本地控制接口 |
| `iphone-control mcp` | 每个 agent 会话一个 | MCP stdio 服务,把工具调用翻译成对守护进程的请求;`--url` 时改为把 stdio 转接到另一台机器控制台的 `/mcp`(`mcp_bridge.rs`) |
-| `iphone-control viewer` | 显式开启,可作为单独的后台服务(`service viewer install`) | 浏览器里的控制台和同一个端口上的 HTTP MCP(`/mcp`);要令牌登录,`--lan` 时对局域网开放、走 HTTPS(`viewer/`:`auth.rs` 登录、`lan.rs` 地址检查、`tls.rs` 按首字节分 TLS 和明文、`mcp.rs` 接 rmcp、`peer.rs` 查本机调用方进程) |
-| `iphone-control task run` | 一个外部 AI 任务一个 | 开任务、持有租约、在任务里运行命令(`task.rs`);`--url` 时经另一台机器的控制台(`remote.rs`) |
+| `iphone-control viewer` | 显式开启,可作为单独的后台服务(`service viewer install`) | 浏览器里的控制台和同一个端口上的 HTTP MCP(`/mcp`);要令牌登录,`--lan` 时对局域网开放、走 HTTPS(`viewer/`:`auth.rs` 登录、`lan.rs` 地址检查、`tls.rs` 按首字节分 TLS 和明文、`mcp.rs` 接 rmcp、`peer.rs` 查本机调用方进程、`api.rs` 把守护进程的数据转成页面的 JSON) |
+| `iphone-control task run` | 一个外部 AI 任务一个 | 开任务、持有租约、在任务里运行命令(`task.rs`);`--url` 时经另一台机器的控制台(`remote.rs`)。命令在自己的进程组里运行,停任务时整组结束(`procgroup.rs`,控制台的 agent 也用它) |
| `usbmuxd` | 系统的服务:Linux 上是发行版的包(.deb 依赖它,udev 在插上手机时启动),macOS 自带;守护进程不启动也不重启它 | Linux 上是系统包,GPL-3.0,独立进程运行,不链接 |
| `iphone-control`(不带命令)、`setup`、`service`、`doctor`、`sign` 等 | 一次性 | 首次运行引导(`guide.rs`)、后台服务管理(`service.rs`)和运维命令,通过控制接口或直接调用库。启动时先把 `~/.config/iphone-control/env` 读进环境(`envfile.rs`,已有的环境变量优先) |
@@ -115,12 +115,12 @@
| `ictl-wda` | `WdaRunner`(XCUITestService 启动/停止)、`WdaClient`(会话、点击、W3C actions、keys、source、screenshot、appium settings、锁屏核对)、经 usbmuxd 直连设备 8100 端口的 HTTP 传输(区分连不上和请求超时)、元素树解析(纯函数,可单测) | `idevice`(`xctest`)、`quick-xml` |
| `ictl-webinspector` | Web Inspector 服务(`com.apple.webinspector`,经 lockdown)的客户端:列出可检查的网页和 WebView、在页面里执行 JavaScript(`Target` 域和旧版直接收命令两种都支持,Promise 用 `Runtime.awaitPromise` 等待)。纯协议,消息解析可单测 | `idevice`、`plist` |
| `ictl-l10n` | 界面文字的语言:取当前语言,`tr!` / `trf!` / `log_tr!` / `log_trf!` 宏(每条文字在代码里原地写成中英一对,见 D12) | 无 |
-| `ictl-protocol` | 控制接口的 `Request`/`Response` 类型和客户端 `call(socket, req, timeout)`、任务的流式请求;默认的数据目录、socket 路径和 root 判断 | `serde`、`serde_json`、`tokio`、`libc`、`ictl-l10n` |
+| `ictl-protocol` | 控制接口的 `Request`/`Response` 类型和客户端 `call(socket, req, timeout)`、任务的流式请求;`Response::Text` 除了给人和 agent 看的文字,还可以带 `data`(状态、元素、App 列表、系统弹窗的结构化字段,给控制台这类程序用,文字措辞改了也不影响它们);默认的数据目录、socket 路径和 root 判断 | `serde`、`serde_json`、`tokio`、`libc`、`ictl-l10n` |
| `ictl-sign` | Apple ID 登录(含双重认证交互)、会话持久化、注册设备、App ID、描述文件、签名 `.app`/`.ipa`(**包括 `.xctest`**;bundle 逻辑改写自 plume_utils)、签后自检 | vendored 的 `plume_core`/`plume_store`(MPL-2.0/MIT;经 plume_core 用 vendored 的 `omnisette` 和打过补丁的 `apple-codesign`) |
| `ictl-unlock` | 锁屏密码键盘定位、逐位输入并核对密码栏、从第 2 位起先写停用标记 | `ictl-wda` |
| `ictl-daemon` | `core`(共享状态、请求分发、快照)、`supervise`(巡检、后台启动 WDA、重签、会话检查)、`tools`(工具的实现、HID 后备)、`devtools`(日志采集、崩溃报告、安装、卸载)、`web`(Web Inspector 工具,保留一条连接复用)、`devices`(列出、选择设备)、`doctor`;通知(Bark/Telegram)、截图缩放/裁剪、控制接口服务端 | 以上全部、`tokio`、`reqwest`、`image` |
| `ictl-mcp` | MCP stdio 服务,`iphone_*` 工具 17 个,开启开发者工具后 23 个:toolkit 的 13 个 + `iphone_wait_for`、`iphone_batch`、`iphone_list_devices`、`iphone_select_device`,以及 6 个可选的开发者工具(D13);操作类工具可带 `then` 顺带返回操作后的界面;任务里另有 `iphone_confirm`;经控制接口调用守护进程。同一套工具也给控制台的 `/mcp` 用(`http_service`,Streamable HTTP) | `ictl-protocol`、`ictl-l10n`、`rmcp`(`server`、`transport-io`、`transport-streamable-http-server`)、`http` |
-| `apps/iphone-control` | CLI 入口:不带命令时是首次运行引导或状态(`guide.rs`)、`daemon`、`mcp`、`mcp-config`、`status`、`doctor`、`setup [--reconfigure]`、`service`(`service.rs`:launchd / systemd 用户服务)、`login`、`sign`、`resign`、`passcode`、`unlock-reset`、`devices`、`select`、`wda-bridge`、`viewer`(`viewer.rs`:本机控制台网页,实时画面、设备面板;`video/`:画面的 H.264 编码(外部 ffmpeg)和 MJPEG 去重;`agent.rs`:页面上的 AI 任务,`viewer.html` 是页面)、`viewer token …`(命名令牌、只读令牌)、`task …`(`task.rs`、`remote.rs`)、`mcp --url`(`mcp_bridge.rs`)、`update …`(`update.rs`、`update/`:签名清单、事务式替换)、`completions`、`notify-test`;隐藏的 `debug <ddi\|hid\|screenshot\|soak\|wda\|e2e>` 真机诊断(原第 0 步 spike,不经守护进程;feature `debug-cmds`,默认不编译) | `clap` |
+| `apps/iphone-control` | CLI 入口(`main.rs`;和守护进程打交道的公共函数在 `client.rs`,控制台、引导和更新器都用它):不带命令时是首次运行引导或状态(`guide.rs`)、`daemon`、`mcp`、`mcp-config`、`status`、`doctor`、`setup [--reconfigure]`、`service`(`service.rs`:launchd / systemd 用户服务)、`login`、`sign`、`resign`、`passcode`、`unlock-reset`、`devices`、`select`、`wda-bridge`、`viewer`(`viewer.rs`:本机控制台网页,实时画面、设备面板;`video/`:画面的 H.264 编码(外部 ffmpeg)和 MJPEG 去重;`agent.rs`:页面上的 AI 任务,`viewer.html` 是页面)、`viewer token …`(命名令牌、只读令牌)、`task …`(`task.rs`、`remote.rs`)、`mcp --url`(`mcp_bridge.rs`)、`update …`(`update.rs`、`update/`:签名清单、事务式替换)、`completions`、`notify-test`;隐藏的 `debug <ddi\|hid\|screenshot\|soak\|wda\|e2e>` 真机诊断(原第 0 步 spike,不经守护进程;feature `debug-cmds`,默认不编译) | `clap` |
依赖方向:`apps` → `ictl-daemon` / `ictl-mcp`,还直接依赖 `ictl-device`、`ictl-sign`;`ictl-daemon` → `ictl-unlock` → `ictl-wda` → `ictl-device`;`ictl-daemon` 还直接依赖 `ictl-webinspector`、`ictl-sign` 和 `ictl-protocol`。`ictl-device` 也依赖 `ictl-webinspector`(打开连接)。`ictl-mcp` 只依赖 `ictl-protocol` 和 `ictl-l10n`,不依赖守护进程和设备层。`ictl-l10n` 不依赖其他 crate,除 `ictl-webinspector` 外都用它。`apps` 的 `debug`(feature `debug-cmds`)直接调用 `ictl-device`、`ictl-wda`。