From 03840cb7cbc5a6c125599228ed82a88ad77136f8 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:26:09 +0800 Subject: [PATCH 1/2] fix(daemon): concurrency and cancellation safety (review P0-B) - ictl-ax: a request dropped halfway (a background check giving way) abandons the accessibility session instead of leaving its stream mid-message; writes time out; a closed connection ends the wait; an unanswered request keeps the session - background checks never restart the phone's accessibility daemon - an action counts as waiting for the phone only while it waits for the lock, not while its task is paused - main loop: an asked-for supervision round that couldn't run is retried 200 ms later; at most 256 clients at once; finished connections are reaped first - scoped tasks: the front app is checked again once the action holds the device lock; WebEval is checked against the app that shows the page - TapElement scroll.max is bounded (1..=15); scroll search and wait_for stop when the task is paused or the caller goes away Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 + CHANGELOG.zh-CN.md | 5 + crates/ictl-ax/src/session.rs | 189 ++++++++++++++++++--- crates/ictl-daemon/src/core.rs | 214 ++++++++++++++++++++---- crates/ictl-daemon/src/lib.rs | 34 ++-- crates/ictl-daemon/src/tasks.rs | 23 ++- crates/ictl-daemon/src/tools/input.rs | 18 +- crates/ictl-daemon/src/tools/native.rs | 9 + crates/ictl-daemon/src/tools/observe.rs | 15 +- crates/ictl-daemon/src/tools/scroll.rs | 2 +- crates/ictl-daemon/src/web.rs | 41 ++++- docs/dev/regression-cases.md | 5 + 12 files changed, 484 insertions(+), 76 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 594609b9..90ec4667 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,11 @@ What changed in each release, one line per change. Versions follow [Semantic Ver ### Fixes +- iOS 27+: an action that comes while the control page checks the phone in the background no longer leaves the accessibility connection half-read, and those checks no longer restart the phone's accessibility daemon; only actions decide that (#197). +- A task paused for a long time no longer keeps the control page's background checks from running (#197). +- Switching back to a phone made ready in the background takes effect at once even when the daemon was busy at that moment; it could wait 10 seconds. The daemon serves at most 256 clients at once; more wait their turn (#197). +- AI tasks limited to some apps: an action is checked again once it has the phone, in case another app came to the front meanwhile, and `iphone_web_eval` is checked against the app that shows the page (#197). +- `iphone_tap_element`'s scroll search and `iphone_wait_for` stop as soon as the task is paused or taken over or the caller goes away, instead of holding the phone until they time out; the daemon also limits a scroll search to 15 swipes (#197). - iOS 17–18: the developer disk image is mounted the way these versions need, so WebDriverAgent starts on them again (#186). - Times in `status`, `doctor` and the event log are shown in local time with the time zone; they were UTC without saying so (#184). - Errors from `iphone-control update`, `service` and the update panel on the control page follow the chosen language; they were always in English (#184). diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 62ab15ae..5ca29410 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -16,6 +16,11 @@ ### 修复 +- iOS 27 起:控制台在后台检查手机时来了操作,检查中途让路后无障碍连接不再停在半条消息上;这类检查也不再重启手机的无障碍服务,要不要重启只由操作决定(#197)。 +- 任务暂停很久时,控制台的后台检查不再一直跑不了(#197)。 +- 切回一台在后台准备好的手机时,即使守护进程当时正忙也马上生效,之前可能要等 10 秒;守护进程同时最多服务 256 个客户端,更多的排队等候(#197)。 +- 限定了 App 范围的 AI 任务:操作拿到手机后再查一次前台 App,以防期间换了别的 App;`iphone_web_eval` 按显示页面的 App 检查(#197)。 +- `iphone_tap_element` 的边滑边找和 `iphone_wait_for` 在任务暂停、被接管或调用方离开时立刻停下,不再占着手机等到超时;守护进程也把边滑边找限制在 15 次以内(#197)。 - iOS 17–18:开发者镜像按这些版本需要的方式挂载,WebDriverAgent 又能在上面启动了(#186)。 - `status`、`doctor` 和事件日志里的时间改为本地时间并标明时区,之前显示的是 UTC 却没有说明(#184)。 - `iphone-control update`、`service` 和控制台更新面板里的报错跟随界面语言,之前总是英文(#184)。 diff --git a/crates/ictl-ax/src/session.rs b/crates/ictl-ax/src/session.rs index e6822703..9caf6357 100644 --- a/crates/ictl-ax/src/session.rs +++ b/crates/ictl-ax/src/session.rs @@ -7,7 +7,7 @@ //! `deviceAPIVersion` before `clientNeedsAccessibility:` keeps it answering without WDA (round 3). use std::collections::{HashMap, HashSet, VecDeque}; -use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -84,6 +84,9 @@ pub struct Session { /// When the phone last said the screen is changing (a notification before the next tree) changes: watch::Receiver>, closed: watch::Receiver, + /// A request stopped halfway (cancelled, or its write failed): what is on the stream is no longer known (half a + /// message written, an answer still to come for nobody), so the session counts as closed and is opened again + abandoned: AtomicBool, requests: tokio::sync::Mutex<()>, next_id: AtomicU32, reader: tokio::task::JoinHandle<()>, @@ -95,6 +98,38 @@ impl Drop for Session { } } +/// One request on the stream: unless [`InFlight::done`] is called, dropping it (the request was cancelled, or failed +/// writing) abandons the session ([`Session::is_closed`]), and the answer channel is let go either way +struct InFlight<'a> { + abandoned: &'a AtomicBool, + waiter: &'a Waiter, + done: bool, +} + +impl InFlight<'_> { + fn done(mut self) { + self.done = true; + } +} + +impl Drop for InFlight<'_> { + fn drop(&mut self) { + if !self.done { + self.abandoned.store(true, Ordering::SeqCst); + } + self.waiter.lock().unwrap_or_else(|p| p.into_inner()).take(); + } +} + +/// Writing one request, at most this long: a stream that takes no more means the phone or the link stopped +const WRITE_TIMEOUT: Duration = Duration::from_secs(5); + +/// A write that didn't finish in time: the link, not the service (an unanswered service is [`AxError::Timeout`], +/// which the daemon restarts it for) +fn write_stalled() -> AxError { + AxError::Io(std::io::Error::new(std::io::ErrorKind::TimedOut, "writing a request took too long")) +} + async fn send(w: &mut W, bytes: &[u8]) -> Result<()> { w.write_all(bytes).await?; w.flush().await?; @@ -151,6 +186,7 @@ impl Session { pushes, changes, closed, + abandoned: AtomicBool::new(false), requests: tokio::sync::Mutex::new(()), next_id: AtomicU32::new(4), reader, @@ -225,8 +261,21 @@ fn describe(o: &Obj) -> String { } impl Session { + /// Registers for the next answers, once the stream is known to be open (checked after registering: a stream + /// that closed in between would otherwise leave the request waiting out its timeout) + fn start(&self) -> Result<(mpsc::UnboundedReceiver, InFlight<'_>)> { + let (tx, rx) = mpsc::unbounded_channel(); + *self.waiter.lock().unwrap_or_else(|p| p.into_inner()) = Some(tx); + let flight = InFlight { abandoned: &self.abandoned, waiter: &self.waiter, done: false }; + if self.is_closed() { + flight.done(); + return Err(AxError::Closed); + } + Ok((rx, flight)) + } + pub fn is_closed(&self) -> bool { - *self.closed.borrow() + *self.closed.borrow() || self.abandoned.load(Ordering::SeqCst) } /// The last tree the phone pushed @@ -271,29 +320,43 @@ impl Session { return Err(AxError::Closed); } let _one = self.requests.lock().await; - let (tx, mut rx) = mpsc::unbounded_channel(); - *self.waiter.lock().unwrap_or_else(|p| p.into_inner()) = Some(tx); + let (mut rx, flight) = self.start()?; + let mut closed = self.closed.clone(); let r = async { let body = archive::encode_data(&archive::encode_request(request_type, 0, object, params, CLIENT_TYPE)); let id = self.next_id.fetch_add(1, Ordering::Relaxed); - send(&mut *self.writer.lock().await, &dtx::invocation(id, "processDataFromHost:", vec![body], false)) - .await?; + let msg = dtx::invocation(id, "processDataFromHost:", vec![body], false); + match tokio::time::timeout(WRITE_TIMEOUT, async { send(&mut *self.writer.lock().await, &msg).await }).await + { + Ok(r) => r?, + Err(_) => return Err(write_stalled()), + } let deadline = tokio::time::Instant::now() + REQUEST_TIMEOUT; loop { - let r = match tokio::time::timeout_at(deadline, rx.recv()).await { - Ok(Some(r)) => r, - Ok(None) => return Err(AxError::Closed), - Err(_) => return Err(AxError::Timeout("request")), + let r = tokio::select! { + r = tokio::time::timeout_at(deadline, rx.recv()) => match r { + Ok(Some(r)) => r, + Ok(None) => return Err(AxError::Closed), + Err(_) => return Ok(Err(AxError::Timeout("request"))), + }, + _ = closed.wait_for(|c| *c) => return Err(AxError::Closed), }; let same_object = object.is_none_or(|o| r.object.is_none_or(|a| (a.pid, a.id) == (o.pid, o.id))); if r.request_type == request_type && same_object { - return Ok(r); + return Ok(Ok(r)); } tracing::debug!("remoteAXService: passed over a late answer to request type {}", r.request_type); } } .await; - self.waiter.lock().unwrap_or_else(|p| p.into_inner()).take(); + // written whole: an unanswered request (a timeout) leaves the stream as it was; a late answer is passed over + let r = match r { + Ok(r) => { + flight.done(); + r + } + Err(e) => return Err(e), + }; let r = r?; if r.error != 0 { return Err(AxError::Protocol(format!("request type {request_type} failed: error {}", r.error))); @@ -312,11 +375,11 @@ impl Session { return Ok(out); } let _one = self.requests.lock().await; - let (tx, mut rx) = mpsc::unbounded_channel(); - *self.waiter.lock().unwrap_or_else(|p| p.into_inner()) = Some(tx); + let (mut rx, flight) = self.start()?; + let mut closed = self.closed.clone(); let r = async { let list = Param::Ints(attr::WALK.to_vec()); - { + let write = async { let mut w = self.writer.lock().await; for o in objects { let req = archive::encode_request( @@ -331,15 +394,24 @@ impl Session { w.write_all(&msg).await?; } w.flush().await?; + Ok::<_, AxError>(()) + }; + let many = WRITE_TIMEOUT + Duration::from_millis(5) * objects.len() as u32; + match tokio::time::timeout(many, write).await { + Ok(r) => r?, + Err(_) => return Err(write_stalled()), } let mut pending: Vec = objects.to_vec(); let deadline = tokio::time::Instant::now() + REQUEST_TIMEOUT + Duration::from_millis(20) * objects.len() as u32; while !pending.is_empty() { - let r = match tokio::time::timeout_at(deadline, rx.recv()).await { - Ok(Some(r)) => r, - Ok(None) => return Err(AxError::Closed), - Err(_) => return Err(AxError::Timeout("attributes")), + let r = tokio::select! { + r = tokio::time::timeout_at(deadline, rx.recv()) => match r { + Ok(Some(r)) => r, + Ok(None) => return Err(AxError::Closed), + Err(_) => return Ok(Err(AxError::Timeout("attributes"))), + }, + _ = closed.wait_for(|c| *c) => return Err(AxError::Closed), }; if r.request_type != request::ATTRIBUTES { continue; @@ -355,11 +427,16 @@ impl Session { out.insert(o, r.result); } } - Ok(()) + Ok(Ok(())) } .await; - self.waiter.lock().unwrap_or_else(|p| p.into_inner()).take(); - r.map(|()| out) + match r { + Ok(r) => { + flight.done(); + r.map(|()| out) + } + Err(e) => Err(e), + } } /// The frontmost application's element @@ -474,6 +551,11 @@ impl Session { /// Tells the phone this client no longer needs accessibility (it then closes the connection) pub async fn close(&self) { + // half a request may be on the stream: nothing more is written, the connection just goes + if self.abandoned.load(Ordering::SeqCst) { + self.reader.abort(); + return; + } let no = archive::encode_scalar(Value::Boolean(false)); let id = self.next_id.fetch_add(1, Ordering::Relaxed); let msg = dtx::invocation(id, "clientNeedsAccessibility:", vec![no], false); @@ -483,3 +565,66 @@ impl Session { self.reader.abort(); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A phone that answers the handshake and then reads everything without answering, until `hang_up` fires + async fn phone(hang_up: tokio::sync::oneshot::Receiver<()>) -> Session { + let (ours, theirs) = tokio::io::duplex(1 << 20); + tokio::spawn(async move { + let (mut r, mut w) = tokio::io::split(theirs); + let serve = async { + while let Ok(f) = dtx::read_frame(&mut r).await { + if f.selector().as_deref() == Some("deviceAPIVersion") { + let _ = send(&mut w, &dtx::reply(&f, Some(Value::Integer(7u64.into())))).await; + } + } + }; + tokio::select! { + () = serve => {} + _ = hang_up => {} + } + }); + Session::connect(ours, Duration::from_secs(2)).await.unwrap() + } + + /// A request dropped halfway (a background check that gave way to an action) leaves the stream in an unknown + /// state: the session counts as closed, so the next request opens a new one instead of reading a stale answer + #[tokio::test] + async fn a_cancelled_request_abandons_the_session() { + let (_keep, rx) = tokio::sync::oneshot::channel(); + let s = phone(rx).await; + assert!(!s.is_closed()); + let cancelled = tokio::time::timeout(Duration::from_millis(50), s.request(request::FRONTMOST_APP, None, &[])); + assert!(cancelled.await.is_err()); + assert!(s.is_closed(), "abandoned"); + assert!(matches!(s.request(request::FRONTMOST_APP, None, &[]).await, Err(AxError::Closed))); + } + + /// Not answered in time (the service is stuck, which the daemon may restart it for): the request was written + /// whole, so the session stays usable + #[tokio::test] + async fn an_unanswered_request_keeps_the_session() { + let (_keep, rx) = tokio::sync::oneshot::channel(); + let s = phone(rx).await; + assert!(matches!(s.request(request::FRONTMOST_APP, None, &[]).await, Err(AxError::Timeout(_)))); + assert!(!s.is_closed()); + } + + /// The phone hangs up while a request waits: it ends at once, not when its time is up + #[tokio::test] + async fn a_closed_connection_ends_the_wait() { + let (hang_up, rx) = tokio::sync::oneshot::channel(); + let s = phone(rx).await; + let t0 = Instant::now(); + let asked = s.request(request::FRONTMOST_APP, None, &[]); + let (r, ()) = tokio::join!(asked, async { + tokio::time::sleep(Duration::from_millis(100)).await; + let _ = hang_up.send(()); + }); + assert!(matches!(r, Err(AxError::Closed)), "{r:?}"); + assert!(t0.elapsed() < REQUEST_TIMEOUT, "{:?}", t0.elapsed()); + } +} diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs index 7a43bad0..46d630f8 100644 --- a/crates/ictl-daemon/src/core.rs +++ b/crates/ictl-daemon/src/core.rs @@ -1034,6 +1034,8 @@ impl Daemon { /// A request's lock, once the tasks still let it through ([`crate::tasks::Tasks::still`]): it may have queued /// behind other requests while the user paused, took over or handed back. A task's request waits for the task to /// run again, without the lock + /// `counted`: while it waits for the lock it counts in [`Daemon::waiting`] (background checks give way to it); not + /// while it waits for a paused task, which may be for minutes: the page's checks go on meanwhile async fn lock_admitted<'a, T>( &self, lock: &'a Mutex, @@ -1041,10 +1043,13 @@ impl Daemon { admission: &crate::tasks::Admission, queued_at: &mut Instant, gone: &mut Option>, + counted: bool, ) -> Result, Response> { use crate::tasks::Still; loop { + let waiting = counted.then(|| Waiting::new(self)); let g = acquire(lock, gone).await?; + drop(waiting); match self.tasks.still(admission, req) { Still::Admitted => return Ok(g), Still::Refused(r) => return Err(r), @@ -1070,36 +1075,61 @@ impl Daemon { let Some(check) = crate::tasks::scope_check(req) else { return Ok(false) }; let target = match check { Check::Url(u) => Target::Url(u), + // the page's app is checked once the page is picked, in the Web lane + Check::Page => return Ok(false), Check::Always { action, detail } => Target::Always { action, detail }, Check::Launch(app) => { let mut g = acquire(&self.inner, gone).await?; Target::Launch(self.resolve_app(&mut g, &app).await.map_err(Response::error)?) } Check::Foreground => { + // the lock is let go before the user is asked (below); the action checks again once it holds it let mut g = acquire(&self.inner, gone).await?; - // can't tell which app is in front: a scoped task doesn't act blind - let unknown = |why: String| { - Response::error(ictl_l10n::trf!( - "看不出前台是哪个 App({why});这个任务限定了 App 范围,所以没有操作。稍后截图再试", - "Can't tell which app is in front ({why}); this task is limited to some apps, so nothing was done. Take a screenshot and try again shortly" - )) - }; - // the lock is let go before the user is asked (below) - let app = match self.route(&mut g) { - Route::Wda(w) => w.active_app().await.map_err(|e| unknown(e.to_string()))?, - Route::Native => { - Box::pin(self.native_foreground(&mut g)).await.map_err(|e| unknown(e.to_string()))? - } - Route::Hid | Route::Unavailable => { - return Err(unknown(ictl_l10n::tr!("WDA 不可用", "WDA unavailable").into())); - } - }; - Target::Foreground(app) + Target::Foreground(self.front_app(&mut g).await?) } }; task.check_scope(&target, step, gone).await } + /// The app in front, for a scoped task's check. `Err`: why it can't be told, and so nothing is done + async fn front_app(&self, g: &mut Inner) -> Result { + // can't tell which app is in front: a scoped task doesn't act blind + let unknown = |why: String| { + Response::error(ictl_l10n::trf!( + "看不出前台是哪个 App({why});这个任务限定了 App 范围,所以没有操作。稍后截图再试", + "Can't tell which app is in front ({why}); this task is limited to some apps, so nothing was done. Take a screenshot and try again shortly" + )) + }; + match self.route(g) { + Route::Wda(w) => w.active_app().await.map_err(|e| unknown(e.to_string())), + Route::Native => Box::pin(self.native_foreground(g)).await.map_err(|e| unknown(e.to_string())), + Route::Hid | Route::Unavailable => Err(unknown(ictl_l10n::tr!("WDA 不可用", "WDA unavailable").into())), + } + } + + /// A scoped task's action on the app in front, checked again once it holds the device lock: the app may have + /// changed since [`Self::scope_gate`] looked (it lets the lock go, and a request of the agent's or the user may + /// come in between). Nobody is asked now (that would hold the lock): out of scope by now, it is refused + async fn scope_recheck( + &self, + g: &mut Inner, + req: &Request, + admission: &crate::tasks::Admission, + ) -> Result<(), Response> { + let crate::tasks::Admission::Actor(t) = admission else { return Ok(()) }; + if !t.scoped() || !matches!(crate::tasks::scope_check(req), Some(crate::tasks::Check::Foreground)) { + return Ok(()); + } + let app = self.front_app(g).await?; + if t.within_scope(&crate::tasks::Target::Foreground(app.clone())) { + return Ok(()); + } + Err(crate::tasks::refuse(&ictl_l10n::trf!( + "前台 App 刚变成了任务范围以外的 {app},这一步没有执行。先截图看看再继续", + "The app in front just became {app}, outside the task's scope; this step wasn't done. Take a screenshot before going on" + ))) + } + /// A task's scope from names or bundle IDs: the bundle IDs, each once. `Err` names the app that isn't there pub(crate) async fn resolve_scope(&self, apps: &[String]) -> crate::error::Result> { let apps: Vec<&str> = apps.iter().map(|a| a.trim()).filter(|a| !a.is_empty()).collect(); @@ -1143,11 +1173,11 @@ impl Daemon { } // Web Inspector talks to the page, not to WDA: its own lock, the device lock only to look up the device Lane::Web => { - let mut slot = match self.lock_admitted(&self.web, &req, admission, &mut queued_at, &mut ctx.gone).await - { - Ok(s) => s, - Err(r) => return r, - }; + let mut slot = + match self.lock_admitted(&self.web, &req, admission, &mut queued_at, &mut ctx.gone, false).await { + Ok(s) => s, + Err(r) => return r, + }; let device = self.inner.lock().await.device.clone(); if let Err(r) = admit(&req, queued_at, &ctx, device.as_ref().map(|d| d.udid.as_str())) { return r; @@ -1158,7 +1188,20 @@ impl Daemon { return text(match req { Request::WebTargets => self.web_targets(&mut slot, &device).await, Request::WebEval { target, expression, timeout_ms } => { - self.web_eval(&mut slot, &device, &target, &expression, Duration::from_millis(timeout_ms)).await + // a scoped task: the app that shows the page must be in its scope, whatever is in front + let scope = match admission { + crate::tasks::Admission::Actor(t) if t.scoped() => Some(t), + _ => None, + }; + let gate = crate::web::Gate { task: scope, step: ctx.task_step, gone: &mut ctx.gone }; + let timeout = Duration::from_millis(timeout_ms); + match self.web_eval(&mut slot, &device, &target, &expression, timeout, gate).await { + Ok(v) => Ok(v), + Err(crate::web::EvalError::Refused(r)) => { + return r.with_failure(Delivery::NotSent, FailureStage::Preflight); + } + Err(crate::web::EvalError::Failed(e)) => Err(e), + } } _ => unreachable!("lane"), }); @@ -1211,9 +1254,8 @@ impl Daemon { _ => 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 { + match self.lock_admitted(&self.inner, &req, admission, &mut queued_at, &mut ctx.gone, true).await { Ok(g) => g, Err(r) => return r.with_failure(Delivery::NotSent, FailureStage::Preflight), } @@ -1222,6 +1264,9 @@ impl Daemon { if let Err(r) = admit(&req, queued_at, &ctx, g.device.as_ref().map(|d| d.udid.as_str())) { return r.with_failure(Delivery::NotSent, FailureStage::Preflight); } + if let Err(r) = self.scope_recheck(g, &req, admission).await { + return r.with_failure(Delivery::NotSent, FailureStage::Preflight); + } let view = ctx.expect_view.as_deref(); // 改变界面的操作做完后缓存的元素树就作废;只有调用方声明「不改变布局」的按名字点击(max_age_ms > 0)保留 let keeps_cache = matches!(req, Request::TapElement { max_age_ms, .. } if max_age_ms > 0); @@ -1243,8 +1288,13 @@ impl Daemon { if self.waiting.load(std::sync::atomic::Ordering::SeqCst) > 0 { gave_way() } else { + // dropping it halfway may leave the accessibility session's stream mid-message: the session then + // counts as closed and is opened again (`ictl_ax::Session`); a check doesn't restart the phone's + // accessibility daemon either, that is for actions to decide + let check = + BACKGROUND.scope(true, Box::pin(self.dispatch(g, req, view, ctx.watched, &mut may_continue))); tokio::select! { - r = Box::pin(self.dispatch(g, req, view, ctx.watched, &mut may_continue)) => r, + r = check => r, () = action => gave_way(), } } @@ -1315,8 +1365,9 @@ impl Daemon { } Request::Tap { x, y, count } => self.tap(g, x, y, count, view).await, Request::TapSequence { points } => self.tap_sequence(g, &points).await, - Request::TapElement { text, index, max_age_ms, scroll } => { - let r = self.tap_element(g, &text, index, Duration::from_millis(max_age_ms), scroll).await; + Request::TapElement { ref text, index, max_age_ms, scroll } => { + let age = Duration::from_millis(max_age_ms); + let r = self.tap_element(g, text, index, age, scroll, &mut || may_continue(&req)).await; r.map(|(t, missed)| { outcome.tapped_nothing = missed; // nothing was tapped: there is no "before the action" to compare the screen with, or the next @@ -1369,11 +1420,11 @@ impl Daemon { data = Some(crate::protocol::Data::Alert { text: alert }); text }), - Request::WaitFor { text, timeout_ms } => { - self.wait_for(g, &text, Duration::from_millis(timeout_ms), false).await + Request::WaitFor { ref text, timeout_ms } => { + self.wait_for(g, text, Duration::from_millis(timeout_ms), false, &mut || may_continue(&req)).await } - Request::WaitForDisappearance { text, timeout_ms } => { - self.wait_for(g, &text, Duration::from_millis(timeout_ms), true).await + Request::WaitForDisappearance { ref text, timeout_ms } => { + self.wait_for(g, text, Duration::from_millis(timeout_ms), true, &mut || may_continue(&req)).await } Request::Doctor => Ok(self.doctor(g).await), Request::UnlockReset => { @@ -1553,6 +1604,17 @@ fn gave_way() -> Response { ) } +tokio::task_local! { + /// A background check is being dispatched ([`ictl_protocol::BACKGROUND`]): it may be dropped halfway for an action + /// and has no business with side effects such as restarting the phone's accessibility daemon + pub(crate) static BACKGROUND: bool; +} + +/// Whether the request being dispatched is a background check ([`BACKGROUND`]) +pub(crate) fn in_background() -> bool { + BACKGROUND.try_with(|b| *b).unwrap_or(false) +} + /// An action waiting for the device lock, counted in [`Daemon::waiting`] until it has it struct Waiting<'a>(&'a Daemon); @@ -1604,6 +1666,13 @@ fn check_request(req: &Request) -> Result<(), String> { { return Err(ictl_l10n::tr!("超出滚动或行数上限", "scroll or row limit is out of range").into()); } + Request::TapElement { scroll: Some(s), .. } if !(1..=crate::protocol::MAX_SEARCH_SCROLLS).contains(&s.max) => { + return Err(ictl_l10n::trf!( + "scroll 最多滑 1 到 {} 次", + "scroll can swipe 1 to {} times", + crate::protocol::MAX_SEARCH_SCROLLS + )); + } Request::ScrollCollect(scan) if scan.x.is_some_and(|x| !x.is_finite() || x < 0.0) => { return Err(ictl_l10n::tr!("x 不能是负数", "x can't be negative").into()); } @@ -1886,6 +1955,85 @@ pub(crate) mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// An action counts as waiting for the phone (background checks give way) only while it waits for the lock, not + /// while its task is paused: the page's checks went on giving way for as long as the pause lasted + #[tokio::test] + async fn waiting_for_a_paused_task_doesnt_hold_off_the_checks() { + use std::sync::atomic::Ordering::SeqCst; + let (d, dir) = test_daemon("waiting-paused"); + let t = d.tasks.open("x", "test", Some("phone"), Vec::new(), None).unwrap(); + let tap = Request::Tap { x: 1.0, y: 1.0, count: 1 }; + let admission = crate::tasks::Admission::Actor(t.clone()); + let (mut queued, mut gone) = (Instant::now(), None); + { + let held = d.inner.lock().await; + let locked = d.lock_admitted(&d.inner, &tap, &admission, &mut queued, &mut gone, true); + tokio::pin!(locked); + assert!(tokio::time::timeout(Duration::from_millis(30), &mut locked).await.is_err()); + assert_eq!(d.waiting.load(SeqCst), 1, "waits for the lock: counted"); + t.control_as_user("pause").unwrap(); + drop(held); + assert!(tokio::time::timeout(Duration::from_millis(30), &mut locked).await.is_err(), "the task is paused"); + assert_eq!(d.waiting.load(SeqCst), 0, "waits for the task: not counted"); + t.control_as_user("resume").unwrap(); + assert!(locked.await.is_ok()); + assert_eq!(d.waiting.load(SeqCst), 0); + } + // the Web lane's lock isn't the device's: never counted + let held = d.web.lock().await; + let web = d.lock_admitted(&d.web, &tap, &admission, &mut queued, &mut gone, false); + tokio::pin!(web); + assert!(tokio::time::timeout(Duration::from_millis(30), &mut web).await.is_err()); + assert_eq!(d.waiting.load(SeqCst), 0); + drop(held); + assert!(web.await.is_ok()); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A scoped task's action on the app in front is checked again with the lock held; it can't act blind. Unscoped + /// tasks, requests that don't act on the front app and scripts in pages (checked by the page's app) aren't + #[tokio::test] + async fn a_scoped_action_is_checked_again_with_the_lock_held() { + let (d, dir) = test_daemon("scope-recheck"); + let scoped = d.tasks.open("x", "test", Some("phone"), vec!["com.apple.Preferences".into()], None).unwrap(); + let tap = Request::Tap { x: 1.0, y: 1.0, count: 1 }; + let mut g = d.inner.lock().await; + let actor = crate::tasks::Admission::Actor(scoped.clone()); + let r = d.scope_recheck(&mut g, &tap, &actor).await; + assert!( + matches!(&r, Err(Response::Error { message, .. }) if message.contains("看不出前台") || message.contains("Can't tell")), + "{r:?}" + ); + let home = Request::PressButton { button: "home".into() }; + assert!(d.scope_recheck(&mut g, &home, &actor).await.is_ok(), "the way back is never held"); + let eval = Request::WebEval { target: String::new(), expression: "1".into(), timeout_ms: 1000 }; + assert!(d.scope_recheck(&mut g, &eval, &actor).await.is_ok(), "the page's app is checked in the Web lane"); + assert!(d.scope_recheck(&mut g, &tap, &crate::tasks::Admission::Free).await.is_ok()); + scoped.end(crate::tasks::End::Cancelled, ""); + let open = d.tasks.open("y", "test", Some("phone"), Vec::new(), None).unwrap(); + let r = d.scope_recheck(&mut g, &tap, &crate::tasks::Admission::Actor(open)).await; + assert!(r.is_ok(), "no scope: nothing to look up"); + drop(g); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_tap_by_text_scrolls_within_bounds() { + let tap = |max| Request::TapElement { + text: "x".into(), + index: 0, + max_age_ms: 0, + scroll: Some(crate::protocol::ScrollSearch { down: true, max }), + }; + for (max, ok) in + [(0, false), (1, true), (crate::protocol::MAX_SEARCH_SCROLLS, true), (16, false), (u32::MAX, false)] + { + assert_eq!(check_request(&tap(max)).is_ok(), ok, "{max}"); + } + let plain = Request::TapElement { text: "x".into(), index: 0, max_age_ms: 0, scroll: None }; + assert!(check_request(&plain).is_ok()); + } + /// 调用方已经断开:还在排队等设备锁的请求不执行 #[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 2393fa6f..e5638b59 100644 --- a/crates/ictl-daemon/src/lib.rs +++ b/crates/ictl-daemon/src/lib.rs @@ -73,6 +73,11 @@ pub async fn run(cfg: Config) -> anyhow::Result<()> { r } +/// A supervision round asked for that couldn't take the device is asked for again this much later +const RETRY_ROUND: std::time::Duration = std::time::Duration::from_millis(200); +/// Clients served at once on the control socket; more wait in its queue +const MAX_CONNECTIONS: usize = 256; + async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::Result<()> { let daemon = Daemon::new(cfg); daemon.log.log(ictl_l10n::log_tr!("守护进程启动", "Daemon started")); @@ -86,14 +91,11 @@ async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::Resul // the round running, and whether it was asked for (`Daemon::wake`) let mut ticking: Option<(JoinHandle, bool)> = None; // a round asked for while one was still running: it starts once that one is done. One asked for that couldn't - // run (a request held the device) is asked for again: a phone made ready in the background waited 10 s for the - // next round when switching back to it + // run (a request held the device) is asked for again shortly (`retry`): a phone made ready in the background + // waited 10 s for the next round when switching back to it let mut woken = false; + let mut retry: Option = None; loop { - if let Some((h, asked)) = ticking.take_if(|(h, _)| h.is_finished()) { - let ran = h.await.unwrap_or(true); - woken |= asked && !ran; - } if woken && ticking.is_none() { woken = false; ticking = Some((tokio::task::spawn_local(daemon.clone().tick()), true)); @@ -102,7 +104,16 @@ async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::Resul biased; _ = term.recv() => break, _ = tokio::signal::ctrl_c() => break, - r = listener.accept() => match r { + // the round that runs ended: an asked-for one that couldn't take the device is asked for again + r = async { (&mut ticking.as_mut().expect("guarded").0).await }, if ticking.is_some() => { + let asked = ticking.take().is_some_and(|(_, asked)| asked); + if asked && !r.unwrap_or(true) { + retry = Some(tokio::time::Instant::now() + RETRY_ROUND); + } + } + Some(_) = conns.join_next(), if !conns.is_empty() => {} + // at most MAX_CONNECTIONS clients at once: more wait in the socket's queue + r = listener.accept(), if conns.len() < MAX_CONNECTIONS => match r { Ok((stream, _)) => { conns.spawn_local(serve_conn(daemon.clone(), stream)); } @@ -112,16 +123,17 @@ async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::Resul tokio::time::sleep(std::time::Duration::from_millis(100)).await; } }, - Some(_) = conns.join_next(), if !conns.is_empty() => {} _ = tick.tick() => { // 上一轮还没跑完(例如在重启 usbmuxd)就不叠加 - if ticking.as_ref().is_none_or(|(h, _)| h.is_finished()) { + if ticking.is_none() { ticking = Some((tokio::task::spawn_local(daemon.clone().tick()), false)); } } () = daemon.wake.notified() => woken = true, - // waiting for the round that runs to end, before the one asked for - () = tokio::time::sleep(std::time::Duration::from_millis(200)), if woken => {} + () = tokio::time::sleep_until(retry.unwrap_or_else(tokio::time::Instant::now)), if retry.is_some() => { + retry = None; + woken = true; + } } } // stopping: new clients are refused at once (instead of waiting in the queue for a reply that never comes), and diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rs index 42cadde5..b69e9263 100644 --- a/crates/ictl-daemon/src/tasks.rs +++ b/crates/ictl-daemon/src/tasks.rs @@ -160,7 +160,7 @@ fn now_ms() -> u64 { SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0) } -fn refuse(msg: &str) -> Response { +pub(crate) fn refuse(msg: &str) -> Response { Response::error(msg) } @@ -196,6 +196,9 @@ pub enum Check { Url(String), /// Acts on whatever app is in front Foreground, + /// Runs script in a web page: checked against the app that shows the page, which needn't be the one in front, once + /// the page is known (`Daemon::web_eval`) + Page, /// Always asks, whatever the scope Always { action: String, detail: String }, } @@ -227,8 +230,8 @@ pub fn scope_check(req: &Request) -> Option { | Request::Swipe { .. } | Request::TypeText { .. } | Request::ReplaceText { .. } - | Request::WebEval { .. } | Request::Touch { phase: TouchPhase::Down | TouchPhase::Move, .. } => Some(Check::Foreground), + Request::WebEval { .. } => Some(Check::Page), Request::InstallApp { path } => { Some(Check::Always { action: ictl_l10n::tr!("安装 App", "Install an app").into(), detail: path.clone() }) } @@ -617,6 +620,11 @@ impl Task { !self.lock().scope.is_empty() } + /// Whether `target` is within the scope now, without asking anyone + pub fn within_scope(&self, target: &Target) -> bool { + out_of_scope(&self.lock().scope, target).is_none() + } + /// Before an action of a scoped task: within its scope it goes on; outside it waits for the user. Approving lets /// the task into that app for the rest of it; rejecting refuses this action only, so the agent can go back /// (unlike a rejected [`Self::confirm`], the task doesn't end as rejected). `step`: the tool call the action @@ -679,6 +687,12 @@ impl Task { self.end(end, if summary.is_empty() { fallback } else { summary }); } + /// The user's pause, resume and the like, for the daemon's own tests + #[cfg(test)] + pub(crate) fn control_as_user(&self, action: &str) -> Result<(), String> { + self.control(action, None, false, None) + } + /// `by`: who asked, for the log (a `control` event after the change) fn control(&self, action: &str, step: Option, approve: bool, by: Option<&str>) -> Result<(), String> { let mut st = self.lock(); @@ -1631,6 +1645,8 @@ mod tests { assert_eq!(scope_check(&Request::LaunchApp { app: "设置".into() }), Some(Check::Launch("设置".into()))); assert_eq!(scope_check(&Request::OpenUrl { url: "tel:10086".into() }), Some(Check::Url("tel:10086".into()))); assert!(matches!(scope_check(&Request::UninstallApp { app: "x".into() }), Some(Check::Always { .. }))); + let eval = Request::WebEval { target: "1".into(), expression: "1".into(), timeout_ms: 1000 }; + assert_eq!(scope_check(&eval), Some(Check::Page), "the page's app, not the one in front"); // the ways back after a refusal, and looking, are never held assert_eq!(scope_check(&Request::PressButton { button: "home".into() }), None); assert_eq!(scope_check(&Request::TerminateApp { app: "x".into() }), None); @@ -1677,8 +1693,11 @@ mod tests { let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"]), None).unwrap(); assert!(t.scoped()); let wechat = Target::Foreground("com.tencent.xin".into()); + assert!(!t.within_scope(&wechat), "outside, and nobody is asked"); + assert_eq!(t.info().state, "running"); answer_soon(&t, true).await; assert_eq!(t.check_scope(&wechat, None, &mut None).await.ok(), Some(true), "asked, then let through"); + assert!(t.within_scope(&wechat)); assert_eq!(t.check_scope(&wechat, None, &mut None).await.ok(), Some(false), "not asked again"); assert_eq!(t.info().apps, scope(&["com.apple.Preferences", "com.tencent.xin"])); assert_eq!(t.info().state, "running"); diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rs index b97ed7d7..f559e4d4 100644 --- a/crates/ictl-daemon/src/tools/input.rs +++ b/crates/ictl-daemon/src/tools/input.rs @@ -283,6 +283,7 @@ impl Daemon { index: usize, max_age: Duration, scroll: Option, + may_continue: &mut dyn FnMut() -> bool, ) -> crate::error::Result<(String, bool)> { self.ensure_unlocked(g).await.map_err(Error::preflight)?; let mut tree = self.tree(g, max_age).await.map_err(Error::preflight)?; @@ -310,10 +311,14 @@ impl Daemon { if at_end || scrolled >= s.max { break; } + // the task was paused or the caller went away: no more swiping, and nothing tapped + if !may_continue() { + return Err(Error::preflight(stopped_searching(scrolled))); + } let next = Box::pin(self.search_scroll(g, s.down, None)).await.map_err(|e| failed_scroll(e, scrolled))?; scrolled += 1; - at_end = next.close_to(&tree, STILL_TOLERANCE); + at_end = super::scroll::unchanged_viewport(&tree, &next); tree = next; } // 没有文字完全相同的,包含它的又已经滑过去了:往回滑到看到它的地方(多滑一次,前后两屏有重叠) @@ -322,6 +327,9 @@ impl Daemon { && let Some(k) = partial_at { while back <= scrolled - k && !reachable(&tree, text, index) { + if !may_continue() { + return Err(Error::preflight(stopped_searching(scrolled + back))); + } tree = Box::pin(self.search_scroll(g, !s.down, None)) .await .map_err(|e| failed_scroll(e, scrolled + back))?; @@ -1075,6 +1083,14 @@ async fn verify_typed(w: &mut WdaClient, before } } +/// [`Daemon::tap_element`] stopped searching: the task was paused or taken over, or the caller went away +fn stopped_searching(completed: u32) -> String { + ictl_l10n::trf!( + "查找目标时被打断(任务暂停、被接管或调用方已离开),此前已完成 {completed} 次滑动,没有点击;请先查看屏幕", + "The scroll search was interrupted (the task was paused or taken over, or the caller went away) after {completed} swipes; nothing was tapped. Look at the screen first" + ) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ictl-daemon/src/tools/native.rs b/crates/ictl-daemon/src/tools/native.rs index b9befe20..9dfc4c8d 100644 --- a/crates/ictl-daemon/src/tools/native.rs +++ b/crates/ictl-daemon/src/tools/native.rs @@ -171,6 +171,11 @@ impl Daemon { /// remoteAXService didn't answer: unless that was already tried within [`AX_RESTART_EVERY`], end axauditd on the /// phone ([`ictl_device::Tunnel::restart_ax_daemon`]). Whether it was ended, so the read is worth repeating async fn restart_stuck_ax(&self, g: &mut Inner, device: &ictl_device::Device, why: &str) -> bool { + // a background check (the page's alert and status polls) doesn't restart it: it may be dropped halfway for an + // action, and the next action finds out for itself + if crate::core::in_background() { + return false; + } if g.dev.ax_restarted.is_some_and(|t| t.elapsed() < AX_RESTART_EVERY) { return false; } @@ -470,6 +475,7 @@ impl Daemon { text: &str, timeout: Duration, disappeared: bool, + may_continue: &mut dyn FnMut() -> bool, ) -> crate::error::Result { use super::observe::Waited; let t0 = Instant::now(); @@ -512,6 +518,9 @@ impl Daemon { if t0.elapsed() >= timeout { return Err(super::observe::wait_timeout(text, timeout, why)); } + if !may_continue() { + return Err(super::observe::wait_interrupted(text, t0.elapsed())); + } tokio::time::sleep(Duration::from_millis(300).min(timeout.saturating_sub(t0.elapsed()))).await; } } diff --git a/crates/ictl-daemon/src/tools/observe.rs b/crates/ictl-daemon/src/tools/observe.rs index a453570c..81fb5d34 100644 --- a/crates/ictl-daemon/src/tools/observe.rs +++ b/crates/ictl-daemon/src/tools/observe.rs @@ -251,12 +251,13 @@ impl Daemon { text: &str, timeout: Duration, disappeared: bool, + may_continue: &mut dyn FnMut() -> bool, ) -> crate::error::Result { self.ensure_unlocked(g).await?; let t0 = Instant::now(); let w = match self.route(g) { Route::Wda(w) => w, - Route::Native => return Box::pin(self.native_wait_for(g, text, timeout, disappeared)).await, + Route::Native => return Box::pin(self.native_wait_for(g, text, timeout, disappeared, may_continue)).await, Route::Hid | Route::Unavailable => return Err(wda_unavailable(g)), }; // 轮询时不等界面空闲:页面还在加载、播放动画时每次读树也只要约 0.2 秒 @@ -282,6 +283,9 @@ impl Daemon { if t0.elapsed() >= timeout { return Err(wait_timeout(text, timeout, why)); } + if !may_continue() { + return Err(wait_interrupted(text, t0.elapsed())); + } tokio::time::sleep(Duration::from_millis(300).min(timeout.saturating_sub(t0.elapsed()))).await; } } @@ -291,6 +295,15 @@ impl Daemon { } } +/// [`Daemon::wait_for`] stopped before it was done: the task was paused or taken over, or the caller went away +pub(super) fn wait_interrupted(text: &str, waited: Duration) -> Error { + let waited = waited.as_secs_f64(); + Error::from(ictl_l10n::trf!( + "等「{text}」时被打断(任务暂停、被接管或调用方已离开),已等 {waited:.1} 秒", + "Waiting for \"{text}\" was interrupted (the task was paused or taken over, or the caller went away) after {waited:.1} s" + )) +} + pub(super) fn wait_match(tree: &Tree, text: &str, disappeared: bool, elapsed: Duration) -> Option { let matches = elements::find_shown(&tree.elements, text); let elapsed = elapsed.as_secs_f64(); diff --git a/crates/ictl-daemon/src/tools/scroll.rs b/crates/ictl-daemon/src/tools/scroll.rs index ee11f4e2..c2820637 100644 --- a/crates/ictl-daemon/src/tools/scroll.rs +++ b/crates/ictl-daemon/src/tools/scroll.rs @@ -87,7 +87,7 @@ impl Daemon { } /// A truncated read can omit the rows that moved. Only two complete, populated reads can show the end. -fn unchanged_viewport(before: &Tree, after: &Tree) -> bool { +pub(super) fn unchanged_viewport(before: &Tree, after: &Tree) -> bool { !before.incomplete && !after.incomplete && !after.elements.is_empty() && after.close_to(before, STILL_TOLERANCE) } diff --git a/crates/ictl-daemon/src/web.rs b/crates/ictl-daemon/src/web.rs index 26e0bfee..840ea1dc 100644 --- a/crates/ictl-daemon/src/web.rs +++ b/crates/ictl-daemon/src/web.rs @@ -20,6 +20,25 @@ use crate::core::Daemon; /// A kept connection is closed after this long without a request const WEB_IDLE: Duration = Duration::from_secs(5 * 60); +/// A scoped task's check for `WebEval` (`task` is `None` for anyone else) +pub(crate) struct Gate<'a> { + pub task: Option<&'a std::sync::Arc>, + pub step: Option, + pub gone: &'a mut Option>, +} + +/// Why a page wasn't evaluated: it failed, or the task's scope refused it (a whole answer, passed on as it is) +pub(crate) enum EvalError { + Failed(crate::error::Error), + Refused(crate::protocol::Response), +} + +impl> From for EvalError { + fn from(e: E) -> Self { + Self::Failed(e.into()) + } +} + /// The kept Web Inspector connection, for one device pub(crate) struct WebConn { udid: String, @@ -65,7 +84,8 @@ impl Daemon { target: &str, expression: &str, timeout: Duration, - ) -> crate::error::Result { + gate: Gate<'_>, + ) -> Result { let (apps, pages) = web_pages(slot, device).await?; let page = pick(&pages, target).map_err(|e| match e { Pick::None => ictl_l10n::trf!( @@ -78,7 +98,14 @@ impl Daemon { c.iter().map(|p| target_line(p, &apps)).collect::>().join("\n") ), })?; - let conn = slot.as_mut().ok_or("Web Inspector")?; + // a task limited to some apps: the app that shows the page, which needn't be the one in front + if let Some(t) = gate.task { + let app = shown_app(page, &apps).map(|a| a.bundle_id.clone()).unwrap_or_default(); + t.check_scope(&crate::tasks::Target::Foreground(app), gate.step, gate.gone) + .await + .map_err(EvalError::Refused)?; + } + let conn = slot.as_mut().ok_or(crate::error::Error::from("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 { @@ -167,11 +194,15 @@ fn breaks_connection(e: &ictl_webinspector::Error) -> bool { !matches!(e, ictl_webinspector::Error::Timeout(_) | ictl_webinspector::Error::Command(_)) } +/// The app that shows a page: a WebContent process stands in for it +fn shown_app<'a>(p: &Page, apps: &'a [App]) -> Option<&'a App> { + let app = apps.iter().find(|a| a.id == p.app_id); + app.and_then(|a| a.host.as_deref()).and_then(|h| apps.iter().find(|a| a.id == h)).or(app) +} + /// `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 shown = shown_app(p, apps); 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 { "" }; diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index eaf9b322..fe55fd2a 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -190,3 +190,8 @@ | 184 | 浏览器解不了 HEVC 时,每个看手机原生视频的控制台页面各起一个 ffmpeg 解 60 帧的 HEVC 再编 H.264,没有上限:开几个页面就能把主机 CPU 或显卡的编码会话占满 | 同时最多 4 个页面转码(`transcode::Slots`),再多的回 503(`Retry-After`),页面显示「画面断开 · 自动重试中」、等有页面关掉后接上;日志每分钟最多记一次 | 单测 `transcoding_pages_are_limited_and_their_places_come_back` + 真机 | | 185 | 控制台页面各自定时轮询:`/api/info` 每 2 秒、任务列表每 3 秒、设备面板每 10 秒三个请求(`/api/daemon`、`/api/devices` 读的是同一份快照),后台标签页也照常轮询;几个页面开着时守护进程的请求成倍增加 | 任务列表随 `/api/info?tasks=1` 一起取(只在页面要接任务时带上);`/api/daemon` 带上设备列表,一轮两个请求;页面在后台时 `/api/info`、设备面板、弹窗检查都不问,切回前台立刻补一次 | 页面测试 `a task list from the info poll is used as it is` 和原有的任务接续测试 + 真机 | | 186 | 守护进程开着 HID 会话就退出(看门狗判定卡死后 `exit(1)`、崩溃、kill -9):屏幕媒体流没停,手机一直显示「正在被查看」、一直不自动锁屏(iPhone 15 Pro Max iOS 27.2.1:kill -9 后 5 分钟仍是这样),直到下次有程序开了再正常关 HID。看门狗退出时拿不到设备锁,没法先收尾 | 开 HID 时写 `hid-open/`,正常关掉时删;启动时发现残留的,等那台手机就绪后开一下 HID 再正常关掉(最多试 3 次),事件日志记一笔 | 单测 `markers_outlive_the_process_until_cleared` + 真机(开着 HID 时 kill -9 守护进程,看灵动岛的图标) | +| 191 | 原生控制(iOS 27)下,后台检查(控制台的弹窗、状态轮询)给操作让路时在无障碍请求中途被丢掉:DTX 会话的流停在半条消息上,下一个请求读到错位的应答;后台检查读不到应答时还会重启手机的 axauditd | 请求中途被丢掉时把会话标记为作废,下次重新打开;写入 5 秒超时(算 I/O 超时,不触发重启 axauditd);连接关闭时结束等待;后台检查(`core::BACKGROUND`)不重启 axauditd | 单测 `a_cancelled_request_abandons_the_session`、`an_unanswered_request_keeps_the_session`、`a_closed_connection_ends_the_wait` + 真机(iPhone 15 Pro Max iOS 27.2.1:两个线程以 background 标记连续发弹窗检查和状态,同时做 24 个操作 ×2 轮:操作 0 失败,9000 多次后台检查都让路,日志里没有重连或重启 axauditd;操作停下 4 秒后后台检查照常应答) | +| 192 | 任务暂停时排队的操作一直算在「等设备的操作」里:暂停多久,控制台的后台检查就让路多久 | 只在等设备锁时计数,等任务恢复时不算;Web 通道的锁不算 | 单测 `waiting_for_a_paused_task_doesnt_hold_off_the_checks` | +| 193 | 守护进程主循环:要求的一轮巡检因设备忙没跑成时,只在循环下一次醒来时才发现,可能要等 10 秒的定时巡检;同时服务的连接数没有上限 | 直接等这一轮结束,没跑成就 200 毫秒后再要一轮;同时最多 256 个连接,更多的留在套接字队列里;先收割结束的连接再接受新的 | 真机(iPhone 和 iPad 之间来回切换:切回 iPhone 0.66 秒就绪,切到 iPad 2 秒就绪) | +| 194 | 限定 App 范围的任务:检查前台 App 后放开设备锁、等真正操作时前台可能已经换了;`iphone_web_eval` 按前台 App 检查,而不是显示页面的 App | 操作拿到设备锁后再查一次前台 App(不再问用户,越界就拒绝);`web_eval` 选定页面后按它的宿主 App 检查(`Check::Page`),不再先查前台 | 单测 `a_scoped_action_is_checked_again_with_the_lock_held`、`what_each_request_checks_against_the_scope`、`an_approved_app_joins_the_scope_for_the_rest_of_the_task` + 真机(范围只有设置的任务:边滑边找、点击、启动设置都照常;打开备忘录被询问、拒绝后不执行;Safari 在前台时 `web_eval` 被询问一次,拒绝后不执行,同意后执行,之后不再问) | +| 195 | 直接走协议的 `TapElement.scroll.max` 没有上限(`u32::MAX` 能占着手机几个小时);边滑边找和 `wait_for` 在任务暂停或调用方离开后照样跑到底 | 守护进程也只收 1 到 15 次;每次滑动前、每轮等待之间都问一次能不能继续,不能就停下(边滑边找不点击) | 单测 `a_tap_by_text_scrolls_within_bounds` + 真机(`max` 16 和 0 都被拒绝;`wait_for` 等 20 秒,2.5 秒时暂停任务,2.7 秒返回「被打断」;边滑边找时暂停,滑了 1 次就停下、没有点击) | From 685220de68ae2117985a41b35044a36ae3057fd4 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:55:29 +0800 Subject: [PATCH 2/2] fix(daemon): review of #197 (unknown front app, web scope without the lock, tap check, AX reader) - scope_recheck: an action the user just allowed on a screen whose app WDA didn't name goes through while it is still unnamed; an unnamed front app otherwise gets the full "can't tell" text (it said "became ") - WebEval in a scoped task asks the user without holding the Web Inspector, then starts over (lock, task state, device, page) and runs only on the app allowed; a page whose host isn't known (unlisted host, WebKit's own process) counts as an unknown app and never joins the scope - tap_element checks may_continue right before tapping - ictl-ax: a request dropped halfway also stops the session's reader; the reader's replies time out after 5 s - main loop: a round that ran clears a pending retry; supervision rounds come before new clients; scope_gate's look-up counts as waiting Co-Authored-By: Claude Opus 5.5 --- crates/ictl-ax/src/session.rs | 21 ++- crates/ictl-daemon/src/core.rs | 187 +++++++++++++++++++------- crates/ictl-daemon/src/lib.rs | 33 +++-- crates/ictl-daemon/src/tools/input.rs | 10 +- crates/ictl-daemon/src/web.rs | 104 ++++++++++++-- docs/dev/regression-cases.md | 6 +- 6 files changed, 276 insertions(+), 85 deletions(-) diff --git a/crates/ictl-ax/src/session.rs b/crates/ictl-ax/src/session.rs index 9caf6357..7a1c9182 100644 --- a/crates/ictl-ax/src/session.rs +++ b/crates/ictl-ax/src/session.rs @@ -99,10 +99,12 @@ impl Drop for Session { } /// One request on the stream: unless [`InFlight::done`] is called, dropping it (the request was cancelled, or failed -/// writing) abandons the session ([`Session::is_closed`]), and the answer channel is let go either way +/// writing) abandons the session ([`Session::is_closed`]) and stops its reader, which would otherwise go on answering +/// the phone on a stream that may hold half a message; the answer channel is let go either way struct InFlight<'a> { abandoned: &'a AtomicBool, waiter: &'a Waiter, + reader: &'a tokio::task::JoinHandle<()>, done: bool, } @@ -116,6 +118,7 @@ impl Drop for InFlight<'_> { fn drop(&mut self) { if !self.done { self.abandoned.store(true, Ordering::SeqCst); + self.reader.abort(); } self.waiter.lock().unwrap_or_else(|p| p.into_inner()).take(); } @@ -210,8 +213,12 @@ async fn read_loop( break; } }; + // a reply that can't be written in time: the link stopped, the session is done if let Some(b) = answer(&f) - && send(&mut *writer.lock().await, &b).await.is_err() + && !matches!( + tokio::time::timeout(WRITE_TIMEOUT, async { send(&mut *writer.lock().await, &b).await }).await, + Ok(Ok(())) + ) { break; } @@ -266,7 +273,7 @@ impl Session { fn start(&self) -> Result<(mpsc::UnboundedReceiver, InFlight<'_>)> { let (tx, rx) = mpsc::unbounded_channel(); *self.waiter.lock().unwrap_or_else(|p| p.into_inner()) = Some(tx); - let flight = InFlight { abandoned: &self.abandoned, waiter: &self.waiter, done: false }; + let flight = InFlight { abandoned: &self.abandoned, waiter: &self.waiter, reader: &self.reader, done: false }; if self.is_closed() { flight.done(); return Err(AxError::Closed); @@ -601,6 +608,14 @@ mod tests { assert!(cancelled.await.is_err()); assert!(s.is_closed(), "abandoned"); assert!(matches!(s.request(request::FRONTMOST_APP, None, &[]).await, Err(AxError::Closed))); + // nothing reads or answers on that stream any more + tokio::time::timeout(Duration::from_secs(1), async { + while !s.reader.is_finished() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the reader stopped"); } /// Not answered in time (the service is stuck, which the daemon may restart it for): the request was written diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs index 46d630f8..dabab4b1 100644 --- a/crates/ictl-daemon/src/core.rs +++ b/crates/ictl-daemon/src/core.rs @@ -996,17 +996,17 @@ impl Daemon { Err(r) => return r.with_failure(Delivery::NotSent, FailureStage::Preflight), }; // a task limited to some apps: outside them, the action waits for the user (docs/task-control.md §2.6) - let mut asked = false; + let mut gated = Gated::default(); if let crate::tasks::Admission::Actor(t) = &admission && t.scoped() { match self.scope_gate(t, &req, ctx.task_step, &mut ctx.gone).await { - Ok(a) => asked = a, + Ok(g) => gated = g, Err(r) => return r.with_failure(Delivery::NotSent, FailureStage::Preflight), } } // held while the task was paused or waiting for the user: the time in the queue starts now - let queued_at = if waited || asked { Instant::now() } else { queued_at }; + let queued_at = if waited || gated.asked { Instant::now() } else { queued_at }; // an action of the task that no announced step covers is a step of its own let auto = match &admission { crate::tasks::Admission::Actor(t) if ctx.task_step.is_none() && req.is_device_action() => { @@ -1017,7 +1017,7 @@ impl Daemon { let t0 = Instant::now(); let looks = crate::tasks::observes(&req); // boxed: the request's state machine is large, and a connection's task shouldn't carry it on the stack - let resp = Box::pin(self.handle_admitted(req, queued_at, ctx, &admission)).await; + let resp = Box::pin(self.handle_admitted(req, queued_at, ctx, &admission, gated.unknown_approved)).await; if let Some((t, step)) = auto { self.tasks.auto_step_done(&t, step, &resp, t0.elapsed().as_millis() as u64); } @@ -1063,32 +1063,44 @@ impl Daemon { } /// What an action of a scoped task touches, then [`crate::tasks::Task::check_scope`]. The device lock is only held - /// to look it up, not while the user decides (the user may take over meanwhile). Returns whether it waited + /// to look it up, not while the user decides (the user may take over meanwhile) async fn scope_gate( &self, task: &crate::tasks::Task, req: &Request, step: Option, gone: &mut Option>, - ) -> Result { + ) -> Result { use crate::tasks::{Check, Target}; - let Some(check) = crate::tasks::scope_check(req) else { return Ok(false) }; + let Some(check) = crate::tasks::scope_check(req) else { return Ok(Gated::default()) }; let target = match check { Check::Url(u) => Target::Url(u), // the page's app is checked once the page is picked, in the Web lane - Check::Page => return Ok(false), + Check::Page => return Ok(Gated::default()), Check::Always { action, detail } => Target::Always { action, detail }, Check::Launch(app) => { - let mut g = acquire(&self.inner, gone).await?; + let mut g = self.lock_counted(gone).await?; Target::Launch(self.resolve_app(&mut g, &app).await.map_err(Response::error)?) } Check::Foreground => { // the lock is let go before the user is asked (below); the action checks again once it holds it - let mut g = acquire(&self.inner, gone).await?; + let mut g = self.lock_counted(gone).await?; Target::Foreground(self.front_app(&mut g).await?) } }; - task.check_scope(&target, step, gone).await + let asked = task.check_scope(&target, step, gone).await?; + // an unknown screen is never let into the scope: the user allowed this action on it, nothing more + let unknown_approved = asked && target == Target::Foreground(String::new()); + Ok(Gated { asked, unknown_approved }) + } + + /// The device lock for a short look-up on behalf of an action: background checks give way meanwhile + async fn lock_counted( + &self, + gone: &mut Option>, + ) -> Result, Response> { + let _waiting = Waiting::new(self); + acquire(&self.inner, gone).await } /// The app in front, for a scoped task's check. `Err`: why it can't be told, and so nothing is done @@ -1109,27 +1121,47 @@ impl Daemon { /// A scoped task's action on the app in front, checked again once it holds the device lock: the app may have /// changed since [`Self::scope_gate`] looked (it lets the lock go, and a request of the agent's or the user may - /// come in between). Nobody is asked now (that would hold the lock): out of scope by now, it is refused + /// come in between). Nobody is asked now (that would hold the lock): out of scope by now, it is refused. + /// `unknown_approved`: the user just allowed this action on a screen whose app WDA didn't name ([`Gated`]); that + /// screen, still unnamed, is let through, since an unknown app never joins the scope async fn scope_recheck( &self, g: &mut Inner, req: &Request, admission: &crate::tasks::Admission, + unknown_approved: bool, ) -> Result<(), Response> { let crate::tasks::Admission::Actor(t) = admission else { return Ok(()) }; if !t.scoped() || !matches!(crate::tasks::scope_check(req), Some(crate::tasks::Check::Foreground)) { return Ok(()); } let app = self.front_app(g).await?; - if t.within_scope(&crate::tasks::Target::Foreground(app.clone())) { - return Ok(()); - } - Err(crate::tasks::refuse(&ictl_l10n::trf!( - "前台 App 刚变成了任务范围以外的 {app},这一步没有执行。先截图看看再继续", - "The app in front just became {app}, outside the task's scope; this step wasn't done. Take a screenshot before going on" - ))) + recheck_front(t, &app, unknown_approved) + } +} + +/// [`Daemon::scope_recheck`]'s verdict on the app now in front (`""`: WDA didn't name it) +fn recheck_front(t: &crate::tasks::Task, app: &str, unknown_approved: bool) -> Result<(), Response> { + if app.is_empty() { + return if unknown_approved { + Ok(()) + } else { + Err(crate::tasks::refuse(ictl_l10n::tr!( + "看不出前台是哪个 App;这个任务限定了 App 范围,所以这一步没有执行。先截图看看再继续", + "Can't tell which app is in front; this task is limited to some apps, so this step wasn't done. Take a screenshot before going on" + ))) + }; + } + if t.within_scope(&crate::tasks::Target::Foreground(app.into())) { + return Ok(()); } + Err(crate::tasks::refuse(&ictl_l10n::trf!( + "前台 App 刚变成了任务范围以外的 {app},这一步没有执行。先截图看看再继续", + "The app in front just became {app}, outside the task's scope; this step wasn't done. Take a screenshot before going on" + ))) +} +impl Daemon { /// A task's scope from names or bundle IDs: the bundle IDs, each once. `Err` names the app that isn't there pub(crate) async fn resolve_scope(&self, apps: &[String]) -> crate::error::Result> { let apps: Vec<&str> = apps.iter().map(|a| a.trim()).filter(|a| !a.is_empty()).collect(); @@ -1154,6 +1186,7 @@ impl Daemon { mut queued_at: Instant, mut ctx: CallCtx, admission: &crate::tasks::Admission, + unknown_approved: bool, ) -> Response { let text = |r: crate::error::Result| { r.map(|t| Response::text_with(t, crate::protocol::Outcome::default())).unwrap_or_else(Response::error) @@ -1173,38 +1206,55 @@ impl Daemon { } // Web Inspector talks to the page, not to WDA: its own lock, the device lock only to look up the device Lane::Web => { - let mut slot = - match self.lock_admitted(&self.web, &req, admission, &mut queued_at, &mut ctx.gone, false).await { + // a scoped task: the app that shows the page must be in its scope, whatever is in front + let scoped = match admission { + crate::tasks::Admission::Actor(t) if t.scoped() => Some(t.clone()), + _ => None, + }; + // the page's app the user allowed (asked without the lock held), for the next round + let mut approved: Option = None; + loop { + let mut slot = match self + .lock_admitted(&self.web, &req, admission, &mut queued_at, &mut ctx.gone, false) + .await + { Ok(s) => s, - Err(r) => return r, + Err(r) => return r.with_failure(Delivery::NotSent, FailureStage::Preflight), }; - let device = self.inner.lock().await.device.clone(); - if let Err(r) = admit(&req, queued_at, &ctx, device.as_ref().map(|d| d.udid.as_str())) { - return r; - } - let Some(device) = device else { - return Response::error(ictl_l10n::tr!("手机未连接", "Phone not connected")); - }; - return text(match req { - Request::WebTargets => self.web_targets(&mut slot, &device).await, - Request::WebEval { target, expression, timeout_ms } => { - // a scoped task: the app that shows the page must be in its scope, whatever is in front - let scope = match admission { - crate::tasks::Admission::Actor(t) if t.scoped() => Some(t), - _ => None, - }; - let gate = crate::web::Gate { task: scope, step: ctx.task_step, gone: &mut ctx.gone }; - let timeout = Duration::from_millis(timeout_ms); - match self.web_eval(&mut slot, &device, &target, &expression, timeout, gate).await { - Ok(v) => Ok(v), - Err(crate::web::EvalError::Refused(r)) => { + let device = self.inner.lock().await.device.clone(); + if let Err(r) = admit(&req, queued_at, &ctx, device.as_ref().map(|d| d.udid.as_str())) { + return r; + } + let Some(device) = device else { + return Response::error(ictl_l10n::tr!("手机未连接", "Phone not connected")); + }; + let (target, expression, timeout_ms) = match &req { + Request::WebTargets => return text(self.web_targets(&mut slot, &device).await), + Request::WebEval { target, expression, timeout_ms } => (target, expression, *timeout_ms), + _ => unreachable!("lane"), + }; + let scope = scoped.as_deref().map(|task| crate::web::Scope { task, approved: approved.as_deref() }); + let timeout = Duration::from_millis(timeout_ms); + match self.web_eval(&mut slot, &device, target, expression, timeout, scope).await { + Ok(v) => return text(Ok(v)), + Err(crate::web::EvalError::Failed(e)) => return text(Err(e)), + Err(crate::web::EvalError::Refused(r)) => { + return r.with_failure(Delivery::NotSent, FailureStage::Preflight); + } + // the user is asked without the Web Inspector held; then everything is looked up again: the + // task may have been paused or taken over, the page may have gone or changed + Err(crate::web::EvalError::Ask(app)) => { + drop(slot); + let t = scoped.as_ref().expect("asked only for a scoped task"); + let target = crate::tasks::Target::Foreground(app.clone()); + if let Err(r) = t.check_scope(&target, ctx.task_step, &mut ctx.gone).await { return r.with_failure(Delivery::NotSent, FailureStage::Preflight); } - Err(crate::web::EvalError::Failed(e)) => Err(e), + approved = Some(app); + queued_at = Instant::now(); } } - _ => unreachable!("lane"), - }); + } } // an install can take minutes and doesn't hold the device lock; installs queue among themselves Lane::Install => { @@ -1264,7 +1314,7 @@ impl Daemon { if let Err(r) = admit(&req, queued_at, &ctx, g.device.as_ref().map(|d| d.udid.as_str())) { return r.with_failure(Delivery::NotSent, FailureStage::Preflight); } - if let Err(r) = self.scope_recheck(g, &req, admission).await { + if let Err(r) = self.scope_recheck(g, &req, admission, unknown_approved).await { return r.with_failure(Delivery::NotSent, FailureStage::Preflight); } let view = ctx.expect_view.as_deref(); @@ -1604,6 +1654,14 @@ fn gave_way() -> Response { ) } +/// What [`Daemon::scope_gate`] found: whether the user was asked, and whether what they allowed was an action on a +/// screen whose app is unknown (it doesn't join the scope, so [`Daemon::scope_recheck`] needs to know) +#[derive(Debug, Default, Clone, Copy)] +struct Gated { + asked: bool, + unknown_approved: bool, +} + tokio::task_local! { /// A background check is being dispatched ([`ictl_protocol::BACKGROUND`]): it may be dropped halfway for an action /// and has no business with side effects such as restarting the phone's accessibility daemon @@ -1999,24 +2057,51 @@ pub(crate) mod tests { let tap = Request::Tap { x: 1.0, y: 1.0, count: 1 }; let mut g = d.inner.lock().await; let actor = crate::tasks::Admission::Actor(scoped.clone()); - let r = d.scope_recheck(&mut g, &tap, &actor).await; + let r = d.scope_recheck(&mut g, &tap, &actor, false).await; assert!( matches!(&r, Err(Response::Error { message, .. }) if message.contains("看不出前台") || message.contains("Can't tell")), "{r:?}" ); let home = Request::PressButton { button: "home".into() }; - assert!(d.scope_recheck(&mut g, &home, &actor).await.is_ok(), "the way back is never held"); + assert!(d.scope_recheck(&mut g, &home, &actor, false).await.is_ok(), "the way back is never held"); let eval = Request::WebEval { target: String::new(), expression: "1".into(), timeout_ms: 1000 }; - assert!(d.scope_recheck(&mut g, &eval, &actor).await.is_ok(), "the page's app is checked in the Web lane"); - assert!(d.scope_recheck(&mut g, &tap, &crate::tasks::Admission::Free).await.is_ok()); + assert!( + d.scope_recheck(&mut g, &eval, &actor, false).await.is_ok(), + "the page's app is checked in the Web lane" + ); + assert!(d.scope_recheck(&mut g, &tap, &crate::tasks::Admission::Free, false).await.is_ok()); scoped.end(crate::tasks::End::Cancelled, ""); let open = d.tasks.open("y", "test", Some("phone"), Vec::new(), None).unwrap(); - let r = d.scope_recheck(&mut g, &tap, &crate::tasks::Admission::Actor(open)).await; + let r = d.scope_recheck(&mut g, &tap, &crate::tasks::Admission::Actor(open), false).await; assert!(r.is_ok(), "no scope: nothing to look up"); drop(g); std::fs::remove_dir_all(dir).unwrap(); } + /// The app in front, read again with the lock held: within the scope it goes on; another one is refused and + /// named; an unknown one only when the user just allowed acting on an unknown screen (it never joins the scope) + #[test] + fn the_app_in_front_is_judged_again_without_asking() { + let ts = crate::tasks::Tasks::load(None); + let t = ts.open("x", "test", Some("phone"), vec!["com.apple.Preferences".into()], None).unwrap(); + let refused = |r: Result<(), Response>| match r { + Err(Response::Error { message, .. }) => message, + other => panic!("{other:?}"), + }; + assert!(recheck_front(&t, "com.apple.Preferences", false).is_ok()); + assert!(recheck_front(&t, "com.apple.springboard", false).is_ok(), "the home screen is always in scope"); + let m = refused(recheck_front(&t, "com.tencent.xin", false)); + assert!(m.contains("com.tencent.xin"), "{m}"); + assert!( + refused(recheck_front(&t, "com.tencent.xin", true)).contains("com.tencent.xin"), + "allowed was the unknown" + ); + assert!(recheck_front(&t, "", true).is_ok(), "the user just allowed this on an unknown screen"); + let m = refused(recheck_front(&t, "", false)); + assert!(m.contains("看不出前台") || m.contains("Can't tell"), "{m}"); + assert!(!m.contains("的 ,"), "no empty name in the text: {m}"); + } + #[test] fn a_tap_by_text_scrolls_within_bounds() { let tap = |max| Request::TapElement { diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs index e5638b59..e4c5abee 100644 --- a/crates/ictl-daemon/src/lib.rs +++ b/crates/ictl-daemon/src/lib.rs @@ -98,6 +98,8 @@ async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::Resul loop { if woken && ticking.is_none() { woken = false; + // this round is the one asked for: should it not run either, it asks again when it ends + retry = None; ticking = Some((tokio::task::spawn_local(daemon.clone().tick()), true)); } tokio::select! { @@ -107,10 +109,26 @@ async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::Resul // the round that runs ended: an asked-for one that couldn't take the device is asked for again r = async { (&mut ticking.as_mut().expect("guarded").0).await }, if ticking.is_some() => { let asked = ticking.take().is_some_and(|(_, asked)| asked); - if asked && !r.unwrap_or(true) { - retry = Some(tokio::time::Instant::now() + RETRY_ROUND); + match r.unwrap_or(true) { + // a round that ran did what the one waiting to be retried would have + true => retry = None, + false if asked => retry = Some(tokio::time::Instant::now() + RETRY_ROUND), + false => {} } } + // the rounds before new clients: a stream of short connections mustn't starve the supervision (and the + // watchdog's heartbeat it carries) + _ = tick.tick() => { + // 上一轮还没跑完(例如在重启 usbmuxd)就不叠加 + if ticking.is_none() { + ticking = Some((tokio::task::spawn_local(daemon.clone().tick()), false)); + } + } + () = daemon.wake.notified() => woken = true, + () = tokio::time::sleep_until(retry.unwrap_or_else(tokio::time::Instant::now)), if retry.is_some() => { + retry = None; + woken = true; + } Some(_) = conns.join_next(), if !conns.is_empty() => {} // at most MAX_CONNECTIONS clients at once: more wait in the socket's queue r = listener.accept(), if conns.len() < MAX_CONNECTIONS => match r { @@ -123,17 +141,6 @@ async fn serve(cfg: Config, listener: tokio::net::UnixListener) -> anyhow::Resul tokio::time::sleep(std::time::Duration::from_millis(100)).await; } }, - _ = tick.tick() => { - // 上一轮还没跑完(例如在重启 usbmuxd)就不叠加 - if ticking.is_none() { - ticking = Some((tokio::task::spawn_local(daemon.clone().tick()), false)); - } - } - () = daemon.wake.notified() => woken = true, - () = tokio::time::sleep_until(retry.unwrap_or_else(tokio::time::Instant::now)), if retry.is_some() => { - retry = None; - woken = true; - } } } // stopping: new clients are refused at once (instead of waiting in the queue for a reply that never comes), and diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rs index f559e4d4..82e56e9b 100644 --- a/crates/ictl-daemon/src/tools/input.rs +++ b/crates/ictl-daemon/src/tools/input.rs @@ -409,6 +409,10 @@ impl Daemon { )); } }; + // paused, taken over or left while the tree was read or the list moved: nothing is tapped + if !may_continue() { + return Err(Error::preflight(stopped_searching(scrolled + back))); + } self.tap_at(g, x, y).await?; let note = if matches.len() > 1 { ictl_l10n::trf!("(共匹配 {} 个,点的是第 {index} 个)", " ({} matches, tapped number {index})", matches.len()) @@ -1083,11 +1087,11 @@ async fn verify_typed(w: &mut WdaClient, before } } -/// [`Daemon::tap_element`] stopped searching: the task was paused or taken over, or the caller went away +/// [`Daemon::tap_element`] stopped before tapping: the task was paused or taken over, or the caller went away fn stopped_searching(completed: u32) -> String { ictl_l10n::trf!( - "查找目标时被打断(任务暂停、被接管或调用方已离开),此前已完成 {completed} 次滑动,没有点击;请先查看屏幕", - "The scroll search was interrupted (the task was paused or taken over, or the caller went away) after {completed} swipes; nothing was tapped. Look at the screen first" + "点击前被打断(任务暂停、被接管或调用方已离开),此前已完成 {completed} 次滑动,没有点击;请先查看屏幕", + "Interrupted before tapping (the task was paused or taken over, or the caller went away) after {completed} swipes; nothing was tapped. Look at the screen first" ) } diff --git a/crates/ictl-daemon/src/web.rs b/crates/ictl-daemon/src/web.rs index 840ea1dc..59a0a3bc 100644 --- a/crates/ictl-daemon/src/web.rs +++ b/crates/ictl-daemon/src/web.rs @@ -20,16 +20,18 @@ use crate::core::Daemon; /// A kept connection is closed after this long without a request const WEB_IDLE: Duration = Duration::from_secs(5 * 60); -/// A scoped task's check for `WebEval` (`task` is `None` for anyone else) -pub(crate) struct Gate<'a> { - pub task: Option<&'a std::sync::Arc>, - pub step: Option, - pub gone: &'a mut Option>, +/// A scoped task's `WebEval`: the app that shows the page must be in its scope. `approved`: the app the user just +/// allowed (an unknown app, `""`, never joins the scope) +pub(crate) struct Scope<'a> { + pub task: &'a crate::tasks::Task, + pub approved: Option<&'a str>, } -/// Why a page wasn't evaluated: it failed, or the task's scope refused it (a whole answer, passed on as it is) +/// Why a page wasn't evaluated: it failed; the user is to be asked about the page's app (without the Web Inspector +/// held, then again from the start); or, asked already, the page's app is another one now (a whole answer) pub(crate) enum EvalError { Failed(crate::error::Error), + Ask(String), Refused(crate::protocol::Response), } @@ -84,7 +86,7 @@ impl Daemon { target: &str, expression: &str, timeout: Duration, - gate: Gate<'_>, + scope: Option>, ) -> Result { let (apps, pages) = web_pages(slot, device).await?; let page = pick(&pages, target).map_err(|e| match e { @@ -99,11 +101,8 @@ impl Daemon { ), })?; // a task limited to some apps: the app that shows the page, which needn't be the one in front - if let Some(t) = gate.task { - let app = shown_app(page, &apps).map(|a| a.bundle_id.clone()).unwrap_or_default(); - t.check_scope(&crate::tasks::Target::Foreground(app), gate.step, gate.gone) - .await - .map_err(EvalError::Refused)?; + if let Some(s) = scope { + page_in_scope(&s, host_bundle(page, &apps))?; } let conn = slot.as_mut().ok_or(crate::error::Error::from("Web Inspector"))?; conn.used = Instant::now(); @@ -200,6 +199,39 @@ fn shown_app<'a>(p: &Page, apps: &'a [App]) -> Option<&'a App> { app.and_then(|a| a.host.as_deref()).and_then(|h| apps.iter().find(|a| a.id == h)).or(app) } +/// Whether a scoped task may run script in a page shown by `app`: within the scope, or the app the user just +/// allowed; otherwise the user is to be asked, or, asked already about another one, it is refused +fn page_in_scope(s: &Scope<'_>, app: String) -> Result<(), EvalError> { + if s.task.within_scope(&crate::tasks::Target::Foreground(app.clone())) || s.approved == Some(app.as_str()) { + return Ok(()); + } + Err(match s.approved { + None => EvalError::Ask(app), + Some(_) => { + let shown = if app.is_empty() { ictl_l10n::tr!("不明 App", "an unknown app") } else { &app }; + EvalError::Refused(crate::tasks::refuse(&ictl_l10n::trf!( + "页面所在的 App 刚变成了任务范围以外的「{shown}」,脚本没有执行。先用 iphone_web_targets 看看再继续", + "The page's app just became “{shown}”, outside the task's scope; the script wasn't run. Look with iphone_web_targets before going on" + ))) + } + }) +} + +/// The bundle ID of the app that shows a page, for a task's scope; empty when that isn't known for sure: a +/// WebContent process whose host isn't listed (or that is WebKit's own) must not stand for itself, or approving it +/// once would let every unlisted web view in +fn host_bundle(p: &Page, apps: &[App]) -> String { + let Some(app) = apps.iter().find(|a| a.id == p.app_id) else { return String::new() }; + let shown = match app.host.as_deref() { + Some(h) => match apps.iter().find(|a| a.id == h) { + Some(host) => host, + None => return String::new(), + }, + None => app, + }; + if shown.bundle_id.starts_with("com.apple.WebKit.") { String::new() } else { shown.bundle_id.clone() } +} + /// `PID:812/1 WebPage Safari (com.apple.mobilesafari) Title — https://…` fn target_line(p: &Page, apps: &[App]) -> String { let shown = shown_app(p, apps); @@ -249,6 +281,54 @@ mod tests { Page { app_id: app.into(), id, kind: "WebPage".into(), title: title.into(), url: url.into(), in_use: false } } + /// The app a scoped task's script runs in: the host a WebContent process renders for; unknown (`""`, never let + /// into the scope) when the host isn't listed or the process is WebKit's own + #[test] + fn a_page_s_app_for_the_scope_is_its_host_or_unknown() { + let app = |id: &str, bundle: &str, host: Option<&str>| App { + id: id.into(), + name: bundle.into(), + bundle_id: bundle.into(), + host: host.map(Into::into), + active: true, + }; + let apps = [ + app("PID:1", "com.apple.mobilesafari", None), + app("PID:2", "com.apple.WebKit.WebContent", Some("PID:1")), + app("PID:3", "com.apple.WebKit.WebContent", Some("PID:9")), + app("PID:4", "com.apple.WebKit.WebContent", None), + app("PID:5", "com.example.app", None), + ]; + let host = |a: &str| host_bundle(&page(a, 1, "https://x", "x"), &apps); + assert_eq!(host("PID:1"), "com.apple.mobilesafari"); + assert_eq!(host("PID:2"), "com.apple.mobilesafari", "WebContent stands in for its host"); + assert_eq!(host("PID:3"), "", "host not listed: unknown, not WebContent itself"); + assert_eq!(host("PID:4"), "", "WebKit's own process"); + assert_eq!(host("PID:5"), "com.example.app"); + assert_eq!(host("PID:7"), "", "an app not listed at all"); + } + + /// Asked once, without the Web Inspector held; the round after the user said yes runs only on that same app + #[test] + fn a_page_outside_the_scope_is_asked_about_once() { + let ts = crate::tasks::Tasks::load(None); + let task = ts.open("x", "test", Some("phone"), vec!["com.apple.Preferences".into()], None).unwrap(); + let first = Scope { task: &task, approved: None }; + assert!(page_in_scope(&first, "com.apple.Preferences".into()).is_ok()); + assert!( + matches!(page_in_scope(&first, "com.apple.mobilesafari".into()), Err(EvalError::Ask(a)) if a == "com.apple.mobilesafari") + ); + assert!(matches!(page_in_scope(&first, String::new()), Err(EvalError::Ask(a)) if a.is_empty())); + let unknown = Scope { task: &task, approved: Some("") }; + assert!(page_in_scope(&unknown, String::new()).is_ok(), "the unknown app the user allowed"); + let r = page_in_scope(&unknown, "com.tencent.xin".into()); + assert!( + matches!(&r, Err(EvalError::Refused(crate::protocol::Response::Error { message, .. })) if message.contains("com.tencent.xin")) + ); + let safari = Scope { task: &task, approved: Some("com.apple.mobilesafari") }; + assert!(matches!(page_in_scope(&safari, String::new()), Err(EvalError::Refused(_))), "not asked twice"); + } + #[test] fn only_a_page_timeout_keeps_the_connection() { use ictl_webinspector::Error; diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index fe55fd2a..bb708c50 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -190,8 +190,8 @@ | 184 | 浏览器解不了 HEVC 时,每个看手机原生视频的控制台页面各起一个 ffmpeg 解 60 帧的 HEVC 再编 H.264,没有上限:开几个页面就能把主机 CPU 或显卡的编码会话占满 | 同时最多 4 个页面转码(`transcode::Slots`),再多的回 503(`Retry-After`),页面显示「画面断开 · 自动重试中」、等有页面关掉后接上;日志每分钟最多记一次 | 单测 `transcoding_pages_are_limited_and_their_places_come_back` + 真机 | | 185 | 控制台页面各自定时轮询:`/api/info` 每 2 秒、任务列表每 3 秒、设备面板每 10 秒三个请求(`/api/daemon`、`/api/devices` 读的是同一份快照),后台标签页也照常轮询;几个页面开着时守护进程的请求成倍增加 | 任务列表随 `/api/info?tasks=1` 一起取(只在页面要接任务时带上);`/api/daemon` 带上设备列表,一轮两个请求;页面在后台时 `/api/info`、设备面板、弹窗检查都不问,切回前台立刻补一次 | 页面测试 `a task list from the info poll is used as it is` 和原有的任务接续测试 + 真机 | | 186 | 守护进程开着 HID 会话就退出(看门狗判定卡死后 `exit(1)`、崩溃、kill -9):屏幕媒体流没停,手机一直显示「正在被查看」、一直不自动锁屏(iPhone 15 Pro Max iOS 27.2.1:kill -9 后 5 分钟仍是这样),直到下次有程序开了再正常关 HID。看门狗退出时拿不到设备锁,没法先收尾 | 开 HID 时写 `hid-open/`,正常关掉时删;启动时发现残留的,等那台手机就绪后开一下 HID 再正常关掉(最多试 3 次),事件日志记一笔 | 单测 `markers_outlive_the_process_until_cleared` + 真机(开着 HID 时 kill -9 守护进程,看灵动岛的图标) | -| 191 | 原生控制(iOS 27)下,后台检查(控制台的弹窗、状态轮询)给操作让路时在无障碍请求中途被丢掉:DTX 会话的流停在半条消息上,下一个请求读到错位的应答;后台检查读不到应答时还会重启手机的 axauditd | 请求中途被丢掉时把会话标记为作废,下次重新打开;写入 5 秒超时(算 I/O 超时,不触发重启 axauditd);连接关闭时结束等待;后台检查(`core::BACKGROUND`)不重启 axauditd | 单测 `a_cancelled_request_abandons_the_session`、`an_unanswered_request_keeps_the_session`、`a_closed_connection_ends_the_wait` + 真机(iPhone 15 Pro Max iOS 27.2.1:两个线程以 background 标记连续发弹窗检查和状态,同时做 24 个操作 ×2 轮:操作 0 失败,9000 多次后台检查都让路,日志里没有重连或重启 axauditd;操作停下 4 秒后后台检查照常应答) | +| 191 | 原生控制(iOS 27)下,后台检查(控制台的弹窗、状态轮询)给操作让路时在无障碍请求中途被丢掉:DTX 会话的流停在半条消息上,下一个请求读到错位的应答;后台检查读不到应答时还会重启手机的 axauditd | 请求中途被丢掉时把会话标记为作废并停掉它的读循环(不再往那条流上回应答),下次重新打开;写入(包括读循环回应答)5 秒超时(算 I/O 超时,不触发重启 axauditd);连接关闭时结束等待;后台检查(`core::BACKGROUND`)不重启 axauditd | 单测 `a_cancelled_request_abandons_the_session`、`an_unanswered_request_keeps_the_session`、`a_closed_connection_ends_the_wait` + 真机(iPhone 15 Pro Max iOS 27.2.1:两个线程以 background 标记连续发弹窗检查和状态,同时做 24 个操作 ×2 轮:操作 0 失败,9000 多次后台检查都让路,日志里没有重连或重启 axauditd;操作停下 4 秒后后台检查照常应答) | | 192 | 任务暂停时排队的操作一直算在「等设备的操作」里:暂停多久,控制台的后台检查就让路多久 | 只在等设备锁时计数,等任务恢复时不算;Web 通道的锁不算 | 单测 `waiting_for_a_paused_task_doesnt_hold_off_the_checks` | | 193 | 守护进程主循环:要求的一轮巡检因设备忙没跑成时,只在循环下一次醒来时才发现,可能要等 10 秒的定时巡检;同时服务的连接数没有上限 | 直接等这一轮结束,没跑成就 200 毫秒后再要一轮;同时最多 256 个连接,更多的留在套接字队列里;先收割结束的连接再接受新的 | 真机(iPhone 和 iPad 之间来回切换:切回 iPhone 0.66 秒就绪,切到 iPad 2 秒就绪) | -| 194 | 限定 App 范围的任务:检查前台 App 后放开设备锁、等真正操作时前台可能已经换了;`iphone_web_eval` 按前台 App 检查,而不是显示页面的 App | 操作拿到设备锁后再查一次前台 App(不再问用户,越界就拒绝);`web_eval` 选定页面后按它的宿主 App 检查(`Check::Page`),不再先查前台 | 单测 `a_scoped_action_is_checked_again_with_the_lock_held`、`what_each_request_checks_against_the_scope`、`an_approved_app_joins_the_scope_for_the_rest_of_the_task` + 真机(范围只有设置的任务:边滑边找、点击、启动设置都照常;打开备忘录被询问、拒绝后不执行;Safari 在前台时 `web_eval` 被询问一次,拒绝后不执行,同意后执行,之后不再问) | -| 195 | 直接走协议的 `TapElement.scroll.max` 没有上限(`u32::MAX` 能占着手机几个小时);边滑边找和 `wait_for` 在任务暂停或调用方离开后照样跑到底 | 守护进程也只收 1 到 15 次;每次滑动前、每轮等待之间都问一次能不能继续,不能就停下(边滑边找不点击) | 单测 `a_tap_by_text_scrolls_within_bounds` + 真机(`max` 16 和 0 都被拒绝;`wait_for` 等 20 秒,2.5 秒时暂停任务,2.7 秒返回「被打断」;边滑边找时暂停,滑了 1 次就停下、没有点击) | +| 194 | 限定 App 范围的任务:检查前台 App 后放开设备锁、等真正操作时前台可能已经换了;`iphone_web_eval` 按前台 App 检查,而不是显示页面的 App | 操作拿到设备锁后再查一次前台 App(不再问用户,越界就拒绝;用户刚同意在不明 App 上操作、前台仍不明的放行);`web_eval` 选定页面后按它的宿主 App 检查(`Check::Page`),不再先查前台:要问用户时先放开 Web Inspector 的锁,同意后从头再来(重新排队、查任务状态、选页面),这时页面换到别的范围外 App 就拒绝;宿主不明(WebContent 找不到宿主、WebKit 自己的进程)按不明 App 处理,同意了也不加进范围 | 单测 `a_scoped_action_is_checked_again_with_the_lock_held`、`the_app_in_front_is_judged_again_without_asking`、`a_page_outside_the_scope_is_asked_about_once`、`a_page_s_app_for_the_scope_is_its_host_or_unknown`、`what_each_request_checks_against_the_scope`、`an_approved_app_joins_the_scope_for_the_rest_of_the_task` + 真机(范围只有设置的任务:边滑边找、点击、启动设置都照常;打开备忘录被询问、拒绝后不执行;Safari 在前台时 `web_eval` 被询问一次,拒绝后不执行,同意后执行,之后不再问) | +| 195 | 直接走协议的 `TapElement.scroll.max` 没有上限(`u32::MAX` 能占着手机几个小时);边滑边找和 `wait_for` 在任务暂停或调用方离开后照样跑到底 | 守护进程也只收 1 到 15 次;每次滑动前、点击前、每轮等待之间都问一次能不能继续,不能就停下(不点击) | 单测 `a_tap_by_text_scrolls_within_bounds` + 真机(`max` 16 和 0 都被拒绝;`wait_for` 等 20 秒,2.5 秒时暂停任务,2.7 秒返回「被打断」;边滑边找时暂停,滑了 1 次就停下、没有点击) |