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

fix(viewer): Home from the control page doesn't look for an alert first (#102)

Qinghe Li05c1e5378972
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0fb87b0..cbc62d8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ All notable changes to this project are documented here. The format is based on
### Fixed
+- Home on the control page is pressed at once: about 0.5 s instead of 1 s on an iPhone's home screen. The daemon first looked for a system alert that would stop Home working (0.8 s on the home screen), which the person at the page sees anyway; the page's requests now say someone is watching (`watched`), and for them the daemon looks only when the press didn't get to the home screen. Agents (MCP, CLI) are checked first as before.
- Taps and Home presses on the control page no longer wait behind its background checks. While it shows the phone's own picture the page asks every few seconds whether a system alert is up, which on the home screen keeps WDA busy for about 0.8 s, and its status check takes the phone too: an action that came meanwhile waited for them. These checks now give way: they don't start within 4 s (the status: 1 s) of an action, nor while one waits, and one that runs is dropped when an action comes. With the page checking, a finger's press went from 775 ms to 25 ms at the 90th percentile, a Home press from 1.8 s to 1.3 s.
- The phone's own picture (HEVC) on the control page no longer stops for half a second to a second now and then over Wi-Fi. A report from the page that came a few hundred milliseconds late made the picture skip to the next keyframe; frames now wait up to 400 ms for such a page, the allowance follows how much the link's round trip varies, and the page has two reports on the way at most instead of one. Under emulated Wi-Fi delays the longest stop went from 1.1 s to 0.1 s.
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 850757b..fc6ce7e 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -8,6 +8,7 @@
### 修复
+- 控制台上按 Home 立即按下:iPhone 主屏幕上从约 1 秒降到约 0.5 秒。守护进程原来先查一遍有没有挡住 Home 的系统弹窗(主屏幕上要 0.8 秒),而页面前的人本来就看得见;现在页面的请求会注明有人在看(`watched`),守护进程只在按下后没回到主屏幕时才去查。Agent(MCP、命令行)仍和原来一样先查。
- 控制台上的点按和按 Home 不再排在页面的后台查询后面。显示手机自己的画面时,页面每隔几秒查一次有没有系统弹窗,在主屏幕上这一下要占用 WDA 约 0.8 秒,状态查询也要占用手机,期间来的操作只能等着。现在这些查询会让路:操作后 4 秒内(状态查询 1 秒内)不查,有操作在排队时不开始,查到一半来了操作就放弃。页面在查询时,手指按下的 P90 从 775 毫秒降到 25 毫秒,按 Home 从 1.8 秒降到 1.3 秒。
- 控制台上手机自己的画面(HEVC)在 Wi-Fi 下不再时不时卡住半秒到一秒。页面的一次回报晚到几百毫秒,画面就会丢到下一个关键帧;现在这种情况下帧会先等最多 400 毫秒,允许的延迟也跟着链路往返的波动走,页面同时最多有两个回报在路上(原来一个)。模拟 Wi-Fi 延迟时,最长卡顿从 1.1 秒降到 0.1 秒。
diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs
index 7d3fb6d..bb7ef3d 100644
--- a/apps/iphone-control/src/viewer.rs
+++ b/apps/iphone-control/src/viewer.rs
@@ -1258,8 +1258,9 @@ fn action(name: &str, b: &Value) -> Option<Request> {
const SHORT: Duration = Duration::from_secs(120);
const SIGN: Duration = Duration::from_secs(16 * 60);
+/// An action from the page: the person sees the screen ([`protocol::WATCHED`])
async fn run_action(socket: &Path, req: &Request, udid: Option<&str>, timeout: Duration) -> Value {
- action_result(req, protocol::call_expecting(socket, req, Some(timeout), udid).await)
+ action_result(req, protocol::call_watched(socket, req, Some(timeout), udid).await)
}
fn action_result(req: &Request, result: Result<Response, impl std::fmt::Display>) -> Value {
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index 87ae22a..1f15020 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -238,6 +238,8 @@ pub struct CallCtx {
pub peer: Option<u32>,
/// A poll that gives way to actions ([`ictl_protocol::BACKGROUND`])
pub background: bool,
+ /// Someone watches the screen ([`ictl_protocol::WATCHED`])
+ pub watched: bool,
}
/// Logical points measured on this connection. A different id invalidates queued coordinates.
@@ -990,14 +992,14 @@ impl Daemon {
gave_way()
} else {
tokio::select! {
- r = Box::pin(self.dispatch(g, req, view)) => r,
+ r = Box::pin(self.dispatch(g, req, view, ctx.watched)) => r,
() = action => gave_way(),
}
}
} else {
let acted = req.is_device_action();
// boxed, like the request in `handle`: two of its large state machine on the stack overflowed a test thread
- let r = Box::pin(self.dispatch(g, req, view)).await;
+ let r = Box::pin(self.dispatch(g, req, view, ctx.watched)).await;
if acted {
*self.last_action.lock().unwrap_or_else(|p| p.into_inner()) = Some(Instant::now());
}
@@ -1010,7 +1012,7 @@ impl Daemon {
response
}
- async fn dispatch(&self, g: &mut Inner, req: Request, view: Option<&str>) -> Response {
+ async fn dispatch(&self, g: &mut Inner, req: Request, view: Option<&str>, watched: bool) -> 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)
@@ -1045,7 +1047,7 @@ impl Daemon {
Request::LongPress { x, y, seconds } => self.long_press(g, x, y, seconds, view).await,
Request::Swipe { from, to, seconds } => self.swipe(g, from, to, seconds, view).await,
Request::TypeText { text, submit } => self.type_text(g, &text, submit).await,
- Request::PressButton { button } => self.press_button(g, &button).await,
+ Request::PressButton { button } => self.press_button(g, &button, watched).await,
Request::Touch { phase, x, y } => {
return self
.touch(g, phase, x, y, view)
diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs
index 55519fc..ac798de 100644
--- a/crates/ictl-daemon/src/lib.rs
+++ b/crates/ictl-daemon/src/lib.rs
@@ -214,7 +214,7 @@ async fn serve_conn(daemon: Arc<Daemon>, stream: tokio::net::UnixStream) {
/// No language (an older client) means Chinese, which is what those clients expect and parse
fn parse_request(line: &[u8]) -> serde_json::Result<(protocol::Request, bool, core::CallCtx, ictl_l10n::Lang)> {
let mut v: serde_json::Value = serde_json::from_slice(line)?;
- let (cancel, udid, view, lang, task, task_step, background) = match v.as_object_mut() {
+ let (cancel, udid, view, lang, task, task_step, background, watched) = match v.as_object_mut() {
Some(o) => (
o.remove(protocol::CANCEL_ON_CLOSE).is_some_and(|c| c == true),
o.remove(protocol::EXPECT_UDID).and_then(|u| u.as_str().map(str::to_owned)),
@@ -223,13 +223,23 @@ fn parse_request(line: &[u8]) -> serde_json::Result<(protocol::Request, bool, co
o.remove(protocol::TASK).and_then(|t| t.as_str().map(str::to_owned)),
o.remove(protocol::TASK_STEP).and_then(|s| s.as_u64()),
o.remove(protocol::BACKGROUND).is_some_and(|b| b == true),
+ o.remove(protocol::WATCHED).is_some_and(|b| b == true),
),
- None => (false, None, None, None, None, None, false),
+ None => (false, None, None, None, None, None, false, false),
};
Ok((
serde_json::from_value(v)?,
cancel,
- core::CallCtx { gone: None, expect_udid: udid, expect_view: view, task, task_step, peer: None, background },
+ core::CallCtx {
+ gone: None,
+ expect_udid: udid,
+ expect_view: view,
+ task,
+ task_step,
+ peer: None,
+ background,
+ watched,
+ },
lang.unwrap_or(ictl_l10n::Lang::Zh),
))
}
@@ -410,6 +420,10 @@ mod tests {
assert!(!cancel && expect.expect_udid.is_none() && expect.task.is_none() && expect.task_step.is_none());
let (_, _, ctx, _) = parse_request(br#"{"op":"tap","x":1.0,"y":2.0,"task":"T","task_step":3}"#).unwrap();
assert_eq!((ctx.task.as_deref(), ctx.task_step), (Some("T"), Some(3)));
+ assert!(!ctx.watched && !ctx.background);
+ let (req, _, ctx, _) = parse_request(br#"{"op":"press_button","button":"home","watched":true}"#).unwrap();
+ assert_eq!(req, protocol::Request::PressButton { button: "home".into() });
+ assert!(ctx.watched && !ctx.background);
assert_eq!(lang, Lang::Zh);
let (_, _, _, lang) = parse_request(br#"{"op":"status","lang":"klingon"}"#).unwrap();
assert_eq!(lang, Lang::Zh);
diff --git a/crates/ictl-daemon/src/tools/keys.rs b/crates/ictl-daemon/src/tools/keys.rs
index ecdec33..1493ba9 100644
--- a/crates/ictl-daemon/src/tools/keys.rs
+++ b/crates/ictl-daemon/src/tools/keys.rs
@@ -3,7 +3,14 @@
use super::*;
impl Daemon {
- pub(crate) async fn press_button(&self, g: &mut Inner, button: &str) -> crate::error::Result<String> {
+ /// `watched`: someone watches the screen ([`ictl_protocol::WATCHED`]), so Home is pressed without first looking for
+ /// an alert in the way; only when it didn't get to the home screen
+ pub(crate) async fn press_button(
+ &self,
+ g: &mut Inner,
+ button: &str,
+ watched: bool,
+ ) -> crate::error::Result<String> {
let hid_button = Button::parse(button).ok_or(ictl_l10n::tr!(
"button 只能是 home / volume_up / volume_down / lock",
"button must be home / volume_up / volume_down / lock"
@@ -20,6 +27,7 @@ impl Daemon {
// Home 在系统弹窗(定位、通知权限等)挡着时不生效,WDA 却照样返回成功。弹窗属于 SpringBoard,
// 看前台 App 发现不了,要单独查;按之前查(App 静止时约 0.4 秒,按下后动画中查要好几秒)
if hid_button == Button::Home
+ && !watched
&& let Ok(Some(text)) = w.alert_text().await
{
return Ok(ictl_l10n::trf!(
@@ -37,6 +45,19 @@ impl Daemon {
} else {
w.press_button(wda_name).await.map(|()| ictl_l10n::trf!("已按 {button}", "Pressed {button}"))
};
+ // not looked for before: an alert is the likely reason Home didn't get to the home screen
+ if watched
+ && hid_button == Button::Home
+ && home_worked.is_none()
+ && r.is_ok()
+ && let Ok(Some(text)) = w.alert_text().await
+ {
+ return Ok(ictl_l10n::trf!(
+ "{},按 Home 没有生效,先点弹窗上的按钮",
+ "{}, pressing Home had no effect; first tap a button on the alert",
+ blocking(&text)
+ ));
+ }
if let Some(via_xctest) = home_worked {
g.dev.home_via_xctest = via_xctest;
}
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index 1dda6f4..49bcec8 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -657,6 +657,10 @@ pub const LANG: &str = "lang";
/// when an action waits for the phone, and drops it when one comes while it runs, answering [`Data::Busy`]: such a
/// check took the phone for up to a second (WDA's alert lookup on the home screen) while a tap waited behind it
pub const BACKGROUND: &str = "background";
+/// Request key: someone watches the screen (the control page), so the daemon doesn't look before acting for what they
+/// see anyway. Pressing Home skips the alert lookup that comes first (0.8 s of a 1.3 s press on the home screen) and
+/// looks only when the press didn't get to the home screen
+pub const WATCHED: &str = "watched";
/// 发一个请求、读一个响应(客户端用)。`timeout` 为 None 时一直等(例如 `sign` 要等签名装完)。
/// 返回之前被丢掉(超时、调用方取消)时连接随之关闭,守护进程会放弃还在排队的这个请求
@@ -674,7 +678,7 @@ pub async fn call_background(
req: &Request,
timeout: Option<std::time::Duration>,
) -> std::io::Result<Response> {
- exchange_on(socket, req, timeout, None, None, true).await
+ exchange_on(socket, req, timeout, None, None, Some(BACKGROUND)).await
}
/// 同 [`call`];`expect_udid` 见 [`EXPECT_UDID`]
@@ -684,7 +688,17 @@ pub async fn call_expecting(
timeout: Option<std::time::Duration>,
expect_udid: Option<&str>,
) -> std::io::Result<Response> {
- exchange_on(socket, req, timeout, expect_udid, None, false).await
+ exchange_on(socket, req, timeout, expect_udid, None, None).await
+}
+
+/// [`call_expecting`] for someone watching the screen ([`WATCHED`])
+pub async fn call_watched(
+ socket: &std::path::Path,
+ req: &Request,
+ timeout: Option<std::time::Duration>,
+ expect_udid: Option<&str>,
+) -> std::io::Result<Response> {
+ exchange_on(socket, req, timeout, expect_udid, None, Some(WATCHED)).await
}
/// Send a coordinate action only if this device and its measured geometry still match.
@@ -695,7 +709,7 @@ pub async fn call_in_view(
udid: &str,
view: &str,
) -> std::io::Result<Response> {
- exchange_on(socket, req, timeout, Some(udid), Some(view), false).await
+ exchange_on(socket, req, timeout, Some(udid), Some(view), None).await
}
async fn exchange_on(
@@ -704,7 +718,7 @@ async fn exchange_on(
timeout: Option<std::time::Duration>,
expect_udid: Option<&str>,
expect_view: Option<&str>,
- background: bool,
+ flag: Option<&str>,
) -> std::io::Result<Response> {
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
let exchange = async {
@@ -720,8 +734,9 @@ async fn exchange_on(
if let Some(u) = expect_udid {
o.insert(EXPECT_UDID.into(), u.into());
}
- if background {
- o.insert(BACKGROUND.into(), true.into());
+ // [`BACKGROUND`] or [`WATCHED`]
+ if let Some(f) = flag {
+ o.insert(f.into(), true.into());
}
add_task_keys(o);
}