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: Web Inspector crate and web page tools (#36)

TheSalaty0476f220f187
diff --git a/.env.example b/.env.example
index 7192fd9..7875f2e 100644
--- a/.env.example
+++ b/.env.example
@@ -13,8 +13,8 @@ DATA_DIR=./data
# 容器部署时也管 docker exec 起的 MCP 和命令行。
IPHONE_CONTROL_LANG=
-# 开发者工具:设为 1 时 MCP 服务多出日志、崩溃报告、安装和卸载 App 四个工具(默认关闭,免得 agent 多读工具说明)
-# Developer tools: 1 adds four MCP tools for logs, crash reports, installing and removing apps (off by default).
+# 开发者工具:设为 1 时 MCP 服务多出日志、崩溃报告、安装和卸载 App、网页检查(Web Inspector)六个工具(默认关闭,免得 agent 多读工具说明)
+# Developer tools: 1 adds six MCP tools for logs, crash reports, installing and removing apps, and web pages (Web Inspector) (off by default).
IPHONE_CONTROL_DEV_TOOLS=
# 固定控制哪台设备,设了就不能切换。留空为自动选:正在控制的那台一直用到它断开;
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bc0d9c3..c7f1537 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -46,7 +46,7 @@ jobs:
- uses: Swatinem/rust-cache@v2
# vendor/ 是上游代码,不格式化;只检查本仓库的包
- name: fmt
- run: for p in ictl-l10n ictl-device ictl-wda ictl-sign ictl-unlock ictl-daemon ictl-mcp ictl-protocol iphone-control; do cargo fmt -p $p -- --check; done
+ run: for p in ictl-l10n ictl-webinspector ictl-device ictl-wda ictl-sign ictl-unlock ictl-daemon ictl-mcp ictl-protocol iphone-control; do cargo fmt -p $p -- --check; done
# --all-features:默认不编的 debug-cmds(调试子命令)也要能编译
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
- run: cargo test --workspace --all-features --locked
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3fe5cb3..f1ba1b0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@ All notable changes to this project are documented here. The format is based on
- Text responses carry an optional `outcome` (`tapped_nothing`, `alert_reported`), so the MCP server no longer reads result text to stop a batch after a missed tap or to skip the extra alert check. Responses without it (older daemons) are still recognised by their Chinese prefixes.
- `iphone-control viewer [--port]`: watch and control the phone live in a browser (opt-in, 127.0.0.1:8200 by default). Taps, swipes, long presses, typing and buttons go through the daemon, so they queue with the agent's calls and unlock the phone first. It binds the loopback address only, checks `Host`, and also checks `Origin` on actions; other local users can reach the port, so stop it when done.
- Developer tools, opt-in with `IPHONE_CONTROL_DEV_TOOLS=1`: `iphone_app_logs` (the phone's unified log, filtered by app or process, text and time), `iphone_crash_reports`, `iphone_install_app` and `iphone_uninstall_app` (both marked destructive; uninstalling the WebDriverAgent runner is refused). Without the switch the tool list is unchanged.
+- Web Inspector, part of the developer tools: `iphone_web_targets` lists inspectable web pages and WebViews (Safari tabs, debug builds of hybrid apps), and `iphone_web_eval` runs JavaScript in one and returns the result as JSON. A new crate, `ictl-webinspector`, implements the client for the phone's Web Inspector service.
### Fixed
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 2c328fd..26d3b8e 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -13,6 +13,7 @@
- 文字响应带可选的 `outcome`(`tapped_nothing`、`alert_reported`),MCP 端据此在没点到时停下批量、跳过多余的弹窗检查,不再从结果文字里认;没有这个字段的响应(旧版本守护进程)照旧按中文开头认。
- `iphone-control viewer [--port]`:在浏览器里看实时画面并操作手机(默认 127.0.0.1:8200,显式开启)。点击、滑动、长按、输入和按键都经守护进程,和 agent 的调用排队,并先自动解锁。只绑本机回环地址,检查 `Host`,操作还检查 `Origin`;本机其他用户能连上这个端口,用完就停。
- 开发者工具,设 `IPHONE_CONTROL_DEV_TOOLS=1` 开启:`iphone_app_logs`(手机的系统日志,可按 App 或进程、文字、时间筛选)、`iphone_crash_reports`、`iphone_install_app` 和 `iphone_uninstall_app`(后两个标为破坏性操作;拒绝卸载 WebDriverAgent)。不设就和原来一样,工具列表不变。
+- Web Inspector,属于开发者工具:`iphone_web_targets` 列出可检查的网页和 WebView(Safari 标签页、混合 App 的调试构建),`iphone_web_eval` 在其中执行 JavaScript 并以 JSON 返回结果。新的 `ictl-webinspector` crate 实现了手机 Web Inspector 服务的客户端。
### 修复
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 834932e..f6e76e9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -19,7 +19,7 @@ You need Rust 1.88 or later (CI pins 1.99.1) and a C compiler. Everything except
cargo test --workspace --all-features --locked
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
# vendor/ is upstream code and isn't formatted; check only this repository's packages:
-for p in ictl-l10n ictl-device ictl-wda ictl-sign ictl-unlock ictl-daemon ictl-mcp ictl-protocol iphone-control; do cargo fmt -p $p -- --check; done
+for p in ictl-l10n ictl-webinspector ictl-device ictl-wda ictl-sign ictl-unlock ictl-daemon ictl-mcp ictl-protocol iphone-control; do cargo fmt -p $p -- --check; done
```
Or, without Rust installed:
diff --git a/Cargo.lock b/Cargo.lock
index 8785186..001218a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1957,6 +1957,7 @@ dependencies = [
"ictl-sign",
"ictl-unlock",
"ictl-wda",
+ "ictl-webinspector",
"image",
"reqwest 0.13.5",
"serde",
@@ -1971,6 +1972,7 @@ name = "ictl-device"
version = "0.1.4"
dependencies = [
"ictl-l10n",
+ "ictl-webinspector",
"idevice",
"plist",
"reqwest 0.13.5",
@@ -2054,6 +2056,19 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "ictl-webinspector"
+version = "0.1.4"
+dependencies = [
+ "idevice",
+ "plist",
+ "serde_json",
+ "thiserror 2.0.21",
+ "tokio",
+ "tracing",
+ "uuid",
+]
+
[[package]]
name = "icu_collections"
version = "2.4.0"
diff --git a/Cargo.toml b/Cargo.toml
index 17fe561..d22f083 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -5,6 +5,7 @@ members = [
"crates/ictl-wda",
"crates/ictl-protocol",
"crates/ictl-l10n",
+ "crates/ictl-webinspector",
"crates/ictl-sign",
"crates/ictl-unlock",
"crates/ictl-daemon",
@@ -78,6 +79,7 @@ ictl-device = { path = "crates/ictl-device" }
ictl-wda = { path = "crates/ictl-wda" }
ictl-protocol = { path = "crates/ictl-protocol" }
ictl-l10n = { path = "crates/ictl-l10n" }
+ictl-webinspector = { path = "crates/ictl-webinspector" }
ictl-sign = { path = "crates/ictl-sign" }
ictl-unlock = { path = "crates/ictl-unlock" }
ictl-daemon = { path = "crates/ictl-daemon" }
diff --git a/crates/ictl-daemon/Cargo.toml b/crates/ictl-daemon/Cargo.toml
index e231537..f1b2971 100644
--- a/crates/ictl-daemon/Cargo.toml
+++ b/crates/ictl-daemon/Cargo.toml
@@ -11,6 +11,7 @@ description = "守护进程:状态机、usbmuxd 看护、重签、通知、控
[dependencies]
ictl-l10n.workspace = true
+ictl-webinspector.workspace = true
ictl-device.workspace = true
ictl-wda.workspace = true
ictl-sign.workspace = true
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index bd9dd56..4a87280 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -34,6 +34,8 @@ pub const STALE: Duration = Duration::from_secs(30);
pub const MAX_GESTURE_SECONDS: f64 = 10.0;
/// 等界面稳定、等元素出现的上限(毫秒):持着设备锁等,不能太久
pub const MAX_WAIT_MS: u64 = 30_000;
+/// Longest a JavaScript evaluation in a page may take (`WebEval`)
+pub const MAX_WEB_EVAL_MS: u64 = 60_000;
/// 持久化到 `state.json` 的状态(不含秘密)
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
@@ -251,6 +253,9 @@ pub struct Daemon {
pub log: EventLog,
pub(crate) inner: Mutex<Inner>,
snap: watch::Sender<Snapshot>,
+ /// The kept Web Inspector connection (developer tools), separate from `inner` so a slow page doesn't hold up
+ /// taps and screenshots; see [`crate::web`]
+ pub(crate) web: Mutex<Option<crate::web::WebConn>>,
}
/// 停掉 HID 会话(屏幕媒体流),隧道保留。媒体流不停的话手机一直以为「配对的电脑」在看屏幕:
@@ -365,7 +370,7 @@ impl Daemon {
log_tail: Vec::new(),
};
let (snap, _) = watch::channel(first);
- Arc::new(Self { cfg, log, inner: Mutex::new(inner), snap })
+ Arc::new(Self { cfg, log, inner: Mutex::new(inner), snap, web: Mutex::new(None) })
}
/// 自动解锁配置:用设备 `udid` 自己的密码。没接设备时密码文件不存在(自动解锁不可用)
@@ -540,6 +545,22 @@ impl Daemon {
Request::Resign { force } => {
return self.resign_now(force).await.map(Response::text).unwrap_or_else(Response::error);
}
+ // Web Inspector requests talk to the page, not to WDA; they only take the lock to find the device
+ Request::WebTargets => return self.web_targets().await.map(Response::text).unwrap_or_else(Response::error),
+ Request::WebEval { target, expression, timeout_ms } => {
+ if expression.trim().is_empty() || timeout_ms > MAX_WEB_EVAL_MS {
+ return Response::error(ictl_l10n::trf!(
+ "expression 不能为空,timeout 最多 {} 秒",
+ "expression can't be empty, and timeout can be at most {} seconds",
+ MAX_WEB_EVAL_MS / 1000
+ ));
+ }
+ return self
+ .web_eval(&target, &expression, Duration::from_millis(timeout_ms))
+ .await
+ .map(Response::text)
+ .unwrap_or_else(Response::error);
+ }
// an install can take minutes; it doesn't hold the lock meanwhile
Request::InstallApp { path } => {
return self.install_app(&path).await.map(Response::text).unwrap_or_else(Response::error);
@@ -634,7 +655,11 @@ impl Daemon {
}
Request::CrashReports { filter, name } => self.crash_reports(g, &filter, &name).await,
Request::UninstallApp { app } => self.uninstall_app(g, &app).await,
- Request::Daemon | Request::Resign { .. } | Request::InstallApp { .. } => unreachable!("上面已处理"),
+ Request::Daemon
+ | Request::Resign { .. }
+ | Request::InstallApp { .. }
+ | Request::WebTargets
+ | Request::WebEval { .. } => unreachable!("上面已处理"),
};
if invalidates {
g.elements_cache = None;
diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs
index 4b9853c..884c6d8 100644
--- a/crates/ictl-daemon/src/lib.rs
+++ b/crates/ictl-daemon/src/lib.rs
@@ -17,6 +17,7 @@ pub mod notify;
mod supervise;
mod tools;
mod wda_pkg;
+mod web;
pub use ictl_protocol as protocol;
diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rs
index 12d903d..893683b 100644
--- a/crates/ictl-daemon/src/supervise.rs
+++ b/crates/ictl-daemon/src/supervise.rs
@@ -191,6 +191,7 @@ impl Daemon {
g.next_session_check = now + self.cfg.session_check;
tokio::task::spawn_local(self.clone().check_session());
}
+ self.web_housekeeping(g.device.as_ref().map(|d| d.udid.as_str()));
self.publish(g);
}
diff --git a/crates/ictl-daemon/src/web.rs b/crates/ictl-daemon/src/web.rs
new file mode 100644
index 0000000..f44e880
--- /dev/null
+++ b/crates/ictl-daemon/src/web.rs
@@ -0,0 +1,227 @@
+//! Web Inspector tools (part of the developer tools): list inspectable pages and WebViews, evaluate JavaScript.
+//!
+//! One Web Inspector connection is kept and reused across requests. Opening a new one shortly after the last one
+//! closed takes about 8 seconds, and after a few connect/disconnect rounds the phone stopped reporting Safari to new
+//! connections until Safari was restarted (iPhone 15 Pro Max, iOS 27.0.1); on a kept connection listing and
+//! evaluating take a few milliseconds. The connection is closed after [`WEB_IDLE`] without a request, when the
+//! daemon controls another device or none, and after an error (the next request opens a new one).
+//!
+//! Web requests take their own lock, and the daemon lock only to look up the device, so a slow page doesn't hold up
+//! taps and screenshots.
+
+use std::time::{Duration, Instant};
+
+use ictl_webinspector::{App, Eval, Page, WebInspector};
+
+use crate::core::Daemon;
+
+/// A kept connection is closed after this long without a request
+const WEB_IDLE: Duration = Duration::from_secs(5 * 60);
+
+/// The kept Web Inspector connection, for one device
+pub(crate) struct WebConn {
+ udid: String,
+ w: WebInspector,
+ used: Instant,
+}
+
+/// How long applications get to report their pages
+const LISTING_WAIT: Duration = Duration::from_secs(3);
+const MAX_RESULT_CHARS: usize = 50_000;
+
+impl Daemon {
+ pub(crate) async fn web_targets(&self) -> Result<String, String> {
+ let mut slot = self.web.lock().await;
+ let (apps, pages) = self.web_pages(&mut slot).await?;
+ if pages.is_empty() {
+ return Ok(ictl_l10n::tr!(
+ "没有可检查的页面。需要:设置 → Safari → 高级 → 网页检查器 打开;App 里的 WebView 要是调试构建或设了 isInspectable;页面所在的 App 在前台(刚打开的 App 等几秒再试)",
+ "No inspectable pages. Needed: Settings → Safari → Advanced → Web Inspector on; WebViews in apps must be debug builds or have isInspectable set; the app showing the page is in the foreground (wait a few seconds after opening it)"
+ )
+ .into());
+ }
+ let mut out = ictl_l10n::tr!(
+ "可检查的页面(id 用于 iphone_web_eval 的 target):",
+ "Inspectable pages (pass the id as target to iphone_web_eval):"
+ )
+ .to_owned();
+ for p in &pages {
+ out.push('\n');
+ out += &target_line(p, &apps);
+ }
+ Ok(out)
+ }
+
+ pub(crate) async fn web_eval(&self, target: &str, expression: &str, timeout: Duration) -> Result<String, String> {
+ let mut slot = self.web.lock().await;
+ let (apps, pages) = self.web_pages(&mut slot).await?;
+ let page = pick(&pages, target).map_err(|e| match e {
+ Pick::None => ictl_l10n::trf!(
+ "没有和「{target}」对应的页面,用 iphone_web_targets 查看",
+ "No page matches “{target}”; see iphone_web_targets"
+ ),
+ Pick::Several(c) => ictl_l10n::trf!(
+ "「{target}」对应多个页面,用 id 指定其中一个:\n{}",
+ "“{target}” matches several pages; pass one id:\n{}",
+ c.iter().map(|p| target_line(p, &apps)).collect::<Vec<_>>().join("\n")
+ ),
+ })?;
+ let conn = slot.as_mut().ok_or("Web Inspector")?;
+ conn.used = Instant::now();
+ // not retried on a new connection: the script may already have run
+ let r = match conn.w.evaluate(page, expression, timeout).await {
+ Ok(r) => r,
+ Err(e) => {
+ if breaks_connection(&e) {
+ *slot = None;
+ }
+ return Err(e.to_string());
+ }
+ };
+ Ok(match r {
+ Eval::Value(None) => "undefined".into(),
+ Eval::Value(Some(v)) => truncate(v.to_string()),
+ Eval::Thrown(d) => return Err(ictl_l10n::trf!("页面里抛出异常:{d}", "The page threw: {d}")),
+ })
+ }
+
+ /// The pages, on the kept connection (opened if there is none, or it belongs to another device). A connection
+ /// that turns out to be broken is replaced once: listing pages changes nothing on the phone
+ async fn web_pages(&self, slot: &mut Option<WebConn>) -> Result<(Vec<App>, Vec<Page>), String> {
+ let device =
+ self.inner.lock().await.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
+ if slot.as_ref().is_some_and(|c| c.udid != device.udid) {
+ *slot = None;
+ }
+ for attempt in 0..2 {
+ if slot.is_none() {
+ let w = device.web_inspector().await.map_err(|e| e.to_string())?;
+ *slot = Some(WebConn { udid: device.udid.clone(), w, used: Instant::now() });
+ }
+ let conn = slot.as_mut().ok_or("Web Inspector")?;
+ conn.used = Instant::now();
+ match conn.w.pages(LISTING_WAIT).await {
+ Ok(r) => return Ok(r),
+ Err(e) if breaks_connection(&e) => {
+ *slot = None;
+ if attempt == 1 {
+ return Err(e.to_string());
+ }
+ tracing::debug!("Web Inspector connection broken, opening a new one: {e}");
+ }
+ Err(e) => return Err(e.to_string()),
+ }
+ }
+ unreachable!("the second attempt returns")
+ }
+
+ /// Closes the kept connection after [`WEB_IDLE`], or when the daemon no longer controls its device. Called from
+ /// the health check; skipped while a web request is running
+ pub(crate) fn web_housekeeping(&self, controlled: Option<&str>) {
+ if let Ok(mut slot) = self.web.try_lock()
+ && slot.as_ref().is_some_and(|c| c.used.elapsed() > WEB_IDLE || Some(c.udid.as_str()) != controlled)
+ {
+ *slot = None;
+ }
+ }
+}
+
+/// Errors after which the connection can't be trusted to be in step: everything except a page that didn't answer
+/// in time (the session is closed and late answers for it are dropped)
+fn breaks_connection(e: &ictl_webinspector::Error) -> bool {
+ !matches!(e, ictl_webinspector::Error::Timeout(_))
+}
+
+/// `PID:812/1 WebPage Safari (com.apple.mobilesafari) Title — https://…`
+fn target_line(p: &Page, apps: &[App]) -> String {
+ let app = apps.iter().find(|a| a.id == p.app_id);
+ // a WebContent process stands in for the app that shows the page
+ let shown = app.and_then(|a| a.host.as_deref()).and_then(|h| apps.iter().find(|a| a.id == h)).or(app);
+ let who = shown.map(|a| format!("{} ({})", a.name, a.bundle_id)).unwrap_or_else(|| p.app_id.clone());
+ let busy =
+ if p.in_use { ictl_l10n::tr!(" [另一个调试器已连接]", " [another debugger is attached]") } else { "" };
+ format!("{}/{} {} {who} {} — {}{busy}", p.app_id, p.id, p.kind, p.title, p.url)
+}
+
+enum Pick<'a> {
+ None,
+ Several(Vec<&'a Page>),
+}
+
+/// `target` is an id from the list (`PID:812/1`), or text in the URL or title; empty means the only page there is
+fn pick<'a>(pages: &'a [Page], target: &str) -> Result<&'a Page, Pick<'a>> {
+ if let Some(p) = pages.iter().find(|p| format!("{}/{}", p.app_id, p.id) == target) {
+ return Ok(p);
+ }
+ let t = target.to_lowercase();
+ let hits: Vec<&Page> =
+ pages.iter().filter(|p| p.url.to_lowercase().contains(&t) || p.title.to_lowercase().contains(&t)).collect();
+ match hits.len() {
+ 0 => Err(Pick::None),
+ 1 => Ok(hits[0]),
+ _ => Err(Pick::Several(hits)),
+ }
+}
+
+fn truncate(s: String) -> String {
+ let n = s.chars().count();
+ if n <= MAX_RESULT_CHARS {
+ return s;
+ }
+ let head: String = s.chars().take(MAX_RESULT_CHARS).collect();
+ head + &ictl_l10n::trf!(
+ "\n…(共 {n} 个字符,只返回前 {MAX_RESULT_CHARS} 个;在表达式里只取需要的部分)",
+ "\n… ({n} characters in total, only the first {MAX_RESULT_CHARS} returned; select just what you need in the expression)"
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn page(app: &str, id: u64, url: &str, title: &str) -> Page {
+ Page { app_id: app.into(), id, kind: "WebPage".into(), title: title.into(), url: url.into(), in_use: false }
+ }
+
+ #[test]
+ fn only_a_page_timeout_keeps_the_connection() {
+ use ictl_webinspector::Error;
+ assert!(!breaks_connection(&Error::Timeout("the page to answer")));
+ assert!(breaks_connection(&Error::Protocol("x".into())));
+ assert!(breaks_connection(&Error::Io(std::io::Error::other("closed"))));
+ }
+
+ #[test]
+ fn picks_by_id_or_text() {
+ let pages =
+ [page("PID:1", 1, "capacitor://localhost", "Taulit"), page("PID:2", 4, "https://example.com/a", "Example")];
+ assert_eq!(pick(&pages, "PID:2/4").ok().map(|p| p.id), Some(4));
+ assert_eq!(pick(&pages, "capacitor").ok().map(|p| p.id), Some(1));
+ assert_eq!(pick(&pages, "EXAMPLE").ok().map(|p| p.id), Some(4));
+ assert!(matches!(pick(&pages, ""), Err(Pick::Several(v)) if v.len() == 2));
+ assert!(matches!(pick(&pages, "nothing"), Err(Pick::None)));
+ assert_eq!(pick(&pages[..1], "").ok().map(|p| p.id), Some(1));
+ }
+
+ #[test]
+ fn webcontent_proxies_show_their_host_app() {
+ let apps = [
+ App {
+ id: "PID:640".into(),
+ name: "Taulit".into(),
+ bundle_id: "com.example.taulit".into(),
+ host: None,
+ active: true,
+ },
+ App {
+ id: "PID:812".into(),
+ name: "WebContent".into(),
+ bundle_id: "com.apple.WebKit.WebContent".into(),
+ host: Some("PID:640".into()),
+ active: true,
+ },
+ ];
+ let line = target_line(&page("PID:812", 1, "capacitor://localhost", "Home"), &apps);
+ assert_eq!(line, "PID:812/1 WebPage Taulit (com.example.taulit) Home — capacitor://localhost");
+ }
+}
diff --git a/crates/ictl-device/Cargo.toml b/crates/ictl-device/Cargo.toml
index a2b824a..7d7bb38 100644
--- a/crates/ictl-device/Cargo.toml
+++ b/crates/ictl-device/Cargo.toml
@@ -11,6 +11,7 @@ description = "设备层:发现、配对、隧道、开发者镜像、HID、
[dependencies]
ictl-l10n.workspace = true
+ictl-webinspector.workspace = true
idevice.workspace = true
tokio.workspace = true
thiserror.workspace = true
diff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rs
index 703a08a..4778526 100644
--- a/crates/ictl-device/src/lib.rs
+++ b/crates/ictl-device/src/lib.rs
@@ -488,6 +488,17 @@ impl Device {
.await
}
+ /// Opens the Web Inspector service (inspectable pages and WebViews)
+ pub async fn web_inspector(&self) -> Result<ictl_webinspector::WebInspector> {
+ limit(ictl_l10n::tr!("打开 Web Inspector", "open the Web Inspector"), QUERY, async {
+ ictl_webinspector::WebInspector::open(&*self.provider).await.map_err(|e| match e {
+ ictl_webinspector::Error::Device(e) => e.into(),
+ e => DeviceError::Idevice(e.to_string()),
+ })
+ })
+ .await
+ }
+
/// Starts the phone's unified log stream (os_trace_relay), every process, without debug messages.
/// Asking for debug messages (what idevice's `start_trace` does) makes every process on the phone produce them:
/// about 650 lines a second instead of about 80 on an idle iPhone 15 Pro Max (iOS 27.0.1), and gestures got
diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs
index b14d469..87d11e3 100644
--- a/crates/ictl-mcp/src/lib.rs
+++ b/crates/ictl-mcp/src/lib.rs
@@ -119,8 +119,14 @@ fn acting(title: &str, destructive: bool, idempotent: bool) -> ToolAnnotations {
}
/// Names of the developer tools, listed only with [`dev_tools_enabled`]
-pub const DEV_TOOLS: [&str; 4] =
- ["iphone_app_logs", "iphone_crash_reports", "iphone_install_app", "iphone_uninstall_app"];
+pub const DEV_TOOLS: [&str; 6] = [
+ "iphone_app_logs",
+ "iphone_crash_reports",
+ "iphone_install_app",
+ "iphone_uninstall_app",
+ "iphone_web_targets",
+ "iphone_web_eval",
+];
/// `IPHONE_CONTROL_DEV_TOOLS=1` (or true/yes/on) adds the developer tools; off by default, so agents that don't
/// need them don't pay for their descriptions
@@ -208,6 +214,35 @@ fn dev_tools() -> Vec<Tool> {
),
acting(ictl_l10n::tr!("卸载 App", "Uninstall app"), true, true),
),
+ t(
+ "iphone_web_targets",
+ ictl_l10n::tr!(
+ "列出可检查的网页和 WebView(Web Inspector):Safari 标签页、App 里可检查的 WebView(Capacitor、Cordova、React Native 等的调试构建)。每行:id、类型、所属 App、标题和网址。\n\n\
+何时用:页面内容在网页里时,用 iphone_web_eval 直接读 DOM,比截图和元素树快、省 token、也更准。需要手机上 设置 → Safari → 高级 → 网页检查器 打开。只读。",
+ "List inspectable web pages and WebViews (Web Inspector): Safari tabs and inspectable WebViews in apps (debug builds of Capacitor, Cordova, React Native and similar). One line each: id, type, app, title and URL.\n\nWhen to use: when the content is a web page, read the DOM with iphone_web_eval instead; that is faster, cheaper in tokens and more accurate than screenshots or the element tree. Needs Settings → Safari → Advanced → Web Inspector on. Read-only."
+ ),
+ schema(json!({}), &[]),
+ looking(ictl_l10n::tr!("列出网页", "List web pages")),
+ ),
+ t(
+ "iphone_web_eval",
+ ictl_l10n::tr!(
+ "在网页或 WebView 里执行 JavaScript,返回结果的 JSON(Promise 会等它完成)。例如 document.title、\
+[...document.querySelectorAll('button')].map(b => b.innerText)、document.querySelector('#email').value = '[email protected]'。\n\n\
+何时用:读网页内容、表单状态、控制台变量,或直接操作页面。只取需要的部分,结果超过 5 万字会被截断。\
+脚本能改页面(提交表单、发请求),和点击一样要小心。",
+ "Run JavaScript in a web page or WebView and return the result as JSON (a promise is awaited). For example document.title, [...document.querySelectorAll('button')].map(b => b.innerText), document.querySelector('#email').value = '[email protected]'.\n\nWhen to use: to read page content, form state or JavaScript variables, or to act on the page directly. Select just what you need; results over 50,000 characters are cut. A script can change the page (submit forms, send requests), so take the same care as with taps."
+ ),
+ schema(
+ json!({
+ "expression": {"type": "string", "description": ictl_l10n::tr!("要执行的 JavaScript 表达式", "the JavaScript expression to run")},
+ "target": {"type": "string", "default": "", "description": ictl_l10n::tr!("iphone_web_targets 列出的 id,或网址、标题里的一段文字;只有一个页面时可以不填", "an id from iphone_web_targets, or text in the page's URL or title; may be left out when there is only one page")},
+ "timeout": {"type": "number", "default": 10, "description": ictl_l10n::tr!("最多等多少秒,最多 60", "maximum seconds to wait, at most 60")}
+ }),
+ &["expression"],
+ ),
+ acting(ictl_l10n::tr!("执行 JavaScript", "Run JavaScript"), true, false),
+ ),
]
}
@@ -605,6 +640,20 @@ pub fn to_request(name: &str, args: &Map<String, Value>) -> Result<Request, Stri
"iphone_crash_reports" => Request::CrashReports { filter: a.s_or("filter", "")?, name: a.s_or("name", "")? },
"iphone_install_app" => Request::InstallApp { path: a.s("path")? },
"iphone_uninstall_app" => Request::UninstallApp { app: a.s("app")? },
+ "iphone_web_targets" => Request::WebTargets,
+ "iphone_web_eval" => {
+ let secs = a.f_or("timeout", 10.0)?;
+ if !(0.0..=60.0).contains(&secs) {
+ return Err(
+ ictl_l10n::tr!("timeout 要在 0 到 60 秒之间", "timeout must be between 0 and 60 seconds").into()
+ );
+ }
+ Request::WebEval {
+ target: a.s_or("target", "")?,
+ expression: a.s("expression")?,
+ timeout_ms: (secs * 1000.0) as u64,
+ }
+ }
"iphone_wait_for" => {
let secs = a.f_or("timeout", 5.0)?;
if !(0.0..=30.0).contains(&secs) {
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index 64841f7..33705dc 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -150,6 +150,15 @@ pub enum Request {
UninstallApp {
app: String,
},
+ /// Developer tools: inspectable pages and WebViews (Web Inspector)
+ WebTargets,
+ /// Developer tools: evaluate JavaScript in a page. `target` is an id from `WebTargets`, or text in its URL or title
+ WebEval {
+ #[serde(default)]
+ target: String,
+ expression: String,
+ timeout_ms: u64,
+ },
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -213,6 +222,7 @@ impl Request {
| Self::SelectDevice { .. }
| Self::InstallApp { .. }
| Self::UninstallApp { .. }
+ | Self::WebEval { .. }
)
}
}
diff --git a/crates/ictl-webinspector/Cargo.toml b/crates/ictl-webinspector/Cargo.toml
new file mode 100644
index 0000000..65f5414
--- /dev/null
+++ b/crates/ictl-webinspector/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "ictl-webinspector"
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+license.workspace = true
+publish.workspace = true
+repository.workspace = true
+homepage.workspace = true
+description = "Client for the iOS Web Inspector service (com.apple.webinspector): list inspectable pages and WebViews, evaluate JavaScript"
+
+[dependencies]
+idevice.workspace = true
+tokio.workspace = true
+thiserror.workspace = true
+tracing.workspace = true
+plist.workspace = true
+uuid.workspace = true
+serde_json.workspace = true
diff --git a/crates/ictl-webinspector/src/lib.rs b/crates/ictl-webinspector/src/lib.rs
new file mode 100644
index 0000000..76a1c8e
--- /dev/null
+++ b/crates/ictl-webinspector/src/lib.rs
@@ -0,0 +1,535 @@
+//! Client for the iOS Web Inspector service (`com.apple.webinspector`, started through lockdown).
+//!
+//! It is what Safari's Develop menu talks to. The phone needs Settings → Safari → Advanced → Web Inspector on, and
+//! a page is only listed when it is inspectable: Safari tabs, and WebViews of apps built for debugging or with
+//! `isInspectable` set.
+//!
+//! The service speaks binary plists (a 4-byte big-endian length, then the plist), each
+//! `{__selector, __argument}`. The flow:
+//!
+//! 1. `_rpc_reportIdentifier:` with our connection ID; the phone answers with the connected applications
+//! (`_rpc_reportConnectedApplicationList:`).
+//! 2. `_rpc_forwardGetListing:` per application → `_rpc_applicationSentListing:` with its pages.
+//! 3. `_rpc_forwardSocketSetup:` attaches to a page; `_rpc_forwardSocketData:` carries Web Inspector protocol
+//! JSON to it and `_rpc_applicationSentData:` back. Current WebKit wraps that in the `Target` domain
+//! (`Target.sendMessageToTarget` / `Target.dispatchMessageFromTarget`); older versions take commands directly.
+//! 4. `_rpc_forwardDidClose:` detaches.
+
+use std::collections::{BTreeMap, HashMap};
+use std::time::Duration;
+
+use idevice::{Idevice, IdeviceError, IdeviceService, ReadWrite, provider::IdeviceProvider};
+use plist::{Dictionary, Value};
+use serde_json::json;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::time::Instant;
+
+/// Messages larger than this are refused (a listing or an evaluation result is far smaller)
+const MAX_MESSAGE: usize = 64 * 1024 * 1024;
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error("{0}")]
+ Device(#[from] IdeviceError),
+ #[error("Web Inspector connection: {0}")]
+ Io(#[from] std::io::Error),
+ #[error("Web Inspector message: {0}")]
+ Plist(#[from] plist::Error),
+ #[error("Web Inspector: {0}")]
+ Protocol(String),
+ #[error("timed out waiting for {0}")]
+ Timeout(&'static str),
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+/// An application that hosts inspectable content (Safari, an app, or a WebContent process acting for one)
+#[derive(Debug, Clone, PartialEq)]
+pub struct App {
+ pub id: String,
+ pub name: String,
+ pub bundle_id: String,
+ /// For a WebContent proxy: the application it renders for
+ pub host: Option<String>,
+ pub active: bool,
+}
+
+/// An inspectable page, WebView or JavaScript context
+#[derive(Debug, Clone, PartialEq)]
+pub struct Page {
+ pub app_id: String,
+ pub id: u64,
+ /// `WIRTypeWebPage`, `WIRTypeWeb`, `WIRTypeJavaScript`, `WIRTypeServiceWorker`, … without the `WIRType` prefix
+ pub kind: String,
+ pub title: String,
+ pub url: String,
+ /// Another debugger (Safari's Web Inspector, for example) is attached
+ pub in_use: bool,
+}
+
+/// What a JavaScript evaluation returned
+#[derive(Debug, Clone, PartialEq)]
+pub enum Eval {
+ /// The value, serialized to JSON by the page (`returnByValue`); `undefined` becomes `None`
+ Value(Option<serde_json::Value>),
+ /// The expression threw; the exception's description
+ Thrown(String),
+}
+
+pub struct WebInspector {
+ socket: Box<dyn ReadWrite>,
+ connection: String,
+ apps: BTreeMap<String, App>,
+ listings: HashMap<String, Vec<Page>>,
+ /// Inspector protocol messages that arrived for a session, by sender ID
+ data: HashMap<String, Vec<serde_json::Value>>,
+ /// Pieces of a message the phone split up (`WIRPartialMessageKey`)
+ partial: Vec<u8>,
+ reported: bool,
+}
+
+impl IdeviceService for WebInspector {
+ fn service_name() -> std::borrow::Cow<'static, str> {
+ "com.apple.webinspector".into()
+ }
+
+ async fn from_stream(idevice: Idevice) -> std::result::Result<Self, IdeviceError> {
+ let socket = idevice.get_socket().ok_or(IdeviceError::NoEstablishedConnection)?;
+ Ok(Self {
+ socket,
+ connection: uuid::Uuid::new_v4().to_string().to_uppercase(),
+ apps: BTreeMap::new(),
+ listings: HashMap::new(),
+ data: HashMap::new(),
+ partial: Vec::new(),
+ reported: false,
+ })
+ }
+
+ fn get_socket(&mut self) -> Option<&mut Box<dyn ReadWrite>> {
+ Some(&mut self.socket)
+ }
+}
+
+impl WebInspector {
+ /// Connects through lockdown and announces this client
+ pub async fn open(provider: &dyn IdeviceProvider) -> Result<Self> {
+ let mut w = Self::connect(provider).await?;
+ w.send("_rpc_reportIdentifier:", Dictionary::new()).await?;
+ Ok(w)
+ }
+
+ /// Every inspectable page of every application. Waits up to `wait` for the applications to answer; pages of
+ /// applications that don't answer in time are left out
+ pub async fn pages(&mut self, wait: Duration) -> Result<(Vec<App>, Vec<Page>)> {
+ let deadline = Instant::now() + wait;
+ // asked again every time: on a kept connection, applications may have come and gone since
+ self.reported = false;
+ self.send("_rpc_getConnectedApplications:", Dictionary::new()).await?;
+ while !self.reported {
+ if !self.recv_until(deadline).await? {
+ return Err(Error::Timeout("the list of applications"));
+ }
+ }
+ self.listings.clear();
+ let ids: Vec<String> = self.apps.keys().cloned().collect();
+ for id in &ids {
+ let mut a = Dictionary::new();
+ a.insert("WIRApplicationIdentifierKey".into(), id.clone().into());
+ self.send("_rpc_forwardGetListing:", a).await?;
+ }
+ // suspended apps (in the background) don't answer; only wait for the active ones and the WebContent processes
+ // working for them
+ let awake = |a: &App, apps: &BTreeMap<String, App>| {
+ a.active || a.host.as_ref().and_then(|h| apps.get(h)).is_some_and(|h| h.active)
+ };
+ let waiting: Vec<String> = self.apps.values().filter(|a| awake(a, &self.apps)).map(|a| a.id.clone()).collect();
+ while waiting.iter().any(|id| !self.listings.contains_key(id)) {
+ if !self.recv_until(deadline).await? {
+ break;
+ }
+ }
+ let pages = ids.iter().flat_map(|id| self.listings.get(id).cloned().unwrap_or_default()).collect();
+ Ok((self.apps.values().cloned().collect(), pages))
+ }
+
+ /// Evaluates `expression` in a page and returns its value. A promise is awaited
+ pub async fn evaluate(&mut self, page: &Page, expression: &str, timeout: Duration) -> Result<Eval> {
+ let deadline = Instant::now() + timeout;
+ let sender = uuid::Uuid::new_v4().to_string().to_uppercase();
+ let mut setup = self.page_args(page);
+ setup.insert("WIRSenderKey".into(), sender.clone().into());
+ setup.insert("WIRMessageDataTypeChunkSupportedKey".into(), 0.into());
+ setup.insert("WIRAutomaticallyPause".into(), false.into());
+ self.send("_rpc_forwardSocketSetup:", setup).await?;
+
+ let mut session = Session { sender, target: None, next_id: 1 };
+ // current WebKit announces the page target first; older versions take commands directly
+ let probe = (Instant::now() + Duration::from_millis(1500)).min(deadline);
+ while session.target.is_none() {
+ let got = self.take_data(&session.sender);
+ for m in got {
+ if m["method"] == "Target.targetCreated" && m["params"]["targetInfo"]["type"] == "page" {
+ session.target = m["params"]["targetInfo"]["targetId"].as_str().map(str::to_owned);
+ }
+ }
+ if session.target.is_some() || !self.recv_until(probe).await? {
+ break;
+ }
+ }
+
+ let result = self.run_eval(page, &mut session, expression, deadline).await;
+ let mut close = self.page_args(page);
+ close.insert("WIRSenderKey".into(), session.sender.clone().into());
+ let _ = self.send("_rpc_forwardDidClose:", close).await;
+ self.data.remove(&session.sender);
+ result
+ }
+
+ async fn run_eval(&mut self, page: &Page, s: &mut Session, expression: &str, deadline: Instant) -> Result<Eval> {
+ // Evaluate to a remote object first: with returnByValue WebKit would serialize a promise right away (as {}).
+ // Then await a promise, or fetch an object's value; primitives already carry it
+ let r = self.command(page, s, "Runtime.evaluate", json!({"expression": expression}), deadline).await?;
+ let id = r["result"]["objectId"].clone();
+ // WebKit marks promises by class name (Chrome uses subtype "promise"); functions have no JSON value
+ let r = if r["wasThrown"] == true || id.is_null() || r["result"]["type"] == "function" {
+ r
+ } else if r["result"]["className"] == "Promise" || r["result"]["subtype"] == "promise" {
+ let p = json!({"promiseObjectId": id, "returnByValue": true});
+ self.command(page, s, "Runtime.awaitPromise", p, deadline).await?
+ } else {
+ let f =
+ json!({"objectId": id, "functionDeclaration": "function() { return this; }", "returnByValue": true});
+ let v = self.command(page, s, "Runtime.callFunctionOn", f, deadline).await?;
+ // a DOM node or similar serializes to {}; its description ("body", "div#app") says more
+ let empty = v["result"]["value"].as_object().is_some_and(|o| o.is_empty());
+ let plain = r["result"]["className"] == "Object" || r["result"]["subtype"] == "array";
+ if v["result"].get("value").is_some() && !(empty && !plain) { v } else { r }
+ };
+ Ok(eval_result(&r))
+ }
+
+ /// Sends one Web Inspector protocol command to the page and waits for its result
+ async fn command(
+ &mut self,
+ page: &Page,
+ s: &mut Session,
+ method: &str,
+ params: serde_json::Value,
+ deadline: Instant,
+ ) -> Result<serde_json::Value> {
+ let id = s.next_id;
+ s.next_id += 1;
+ let inner = json!({"id": id, "method": method, "params": params});
+ let msg = match &s.target {
+ Some(t) => json!({"id": id + 1_000_000, "method": "Target.sendMessageToTarget",
+ "params": {"targetId": t, "message": inner.to_string()}}),
+ None => inner,
+ };
+ let mut a = self.page_args(page);
+ a.insert("WIRSessionIdentifierKey".into(), s.sender.clone().into());
+ a.insert("WIRSenderKey".into(), s.sender.clone().into());
+ a.insert("WIRSocketDataKey".into(), Value::Data(msg.to_string().into_bytes()));
+ self.send("_rpc_forwardSocketData:", a).await?;
+ loop {
+ for m in self.take_data(&s.sender) {
+ if let Some(r) = response_for(&m, id) {
+ return r;
+ }
+ }
+ if !self.recv_until(deadline).await? {
+ return Err(Error::Timeout("the page to answer"));
+ }
+ }
+ }
+
+ fn page_args(&self, page: &Page) -> Dictionary {
+ let mut a = Dictionary::new();
+ a.insert("WIRApplicationIdentifierKey".into(), page.app_id.clone().into());
+ a.insert("WIRPageIdentifierKey".into(), page.id.into());
+ a
+ }
+
+ fn take_data(&mut self, sender: &str) -> Vec<serde_json::Value> {
+ self.data.remove(sender).unwrap_or_default()
+ }
+
+ async fn send(&mut self, selector: &str, mut args: Dictionary) -> Result<()> {
+ args.insert("WIRConnectionIdentifierKey".into(), self.connection.clone().into());
+ let mut msg = Dictionary::new();
+ msg.insert("__selector".into(), selector.into());
+ msg.insert("__argument".into(), Value::Dictionary(args));
+ let mut body = Vec::new();
+ plist::to_writer_binary(&mut body, &Value::Dictionary(msg))?;
+ let mut framed = (body.len() as u32).to_be_bytes().to_vec();
+ framed.extend_from_slice(&body);
+ self.socket.write_all(&framed).await?;
+ self.socket.flush().await?;
+ Ok(())
+ }
+
+ /// Reads and handles one message; `false` when `deadline` passed first
+ async fn recv_until(&mut self, deadline: Instant) -> Result<bool> {
+ let Ok(msg) = tokio::time::timeout_at(deadline, self.read_message()).await else {
+ return Ok(false);
+ };
+ let msg = msg?;
+ if let Some(m) = self.unchunk(msg)? {
+ self.handle(m);
+ }
+ Ok(true)
+ }
+
+ async fn read_message(&mut self) -> Result<Dictionary> {
+ let mut len = [0u8; 4];
+ self.socket.read_exact(&mut len).await?;
+ let len = u32::from_be_bytes(len) as usize;
+ if len > MAX_MESSAGE {
+ return Err(Error::Protocol(format!("message of {len} bytes")));
+ }
+ let mut body = vec![0u8; len];
+ self.socket.read_exact(&mut body).await?;
+ Ok(plist::from_bytes(&body)?)
+ }
+
+ fn unchunk(&mut self, msg: Dictionary) -> Result<Option<Dictionary>> {
+ unchunk_into(&mut self.partial, msg)
+ }
+
+ fn handle(&mut self, msg: Dictionary) {
+ let selector = msg.get("__selector").and_then(Value::as_string).unwrap_or_default();
+ let empty = Dictionary::new();
+ let arg = msg.get("__argument").and_then(Value::as_dictionary).unwrap_or(&empty);
+ match selector {
+ "_rpc_reportConnectedApplicationList:" => {
+ self.apps.clear();
+ if let Some(list) = arg.get("WIRApplicationDictionaryKey").and_then(Value::as_dictionary) {
+ for v in list.values() {
+ if let Some(a) = v.as_dictionary().and_then(parse_app) {
+ self.apps.insert(a.id.clone(), a);
+ }
+ }
+ }
+ self.reported = true;
+ }
+ "_rpc_applicationConnected:" | "_rpc_applicationUpdated:" => {
+ if let Some(a) = parse_app(arg) {
+ self.apps.insert(a.id.clone(), a);
+ }
+ }
+ "_rpc_applicationDisconnected:" => {
+ if let Some(id) = arg.get("WIRApplicationIdentifierKey").and_then(Value::as_string) {
+ self.apps.remove(id);
+ self.listings.remove(id);
+ }
+ }
+ "_rpc_applicationSentListing:" => {
+ if let Some(id) = arg.get("WIRApplicationIdentifierKey").and_then(Value::as_string) {
+ self.listings.insert(id.to_owned(), parse_listing(id, arg));
+ }
+ }
+ "_rpc_applicationSentData:" => {
+ let dest = arg.get("WIRDestinationKey").and_then(Value::as_string);
+ let data = arg.get("WIRMessageDataKey").and_then(Value::as_data);
+ if let (Some(dest), Some(data)) = (dest, data)
+ && let Ok(v) = serde_json::from_slice::<serde_json::Value>(data)
+ {
+ self.data.entry(dest.to_owned()).or_default().push(v);
+ }
+ }
+ other => tracing::trace!("webinspector: {other}"),
+ }
+ }
+}
+
+/// Puts split messages back together: parts come as `WIRPartialMessageKey`, the last as `WIRFinalMessageKey`
+fn unchunk_into(partial: &mut Vec<u8>, msg: Dictionary) -> Result<Option<Dictionary>> {
+ let arg = msg.get("__argument").and_then(Value::as_dictionary);
+ if let Some(part) = arg.and_then(|a| a.get("WIRPartialMessageKey")).and_then(Value::as_data) {
+ if partial.len() + part.len() > MAX_MESSAGE {
+ partial.clear();
+ return Err(Error::Protocol(format!("split message over {MAX_MESSAGE} bytes")));
+ }
+ partial.extend_from_slice(part);
+ return Ok(None);
+ }
+ if let Some(last) = arg.and_then(|a| a.get("WIRFinalMessageKey")).and_then(Value::as_data) {
+ partial.extend_from_slice(last);
+ let whole = std::mem::take(partial);
+ return Ok(Some(plist::from_bytes(&whole)?));
+ }
+ Ok(Some(msg))
+}
+
+struct Session {
+ sender: String,
+ /// The page target when WebKit uses the `Target` domain
+ target: Option<String>,
+ next_id: u64,
+}
+
+fn parse_app(d: &Dictionary) -> Option<App> {
+ let s = |k: &str| d.get(k).and_then(Value::as_string).unwrap_or_default().to_owned();
+ let id = s("WIRApplicationIdentifierKey");
+ if id.is_empty() {
+ return None;
+ }
+ let proxy = d.get("WIRIsApplicationProxyKey").and_then(Value::as_boolean).unwrap_or(false);
+ Some(App {
+ name: s("WIRApplicationNameKey"),
+ bundle_id: s("WIRApplicationBundleIdentifierKey"),
+ host: proxy.then(|| s("WIRHostApplicationIdentifierKey")).filter(|h| !h.is_empty()),
+ active: d.get("WIRIsApplicationActiveKey").and_then(Value::as_unsigned_integer).unwrap_or(0) != 0,
+ id,
+ })
+}
+
+fn parse_listing(app_id: &str, arg: &Dictionary) -> Vec<Page> {
+ let Some(listing) = arg.get("WIRListingKey").and_then(Value::as_dictionary) else {
+ return Vec::new();
+ };
+ let mut pages: Vec<Page> = listing
+ .values()
+ .filter_map(Value::as_dictionary)
+ .filter_map(|p| {
+ let s = |k: &str| p.get(k).and_then(Value::as_string).unwrap_or_default().to_owned();
+ Some(Page {
+ app_id: app_id.to_owned(),
+ id: p.get("WIRPageIdentifierKey")?.as_unsigned_integer()?,
+ kind: s("WIRTypeKey").trim_start_matches("WIRType").to_owned(),
+ title: s("WIRTitleKey"),
+ url: s("WIRURLKey"),
+ in_use: p.get("WIRConnectionIdentifierKey").is_some(),
+ })
+ })
+ .collect();
+ pages.sort_by_key(|p| p.id);
+ pages
+}
+
+/// The result of command `id` in an inspector message, unwrapping `Target.dispatchMessageFromTarget`
+fn response_for(m: &serde_json::Value, id: u64) -> Option<Result<serde_json::Value>> {
+ let inner;
+ let m = if m["method"] == "Target.dispatchMessageFromTarget" {
+ inner = serde_json::from_str::<serde_json::Value>(m["params"]["message"].as_str()?).ok()?;
+ &inner
+ } else {
+ m
+ };
+ if m["id"].as_u64() != Some(id) {
+ return None;
+ }
+ Some(match m.get("error") {
+ Some(e) => Err(Error::Protocol(e["message"].as_str().unwrap_or("command failed").to_owned())),
+ None => Ok(m["result"].clone()),
+ })
+}
+
+fn eval_result(r: &serde_json::Value) -> Eval {
+ let v = &r["result"];
+ if r["wasThrown"] == true {
+ return Eval::Thrown(v["description"].as_str().unwrap_or("exception").to_owned());
+ }
+ if v["type"] == "undefined" {
+ return Eval::Value(None);
+ }
+ match v.get("value") {
+ Some(x) => Eval::Value(Some(x.clone())),
+ // functions, symbols and objects that can't be serialized come back without a value
+ None => Eval::Value(v.get("description").cloned()),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn dict(v: serde_json::Value) -> Dictionary {
+ plist::to_value(&v).unwrap().into_dictionary().unwrap()
+ }
+
+ #[test]
+ fn split_messages_are_capped() {
+ let part = |n: usize| dict(json!({"__argument": {}})).tap_part(n);
+ let mut partial = vec![0u8; MAX_MESSAGE - 10];
+ assert!(unchunk_into(&mut partial, part(20)).is_err());
+ assert!(partial.is_empty(), "the pieces are dropped");
+ assert!(unchunk_into(&mut partial, part(20)).unwrap().is_none(), "a new message can start");
+ }
+
+ trait TapPart {
+ fn tap_part(self, n: usize) -> Dictionary;
+ }
+ impl TapPart for Dictionary {
+ fn tap_part(mut self, n: usize) -> Dictionary {
+ let mut a = Dictionary::new();
+ a.insert("WIRPartialMessageKey".into(), Value::Data(vec![0; n]));
+ self.insert("__argument".into(), Value::Dictionary(a));
+ self
+ }
+ }
+
+ #[test]
+ fn parses_apps_and_listing() {
+ let app = dict(json!({"WIRApplicationIdentifierKey": "PID:812", "WIRApplicationNameKey": "WebContent",
+ "WIRApplicationBundleIdentifierKey": "com.apple.WebKit.WebContent", "WIRIsApplicationProxyKey": true,
+ "WIRHostApplicationIdentifierKey": "PID:640", "WIRIsApplicationActiveKey": 1}));
+ let a = parse_app(&app).unwrap();
+ assert_eq!((a.id.as_str(), a.host.as_deref(), a.active), ("PID:812", Some("PID:640"), true));
+
+ let mut arg = dict(json!({"WIRApplicationIdentifierKey": "PID:812"}));
+ let listing = dict(json!({
+ "2": {"WIRPageIdentifierKey": 2, "WIRTypeKey": "WIRTypeWebPage", "WIRTitleKey": "B", "WIRURLKey": "https://b"},
+ "1": {"WIRPageIdentifierKey": 1, "WIRTypeKey": "WIRTypeWebPage", "WIRTitleKey": "A", "WIRURLKey": "capacitor://localhost",
+ "WIRConnectionIdentifierKey": "OTHER"}
+ }));
+ arg.insert("WIRListingKey".into(), Value::Dictionary(listing));
+ let pages = parse_listing("PID:812", &arg);
+ assert_eq!(pages.len(), 2);
+ assert_eq!((pages[0].id, pages[0].kind.as_str(), pages[0].in_use), (1, "WebPage", true));
+ assert_eq!(pages[1].url, "https://b");
+ }
+
+ #[test]
+ fn unwraps_target_messages() {
+ let wrapped = json!({"method": "Target.dispatchMessageFromTarget",
+ "params": {"targetId": "page-1", "message": "{\"id\":3,\"result\":{\"result\":{\"type\":\"number\",\"value\":2}}}"}});
+ let r = response_for(&wrapped, 3).unwrap().unwrap();
+ assert_eq!(eval_result(&r), Eval::Value(Some(json!(2))));
+ assert!(response_for(&wrapped, 4).is_none());
+ let direct = json!({"id": 1, "error": {"message": "no such method"}});
+ assert!(matches!(response_for(&direct, 1), Some(Err(Error::Protocol(m))) if m == "no such method"));
+ }
+
+ #[test]
+ fn evaluation_results() {
+ assert_eq!(eval_result(&json!({"result": {"type": "undefined"}})), Eval::Value(None));
+ assert_eq!(
+ eval_result(&json!({"result": {"type": "object", "value": {"a": [1]}}})),
+ Eval::Value(Some(json!({"a": [1]})))
+ );
+ assert_eq!(
+ eval_result(&json!({"result": {"type": "object", "description": "ReferenceError: x"}, "wasThrown": true})),
+ Eval::Thrown("ReferenceError: x".into())
+ );
+ }
+
+ #[test]
+ fn split_messages_are_joined() {
+ let mut whole = Vec::new();
+ let msg = dict(json!({"__selector": "_rpc_reportSetup:", "__argument": {}}));
+ plist::to_writer_binary(&mut whole, &Value::Dictionary(msg.clone())).unwrap();
+ let (a, b) = whole.split_at(whole.len() / 2);
+ let wrap = |k: &str, d: &[u8]| {
+ let mut arg = Dictionary::new();
+ arg.insert(k.into(), Value::Data(d.to_vec()));
+ let mut m = Dictionary::new();
+ m.insert("__argument".into(), Value::Dictionary(arg));
+ m
+ };
+ let mut partial = Vec::new();
+ assert!(unchunk_into(&mut partial, wrap("WIRPartialMessageKey", a)).unwrap().is_none());
+ assert_eq!(unchunk_into(&mut partial, wrap("WIRFinalMessageKey", b)).unwrap(), Some(msg));
+ assert!(partial.is_empty());
+ }
+}
diff --git a/docs/architecture.md b/docs/architecture.md
index 3e2726e..f79ea5e 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -101,8 +101,9 @@
| crate | 职责 | 主要依赖 |
|---|---|---|
-| `ictl-device` | `Device` 句柄:usbmux 发现与监听、lockdown、配对状态、开发者模式状态、隧道(`Tunnel`,持有 HID 会话和显示媒体流)、开发者镜像(含下载缓存)、截图、App 列表/启动/结束、安装 IPA;所有设备调用都有时限 | `idevice`(锁上游 git 提交) |
+| `ictl-device` | `Device` 句柄:usbmux 发现与监听、lockdown、配对状态、开发者模式状态、隧道(`Tunnel`,持有 HID 会话和显示媒体流)、开发者镜像(含下载缓存)、截图、App 列表/启动/结束、安装 IPA、卸载、崩溃报告、系统日志流(开发者工具)、打开 Web Inspector;所有设备调用都有时限 | `idevice`(锁上游 git 提交) |
| `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-protocol` | 控制接口的 `Request`/`Response` 类型和客户端 `call(socket, req, timeout)` | `serde`、`tokio` |
| `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` |
@@ -110,7 +111,7 @@
| `ictl-mcp` | MCP stdio 服务,17 个 `iphone_*` 工具:toolkit 的 13 个 + `iphone_wait_for`、`iphone_batch`、`iphone_list_devices`、`iphone_select_device`;操作类工具可带 `then` 顺带返回操作后的界面;经控制接口调用守护进程 | `ictl-protocol`、`rmcp`(`server`、`transport-io`) |
| `apps/iphone-control` | CLI 入口:`daemon`、`mcp`、`mcp-config`、`status`、`doctor`、`setup`、`login`、`sign`、`resign`、`passcode`、`unlock-reset`、`devices`、`select`、`wda-bridge`、`viewer`、`notify-test`;隐藏的 `debug <ddi\|hid\|screenshot\|soak\|wda\|e2e>` 真机诊断(原第 0 步 spike,不经守护进程;feature `debug-cmds`,默认不编译) | `clap` |
-依赖方向:`apps` → `ictl-daemon` / `ictl-mcp`;`ictl-daemon` → `ictl-unlock` → `ictl-wda` → `ictl-device`;`ictl-daemon` 还依赖 `ictl-sign` 和 `ictl-protocol`。`ictl-mcp` 只依赖 `ictl-protocol`,不依赖守护进程和设备层。`apps` 的 `debug`(feature `debug-cmds`)直接调用 `ictl-device`、`ictl-wda`。
+依赖方向:`apps` → `ictl-daemon` / `ictl-mcp`;`ictl-daemon` → `ictl-unlock` → `ictl-wda` → `ictl-device`;`ictl-daemon` 还依赖 `ictl-sign` 和 `ictl-protocol`。`ictl-device` 依赖 `ictl-webinspector`。`ictl-mcp` 只依赖 `ictl-protocol`,不依赖守护进程和设备层。`apps` 的 `debug`(feature `debug-cmds`)直接调用 `ictl-device`、`ictl-wda`。
## 5. 截图与坐标
diff --git a/docs/tools.md b/docs/tools.md
index 3df8d7e..8b2d27e 100644
--- a/docs/tools.md
+++ b/docs/tools.md
@@ -1,6 +1,6 @@
# MCP tools
-The MCP server (`iphone-control mcp`) exposes 17 tools (21 with the [developer tools](#developer-tools-opt-in)). The tool descriptions the agent sees, and every result text, are in Simplified Chinese by default, or in English with `IPHONE_CONTROL_LANG=en` (see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration)); this page is the English reference. The definitions live in [`crates/ictl-mcp/src/lib.rs`](../crates/ictl-mcp/src/lib.rs).
+The MCP server (`iphone-control mcp`) exposes 17 tools (23 with the [developer tools](#developer-tools-opt-in)). The tool descriptions the agent sees, and every result text, are in Simplified Chinese by default, or in English with `IPHONE_CONTROL_LANG=en` (see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration)); this page is the English reference. The definitions live in [`crates/ictl-mcp/src/lib.rs`](../crates/ictl-mcp/src/lib.rs).
Coordinates are in **points**, the same unit as the pixels of a full-screen `iphone_screenshot` (for example 430×932 on an iPhone 15 Pro Max), so an agent can read a position off a screenshot and tap it directly. Coordinates follow the current screen orientation: after a rotation the same spot has different coordinates, so take a new screenshot. Screen sizes differ per device (an iPad mini 5 is 768×1024 in portrait); don't assume 430×932.
@@ -39,7 +39,7 @@ Only one device is controlled at a time; every other tool acts on it. With one d
## Developer tools (opt-in)
-With `IPHONE_CONTROL_DEV_TOOLS=1` in the MCP server's environment, four more tools are listed. They are off by default, so agents that don't need them don't pay for their descriptions.
+With `IPHONE_CONTROL_DEV_TOOLS=1` in the MCP server's environment, six more tools are listed. They are off by default, so agents that don't need them don't pay for their descriptions.
| Tool | Parameters | Notes |
|---|---|---|
@@ -47,6 +47,8 @@ With `IPHONE_CONTROL_DEV_TOOLS=1` in the MCP server's environment, four more too
| `iphone_crash_reports` | `filter`, `name` | Lists crash reports, newest first (at most 50); with `name`, returns that report (`.ips`, cut at 40,000 characters). Read-only |
| `iphone_install_app` | `path` | Installs a signed `.ipa` or `.app` from a path on the machine that runs the daemon (inside the container for a container deployment). Destructive: it replaces an installed copy of the same app |
| `iphone_uninstall_app` | `app` | Removes an app and its data. Refuses to remove the WebDriverAgent runner. Destructive |
+| `iphone_web_targets` | — | Inspectable web pages and WebViews over the Web Inspector service: Safari tabs and inspectable WebViews in apps (debug builds of Capacitor, Cordova, React Native…). One line each: id, type, app, title, URL. Only apps in the foreground answer; needs Settings → Safari → Advanced → Web Inspector. Read-only |
+| `iphone_web_eval` | `expression`, `target`, `timeout` (10 s, at most 60) | Runs JavaScript in a page and returns the result as JSON; a promise is awaited, a DOM node comes back as its description (`"<body>"`). `target` is an id from `iphone_web_targets`, or text in the URL or title; it can be left out when there is one page. Not read-only: a script can change the page |
## Auto-unlock and "read-only" tools
diff --git a/website/en/guide/configuration.md b/website/en/guide/configuration.md
index 61f1e74..6f27301 100644
--- a/website/en/guide/configuration.md
+++ b/website/en/guide/configuration.md
@@ -13,7 +13,7 @@ Everything is configured with environment variables, and all of them are optiona
|---|---|---|
| `HTTP_PROXY` / `HTTPS_PROXY` | direct | Proxy for Apple, anisette, Developer Disk Image and notification traffic |
| `IPHONE_CONTROL_LANG` | `zh` | Language: `zh` or `en`. Applies to tool descriptions and results, CLI output, logs and notifications. The MCP server and the CLI each send their own setting and the daemon answers in it; logs and notifications follow the daemon's own setting. So for a source install also set it in the MCP client config (`iphone-control mcp-config` includes it) |
-| `IPHONE_CONTROL_DEV_TOOLS` | off | `1` adds the [developer tools](./tools#developer-tools-opt-in) to the MCP server: logs, crash reports, installing and removing apps. For a source install set it in the MCP client config (`iphone-control mcp-config` includes it when set) |
+| `IPHONE_CONTROL_DEV_TOOLS` | off | `1` adds the [developer tools](./tools#developer-tools-opt-in) to the MCP server: logs, crash reports, installing and removing apps, and Web Inspector (JavaScript in web pages and WebViews). For a source install set it in the MCP client config (`iphone-control mcp-config` includes it when set) |
| `IPHONE_UDID` | automatic | Pin the device to control. Unset: the controlled device is kept until it disconnects, and you can switch with the `select` command or the `iphone_select_device` tool. When set, switching is refused |
| `RESIGN_MIN_DAYS` | `2` | Re-sign when fewer days than this remain |
| `RESIGN_CHECK_HOURS` | `6` | How often to check; it is also checked within a minute after the phone reconnects or you switch devices |
diff --git a/website/en/guide/tools.md b/website/en/guide/tools.md
index 381a15c..075c0d9 100644
--- a/website/en/guide/tools.md
+++ b/website/en/guide/tools.md
@@ -41,7 +41,7 @@ Details: [Several devices](./multi-device).
## Developer tools (opt-in)
-Set `IPHONE_CONTROL_DEV_TOOLS=1` for the MCP server to get four more tools. They are off by default, so agents that don't need them don't pay for their descriptions.
+Set `IPHONE_CONTROL_DEV_TOOLS=1` for the MCP server to get six more tools. They are off by default, so agents that don't need them don't pay for their descriptions.
| Tool | What it does |
|---|---|
@@ -49,6 +49,8 @@ Set `IPHONE_CONTROL_DEV_TOOLS=1` for the MCP server to get four more tools. They
| `iphone_crash_reports` | List crash reports, or read one |
| `iphone_install_app` | Install a signed `.ipa` or `.app` (a path on the machine that runs the daemon) |
| `iphone_uninstall_app` | Remove an app and its data; never the WebDriverAgent runner |
+| `iphone_web_targets` | List inspectable web pages and WebViews (Safari tabs, debug builds of hybrid apps); the app must be in the foreground |
+| `iphone_web_eval` | Run JavaScript in a page and get the result as JSON: faster, cheaper and more accurate than screenshots for web content |
## See the screen after an action: `then`
diff --git a/website/guide/configuration.md b/website/guide/configuration.md
index 0c92121..f6f3b7a 100644
--- a/website/guide/configuration.md
+++ b/website/guide/configuration.md
@@ -13,7 +13,7 @@
|---|---|---|
| `HTTP_PROXY` / `HTTPS_PROXY` | 直连 | 访问苹果、anisette、开发者镜像、推送通知用的代理 |
| `IPHONE_CONTROL_LANG` | `zh` | 界面语言:`zh` 或 `en`。工具说明和结果、命令行输出、日志、通知都按它。MCP 和命令行各自按自己的设置请求,守护进程按请求的语言回答;日志和通知按守护进程自己的设置。从源码运行时要在 MCP 配置里也设上(`iphone-control mcp-config` 会带上) |
-| `IPHONE_CONTROL_DEV_TOOLS` | 关 | 设为 `1` 时 MCP 服务多出[开发者工具](./tools):日志、崩溃报告、安装和卸载 App。从源码运行时要写进 MCP 客户端的配置(设了时 `iphone-control mcp-config` 会带上) |
+| `IPHONE_CONTROL_DEV_TOOLS` | 关 | 设为 `1` 时 MCP 服务多出[开发者工具](./tools):日志、崩溃报告、安装和卸载 App、Web Inspector(在网页和 WebView 里执行 JavaScript)。从源码运行时要写进 MCP 客户端的配置(设了时 `iphone-control mcp-config` 会带上) |
| `IPHONE_UDID` | 自动选 | 固定控制哪台设备。不设时自动选:正在控制的那台一直用到它断开;运行中可以用 `select` 命令或 `iphone_select_device` 工具切换。设了就不能切换 |
| `RESIGN_MIN_DAYS` | `2` | 描述文件剩余不到几天时重签 |
| `RESIGN_CHECK_HOURS` | `6` | 每隔几小时检查一次;手机重新连上或切换设备后 1 分钟内也查一次 |
diff --git a/website/guide/tools.md b/website/guide/tools.md
index b0091a4..39e3d74 100644
--- a/website/guide/tools.md
+++ b/website/guide/tools.md
@@ -41,7 +41,7 @@ MCP 服务提供 17 个工具。坐标单位是**点**,和整屏截图的像
## 开发者工具(显式开启)
-给 MCP 服务设 `IPHONE_CONTROL_DEV_TOOLS=1` 后多出四个工具。默认关闭,用不到的 agent 不必多读这些工具说明。
+给 MCP 服务设 `IPHONE_CONTROL_DEV_TOOLS=1` 后多出六个工具。默认关闭,用不到的 agent 不必多读这些工具说明。
| 工具 | 作用 |
|---|---|
@@ -49,6 +49,8 @@ MCP 服务提供 17 个工具。坐标单位是**点**,和整屏截图的像
| `iphone_crash_reports` | 列出崩溃报告,或读取其中一份 |
| `iphone_install_app` | 安装签好名的 `.ipa` 或 `.app`(路径在运行守护进程的机器上) |
| `iphone_uninstall_app` | 卸载 App 及其数据;不会卸载 WebDriverAgent |
+| `iphone_web_targets` | 列出可检查的网页和 WebView(Safari 标签页、混合 App 的调试构建);页面所在的 App 要在前台 |
+| `iphone_web_eval` | 在页面里执行 JavaScript,以 JSON 返回结果:读网页内容比截图快、省 token、也更准 |
## 操作后顺带看界面:`then`