Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ What changed in each release, one line per change. Versions follow [Semantic Ver

### Fixes

- When pressing Home finds a system alert in the way, the daemon's answer now also marks it in its structured result (`alert_reported`), as launching an app or opening a link does; programs reading the result rather than its text missed it (#200).
- A long press falls back to HID like a tap when WebDriverAgent can't be reached (#200).
- Requests that can't run (a tap count of 0, an empty tap sequence, an unknown button, a point that isn't a number) are refused at once, before waiting for the phone and without dropping the cached screen (#200).
- The control page getting ready for a touch no longer counts as acting: it isn't refused while an AI task runs and doesn't make the agent look again after you take over (#200).
- Requests for a list scan sent by a newer client with extra fields are no longer refused by an older daemon (#200).
- Auto-unlock refuses a saved passcode shorter than 4 digits, as `passcode set` does; `state.json` is no longer replaced by an empty file if it can't be written out; notification keys are never shown in debug output (#200).

- iPads with Touch ID in a language other than Chinese or English: the "Touch ID" prompt after swiping up is known as the lock screen, and auto-unlock taps "Use Passcode" on it; the iPad was taken for unlocked and never checked again (#198).
- A malformed accessibility answer from the phone (iOS 27+) can no longer keep the daemon busy for ever; a malformed touch (a coordinate or duration that isn't a number) is refused instead of crashing or tapping the top-left corner (#198).
- The phone's log is read from now on only: the daemon took old lines for new, such as a past "Enable UI Automation" prompt, and `iphone_app_logs` showed them as just logged (#198).
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@

### 修复

- 按 Home 时发现有系统弹窗挡着,守护进程的应答现在也会在结构化结果里标出(`alert_reported`),和启动 App、打开链接一样;之前只读结果字段、不看文字的程序会漏掉(#200)。
- 长按和点击一样,连不上 WebDriverAgent 时改用 HID(#200)。
- 执行不了的请求(点击次数为 0、空的点击序列、不认识的按键、坐标不是有效数字)立刻拒绝,不再先排队等手机,也不会清掉缓存的界面(#200)。
- 控制台准备触摸不再算作操作:AI 任务进行中不会被拒,你接管时也不会让 agent 之后重新看一遍(#200)。
- 新版客户端发来带额外字段的列表滚动收集请求,旧版守护进程不再拒绝(#200)。
- 自动解锁不再接受不足 4 位的已存密码,和 `passcode set` 一致;`state.json` 写不出来时不会被换成空文件;通知密钥不会出现在调试输出里(#200)。

- 界面语言不是中文或英文的 Touch ID iPad:上滑后的「触控 ID」提示也认作锁屏,自动解锁会点上面的「使用密码」;之前会把锁着的 iPad 当成已解锁,之后再也不查(#198)。
- 手机(iOS 27 起)发来格式异常的无障碍应答,不会再让守护进程一直忙下去;坐标或时长不是有效数字的触摸会被拒绝,不再崩溃或点到左上角(#198)。
- 手机日志只读从现在起产生的:之前守护进程会把旧日志当成新的(比如以前出现过的「Enable UI Automation」密码框),`iphone_app_logs` 也会把它们当成刚记下的(#198)。
Expand Down
33 changes: 32 additions & 1 deletion crates/ictl-daemon/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,27 @@ impl IosBackend {
}
}

#[derive(Debug, Clone, Default)]
#[derive(Clone, Default)]
pub struct NotifyConfig {
pub tg_bot_token: Option<String>,
pub tg_chat_id: Option<String>,
pub bark_server: String,
pub bark_key: Option<String>,
}

/// Written out (a `{:?}` of the [`Config`] in a log or a panic) without the keys: only whether each is set
impl std::fmt::Debug for NotifyConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let set = |v: &Option<String>| if v.is_some() { "<set>" } else { "<unset>" };
f.debug_struct("NotifyConfig")
.field("tg_bot_token", &set(&self.tg_bot_token))
.field("tg_chat_id", &set(&self.tg_chat_id))
.field("bark_server", &self.bark_server)
.field("bark_key", &set(&self.bark_key))
.finish()
}
}

impl NotifyConfig {
pub fn any(&self) -> bool {
(self.tg_bot_token.is_some() && self.tg_chat_id.is_some()) || self.bark_key.is_some()
Expand Down Expand Up @@ -200,3 +213,21 @@ impl Config {
Ok(())
}
}

#[cfg(test)]
mod tests {
use super::*;

/// A debug print of the settings shows whether a key is set, never the key
#[test]
fn notification_keys_stay_out_of_debug_output() {
let n = NotifyConfig {
tg_bot_token: Some("123:secret-token".into()),
tg_chat_id: Some("42".into()),
bark_server: "https://api.day.app".into(),
bark_key: Some("bark-secret".into()),
};
let s = format!("{n:?}");
assert!(!s.contains("secret") && s.contains("<set>") && s.contains("api.day.app"), "{s}");
}
}
94 changes: 83 additions & 11 deletions crates/ictl-daemon/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,13 +274,16 @@ impl Persisted {
pub(crate) fn save(&self, path: &Path) {
use std::io::Write;
let tmp = path.with_extension("json.tmp");
// sync before the rename, or a power cut can leave state.json empty
let r = std::fs::File::create(&tmp)
.and_then(|mut f| {
f.write_all(&serde_json::to_vec_pretty(self).unwrap_or_default())?;
f.sync_all()
})
.and_then(|_| std::fs::rename(&tmp, path));
// nothing written when it doesn't serialize: an empty file in its place would lose the whole state
let r = serde_json::to_vec_pretty(self).map_err(std::io::Error::other).and_then(|data| {
// sync before the rename, or a power cut can leave state.json empty
std::fs::File::create(&tmp)
.and_then(|mut f| {
f.write_all(&data)?;
f.sync_all()
})
.and_then(|_| std::fs::rename(&tmp, path))
});
if let Err(e) = r {
tracing::warn!("{}", ictl_l10n::log_trf!("保存 state.json 失败:{e}", "Saving state.json failed: {e}"));
}
Expand Down Expand Up @@ -1440,7 +1443,10 @@ impl Daemon {
message
})
}
Request::PressButton { button } => self.press_button(g, &button, watched).await,
Request::PressButton { button } => self.press_button(g, &button, watched).await.map(|(t, alert)| {
outcome.alert_reported = alert;
t
}),
Request::Touch { phase, x, y } => {
return self
.touch(g, phase, x, y, view)
Expand Down Expand Up @@ -1755,9 +1761,43 @@ fn check_request(req: &Request) -> Result<(), String> {
MAX_WAIT_MS / 1000
));
}
Request::Touch { x, y, .. } if !x.is_finite() || !y.is_finite() => {
Request::Touch { x, y, .. } | Request::Tap { x, y, .. } | Request::LongPress { x, y, .. }
if !x.is_finite() || !y.is_finite() =>
{
return Err(ictl_l10n::tr!("x、y 要是有效的数", "x and y must be valid numbers").into());
}
Request::Swipe { from, to, .. } if ![from.0, from.1, to.0, to.1].iter().all(|v| v.is_finite()) => {
return Err(
ictl_l10n::tr!("起点、终点要是有效的数", "the start and end points must be valid numbers").into()
);
}
// checked before the device lock is taken and the element cache dropped: a request that can't run doesn't
// cost the next one its cached tree
Request::Tap { count, .. } if !(1..=crate::protocol::MAX_TAP_COUNT).contains(count) => {
return Err(ictl_l10n::trf!(
"count 要是 1 到 {} 的整数",
"count must be a whole number from 1 to {}",
crate::protocol::MAX_TAP_COUNT
));
}
Request::TapSequence { points }
if points.is_empty()
|| points.len() > crate::protocol::MAX_SEQUENCE_POINTS
|| !points.iter().all(|(x, y)| x.is_finite() && y.is_finite()) =>
{
return Err(ictl_l10n::trf!(
"一个手势要点 1 到 {} 个点,坐标要是有效的数",
"a gesture takes 1 to {} points, with valid numbers",
crate::protocol::MAX_SEQUENCE_POINTS
));
}
Request::PressButton { button } if ictl_device::hid::Button::parse(button).is_none() => {
return Err(ictl_l10n::tr!(
"button 只能是 home / volume_up / volume_down / lock",
"button must be home / volume_up / volume_down / lock"
)
.into());
}
Request::AppLogs { since_secs, limit, .. } if *since_secs > 3600 || *limit == 0 || *limit > 1000 => {
return Err(ictl_l10n::tr!(
"since 最多 3600 秒,limit 要在 1 到 1000 之间",
Expand Down Expand Up @@ -1813,8 +1853,12 @@ pub(crate) mod tests {
assert!(!crate::tasks::observes(&req), "this cannot clear a takeover's observation requirement");
let mut wire = serde_json::to_value(&req).unwrap();
assert_eq!(serde_json::from_value::<Request>(wire.clone()).unwrap(), req);
wire["scroll"] = serde_json::json!("sideways");
assert!(serde_json::from_value::<Request>(wire).is_err(), "unknown direct protocol fields must fail");
// a key this daemon doesn't know (a newer client's) is ignored, as for every other request
wire["added_by_a_newer_client"] = serde_json::json!(true);
assert_eq!(serde_json::from_value::<Request>(wire.clone()).unwrap(), req);
// the scan's own fields are still checked: a wrong type is an error
wire["max_scrolls"] = serde_json::json!("sideways");
assert!(serde_json::from_value::<Request>(wire).is_err());
for (max, limit) in [(0, 1), (16, 1), (1, 0), (1, 151)] {
scan.max_scrolls = max;
scan.limit = limit;
Expand Down Expand Up @@ -2102,6 +2146,34 @@ pub(crate) mod tests {
assert!(!m.contains("的 ,"), "no empty name in the text: {m}");
}

/// Requests that can't run are refused before they take the device lock and drop the cached tree
#[test]
fn hopeless_requests_are_refused_up_front() {
let bad = [
Request::Tap { x: 1.0, y: 1.0, count: 0 },
Request::Tap { x: 1.0, y: 1.0, count: crate::protocol::MAX_TAP_COUNT + 1 },
Request::Tap { x: f64::NAN, y: 1.0, count: 1 },
Request::LongPress { x: 1.0, y: f64::INFINITY, seconds: 1.0 },
Request::Swipe { from: (1.0, f64::NAN), to: (1.0, 2.0), seconds: 0.3, hold: 0.0 },
Request::TapSequence { points: vec![] },
Request::TapSequence { points: vec![(1.0, 1.0); crate::protocol::MAX_SEQUENCE_POINTS + 1] },
Request::TapSequence { points: vec![(1.0, f64::NAN)] },
Request::PressButton { button: "power".into() },
];
for r in bad {
assert!(check_request(&r).is_err(), "{r:?}");
}
let good = [
Request::Tap { x: 1.0, y: 1.0, count: crate::protocol::MAX_TAP_COUNT },
Request::TapSequence { points: vec![(1.0, 1.0); crate::protocol::MAX_SEQUENCE_POINTS] },
Request::PressButton { button: "home".into() },
Request::PressButton { button: "volume_up".into() },
];
for r in good {
assert!(check_request(&r).is_ok(), "{r:?}");
}
}

#[test]
fn a_tap_by_text_scrolls_within_bounds() {
let tap = |max| Request::TapElement {
Expand Down
16 changes: 16 additions & 0 deletions crates/ictl-daemon/src/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1289,6 +1289,8 @@ mod tests {
assert!(matches!(admit(&ts, &shot, None).await, Ok((Admission::Free, _))));
let up = Request::Touch { phase: TouchPhase::Up, x: 0.0, y: 0.0 };
assert!(admit(&ts, &up, None).await.is_ok(), "a finger that was down can always be lifted");
let prepare = Request::Touch { phase: TouchPhase::Prepare, x: 0.0, y: 0.0 };
assert!(matches!(admit(&ts, &prepare, None).await, Ok((Admission::Free, _))), "getting ready touches nothing");
let select = Request::SelectDevice { device: "auto".into() };
assert!(admit(&ts, &select, None).await.is_err());

Expand Down Expand Up @@ -1333,6 +1335,20 @@ mod tests {
assert!(message(r).contains("取消"));
}

/// The page getting ready for a touch isn't an action: let through while the task runs, and while the user has
/// taken over it doesn't count as the user acting (a [`Admission::Supervisor`])
#[tokio::test]
async fn getting_ready_for_a_touch_is_not_acting() {
let ts = tasks();
let t = open(&ts);
let prepare = Request::Touch { phase: TouchPhase::Prepare, x: 0.0, y: 0.0 };
t.control("takeover", None, false, None).unwrap();
assert!(matches!(admit(&ts, &prepare, None).await, Ok((Admission::Free, _))));
assert!(matches!(admit(&ts, &tap(), None).await, Ok((Admission::Supervisor(_), _))), "a tap is acting");
assert!(!prepare.is_device_action());
assert!(Request::Touch { phase: TouchPhase::Down, x: 0.0, y: 0.0 }.is_device_action());
}

#[tokio::test]
async fn after_someone_else_acted_the_agent_looks_before_acting() {
let ts = tasks();
Expand Down
31 changes: 24 additions & 7 deletions crates/ictl-daemon/src/tools/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,6 @@ impl Daemon {
"No finger is down; send down first"
)));
};
if !contact {
g.dev.touch_rotation = None;
}
// Reuse the open session without another WDA screen-size lookup on every move.
let h = match g.tunnel.as_mut().and_then(|t| t.open_hid()) {
Some(h) => h,
Expand All @@ -256,6 +253,8 @@ impl Daemon {
let result = Box::pin(h.touch(contact, x, y)).await;
g.hid_used = Some(Instant::now());
match result {
// the finger is up once that was sent, not before: an up refused below leaves it down, to be lifted
Ok(()) if !contact => g.dev.touch_rotation = None,
Ok(()) => {}
// refused before anything was sent (a point that isn't a number, an unknown screen size): the tunnel and
// its sessions are fine; a finger that is down stays where it was
Expand Down Expand Up @@ -454,14 +453,32 @@ impl Daemon {
view: Option<&str>,
) -> crate::error::Result<String> {
self.prepare_coordinates(g, view, true).await.map_err(Error::preflight)?;
match self.route(g) {
Route::Wda(w) => w.touch_and_hold(x, y, seconds).await.map_err(Error::wda_input)?,
Route::Native => Box::pin(self.native_long_press(g, x, y, seconds)).await?,
// as for a tap: without WDA (or when it can't be reached) by HID where the phone has it, unless the point was
// measured on the page's view through WDA
let by_hid = match self.route(g) {
Route::Wda(w) => match w.touch_and_hold(x, y, seconds).await {
Ok(()) => false,
Err(WdaError::Unavailable(_)) if view.is_none() && hid_supported(g.info.as_ref()) => true,
Err(e) => return Err(Error::wda_input(e)),
},
Route::Native => true,
Route::Hid if view.is_none() => true,
Route::Hid | Route::Unavailable => {
return Err(Error::preflight(wda_down(&g.state, g.info.as_ref())));
}
};
if by_hid {
Box::pin(self.native_long_press(g, x, y, seconds)).await?;
}
let (px, py, s) = (fmt_g(x), fmt_g(y), fmt_g(seconds));
// said like the other gestures when HID stood in for WDA (natively it is the way, not a fallback)
if by_hid && !self.native(g) {
return Ok(ictl_l10n::trf!(
"已长按 ({px},{py}) {s} 秒(经 HID)",
"Long-pressed ({px},{py}) for {s} s (via HID)"
));
}
Ok(ictl_l10n::trf!("已长按 ({},{}) {} 秒", "Long-pressed ({},{}) for {} s", fmt_g(x), fmt_g(y), fmt_g(seconds)))
Ok(ictl_l10n::trf!("已长按 ({px},{py}) {s} 秒", "Long-pressed ({px},{py}) for {s} s"))
}

pub(crate) async fn swipe(
Expand Down
30 changes: 18 additions & 12 deletions crates/ictl-daemon/src/tools/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ impl Daemon {
g: &mut Inner,
button: &str,
watched: bool,
) -> crate::error::Result<String> {
) -> crate::error::Result<(String, bool)> {
let hid_button = Button::parse(button).ok_or(ictl_l10n::tr!(
"button 只能是 home / volume_up / volume_down / lock",
"button must be home / volume_up / volume_down / lock"
))?;
let wda_name = match hid_button {
Button::Lock => return self.lock_screen(g).await,
Button::Lock => return self.lock_screen(g).await.map(|t| (t, false)),
Button::Home => "home",
Button::VolumeUp => "volumeUp",
Button::VolumeDown => "volumeDown",
Expand All @@ -30,10 +30,13 @@ impl Daemon {
&& !watched
&& let Ok(Some(text)) = w.alert_text().await
{
return Ok(ictl_l10n::trf!(
"{},按 Home 不会生效,没有按;{TAP_ALERT}",
"{}, pressing Home would have no effect, not pressed; {TAP_ALERT_EN}",
blocking(&text)
return Ok((
ictl_l10n::trf!(
"{},按 Home 不会生效,没有按;{TAP_ALERT}",
"{}, pressing Home would have no effect, not pressed; {TAP_ALERT_EN}",
blocking(&text)
),
true,
));
}
let mut home_worked = None;
Expand All @@ -52,17 +55,20 @@ impl Daemon {
&& r.is_ok()
&& let Ok(Some(text)) = w.alert_text().await
{
return Ok(ictl_l10n::trf!(
"{},按 Home 没有生效,先点弹窗上的按钮",
"{}, pressing Home had no effect; first tap a button on the alert",
blocking(&text)
return Ok((
ictl_l10n::trf!(
"{},按 Home 没有生效,先点弹窗上的按钮",
"{}, pressing Home had no effect; first tap a button on the alert",
blocking(&text)
),
true,
));
}
if let Some(via_xctest) = home_worked {
self.learn(g, |w| w.home_via_xctest = via_xctest);
}
match r {
Ok(text) => return Ok(text),
Ok(text) => return Ok((text, false)),
Err(WdaError::Unavailable(_)) => {}
Err(e) => return Err(e.into()),
}
Expand All @@ -71,7 +77,7 @@ impl Daemon {
return Box::pin(self.native_home(g, watched)).await;
}
self.hid_do(g, |h| Box::pin(h.press(hid_button))).await?;
Ok(ictl_l10n::trf!("已按 {button}", "Pressed {button}"))
Ok((ictl_l10n::trf!("已按 {button}", "Pressed {button}"), false))
}

pub(super) async fn lock_screen(&self, g: &mut Inner) -> crate::error::Result<String> {
Expand Down
Loading
Loading