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): background checks give way to the user's actions (#101)

Qinghe Lida86002a7c67
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8ed521c..0fb87b0 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
+- 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.
## [0.2.5] - 2026-11-14
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 111d8c5..850757b 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -8,6 +8,7 @@
### 修复
+- 控制台上的点按和按 Home 不再排在页面的后台查询后面。显示手机自己的画面时,页面每隔几秒查一次有没有系统弹窗,在主屏幕上这一下要占用 WDA 约 0.8 秒,状态查询也要占用手机,期间来的操作只能等着。现在这些查询会让路:操作后 4 秒内(状态查询 1 秒内)不查,有操作在排队时不开始,查到一半来了操作就放弃。页面在查询时,手指按下的 P90 从 775 毫秒降到 25 毫秒,按 Home 从 1.8 秒降到 1.3 秒。
- 控制台上手机自己的画面(HEVC)在 Wi-Fi 下不再时不时卡住半秒到一秒。页面的一次回报晚到几百毫秒,画面就会丢到下一个关键帧;现在这种情况下帧会先等最多 400 毫秒,允许的延迟也跟着链路往返的波动走,页面同时最多有两个回报在路上(原来一个)。模拟 Wi-Fi 延迟时,最长卡顿从 1.1 秒降到 0.1 秒。
## [0.2.5] - 2026-11-14
diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.html
index 155c6f4..3c9b3c4 100644
--- a/apps/iphone-control/src/viewer.html
+++ b/apps/iphone-control/src/viewer.html
@@ -2455,7 +2455,9 @@ async function loadDeviceState() {
// Video can reconnect while the same device is still waiting for trust or signing.
if (udid !== S.udid || sequence !== statusSequence) return;
S.daemon = d.status === 'fulfilled' ? d.value : null;
- S.dstatus = s.status === 'fulfilled' ? s.value : null;
+ // busy: the phone was busy with one of the user's actions, so the check gave way; what was shown stays, asked again soon
+ if (s.status === 'fulfilled' && s.value.busy) refreshStatusSoon();
+ else S.dstatus = s.status === 'fulfilled' ? s.value : null;
S.statusErr = d.status === 'rejected' ? String(d.reason.message) : s.status === 'rejected' ? String(s.reason.message) : '';
if (l.status === 'fulfilled') { S.devices = l.value.devices || []; S.devicesFixed = !!l.value.fixed; S.devicesErr = ''; } else { S.devices = []; S.devicesErr = String(l.reason.message); }
}
@@ -3162,7 +3164,8 @@ async function pollAlert() {
return;
}
SA.busy = true;
- try { S.sysAlert = (await api('/api/alert')).alert || null; } catch { /* 下一轮再问 */ } finally { SA.busy = false; }
+ // busy:手机正在执行操作,这次没查(让操作先走),保留上次的结果
+ try { const v = await api('/api/alert'); if (!v.busy) S.sysAlert = v.alert || null; } catch { /* 下一轮再问 */ } finally { SA.busy = false; }
renderSysAlert();
}
function renderSysAlert() {
diff --git a/apps/iphone-control/src/viewer/api.rs b/apps/iphone-control/src/viewer/api.rs
index ea3d4bf..130a6af 100644
--- a/apps/iphone-control/src/viewer/api.rs
+++ b/apps/iphone-control/src/viewer/api.rs
@@ -6,7 +6,17 @@ 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 {
+ answer_data(protocol::call(socket, &req, Some(Duration::from_secs(60))).await)
+}
+
+/// [`data_of`] for a check the page repeats anyway: [`protocol::Data::Busy`] when an action wanted the phone
+/// ([`protocol::BACKGROUND`])
+pub(super) async fn polled(socket: &Path, req: Request) -> Result<Option<protocol::Data>, String> {
+ answer_data(protocol::call_background(socket, &req, Some(Duration::from_secs(60))).await)
+}
+
+fn answer_data(r: std::io::Result<Response>) -> Result<Option<protocol::Data>, String> {
+ match r {
Ok(Response::Text { data, .. }) => Ok(data),
Ok(Response::Error { message, .. }) => Err(message),
Ok(Response::Image { caption, .. }) => Err(caption),
@@ -96,8 +106,10 @@ pub(super) async fn devices(ctx: &Ctx) -> Result<Value, String> {
/// `{ 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? {
+ let status = match polled(&ctx.socket, Request::Status).await? {
Some(protocol::Data::Status(s)) => s,
+ // the phone was busy with an action: the page keeps what it showed and asks again
+ Some(protocol::Data::Busy) => return Ok(json!({"busy": true})),
_ => protocol::StatusData::default(),
};
// the HID fallback needs iOS 27; an older device without WDA can't be operated at all
@@ -175,8 +187,10 @@ pub(super) async fn elements(ctx: &Ctx, filter: &str, keep_locked: bool) -> Resu
/// `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 text = match polled(&ctx.socket, Request::AlertCheck).await? {
+ Some(protocol::Data::Alert { text: Some(text) }) => text,
+ Some(protocol::Data::Busy) => return Ok(json!({"busy": true})),
+ _ => 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
diff --git a/crates/ictl-daemon/core b/crates/ictl-daemon/core
new file mode 100644
index 0000000..1fad188
Binary files /dev/null and b/crates/ictl-daemon/core differ
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index 62b7039..87ae22a 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -236,6 +236,8 @@ pub struct CallCtx {
pub task_step: Option<u64>,
/// The process that sent it (the socket's peer), when the system says
pub peer: Option<u32>,
+ /// A poll that gives way to actions ([`ictl_protocol::BACKGROUND`])
+ pub background: bool,
}
/// Logical points measured on this connection. A different id invalidates queued coordinates.
@@ -383,6 +385,13 @@ pub struct Daemon {
/// A supervision round is due now, not at the next [`TICK`]: starting WDA finished, so its outcome is taken
/// (ready seconds sooner after a restart or a hang)
pub(crate) wake: Arc<tokio::sync::Notify>,
+ /// Actions waiting for the device lock: a background check doesn't start while there are any
+ /// ([`ictl_protocol::BACKGROUND`])
+ waiting: std::sync::atomic::AtomicUsize,
+ /// An action started waiting: a background check that runs gives the phone up
+ give_way: tokio::sync::Notify,
+ /// When the last action was done: background checks wait for a quiet moment ([`quiet_before`])
+ last_action: std::sync::Mutex<Option<Instant>>,
}
/// 停掉 HID 会话(屏幕媒体流),隧道保留。媒体流不停的话手机一直以为「配对的电脑」在看屏幕:
@@ -509,6 +518,9 @@ impl Daemon {
heartbeat: Heartbeat::new(),
tasks,
wake: Arc::default(),
+ waiting: std::sync::atomic::AtomicUsize::new(0),
+ give_way: tokio::sync::Notify::new(),
+ last_action: std::sync::Mutex::new(None),
})
}
@@ -932,10 +944,29 @@ impl Daemon {
Lane::Device => {}
}
- // still let through now that it holds the lock: the task may have been paused or taken over meanwhile
- let mut g = match self.lock_admitted(&self.inner, &req, admission, &mut queued_at, &mut ctx.gone).await {
- Ok(g) => g,
- Err(r) => return r,
+ // a check the page repeats anyway: only while nothing else wants the phone ([`ictl_protocol::BACKGROUND`])
+ let background = ctx.background && matches!(req, Request::Status | Request::AlertCheck);
+ // someone is acting on the phone: a slow check now would sit in WDA's queue before their next action (giving
+ // up waiting for its answer doesn't stop WDA working on it)
+ let acting = || {
+ let last = *self.last_action.lock().unwrap_or_else(|p| p.into_inner());
+ last.is_some_and(|t| t.elapsed() < quiet_before(&req))
+ };
+ let mut g = if background {
+ if acting() {
+ return gave_way();
+ }
+ match self.inner.try_lock() {
+ Ok(g) if self.waiting.load(std::sync::atomic::Ordering::SeqCst) == 0 => g,
+ _ => return gave_way(),
+ }
+ } else {
+ let _waiting = Waiting::new(self);
+ // still let through now that it holds the lock: the task may have been paused or taken over meanwhile
+ match self.lock_admitted(&self.inner, &req, admission, &mut queued_at, &mut ctx.gone).await {
+ Ok(g) => g,
+ Err(r) => return r,
+ }
};
let g = &mut *g;
if let Err(r) = admit(&req, queued_at, &ctx, g.device.as_ref().map(|d| d.udid.as_str())) {
@@ -950,7 +981,28 @@ impl Daemon {
if g.wda.as_ref().is_some_and(|w| w.stalled()) {
self.restart_stalled_wda(g).await;
}
- let response = self.dispatch(g, req, view).await;
+ let response = if background {
+ // an action that comes meanwhile gets the phone at once: the check is read-only, dropping it is safe
+ let action = self.give_way.notified();
+ tokio::pin!(action);
+ action.as_mut().enable();
+ if self.waiting.load(std::sync::atomic::Ordering::SeqCst) > 0 {
+ gave_way()
+ } else {
+ tokio::select! {
+ r = Box::pin(self.dispatch(g, req, view)) => 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;
+ if acted {
+ *self.last_action.lock().unwrap_or_else(|p| p.into_inner()) = Some(Instant::now());
+ }
+ r
+ };
if invalidates {
g.elements_cache = None;
}
@@ -1151,6 +1203,45 @@ async fn acquire<'a, T>(
}
}
+/// How long after an action a background check waits. The alert check takes WDA about 0.8 s on the home screen
+/// (it snapshots SpringBoard; not waiting for idle doesn't help) and WDA does one thing at a time, so a tap or a Home
+/// press right after it waited that long; the status check is about 0.2 s
+fn quiet_before(req: &Request) -> Duration {
+ match req {
+ Request::AlertCheck => Duration::from_secs(4),
+ _ => Duration::from_secs(1),
+ }
+}
+
+/// A background check that didn't run, or stopped: an action wanted the phone ([`ictl_protocol::Data::Busy`])
+fn gave_way() -> Response {
+ Response::text_data(
+ ictl_l10n::tr!(
+ "手机正在执行操作,这次没查,稍后再查",
+ "The phone is busy with an action; not checked this time"
+ ),
+ crate::protocol::Outcome::default(),
+ Some(crate::protocol::Data::Busy),
+ )
+}
+
+/// An action waiting for the device lock, counted in [`Daemon::waiting`] until it has it
+struct Waiting<'a>(&'a Daemon);
+
+impl<'a> Waiting<'a> {
+ fn new(d: &'a Daemon) -> Self {
+ d.waiting.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ d.give_way.notify_waiters();
+ Self(d)
+ }
+}
+
+impl Drop for Waiting<'_> {
+ fn drop(&mut self) {
+ self.0.waiting.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
+ }
+}
+
/// Checks done once a request got its lock: the caller's expected device ([`CallCtx::expect_udid`]) and, for actions,
/// how long it queued ([`STALE`])
fn admit(req: &Request, queued_at: Instant, ctx: &CallCtx, controlled: Option<&str>) -> Result<(), Response> {
@@ -1260,6 +1351,44 @@ pub(crate) mod tests {
(Daemon::new(Config::from_env(&dir)), dir)
}
+ /// A background check (the page's status and alert polls) gives way: it doesn't wait for the device lock, nor
+ /// start while an action waits for it; without the flag the same request waits as before
+ #[tokio::test]
+ async fn a_background_check_gives_way_to_actions() {
+ let (d, dir) = test_daemon("background");
+ let busy = |r: &Response| matches!(r, Response::Text { data: Some(crate::protocol::Data::Busy), .. });
+ let bg = || CallCtx { background: true, ..Default::default() };
+ // the lock taken (an action runs): at once, busy
+ let held = d.inner.lock().await;
+ let t = Instant::now();
+ let r = d.handle(Request::AlertCheck, Instant::now(), bg()).await;
+ assert!(busy(&r) && t.elapsed() < Duration::from_millis(100), "{r:?}");
+ let plain = d.handle(Request::Status, Instant::now(), CallCtx::default());
+ tokio::pin!(plain);
+ assert!(
+ tokio::time::timeout(Duration::from_millis(50), &mut plain).await.is_err(),
+ "a check without the flag waits for the lock"
+ );
+ drop(held);
+ assert!(!busy(&plain.await));
+ // an action waiting for the lock: not started
+ let waiting = Waiting::new(&d);
+ assert!(busy(&d.handle(Request::Status, Instant::now(), bg()).await));
+ drop(waiting);
+ // nothing else wants the phone: it runs
+ let r = d.handle(Request::Status, Instant::now(), bg()).await;
+ assert!(matches!(r, Response::Text { data: Some(crate::protocol::Data::Status(_)), .. }), "{r:?}");
+ // right after an action: not yet (the alert check waits longer than the status check)
+ *d.last_action.lock().unwrap() = Some(Instant::now() - Duration::from_secs(2));
+ assert!(!busy(&d.handle(Request::Status, Instant::now(), bg()).await), "status: 1 s after");
+ assert!(busy(&d.handle(Request::AlertCheck, Instant::now(), bg()).await), "the alert check: 4 s after");
+ assert!(
+ !busy(&d.handle(Request::AlertCheck, Instant::now(), CallCtx::default()).await),
+ "unless asked outright"
+ );
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
/// 调用方已经断开:还在排队等设备锁的请求不执行
#[tokio::test]
async fn queued_request_is_dropped_when_caller_is_gone() {
diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs
index fb23217..55519fc 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) = match v.as_object_mut() {
+ let (cancel, udid, view, lang, task, task_step, background) = 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)),
@@ -222,13 +222,14 @@ fn parse_request(line: &[u8]) -> serde_json::Result<(protocol::Request, bool, co
o.remove(protocol::LANG).and_then(|l| l.as_str().and_then(ictl_l10n::parse)),
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),
),
- None => (false, None, None, None, None, None),
+ None => (false, None, None, None, None, None, false),
};
Ok((
serde_json::from_value(v)?,
cancel,
- core::CallCtx { gone: None, expect_udid: udid, expect_view: view, task, task_step, peer: None },
+ core::CallCtx { gone: None, expect_udid: udid, expect_view: view, task, task_step, peer: None, background },
lang.unwrap_or(ictl_l10n::Lang::Zh),
))
}
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index 0b80e0b..1dda6f4 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -354,6 +354,8 @@ pub enum Data {
Alert {
text: Option<String>,
},
+ /// Nothing was read: a [`BACKGROUND`] request gave way to an action
+ Busy,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
@@ -651,6 +653,10 @@ fn current_task() -> (Option<String>, Option<u64>) {
/// Request key carrying the client's language (`zh` / `en`). The daemon answers in it; requests without it
/// (older clients) get Chinese, as before. Older daemons ignore the extra key
pub const LANG: &str = "lang";
+/// Request key: a poll the caller repeats anyway (the control page's status and alert checks). The daemon skips it
+/// 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";
/// 发一个请求、读一个响应(客户端用)。`timeout` 为 None 时一直等(例如 `sign` 要等签名装完)。
/// 返回之前被丢掉(超时、调用方取消)时连接随之关闭,守护进程会放弃还在排队的这个请求
@@ -662,6 +668,15 @@ pub async fn call(
call_expecting(socket, req, timeout, None).await
}
+/// A [`BACKGROUND`] request: answered with [`Data::Busy`] instead of keeping an action waiting
+pub async fn call_background(
+ socket: &std::path::Path,
+ req: &Request,
+ timeout: Option<std::time::Duration>,
+) -> std::io::Result<Response> {
+ exchange_on(socket, req, timeout, None, None, true).await
+}
+
/// 同 [`call`];`expect_udid` 见 [`EXPECT_UDID`]
pub async fn call_expecting(
socket: &std::path::Path,
@@ -669,7 +684,7 @@ 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).await
+ exchange_on(socket, req, timeout, expect_udid, None, false).await
}
/// Send a coordinate action only if this device and its measured geometry still match.
@@ -680,7 +695,7 @@ pub async fn call_in_view(
udid: &str,
view: &str,
) -> std::io::Result<Response> {
- exchange_on(socket, req, timeout, Some(udid), Some(view)).await
+ exchange_on(socket, req, timeout, Some(udid), Some(view), false).await
}
async fn exchange_on(
@@ -689,6 +704,7 @@ async fn exchange_on(
timeout: Option<std::time::Duration>,
expect_udid: Option<&str>,
expect_view: Option<&str>,
+ background: bool,
) -> std::io::Result<Response> {
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
let exchange = async {
@@ -704,6 +720,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());
+ }
add_task_keys(o);
}
let mut line = v.to_string();