From 8c11b201bd53a8f48629e5946972d71a66a135a1 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:31:26 +0800 Subject: [PATCH 1/5] refactor(mcp): split lib.rs by what each part does ictl-mcp's lib.rs had grown to 2,200 lines: tool definitions, argument checking, batch steps, results and the server in one file. It is now schema.rs (instructions and tool definitions), args.rs (checking and turning arguments into requests), batch.rs (iphone_batch steps), result.rs (answers to tool results, input delivery), server.rs (McpServer over stdio and HTTP) and tests.rs. lib.rs re-exports them, so the crate's interface is unchanged. A pure move: concatenated and with whitespace ignored the modules are the old file; only `pub(crate)` was added where one module uses another's items, and rustfmt dropped a few trailing commas in the tests. Co-authored-by: Claude Opus 5.5 --- crates/ictl-mcp/src/args.rs | 322 +++++ crates/ictl-mcp/src/batch.rs | 96 ++ crates/ictl-mcp/src/lib.rs | 2222 +-------------------------------- crates/ictl-mcp/src/result.rs | 162 +++ crates/ictl-mcp/src/schema.rs | 571 +++++++++ crates/ictl-mcp/src/server.rs | 430 +++++++ crates/ictl-mcp/src/tests.rs | 616 +++++++++ docs/tools.md | 2 +- 8 files changed, 2215 insertions(+), 2206 deletions(-) create mode 100644 crates/ictl-mcp/src/args.rs create mode 100644 crates/ictl-mcp/src/batch.rs create mode 100644 crates/ictl-mcp/src/result.rs create mode 100644 crates/ictl-mcp/src/schema.rs create mode 100644 crates/ictl-mcp/src/server.rs create mode 100644 crates/ictl-mcp/src/tests.rs diff --git a/crates/ictl-mcp/src/args.rs b/crates/ictl-mcp/src/args.rs new file mode 100644 index 0000000..226cc52 --- /dev/null +++ b/crates/ictl-mcp/src/args.rs @@ -0,0 +1,322 @@ +use super::*; + +pub(crate) struct Args<'a>(pub(crate) &'a Map); + +/// 数字,或写成字符串的数字(toolkit 的 pydantic 也接受 "3") +pub(crate) fn number(v: &Value) -> Option { + v.as_f64().or_else(|| v.as_str()?.trim().parse().ok()).filter(|x: &f64| x.is_finite()) +} + +/// 参数给了但类型不对就报错,不再悄悄用默认值(例如 index: -1 原来会点第 0 个) +impl Args<'_> { + pub(crate) fn get(&self, k: &str) -> Option<&Value> { + self.0.get(k).filter(|v| !v.is_null()) + } + pub(crate) fn f(&self, k: &str) -> Result { + self.opt_f(k)?.ok_or_else(|| ictl_l10n::trf!("缺少数字参数 {k}", "missing number parameter {k}")) + } + pub(crate) fn f_or(&self, k: &str, d: f64) -> Result { + Ok(self.opt_f(k)?.unwrap_or(d)) + } + pub(crate) fn opt_f(&self, k: &str) -> Result, String> { + self.get(k) + .map(|v| number(v).ok_or_else(|| ictl_l10n::trf!("参数 {k} 要是数字", "parameter {k} must be a number"))) + .transpose() + } + pub(crate) fn s(&self, k: &str) -> Result { + self.get(k) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| ictl_l10n::trf!("缺少文字参数 {k}", "missing text parameter {k}")) + } + pub(crate) fn s_or(&self, k: &str, d: &str) -> Result { + match self.get(k) { + None => Ok(d.to_owned()), + Some(v) => v + .as_str() + .map(str::to_owned) + .ok_or_else(|| ictl_l10n::trf!("参数 {k} 要是文字", "parameter {k} must be text")), + } + } + pub(crate) fn u_or(&self, k: &str, d: usize) -> Result { + match self.get(k) { + None => Ok(d), + Some(v) => number(v).filter(|x| *x >= 0.0 && x.fract() == 0.0).map(|x| x as usize).ok_or_else(|| { + ictl_l10n::trf!("参数 {k} 要是非负整数", "parameter {k} must be a non-negative integer") + }), + } + } + /// 连点次数:不给是 1,给了要是 1 到 [`MAX_TAP_COUNT`] 的整数 + pub(crate) fn count(&self, k: &str) -> Result { + match self.u_or(k, 1)? { + n @ 1.. if n <= MAX_TAP_COUNT as usize => Ok(n as u32), + _ => Err(ictl_l10n::trf!( + "参数 {k} 要是 1 到 {MAX_TAP_COUNT} 的整数", + "parameter {k} must be a whole number from 1 to {MAX_TAP_COUNT}" + )), + } + } + pub(crate) fn b_or(&self, k: &str, d: bool) -> Result { + match self.get(k) { + None => Ok(d), + Some(Value::Bool(b)) => Ok(*b), + Some(Value::String(s)) if s.eq_ignore_ascii_case("true") => Ok(true), + Some(Value::String(s)) if s.eq_ignore_ascii_case("false") => Ok(false), + Some(_) => Err(ictl_l10n::trf!("参数 {k} 要是 true 或 false", "parameter {k} must be true or false")), + } + } +} + +/// 工具调用 → 守护进程请求 +/// `iphone_tap_element` 的 `scroll` / `max_scrolls`:没给 scroll 时不滑 +pub(crate) fn scroll_search(a: &Args) -> Result, String> { + let dir = a.s_or("scroll", "")?; + let max = a.u_or("max_scrolls", 8)?; + if dir.is_empty() { + return Ok(None); + } + checked_scroll(&dir, max).map(Some) +} + +pub(crate) fn checked_scroll(dir: &str, max: usize) -> Result { + let down = match dir { + "down" => true, + "up" => false, + _ => return Err(ictl_l10n::trf!("参数 scroll 要是 down 或 up", "parameter scroll must be down or up")), + }; + if max == 0 || max > ictl_protocol::MAX_SEARCH_SCROLLS as usize { + return Err(ictl_l10n::trf!( + "参数 max_scrolls 要在 1 到 {} 之间", + "parameter max_scrolls must be between 1 and {}", + ictl_protocol::MAX_SEARCH_SCROLLS + )); + } + Ok(protocol::ScrollSearch { down, max: max as u32 }) +} + +pub fn to_request(name: &str, args: &Map) -> Result { + let a = Args(args); + Ok(match name { + "iphone_status" => Request::Status, + "iphone_screenshot" => { + let r = [a.opt_f("x")?, a.opt_f("y")?, a.opt_f("width")?, a.opt_f("height")?]; + let region = match r { + [None, None, None, None] => None, + [Some(x), Some(y), Some(w), Some(h)] => Some((x, y, w, h)), + _ => { + return Err(ictl_l10n::tr!( + "放大区域要同时给出 x、y、width、height", + "a zoom region needs all of x, y, width and height" + ) + .into()); + } + }; + Request::Screenshot { region } + } + "iphone_list_elements" => Request::ListElements { + filter: a.s_or("filter", "")?, + limit: a.u_or("limit", 150)?, + max_age_ms: 0, + keep_locked: false, + }, + "iphone_scroll_collect" => { + let limit = a.u_or("limit", protocol::MAX_SCROLL_ROWS)?; + if !(1..=protocol::MAX_SCROLL_ROWS).contains(&limit) { + return Err(ictl_l10n::trf!( + "limit 要在 1 到 {} 之间", + "limit must be between 1 and {}", + protocol::MAX_SCROLL_ROWS + )); + } + let scroll = checked_scroll(&a.s_or("scroll", "down")?, a.u_or("max_scrolls", 8)?)?; + let x = a.opt_f("x")?; + if x.is_some_and(|x| !x.is_finite() || x < 0.0) { + return Err(ictl_l10n::tr!("x 不能是负数", "x can't be negative").into()); + } + Request::ScrollCollect(protocol::ScrollCollect { + down: scroll.down, + max_scrolls: scroll.max, + until: a.s_or("until", "")?, + filter: a.s_or("filter", "")?, + limit, + x, + }) + } + "iphone_tap" => Request::Tap { x: a.f("x")?, y: a.f("y")?, count: a.count("count")? }, + "iphone_tap_element" => Request::TapElement { + text: a.s("text")?, + index: a.u_or("index", 0)?, + max_age_ms: 0, + scroll: scroll_search(&a)?, + }, + "iphone_long_press" => Request::LongPress { x: a.f("x")?, y: a.f("y")?, seconds: a.f_or("seconds", 1.0)? }, + "iphone_swipe" => Request::Swipe { + from: (a.f("from_x")?, a.f("from_y")?), + to: (a.f("to_x")?, a.f("to_y")?), + seconds: a.f_or("seconds", 0.3)?, + hold: a.f_or("hold", 0.0)?, + }, + "iphone_type_text" => { + let text = a.s("text")?; + let submit = a.b_or("submit", false)?; + if a.b_or("replace", false)? { + Request::ReplaceText { text, submit } + } else { + Request::TypeText { text, submit } + } + } + "iphone_press_button" => Request::PressButton { button: a.s("button")? }, + "iphone_list_apps" => Request::ListApps { include_system: a.b_or("include_system", false)? }, + "iphone_launch_app" => Request::LaunchApp { app: a.s("app")? }, + "iphone_terminate_app" => Request::TerminateApp { app: a.s("app")? }, + "iphone_open_url" => Request::OpenUrl { url: a.s("url")? }, + "iphone_list_devices" => Request::ListDevices, + "iphone_select_device" => Request::SelectDevice { device: a.s("device")? }, + "iphone_app_logs" => Request::AppLogs { + process: a.s_or("process", "")?, + grep: a.s_or("grep", "")?, + since_secs: a.u_or("since", 60)? as u64, + limit: a.u_or("limit", 100)?, + errors_only: a.b_or("errors_only", false)?, + }, + "iphone_crash_reports" => Request::CrashReports { filter: a.s_or("filter", "")?, name: a.s_or("name", "")? }, + "iphone_install_app" => Request::InstallApp { path: a.s("path")? }, + "iphone_uninstall_app" => Request::UninstallApp { app: a.s("app")? }, + "iphone_web_targets" => Request::WebTargets, + "iphone_web_eval" => { + let secs = a.f_or("timeout", 10.0)?; + if !(0.0..=60.0).contains(&secs) { + return Err( + ictl_l10n::tr!("timeout 要在 0 到 60 秒之间", "timeout must be between 0 and 60 seconds").into() + ); + } + Request::WebEval { + target: a.s_or("target", "")?, + expression: a.s("expression")?, + timeout_ms: (secs * 1000.0) as u64, + } + } + "iphone_wait_for" => { + let secs = a.f_or("timeout", 5.0)?; + if !(0.0..=30.0).contains(&secs) { + return Err( + ictl_l10n::tr!("timeout 要在 0 到 30 秒之间", "timeout must be between 0 and 30 seconds").into() + ); + } + let text = a.s("text")?; + let timeout_ms = (secs * 1000.0) as u64; + match a.s_or("state", "appeared")?.as_str() { + "appeared" => Request::WaitFor { text, timeout_ms }, + "disappeared" => Request::WaitForDisappearance { text, timeout_ms }, + _ => { + return Err(ictl_l10n::tr!( + "state 只能是 appeared 或 disappeared", + "state must be appeared or disappeared" + ) + .into()); + } + } + } + other => return Err(ictl_l10n::trf!("未知工具 {other}", "unknown tool {other}")), + }) +} + +/// 操作后顺带返回什么 +#[derive(Debug, Clone, PartialEq)] +pub enum Then { + None, + Elements(String), + Screenshot(Option<(f64, f64, f64, f64)>), +} + +/// then 带的选项:返回什么 + 最多等多久让界面稳定 +#[derive(Debug, Clone, PartialEq)] +pub struct ThenOpts { + pub then: Then, + pub settle_ms: u64, +} + +pub fn parse_then(args: &Map) -> Result { + let a = Args(args); + let then = match a.s_or("then", "none")?.as_str() { + "none" | "" => Then::None, + "elements" => Then::Elements(a.s_or("then_filter", "")?), + "screenshot" => { + let region = + match a.get("then_region") { + None => None, + Some(v) => { + let xs: Option> = v.as_array().map(|arr| arr.iter().filter_map(number).collect()); + match xs.as_deref() { + Some([x, y, w, h]) if *w > 0.0 && *h > 0.0 => Some((*x, *y, *w, *h)), + _ => return Err(ictl_l10n::tr!( + "then_region 要是 [x, y, width, height] 四个数,宽高大于 0", + "then_region must be four numbers [x, y, width, height], with width and height above 0" + ) + .into()), + } + } + }; + Then::Screenshot(region) + } + other => { + return Err(ictl_l10n::trf!( + "then 只能是 none / elements / screenshot,不是 {other}", + "then must be none / elements / screenshot, not {other}" + )); + } + }; + let secs = a.f_or("then_settle", THEN_SETTLE_MS as f64 / 1000.0)?; + if !(0.0..=10.0).contains(&secs) { + return Err( + ictl_l10n::tr!("then_settle 要在 0 到 10 秒之间", "then_settle must be between 0 and 10 seconds").into() + ); + } + Ok(ThenOpts { then, settle_ms: (secs * 1000.0) as u64 }) +} + +/// Each tool's argument names: the properties of its input schema, the developer tools' and +/// [`task::CONFIRM_TOOL`]'s included +pub(crate) static ARG_NAMES: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| { + tools_with(true) + .into_iter() + .chain([confirm_tool()]) + .map(|t| { + let names = t + .input_schema + .get("properties") + .and_then(Value::as_object) + .map(|p| p.keys().cloned().collect()) + .unwrap_or_default(); + (t.name.to_string(), names) + }) + .collect() + }); + +/// Refuses an argument `tool` doesn't take, before anything is done. Unknown arguments used to be dropped: a call +/// with a misspelt name, or with one this version doesn't have yet, ran with the default instead and reported success +/// (`iphone_wait_for` with `state: "disappeared"` answered “appeared” at once, #158). `extra`: names taken besides the +/// schema's (a batch step's `tool`); `then` and the like are only taken where the schema lists them, so not in a +/// batch's steps (the batch's own then applies). A tool this server doesn't know is left to the call to refuse +pub fn check_args(tool: &str, args: &Map, extra: &[&str], then: bool) -> Result<(), String> { + let Some(names) = ARG_NAMES.get(tool) else { return Ok(()) }; + let then_names = ["then", "then_filter", "then_region", "then_settle"]; + let takes = |k: &str| (names.iter().any(|n| n == k) && (then || !then_names.contains(&k))) || extra.contains(&k); + let mut unknown: Vec<&str> = args.keys().map(String::as_str).filter(|k| !takes(k)).collect(); + if unknown.is_empty() { + return Ok(()); + } + unknown.sort_unstable(); + let mut known: Vec<&str> = + names.iter().map(String::as_str).filter(|k| takes(k)).chain(extra.iter().copied()).collect(); + known.sort_unstable(); + known.dedup(); + let sep = ictl_l10n::tr!("、", ", "); + let known = if known.is_empty() { ictl_l10n::tr!("(无)", "(none)").to_owned() } else { known.join(sep) }; + Err(ictl_l10n::trf!( + "{tool} 没有参数 {},什么都没做;它的参数:{known}", + "{tool} has no argument {}, nothing was done; its arguments: {known}", + unknown.join(sep) + )) +} diff --git a/crates/ictl-mcp/src/batch.rs b/crates/ictl-mcp/src/batch.rs new file mode 100644 index 0000000..cb9e2cb --- /dev/null +++ b/crates/ictl-mcp/src/batch.rs @@ -0,0 +1,96 @@ +use super::*; + +/// 批量里的一步 +#[derive(Debug, Clone, PartialEq)] +pub enum Step { + Request { tool: String, req: Request }, + Wait(std::time::Duration), +} + +/// 检查并转换批量步骤(一步都不执行就先把参数错误全挡掉) +pub fn batch_steps(args: &Map) -> Result, String> { + let steps = args + .get("steps") + .and_then(Value::as_array) + .ok_or(ictl_l10n::tr!("缺少 steps(数组)", "missing steps (array)"))?; + let reuse = Args(args).b_or("reuse_elements", false)?; + let one_gesture = Args(args).b_or("one_gesture", false)?; + if steps.is_empty() || steps.len() > BATCH_MAX_STEPS { + return Err(ictl_l10n::trf!( + "steps 要有 1 到 {BATCH_MAX_STEPS} 步", + "steps must have 1 to {BATCH_MAX_STEPS} steps" + )); + } + let steps: Vec = steps + .iter() + .enumerate() + .map(|(i, s)| { + let n = i + 1; + let obj = s.as_object().ok_or_else(|| ictl_l10n::trf!("第 {n} 步不是对象", "step {n} is not an object"))?; + let tool = obj + .get("tool") + .and_then(Value::as_str) + .ok_or_else(|| ictl_l10n::trf!("第 {n} 步缺少 tool", "step {n} has no tool"))?; + if !BATCH_TOOLS.contains(&tool) { + return Err(ictl_l10n::trf!( + "第 {n} 步:批量里不能用 {tool},可用:{}", + "step {n}: {tool} can't be used in a batch; allowed: {}", + BATCH_TOOLS.join(ictl_l10n::tr!("、", ", ")) + )); + } + if tool == "wait" { + if let Some(k) = obj.keys().find(|k| !matches!(k.as_str(), "tool" | "seconds")) { + return Err(ictl_l10n::trf!( + "第 {n} 步:wait 没有参数 {k},它的参数:tool、seconds", + "step {n}: wait has no argument {k}; its arguments: tool, seconds" + )); + } + let secs = Args(obj).f("seconds").map_err(|e| ictl_l10n::trf!("第 {n} 步:{e}", "step {n}: {e}"))?; + if !(0.0..=5.0).contains(&secs) { + return Err(ictl_l10n::trf!( + "第 {n} 步:wait 的 seconds 要在 0 到 5 之间", + "step {n}: wait's seconds must be between 0 and 5" + )); + } + return Ok(Step::Wait(std::time::Duration::from_secs_f64(secs))); + } + let req = match check_args(tool, obj, &["tool"], false) + .and_then(|()| to_request(tool, obj)) + .map_err(|e| ictl_l10n::trf!("第 {n} 步({tool}):{e}", "step {n} ({tool}): {e}"))? + { + Request::TapElement { text, index, scroll, .. } if reuse => { + Request::TapElement { text, index, max_age_ms: BATCH_REUSE_MS, scroll } + } + other => other, + }; + req.check_required_text() + .map_err(|e| ictl_l10n::trf!("第 {n} 步({tool}):{e}", "step {n} ({tool}): {e}"))?; + Ok(Step::Request { tool: tool.to_owned(), req }) + }) + .collect::>()?; + if !one_gesture { + return Ok(steps); + } + // 全是坐标点击才能并成一个手势:别的步骤(按名字点、等待、输入)都要在点之间看界面或花时间 + let points = steps + .iter() + .map(|s| match s { + Step::Request { req: Request::Tap { x, y, count }, .. } => Some((*x, *y, *count)), + _ => None, + }) + .collect::>>() + .ok_or(ictl_l10n::tr!( + "one_gesture 只能用于步骤全是 iphone_tap(按坐标点)的批量", + "one_gesture only works when every step is iphone_tap (tap by coordinates)" + ))?; + // 一个手势里每个点只点一下;要连点用 iphone_tap 的 count,不悄悄当成点一下 + if points.iter().any(|p| p.2 != 1) { + return Err(ictl_l10n::tr!( + "one_gesture 里的 iphone_tap 不能带 count;要在一个点连点,单独调用 iphone_tap 并给 count", + "iphone_tap steps under one_gesture can't take count; to tap one point several times, call iphone_tap on its own with count" + ) + .into()); + } + let points = points.into_iter().map(|(x, y, _)| (x, y)).collect(); + Ok(vec![Step::Request { tool: "iphone_tap".into(), req: Request::TapSequence { points } }]) +} diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs index 2679855..b0d216d 100644 --- a/crates/ictl-mcp/src/lib.rs +++ b/crates/ictl-mcp/src/lib.rs @@ -3,6 +3,12 @@ //! //! 手写 `ServerHandler`(不用宏):参数 schema 直接写 JSON,省掉 schemars; //! 参数到请求的转换([`to_request`])是纯函数,可单测。 +//! +//! - `schema`:服务说明、工具定义(名字、说明、参数 schema、注解) +//! - `args`:参数校验和到请求的转换([`to_request`]、[`parse_then`]、[`check_args`]) +//! - `batch`:`iphone_batch` 的步骤([`batch_steps`]) +//! - `result`:守护进程的回答到工具结果,输入的投递状态 +//! - `server`:[`McpServer`](stdio 和 HTTP),工具调用的执行 use std::path::PathBuf; use std::time::Duration; @@ -20,2210 +26,16 @@ use serde_json::{Map, Value, json}; pub mod task; -/// 服务说明(发给客户端的 instructions):toolkit 的那段,加上自动解锁范围、多设备的说明 -pub fn instructions() -> &'static str { - ictl_l10n::tr!( - "控制一台通过 USB 连接的真实 iPhone(或 iPad)。坐标单位是点(pt),与 iphone_screenshot 图像像素一致。\ -操作前先用 iphone_screenshot 或 iphone_list_elements 看清屏幕;能按名字点就优先用 iphone_tap_element。\ -游戏、地图等界面没有元素树,只能看截图按坐标操作;小图标、小字看不清时用 iphone_screenshot 的区域放大。\ -配置了锁屏密码时,截图、读元素和操作类工具会先自动解锁(iphone_status、列 App、列设备、切换设备和开发者工具不会,按 lock 键也不会)。每次操作后再截图确认结果。\ -涉及付款、删除、发送消息、修改账号或隐私设置的操作,先向用户确认。\ -省时间:操作类工具可带 then=elements 或 then=screenshot,等界面稳定后顺带返回操作后的界面,不用再单独调一次;\ -几步确定的连续操作(按键、逐级点菜单、填表)用 iphone_batch 一次发完;等页面加载用 iphone_wait_for,不要反复截图。\ -接着多台 iPhone/iPad 时同一时间只控制一台:用 iphone_list_devices 查看,iphone_select_device 切换。", - "Controls a real iPhone (or iPad) connected over USB. Coordinates are in points (pt), the same as the pixels of an iphone_screenshot image. Before acting, look at the screen with iphone_screenshot or iphone_list_elements; prefer iphone_tap_element whenever the target has text. Games, maps and similar screens have no element tree: work from screenshots and coordinates, and zoom into small icons or text with an iphone_screenshot region. If a passcode is configured, screenshots, reading elements and the action tools unlock the phone first (iphone_status, listing apps or devices, switching devices and the developer tools don't, nor does pressing lock). Check the result with a screenshot after each action. Ask the user before anything that pays, deletes, sends a message, or changes account or privacy settings. Save time: action tools accept then=elements or then=screenshot to return the screen once it has settled, without a separate call; send a few predictable steps in a row (keys, menu levels, forms) as one iphone_batch; wait for a page with iphone_wait_for instead of repeated screenshots. With several iPhones/iPads connected only one is controlled at a time: see them with iphone_list_devices, switch with iphone_select_device." - ) -} - -fn num(desc: &str) -> Value { - json!({"type": "number", "description": desc}) -} - -fn schema(props: Value, required: &[&str]) -> Map { - let v = json!({"type": "object", "properties": props, "required": required}); - v.as_object().cloned().unwrap_or_default() -} - -/// 操作后顺带返回界面时最多列多少个元素(每步都带太多会占满上下文) -pub const THEN_LIMIT: usize = 80; -/// 顺带返回界面前等界面稳定的上限 -pub const THEN_SETTLE_MS: u64 = 1500; -/// 一次批量最多几步 -pub const BATCH_MAX_STEPS: usize = 20; -/// reuse_elements 时按名字点击复用多旧的元素树(毫秒) -pub const BATCH_REUSE_MS: u64 = 10_000; -/// 批量里能用的工具:改变界面的操作和等待;看界面用 then -pub const BATCH_TOOLS: [&str; 11] = [ - "iphone_tap", - "iphone_tap_element", - "iphone_long_press", - "iphone_swipe", - "iphone_type_text", - "iphone_press_button", - "iphone_launch_app", - "iphone_terminate_app", - "iphone_open_url", - "iphone_wait_for", - "wait", -]; - -/// 操作类工具共有的可选参数:操作后顺带返回界面 -fn then_props() -> Value { - json!({ - "then": {"type": "string", "enum": ["none", "elements", "screenshot"], "default": "none", - "description": ictl_l10n::tr!("操作后等界面稳定,再顺带返回界面:elements=元素列表(最多 80 个),screenshot=截图。省一次单独的调用。操作前看过界面(截图、读元素)时,还会说明和操作前相比界面变没变;没变说明操作可能没生效", "After the action, wait for the screen to settle and return it: elements = element list (up to 80), screenshot = screenshot. Saves a separate call. If the screen was looked at before the action (screenshot, element list), it also says whether the screen changed since; no change means the action may not have taken effect")}, - "then_filter": {"type": "string", "default": "", "description": ictl_l10n::tr!("then=elements 时只列包含这段文字的元素", "With then=elements: only list elements containing this text")}, - "then_region": {"type": "array", "items": {"type": "number"}, "minItems": 4, "maxItems": 4, - "description": ictl_l10n::tr!("then=screenshot 时只返回这块区域的放大图 [x, y, width, height](点),例如游戏棋盘", "With then=screenshot: only return this region, enlarged, as [x, y, width, height] (points), e.g. a game board")}, - "then_settle": {"type": "number", "default": 1.5, - "description": ictl_l10n::tr!("顺带返回界面前最多等几秒让界面稳定(不超过 10)。游戏、地图按画面是否静止判断,消除连锁等长动画可调大,画面一静止就返回", "Maximum seconds to wait for the screen to settle before returning it (up to 10). Games and maps are judged by whether the picture is still; raise it for long animations such as chain reactions, it returns as soon as the picture is still")} - }) -} - -/// 在参数 schema 里加上 then / then_filter -fn with_then(props: Value) -> Value { - let mut p = props; - if let (Some(o), Value::Object(extra)) = (p.as_object_mut(), then_props()) { - o.extend(extra); - } - p -} - -/// 操作类工具描述的共同结尾:返回什么、then 能做什么、自动解锁。 -/// `alert`:不带 then 时会不会查系统弹窗(见 [`wants_alert_check`]) -fn action_desc(body: &str, example: &str, alert: bool) -> String { - let mut s = ictl_l10n::trf!( - "{body}\n\n返回:一行结果文字,例如「{example}」。", - "{body}\n\nReturns: one line of result text, e.g. “{example}”." - ); - if alert { - s += ictl_l10n::tr!( - "不带 then 时,如果系统弹窗挡着屏幕,结果里会提醒(这时操作落在了弹窗上)。", - " Without then, the result warns if a system alert covers the screen (the action then landed on the alert)." - ); - } - s += ictl_l10n::tr!( - "传 then=elements 或 then=screenshot 会等界面稳定后附上操作后的元素列表或截图,省一次单独的调用。\ -配置了锁屏密码时会先自动解锁。", - " With then=elements or then=screenshot it waits for the screen to settle and attaches the element list or screenshot after the action, saving a separate call. If a passcode is configured, the phone is unlocked first." - ); - s -} - -/// 只看不改的工具 -fn looking(title: &str) -> ToolAnnotations { - ToolAnnotations::with_title(title).read_only(true).open_world(false) -} - -/// 改变手机状态的工具。open_world:点击、输入可能经 App 触达外部(发消息、下单),所以都标 true -fn acting(title: &str, destructive: bool, idempotent: bool) -> ToolAnnotations { - ToolAnnotations::with_title(title).read_only(false).destructive(destructive).idempotent(idempotent).open_world(true) -} - -/// Names of the developer tools, listed only with [`dev_tools_enabled`] -pub const DEV_TOOLS: [&str; 6] = [ - "iphone_app_logs", - "iphone_crash_reports", - "iphone_install_app", - "iphone_uninstall_app", - "iphone_web_targets", - "iphone_web_eval", -]; - -/// `IPHONE_CONTROL_DEV_TOOLS=1` (or true/yes/on) adds the developer tools; off by default, so agents that don't -/// need them don't pay for their descriptions -pub fn dev_tools_enabled() -> bool { - std::env::var(ictl_protocol::env::DEV_TOOLS) - .is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on")) -} - -/// The tools this server lists: the 18 standard ones, plus the developer tools when switched on -pub fn tools() -> Vec { - tools_with(dev_tools_enabled()) -} - -pub fn tools_with(dev: bool) -> Vec { - let mut v = standard_tools(); - if dev { - v.extend(dev_tools()); - } - v -} - -/// [`task::CONFIRM_TOOL`], listed only while working for a task (see [`task`]) -pub fn confirm_tool() -> Tool { - Tool::new( - task::CONFIRM_TOOL, - ictl_l10n::tr!( - "请用户确认一步操作(在控制台页面或发起任务的地方),一直等到用户回答。\n\n何时用:付款、购买、下单、转账;删除或清空数据;发送消息、邮件、评论、帖子;\ -修改账号、密码、隐私或安全设置;其他不可撤销的操作。在真正点下那一步之前调用。\n\n\ -返回:用户同意时是普通结果,接着执行;用户拒绝时是错误结果,这时不要执行这一步,也不要换个方式绕过,停下来说明情况。", - "Ask the user to confirm one action (on the control page or wherever the task was started), and wait for the answer.\n\nWhen to use: payments, purchases, orders, transfers; deleting or clearing data; sending messages, emails, comments, posts; changing account, password, privacy or security settings; anything else that can't be undone. Call it right before the step that does it.\n\nReturns: a normal result when the user approves, then go ahead; an error when the user rejects, then don't do that step or work around it: stop and explain." - ) - .to_owned(), - schema( - json!({ - "action": {"type": "string", "description": ictl_l10n::tr!("要做的事,一句话,例如「发送消息」「删除照片」", "what is about to happen, in a few words, e.g. “Send message”, “Delete photo”")}, - "detail": {"type": "string", "description": ictl_l10n::tr!("具体内容:发给谁、发什么、删哪几项、付多少钱", "the specifics: to whom, what, which items, how much")} - }), - &["action", "detail"], - ), - ) - .with_annotations(ToolAnnotations::with_title(ictl_l10n::tr!("请用户确认", "Ask the user")).read_only(true).open_world(false)) -} - -fn dev_tools() -> Vec { - let t = |name: &'static str, desc: &str, s: Map, a: ToolAnnotations| { - Tool::new(name, desc.to_owned(), s).with_annotations(a) - }; - vec![ - t( - "iphone_app_logs", - ictl_l10n::tr!( - "读手机的系统日志(os_log,默认、Error、Fault 级别;Debug、Info 不记录,记录它们会拖慢手机),可按 App 或进程、关键词、时间筛选,每行:多少秒前、进程[pid]、级别、子系统、内容。\n\n\ -何时用:App 崩溃、报错、请求失败、界面没反应时,不靠截图找原因。第一次调用才开始记录(之前的拿不到):先调一次,复现问题,再调一次。\ -记录在 15 分钟没有调用后自动停止。只读。", - "Read the phone's system log (os_log, default, Error and Fault levels; Debug and Info aren't recorded, since streaming them slows the phone down), filtered by app or process, keyword and time; one line per entry: seconds ago, process[pid], level, subsystem, message.\n\nWhen to use: when an app crashes, shows an error, a request fails or the UI doesn't respond, to find the cause without screenshots. Recording starts with the first call (earlier lines aren't available): call it once, reproduce the problem, then call it again. Recording stops by itself after 15 minutes without a call. Read-only." - ), - schema( - json!({ - "process": {"type": "string", "default": "", "description": ictl_l10n::tr!("App 的显示名或 Bundle ID,或进程名(如 SpringBoard);空为全部", "app display name or bundle ID, or a process name (e.g. SpringBoard); empty for all")}, - "grep": {"type": "string", "default": "", "description": ictl_l10n::tr!("只要内容或子系统包含这段文字的行(不分大小写)", "only lines whose message or subsystem contains this text (case-insensitive)")}, - "since": {"type": "number", "default": 60, "description": ictl_l10n::tr!("只看最近多少秒,最多 3600", "only the last this many seconds, at most 3600")}, - "limit": {"type": "integer", "default": 100, "description": ictl_l10n::tr!("最多返回多少行(最新的),1 到 1000", "at most this many lines (the newest), 1 to 1000")}, - "errors_only": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("只看 Error 和 Fault 级别", "only Error and Fault levels")} - }), - &[], - ), - looking(ictl_l10n::tr!("读日志", "Read logs")), - ), - t( - "iphone_crash_reports", - ictl_l10n::tr!( - "列出手机上的崩溃报告(新的在前,最多 50 个),或用 name 读取其中一份(.ips,开头是异常类型、崩溃的线程和 App 版本)。\n\n\ -何时用:App 闪退后找原因。只读。", - "List the crash reports on the phone (newest first, at most 50), or read one with name (.ips; the start has the exception type, the crashed thread and the app version).\n\nWhen to use: to find out why an app quit unexpectedly. Read-only." - ), - schema( - json!({ - "filter": {"type": "string", "default": "", "description": ictl_l10n::tr!("只列文件名包含这段文字的(如进程名)", "only list file names containing this text (e.g. the process name)")}, - "name": {"type": "string", "default": "", "description": ictl_l10n::tr!("要读取的报告文件名(来自列表);给了就返回内容", "file name of the report to read (from the list); if given, returns its content")} - }), - &[], - ), - looking(ictl_l10n::tr!("崩溃报告", "Crash reports")), - ), - t( - "iphone_install_app", - ictl_l10n::tr!( - "安装签好名的 .ipa 或 .app(覆盖已装的同一 App)。path 是运行守护进程的机器上的路径。\ -大的包要一两分钟。", - "Install a signed .ipa or .app (replacing the same app if installed). path is on the machine that runs the daemon. Large packages take a minute or two." - ), - schema( - json!({"path": {"type": "string", "description": ictl_l10n::tr!(".ipa 文件或 .app 目录的路径", "path of the .ipa file or .app directory")}}), - &["path"], - ), - acting(ictl_l10n::tr!("安装 App", "Install app"), true, true), - ), - t( - "iphone_uninstall_app", - ictl_l10n::tr!( - "卸载 App,连同它的数据。不会卸载 WebDriverAgent(iphone-control 靠它控制手机)。卸载前先问用户。", - "Uninstall an app, together with its data. Refuses to remove WebDriverAgent, which iphone-control needs to control the phone. Ask the user before uninstalling." - ), - schema( - json!({"app": {"type": "string", "description": ictl_l10n::tr!("Bundle ID 或显示名", "bundle ID or display name")}}), - &["app"], - ), - acting(ictl_l10n::tr!("卸载 App", "Uninstall app"), true, true), - ), - t( - "iphone_web_targets", - ictl_l10n::tr!( - "列出可检查的网页和 WebView(Web Inspector):Safari 标签页、App 里可检查的 WebView(Capacitor、Cordova、React Native 等的调试构建)。每行:id、类型、所属 App、标题和网址。\n\n\ -何时用:页面内容在网页里时,用 iphone_web_eval 直接读 DOM,比截图和元素树快、省 token、也更准。需要手机上 设置 → Safari → 高级 → 网页检查器 打开。只读。", - "List inspectable web pages and WebViews (Web Inspector): Safari tabs and inspectable WebViews in apps (debug builds of Capacitor, Cordova, React Native and similar). One line each: id, type, app, title and URL.\n\nWhen to use: when the content is a web page, read the DOM with iphone_web_eval instead; that is faster, cheaper in tokens and more accurate than screenshots or the element tree. Needs Settings → Safari → Advanced → Web Inspector on. Read-only." - ), - schema(json!({}), &[]), - looking(ictl_l10n::tr!("列出网页", "List web pages")), - ), - t( - "iphone_web_eval", - ictl_l10n::tr!( - "在网页或 WebView 里执行 JavaScript,返回结果的 JSON(Promise 会等它完成)。例如 document.title、\ -[...document.querySelectorAll('button')].map(b => b.innerText)、document.querySelector('#email').value = 'a@b.c'。\n\n\ -何时用:读网页内容、表单状态、控制台变量,或直接操作页面。只取需要的部分,结果超过 5 万字会被截断。\ -脚本能改页面(提交表单、发请求),和点击一样要小心。", - "Run JavaScript in a web page or WebView and return the result as JSON (a promise is awaited). For example document.title, [...document.querySelectorAll('button')].map(b => b.innerText), document.querySelector('#email').value = 'a@b.c'.\n\nWhen to use: to read page content, form state or JavaScript variables, or to act on the page directly. Select just what you need; results over 50,000 characters are cut. A script can change the page (submit forms, send requests), so take the same care as with taps." - ), - schema( - json!({ - "expression": {"type": "string", "description": ictl_l10n::tr!("要执行的 JavaScript 表达式", "the JavaScript expression to run")}, - "target": {"type": "string", "default": "", "description": ictl_l10n::tr!("iphone_web_targets 列出的 id,或网址、标题里的一段文字;只有一个页面时可以不填", "an id from iphone_web_targets, or text in the page's URL or title; may be left out when there is only one page")}, - "timeout": {"type": "number", "default": 10, "description": ictl_l10n::tr!("最多等多少秒,最多 60", "maximum seconds to wait, at most 60")} - }), - &["expression"], - ), - acting(ictl_l10n::tr!("执行 JavaScript", "Run JavaScript"), true, false), - ), - ] -} - -/// 18 个工具的定义(toolkit 的 13 个 + iphone_wait_for、iphone_batch、iphone_list_devices、iphone_select_device、iphone_scroll_collect)。 -/// 描述可以改写,但工具名、参数、默认返回不改(docs/decisions.md D10) -fn standard_tools() -> Vec { - let t = |name: &'static str, desc: String, s: Map, a: ToolAnnotations| { - Tool::new(name, desc, s).with_annotations(a) - }; - let app = || { - json!({"app": {"type": "string", - "description": ictl_l10n::tr!("Bundle ID(如 com.apple.Preferences)或显示名(如「设置」「微信」)", "Bundle ID (e.g. com.apple.Preferences) or display name (e.g. “Settings”)")}}) - }; - vec![ - t( - "iphone_status", - ictl_l10n::tr!("查看手机和服务的状态:WDA(WebDriverAgent)是否就绪、是否锁屏、能否自动解锁、当前前台 App 的 Bundle ID、\ -屏幕尺寸(点)、守护进程状态。\n\n何时用:开始操作前确认手机可用;操作报错、怀疑 WDA 掉线或手机锁屏时排查。\ -WDA 不可用时会说明哪些功能受影响(读元素、按名字点击、启动 App)。只读,不改变手机状态。", "Show the state of the phone and the service: whether WDA (WebDriverAgent) is ready, whether the phone is locked and can be auto-unlocked, the bundle ID of the foreground app, the screen size (points) and the daemon state.\n\nWhen to use: to check that the phone is usable before starting; to investigate when actions fail or WDA or the lock screen seem to be in the way. If WDA is unavailable it says which features are affected (reading elements, tapping by text, launching apps). Read-only, doesn't change the phone.") - .into(), - schema(json!({}), &[]), - looking(ictl_l10n::tr!("查看状态", "Show status")), - ), - t( - "iphone_screenshot", - ictl_l10n::tr!("截取当前屏幕,返回 JPEG 图像和一行说明。图像已缩放到点尺寸,图中像素坐标可直接用于 iphone_tap、iphone_swipe。\n\n\ -看不清小图标、小字时,传 x/y/width/height(点,四个要一起给)放大这块区域:从原始高清截图裁剪,小区域再额外放大。\ -返回文字里有放大倍数,图中坐标换算回屏幕点:x + 像素/倍数。\n\n\ -何时用:游戏、地图、图片等没有元素树的界面,或要确认画面效果时。只想知道有哪些按钮、文字,iphone_list_elements 更快更省上下文。\ -操作后要看结果时,优先给操作工具带 then=screenshot。WDA 不可用时改用 CoreDevice 截图(iOS 27 起,说明里注明「HID」)。\ -只读:不改变界面,但配置了锁屏密码时会先解锁。", "Capture the current screen and return a JPEG image plus a line of explanation. The image is scaled to points, so its pixel coordinates can be used directly with iphone_tap and iphone_swipe.\n\nTo read small icons or text, pass x/y/width/height (points, all four together) to zoom into that region: it is cropped from the full-resolution capture, and small regions are enlarged further. The text gives the zoom factor; convert image coordinates back to screen points with x + pixel / factor.\n\nWhen to use: screens without an element tree (games, maps, images), or to check how something looks. To find out which buttons and texts are there, iphone_list_elements is faster and uses less context. To see the result of an action, prefer then=screenshot on the action tool. If WDA is unavailable it uses a CoreDevice screenshot instead (iOS 27+, marked “HID”). Read-only: doesn't change the screen, but unlocks the phone first if a passcode is configured.") - .into(), - schema( - json!({"x": num(ictl_l10n::tr!("区域左上角 x(点)", "left edge x of the region (points)")), "y": num(ictl_l10n::tr!("区域左上角 y(点)", "top edge y of the region (points)")), "width": num(ictl_l10n::tr!("区域宽(点)", "region width (points)")), "height": num(ictl_l10n::tr!("区域高(点)", "region height (points)"))}), - &[], - ), - looking(ictl_l10n::tr!("截图", "Screenshot")), - ), - t( - "iphone_list_elements", - ictl_l10n::tr!("列出屏幕上带文字的界面元素,每行一个:类型、标签、名字、值、中心点坐标、尺寸(点)。\n\n\ -何时用:找按钮、输入框、列表项的文字和位置,比截图快、省上下文;找到后用 iphone_tap_element 按文字点。\ -游戏、地图等没有元素树的界面这里是空的,改用 iphone_screenshot。\n\n\ -注意:按坐标判断是否在屏幕内,被弹窗遮住的元素也可能列出来,不确定时截图核对。需要 WDA。\ -只读:不改变界面,但配置了锁屏密码时会先解锁。", "List the UI elements on screen that carry text, one per line: type, label, name, value, center point and size (points).\n\nWhen to use: to find buttons, text fields and list items with their text and position; faster than a screenshot and uses less context. Then tap one by its text with iphone_tap_element. Games, maps and other screens without an element tree return nothing here; use iphone_screenshot.\n\nNote: visibility is judged by position, so elements hidden behind an alert can still be listed; check with a screenshot when in doubt. Needs WDA. Read-only: doesn't change the screen, but unlocks the phone first if a passcode is configured.") - .into(), - schema( - json!({ - "filter": {"type": "string", "default": "", - "description": ictl_l10n::tr!("只返回类型/标签/名字/值里包含这段文字的元素(不区分大小写),例如 SearchField、Button、登录", "Only return elements whose type/label/name/value contains this text (case-insensitive), e.g. SearchField, Button, Login")}, - "limit": {"type": "integer", "default": 150, "description": ictl_l10n::tr!("最多列几个,结构化结果包含匹配总数和截断标记", "Maximum number of elements to return; structured output reports the count and whether it was truncated")} - }), - &[], - ), - looking(ictl_l10n::tr!("列出界面元素", "List UI elements")), - ) - .with_raw_output_schema(std::sync::Arc::new(elements_output_schema())), - t( - "iphone_scroll_collect", - ictl_l10n::tr!("收集连续几屏里可见的文字行,合并相邻屏的重叠内容。可用 until 找到文字就停在当前屏。只滑动,不点击。返回 rows、scrolls、stop_reason,以及找到时当前屏上的 matched。", - "Collect visible text rows across overlapping viewports. Use until to stop with a matching element on screen. Only scrolls, never taps. Returns rows, scrolls, stop_reason and the matched element on the final viewport.").into(), - schema(json!({ - "scroll": {"type": "string", "enum": ["down", "up"], "default": "down", "description": ictl_l10n::tr!("往下或往上找", "look further down or up the list")}, - "until": {"type": "string", "description": ictl_l10n::tr!("可见元素的文字、标识或值包含这段文字时停止,不区分大小写", "stop at a visible label, name or value containing this text, case-insensitive")}, - "filter": {"type": "string", "description": ictl_l10n::tr!("只收集类型或文字包含它的行。与 until 独立", "collect rows whose type or text contains this string, independent of until")}, - "limit": {"type": "integer", "minimum": 1, "maximum": protocol::MAX_SCROLL_ROWS, "default": protocol::MAX_SCROLL_ROWS, "description": ictl_l10n::tr!("最多收集几行", "stop after collecting this many rows")}, - "max_scrolls": {"type": "integer", "minimum": 1, "maximum": protocol::MAX_SEARCH_SCROLLS, "default": 8, "description": ictl_l10n::tr!("最多滚动几次", "maximum number of scrolls")}, - "x": {"type": "number", "minimum": 0, "description": ictl_l10n::tr!("在哪个横坐标上下滑(点),默认屏幕正中。iPad 分栏界面(设置、邮件)只滚动手指所在的那一栏:要滚左栏,给左栏里的横坐标", "where to swipe across, in points from the left; the middle of the screen by default. An iPad split view (Settings, Mail) scrolls only the column swiped in: for the sidebar, an x inside it")} - }), &[]), - acting(ictl_l10n::tr!("滚动收集文字", "Scroll and collect text"), false, false), - ), - t( - "iphone_tap", - action_desc( - ictl_l10n::tr!("点击屏幕上的一个坐标(单位是点,与 iphone_screenshot 全屏图的像素一致,左上角为原点)。\n\n\ -何时用:目标没有文字(图标、图片)、在游戏或地图里,或 iphone_list_elements 里找不到它时。\ -带文字的按钮、列表项优先用 iphone_tap_element,界面布局变了也点得准。按住用 iphone_long_press,滚动用 iphone_swipe。\n\n\ -行为:单指按下约 0.05 秒后抬起,点一次(count 大于 1 时在同一点连点)。不检查坐标上是什么,点之前先截图确认位置。\ -WDA 不可用时改用 CoreDevice HID(iOS 27 起;结果里注明「经 HID」)。", "Tap a point on the screen (in points, the same as the pixels of a full-screen iphone_screenshot, origin at the top left).\n\nWhen to use: the target has no text (icon, image), is in a game or map, or can't be found with iphone_list_elements. For buttons and list items with text prefer iphone_tap_element, which keeps working when the layout changes. Use iphone_long_press to hold and iphone_swipe to scroll.\n\nBehavior: one finger down for about 0.05 s, then up; a single tap (several at the same point with count above 1). It doesn't check what is at that point, so look at a screenshot first. If WDA is unavailable it uses CoreDevice HID instead (iOS 27+; the result says “via HID”)."), - ictl_l10n::tr!("已点击 (120,300)", "Tapped (120,300)"), - true, - ), - schema( - with_then(json!({ - "x": num(ictl_l10n::tr!("x(点)", "x (points)")), - "y": num(ictl_l10n::tr!("y(点)", "y (points)")), - "count": {"type": "integer", "default": 1, "minimum": 1, "maximum": MAX_TAP_COUNT, - "description": ictl_l10n::tr!("在这一点连点几下,一个手势里点完(每下间隔约 0.1 秒):2 是双击;也用于要在短时间内连点几下的入口。分开调用赶不上这类时间窗", "how many times to tap this point, all in one gesture (about 0.1 s apart): 2 is a double tap; also for entries that need several taps in a short time, which separate calls are too slow for")} - })), - &["x", "y"], - ), - acting(ictl_l10n::tr!("点击坐标", "Tap point"), true, false), - ), - t( - "iphone_tap_element", - action_desc( - ictl_l10n::tr!("按文字点击界面元素:先找标签/名字与 text 完全相同的,找不到再找包含 text 的。\ -中心被悬浮栏、键盘等盖住时改点没被盖住的部分,整个被盖住就不点。\n\n\ -何时用:按钮、列表项、标签页等带文字的元素,优先用它而不是按坐标点。不确定文字怎么写时先 iphone_list_elements。\ -没有文字的图标、游戏、地图用 iphone_tap。\n\n\ -行为:没找到、index 超出匹配个数或整个被盖住时不点,返回原因(不算出错;在 iphone_batch 里会让批量停下)。需要 WDA。", "Tap a UI element by its text: first an exact match of label or name with text, otherwise one that contains text. If its center is covered by a floating bar, the keyboard or similar, it taps an uncovered part; if it is completely covered, it doesn't tap.\n\nWhen to use: buttons, list items, tabs and other elements with text; prefer this over coordinates. If unsure how the text is written, use iphone_list_elements first. For icons without text, games and maps use iphone_tap.\n\nBehavior: when nothing matches, index is beyond the number of matches, or the element is completely covered, it doesn't tap and says why (not an error; inside iphone_batch it stops the batch). Needs WDA."), - ictl_l10n::tr!("已点击 Button \"通用\"", "Tapped Button \"General\""), - true, - ), - schema( - with_then(json!({ - "text": {"type": "string", "description": ictl_l10n::tr!("元素的文字(标签或名字),先精确匹配再按包含匹配", "the element's text (label or name); exact match first, then substring")}, - "index": {"type": "integer", "default": 0, - "description": ictl_l10n::tr!("匹配到多个时点第几个(从 0 开始,顺序同 iphone_list_elements)", "which match to tap if there are several (from 0, same order as iphone_list_elements)")}, - "scroll": {"type": "string", "enum": ["down", "up"], - "description": ictl_l10n::tr!("当前屏幕上没有时边滑边找:down 往下找(看下面的内容),up 往上找。每次慢滑约三分之一屏、不带惯性,找到文字完全相同的就点(当前屏只有包含它的不算,接着滑;滑完都没有完全相同的才点包含它的),滑到底(界面不再变)或滑满 max_scrolls 次还没有就停下说明。用于长列表、设置页里不在当前屏的项;不给就只在当前屏幕上找", "If it isn't on the current screen, scroll and look again: down looks further down (the content below), up further up. Each scroll is a slow third of the screen without momentum; it taps as soon as the exact text is found (a row that only contains it doesn't stop the search; if no exact match turns up, one that contains it is tapped), and stops and says so at the end of the list (the screen no longer changes) or after max_scrolls. For items of long lists and settings pages that are off screen; without it only the current screen is searched")}, - "max_scrolls": {"type": "integer", "default": 8, "minimum": 1, "maximum": ictl_protocol::MAX_SEARCH_SCROLLS, - "description": ictl_l10n::tr!("带 scroll 时最多滑几次,默认 8", "with scroll: at most this many scrolls, default 8")} - })), - &["text"], - ), - acting(ictl_l10n::tr!("按文字点击", "Tap by text"), true, false), - ), - t( - "iphone_long_press", - action_desc( - ictl_l10n::tr!("在屏幕坐标(点)上单指按住 seconds 秒再抬起,手指不移动。\n\n\ -何时用:要长按才出现的操作,例如主屏图标的快捷菜单、消息或图片的上下文菜单、选中文字。\ -普通点击用 iphone_tap 或 iphone_tap_element;要移动手指(滚动、拖滑块)用 iphone_swipe。\n\n\ -行为:只按一次。按得太短(不到约 0.5 秒)系统可能当成普通点击。长按弹出的菜单不会自己消失,\ -下一步先看屏幕(或直接带 then=screenshot)。需要 WDA。", "Hold one finger still at a screen point (points) for seconds, then lift.\n\nWhen to use: actions that need a long press, such as home-screen quick actions, context menus on messages or images, or selecting text. For normal taps use iphone_tap or iphone_tap_element; to move the finger (scroll, drag a slider) use iphone_swipe.\n\nBehavior: a single press. Too short a press (under about 0.5 s) may count as a normal tap. Menus opened by a long press stay open, so look at the screen next (or pass then=screenshot). Needs WDA."), - ictl_l10n::tr!("已长按 (200,400) 1 秒", "Long-pressed (200,400) for 1 s"), - true, - ), - schema( - with_then(json!({ - "x": num(ictl_l10n::tr!("x(点)", "x (points)")), - "y": num(ictl_l10n::tr!("y(点)", "y (points)")), - "seconds": {"type": "number", "default": 1.0, "description": ictl_l10n::tr!("按住几秒,默认 1", "seconds to hold, default 1")} - })), - &["x", "y"], - ), - acting(ictl_l10n::tr!("长按", "Long press"), true, false), - ), - t( - "iphone_swipe", - action_desc( - ictl_l10n::tr!("单指从 (from_x, from_y) 按下,用 seconds 秒移到 (to_x, to_y) 后抬起(坐标单位是点)。\n\n\ -何时用:滚动列表或页面、左右翻页、拖动滑块。向上滑看下面的内容:from_y 大、to_y 小(例如 y 从 700 滑到 300);\ -向左滑看右边的内容:from_x 大、to_x 小。点击用 iphone_tap,原地按住用 iphone_long_press。\n\n\ -行为:seconds 越小滑得越快,快滑会带惯性多滚一段;要精确移动(滑块)把 seconds 调到 1 秒左右。\ -滑完会等列表停止滚动(最多 2.5 秒)再返回,还在滚就在结果里说明。WDA 不可用时改用 CoreDevice HID(iOS 27 起)。", "One finger down at (from_x, from_y), moving to (to_x, to_y) over seconds, then up (coordinates in points).\n\nWhen to use: scroll a list or page, page left or right, drag a slider. To see content further down, swipe up: from_y large, to_y small (e.g. y from 700 to 300); to see content to the right, swipe left: from_x large, to_x small. Use iphone_tap to tap and iphone_long_press to hold in place.\n\nBehavior: the smaller seconds, the faster the swipe; a fast swipe keeps scrolling with momentum. For precise moves (sliders) use about 1 second. It waits until the list stops scrolling (up to 2.5 s) before returning and says so if it is still moving. If WDA is unavailable it uses CoreDevice HID instead (iOS 27+)."), - ictl_l10n::tr!("已滑动 (215,700) → (215,300)", "Swiped (215,700) → (215,300)"), - true, - ), - schema( - with_then(json!({ - "from_x": num(ictl_l10n::tr!("起点 x(点)", "start x (points)")), - "from_y": num(ictl_l10n::tr!("起点 y(点)", "start y (points)")), - "to_x": num(ictl_l10n::tr!("终点 x(点)", "end x (points)")), - "to_y": num(ictl_l10n::tr!("终点 y(点)", "end y (points)")), - "seconds": {"type": "number", "default": 0.3, "description": ictl_l10n::tr!("滑动用时(秒),默认 0.3;越小越快、惯性越大", "swipe duration (seconds), default 0.3; smaller is faster with more momentum")}, - "hold": {"type": "number", "default": 0, "minimum": 0, "description": ictl_l10n::tr!("先在起点按住几秒再移动,默认 0(普通滑动)。拖动要先长按才拿得起来的东西时用,例如主屏幕图标、可排序的列表项、文件:hold 0.6~1,seconds 0.7 左右。少于 0.5 秒通常拿不起来,只会滑动或翻页", "seconds to hold still at the start before moving, default 0 (a plain swipe). For dragging things that have to be long-pressed before they can be picked up, such as home-screen icons, reorderable list rows or files: hold 0.6-1, seconds about 0.7. Under 0.5 s usually doesn't pick anything up and just swipes or pages")} - })), - &["from_x", "from_y", "to_x", "to_y"], - ), - acting(ictl_l10n::tr!("滑动", "Swipe"), false, false), - ), - t( - "iphone_type_text", - action_desc( - ictl_l10n::tr!("在当前获得焦点的输入框里输入文字(支持中文),默认从光标处输入。replace=true 替换当前聚焦的普通输入框的全文(text 为空时清空),读回全文一致才按回车。submit=true 时末尾按回车。\n\n\ -何时用:搜索框、表单、聊天框等。要先点中输入框让键盘弹出;屏幕上没有键盘时报错,什么都不输。\ -回车可能会发送消息或提交表单,发送前先向用户确认。\n\n\ -行为:输完会读回输入框核对,少了结尾几个字会自动补上;对不上就报错,也不按回车。\ -WDA 不可用时改用 HID(iOS 27 起):美式键盘上的英文和符号直接按键;中文等经剪贴板粘贴,手机会弹「允许粘贴」,要截图后点它才粘得进去(剪贴板 45 秒后还原)。", "Type text into the focused text field (any language, including Chinese) at the cursor by default. replace=true replaces the contents of a readable focused field (empty text empties it), and presses Return only once the field reads back as exactly the text. With submit=true it presses Return at the end.\n\nWhen to use: search boxes, forms, chat fields. Tap the field first so the keyboard comes up; with no keyboard on screen it fails and types nothing. Return may send a message or submit a form, so ask the user before sending.\n\nBehavior: it reads the field back afterwards; dropped trailing characters are typed again. If it still doesn't match, it reports an error and doesn't press Return. If WDA is unavailable it uses HID instead (iOS 27+): English letters and symbols of a US keyboard are typed as keys, anything else is pasted through the pasteboard, and the phone asks to “Allow Paste”: take a screenshot and tap it to let the text in (the pasteboard is put back after 45 s)."), - ictl_l10n::tr!("已输入 4 个字符,并按了回车", "Typed 4 characters and pressed Return"), - true, - ), - schema( - with_then(json!({ - "text": {"type": "string", "description": ictl_l10n::tr!("要输入的文字", "the text to type")}, - "replace": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("替换当前聚焦输入框的全文,text 为空时清空输入框。仅普通可读输入框(不含密码框);经 WDA 时先清空再输入,失败时原来的文字已删掉;默认在光标处输入", "replace all text in the focused field; with empty text, empty it. Readable fields only (not password fields); through WDA the field is emptied first, so after a failure the old text is gone; defaults to typing at the cursor")}, - "submit": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("输完后按回车(搜索、发送、提交)", "press Return afterwards (search, send, submit)")} - })), - &["text"], - ), - acting(ictl_l10n::tr!("输入文字", "Type text"), false, false), - ), - t( - "iphone_press_button", - action_desc( - ictl_l10n::tr!("按硬件键:home(回主屏幕)、volume_up、volume_down、lock(锁屏)。\n\n\ -何时用:离开当前 App 回主屏幕用 home(App 留在后台,要彻底关掉用 iphone_terminate_app);调音量;锁屏。\ -锁屏后配置了密码的话,下一个操作会先自动解锁。\n\n\ -行为:系统弹窗挡着时按 home 不会生效,这时不按,并提示先点弹窗上的按钮。按 home 会等主屏真的到前台再返回。", "Press a hardware button: home (go to the home screen), volume_up, volume_down, lock (lock the screen).\n\nWhen to use: leave the current app with home (the app stays in the background; use iphone_terminate_app to quit it); change the volume; lock the phone. After locking, if a passcode is configured, the next action unlocks first.\n\nBehavior: while a system alert covers the screen home has no effect, so it isn't pressed and the result says to tap a button on the alert first. home waits until the home screen is really in front before returning."), - ictl_l10n::tr!("已按 home", "Pressed home"), - false, - ), - schema( - with_then(json!({"button": {"type": "string", "enum": ["home", "volume_up", "volume_down", "lock"], - "description": ictl_l10n::tr!("home、volume_up、volume_down 或 lock", "home, volume_up, volume_down or lock")}})), - &["button"], - ), - acting(ictl_l10n::tr!("按硬件键", "Press button"), false, false), - ), - t( - "iphone_list_apps", - ictl_l10n::tr!("列出已安装的 App,每行一个:显示名和 Bundle ID。\n\n\ -何时用:iphone_launch_app、iphone_terminate_app 报「找不到名为…的 App」时,查准确的名字或 Bundle ID。\ -默认只列用户装的 App;设置、相机等系统 App 要 include_system=true(要多花几秒)。结果有缓存。只读。", "List installed apps, one per line: display name and bundle ID.\n\nWhen to use: when iphone_launch_app or iphone_terminate_app report “No app named …”, to look up the exact name or bundle ID. By default only user-installed apps; system apps such as Settings or Camera need include_system=true (takes a few seconds longer). Results are cached. Read-only.") - .into(), - schema( - json!({"include_system": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("同时列出系统 App", "also list system apps")}}), - &[], - ), - looking(ictl_l10n::tr!("列出 App", "List apps")), - ), - t( - "iphone_launch_app", - action_desc( - ictl_l10n::tr!("启动 App 并切到前台。app 是显示名时按已安装的 App 查找,找不到会报错,提示用 iphone_list_apps 查看。\n\n\ -何时用:打开某个 App。要直接进网页或 App 里的某个页面用 iphone_open_url。\ -想从首页重新开始(而不是回到上次的页面),先用 iphone_terminate_app 结束它再启动。\n\n\ -行为:App 已在后台运行时只切回前台,停在上次的页面;没在运行就冷启动。等 App 真的到前台才返回(最多约 8 秒);\ -被系统弹窗(如权限请求)挡住或启动慢时,结果里会说明。需要 WDA。", "Launch an app and bring it to the foreground. A display name is looked up among the installed apps; if not found it fails and suggests iphone_list_apps.\n\nWhen to use: to open an app. To go straight to a web page or a screen inside an app, use iphone_open_url. To start from the app's first screen (instead of where it was), quit it with iphone_terminate_app first.\n\nBehavior: an app already running in the background is only brought back to the front, on the screen it was on; otherwise it cold-starts. It returns once the app is really in front (up to about 8 s); if a system alert (such as a permission prompt) blocks it or it starts slowly, the result says so. Needs WDA."), - ictl_l10n::tr!("已启动 com.apple.Preferences", "Launched com.apple.Preferences"), - true, - ), - schema(with_then(app()), &["app"]), - acting(ictl_l10n::tr!("启动 App", "Launch app"), false, true), - ), - t( - "iphone_terminate_app", - action_desc( - ictl_l10n::tr!("强制结束 App 进程,相当于在多任务界面里把它划掉。app 是显示名时按已安装的 App 查找,找不到会报错。\n\n\ -何时用:App 卡住或状态不对,或者想让下次 iphone_launch_app 从首页冷启动。只想离开 App 用 iphone_press_button 按 home,App 留在后台。\n\n\ -行为:App 里没保存的输入、正在播放的内容会丢失。App 本来没在运行也不报错。结束的是前台 App 时会回到主屏幕。需要 WDA。", "Force-quit an app, like swiping it away in the app switcher. A display name is looked up among the installed apps; if not found it fails.\n\nWhen to use: the app is stuck or in a wrong state, or the next iphone_launch_app should cold-start it on its first screen. To just leave the app, press home with iphone_press_button; the app stays in the background.\n\nBehavior: unsaved input and anything playing is lost. No error if the app wasn't running. Quitting the foreground app returns to the home screen. Needs WDA."), - ictl_l10n::tr!("已结束 com.apple.Preferences", "Terminated com.apple.Preferences"), - false, - ), - schema(with_then(app()), &["app"]), - acting(ictl_l10n::tr!("结束 App", "Quit app"), true, true), - ), - t( - "iphone_open_url", - action_desc( - ictl_l10n::tr!("用系统默认方式打开网址或 URL Scheme:http/https 网页在 Safari 打开,URL Scheme 打开对应的 App。\n\n\ -何时用:直接进入某个网页或 App 里的某个页面,比启动 App 再一级级点快。只想打开 App 用 iphone_launch_app。\n\n\ -行为:有的 URL Scheme 系统会先弹窗问要不要打开,带 then=screenshot 确认。需要 WDA。", "Open a web address or URL scheme the way the system does: http/https pages open in the default browser, URL schemes open their app.\n\nWhen to use: to go straight to a web page or a screen inside an app, faster than launching the app and tapping through. To just open an app use iphone_launch_app.\n\nBehavior: for some URL schemes the system first asks whether to open them; check with then=screenshot. Needs WDA."), - ictl_l10n::tr!("已打开 https://example.com", "Opened https://example.com"), - true, - ), - schema( - with_then(json!({"url": {"type": "string", "description": ictl_l10n::tr!("完整网址(含 https://)或 URL Scheme", "full address (including https://) or URL scheme")}})), - &["url"], - ), - acting(ictl_l10n::tr!("打开链接", "Open URL"), false, false), - ), - t( - "iphone_wait_for", - ictl_l10n::tr!("等含指定文字的元素出现或消失。默认等出现;state=disappeared 时等当前界面没有匹配项。超时报错。\n\n\ -何时用:操作后要等加载时代替反复截图轮询,每 0.3 秒查一次,不占上下文。输入框里的字不算(刚输入的搜索词不会被当成结果)。\ -只读:不改变界面,但配置了锁屏密码时会先解锁。", "Wait for visible UI text to appear (the default), or use state=disappeared to wait for a screen without a match. Returns an error on timeout.\n\nWhen to use: after an action, to wait for loading instead of polling with screenshots; it checks every 0.3 s and uses no context meanwhile. Text inside input fields doesn't count (a search term just typed isn't taken for a result). Read-only: doesn't change the screen, but unlocks the phone first if a passcode is configured.") - .into(), - schema( - json!({ - "text": {"type": "string", "description": ictl_l10n::tr!("要等的文字,元素的标签/名字/值包含它就算出现", "the text to wait for; it counts as appeared when an element's label/name/value contains it")}, - "timeout": {"type": "number", "default": 5, "description": ictl_l10n::tr!("最多等几秒(不超过 30)", "maximum seconds to wait (up to 30)")}, - "state": {"type": "string", "enum": ["appeared", "disappeared"], "default": "appeared", "description": ictl_l10n::tr!("等文字出现或从当前界面消失", "wait for the text to appear or disappear from the visible screen")} - }), - &["text"], - ), - looking(ictl_l10n::tr!("等文字出现", "Wait for text")), - ), - t( - "iphone_list_devices", - ictl_l10n::tr!("列出 USB 上接着的全部 iPhone/iPad,每行一台:设备名、型号、iOS 版本、UDID,标出正在控制哪台、有没有设自动解锁密码。\n\n\ -何时用:接着多台设备、要确认操作落在哪台,或切换前查设备名和 UDID。同一时间只控制一台,其他工具都作用在正在控制的那台上。只读。", "List all iPhones/iPads connected over USB, one per line: device name, model, iOS version, UDID; marks the one being controlled and whether it has an auto-unlock passcode.\n\nWhen to use: with several devices connected, to check which one actions go to, or to look up names and UDIDs before switching. Only one device is controlled at a time; all other tools act on it. Read-only.") - .into(), - schema(json!({}), &[]), - looking(ictl_l10n::tr!("列出设备", "List devices")), - ), - t( - "iphone_select_device", - ictl_l10n::tr!("改为控制另一台设备,之后所有工具都作用在它上面,守护进程重启后还记得。device 是 UDID 或设备名(设备名包含这段文字且只有一台也行),\ -auto 表示取消选定、改回自动选(正在控制的那台断开才换)。\n\n\ -何时用:接着多台设备、要操作的不是正在控制的那台。先用 iphone_list_devices 看有哪几台。\n\n\ -行为:切换后要在新设备上拉起 WDA(10~60 秒),期间读界面、按名字点击等用不了,先用 iphone_status 确认就绪;\ -这台从没装过 WDA 时起不来,要请用户运行 iphone-control setup。\ -自动解锁按设备分开存密码,新设备没设就不会自动解锁。设了 IPHONE_UDID 时不能切换。\n\n\ -返回:一行结果文字,例如「已切换到 Derrors 的 iPad(iPad11,1 iOS 26.6.1,00008020-…)」。", "Control another device from now on: all tools act on it, and the daemon remembers it across restarts. device is a UDID or device name (part of the name works if only one device matches); auto clears the selection and goes back to automatic (switches only when the controlled device disconnects).\n\nWhen to use: with several devices connected, when the one to operate isn't the one being controlled. Look at them with iphone_list_devices first.\n\nBehavior: after switching, WDA has to start on the new device (10-60 s); until then reading the screen, tapping by text etc. don't work, so check readiness with iphone_status. If WDA was never installed on that device it won't start; ask the user to run iphone-control setup. Auto-unlock passcodes are stored per device, so a new device without one isn't auto-unlocked. Not possible while IPHONE_UDID is set.\n\nReturns: one line of result text, e.g. “Switched to Derrors's iPad (iPad11,1 iOS 26.6.1, 00008020-…)”.") - .into(), - schema( - json!({"device": {"type": "string", "description": ictl_l10n::tr!("UDID、设备名,或 auto(改回自动选)", "UDID, device name, or auto (back to automatic)")}}), - &["device"], - ), - ToolAnnotations::with_title(ictl_l10n::tr!("切换设备", "Switch device")).read_only(false).destructive(false).idempotent(true).open_world(false), - ), - t( - "iphone_batch", - action_desc( - ictl_l10n::tr!("按顺序执行几步操作,一次调用完成(最多 20 步),某一步出错就停下,说明停在第几步、后面几步没执行。\n\n\ -steps 每项是 {\"tool\": 工具名, 其余是该工具的参数},可用:iphone_tap、iphone_tap_element、iphone_long_press、\ -iphone_swipe、iphone_type_text、iphone_press_button、iphone_launch_app、iphone_terminate_app、iphone_open_url、\ -iphone_wait_for,以及 {\"tool\": \"wait\", \"seconds\": 秒数}(不超过 5)。iphone_tap_element 没点到也会停下。\ -执行前先检查全部参数,有错一步都不执行。\n\n\ -何时用:结果确定的连续操作(按键、逐级点菜单、填表),每步省一轮往返。每步的结果不确定(点了以后不知道会跳到哪)时,还是一步步来。\ -then 在全部做完(或停下)后返回一次界面。", "Run several steps in order in one call (up to 20); stops at the first error and says which step it stopped at and how many didn't run.\n\nEach item of steps is {\"tool\": tool name, plus that tool's parameters}; allowed: iphone_tap, iphone_tap_element, iphone_long_press, iphone_swipe, iphone_type_text, iphone_press_button, iphone_launch_app, iphone_terminate_app, iphone_open_url, iphone_wait_for, and {\"tool\": \"wait\", \"seconds\": n} (up to 5). An iphone_tap_element that taps nothing also stops it. All parameters are checked first; if any is wrong, no step runs.\n\nWhen to use: sequences with predictable results (keys, menu levels, forms), saving a round trip per step. When the outcome of a step is uncertain (you don't know where a tap leads), go step by step. then returns the screen once, after the last step (or where it stopped)."), - ictl_l10n::tr!("1. iphone_launch_app → 已启动 com.apple.Preferences(每步一行)", "1. iphone_launch_app → Launched com.apple.Preferences (one line per step)"), - true, - ), - schema( - with_then(json!({ - "steps": {"type": "array", "items": {"type": "object"}, - "description": ictl_l10n::tr!("要执行的步骤,1 到 20 个,例如 [{\"tool\": \"iphone_tap_element\", \"text\": \"通用\"}]", "the steps to run, 1 to 20, e.g. [{\"tool\": \"iphone_tap_element\", \"text\": \"General\"}]")}, - "reuse_elements": {"type": "boolean", "default": false, - "description": ictl_l10n::tr!("这批操作不改变界面布局时(例如在同一个键盘上连按)设为 true:按名字点击复用最近读到的元素树,每步省 0.3~0.8 秒。会跳转页面的不要用,否则可能点到旧位置", "Set to true when the steps don't change the layout (e.g. pressing keys on the same keypad): tapping by text reuses the most recent element tree, saving 0.3-0.8 s per step. Don't use it for steps that navigate, or it may tap where things used to be")}, - "one_gesture": {"type": "boolean", "default": false, - "description": ictl_l10n::tr!("步骤全是 iphone_tap 时可设为 true:这些点在一个手势里依次点完(每个点一根手指,间隔约 0.04 秒),中间不等界面空闲。用于在同一个键盘上连按,例如输入框不接受 iphone_type_text 时逐个点数字键:7 个键约 1.9 秒,分开点约 3.6 秒。点的过程中不看界面,中途跳了页面后面的点也照样点下去;点完截图或读元素核对", "Only when every step is iphone_tap: set to true to tap the points one after another in a single gesture (one finger per point, about 0.04 s apart) without waiting for the interface in between. For pressing keys on the same keyboard, e.g. digit keys one by one when a field doesn't take iphone_type_text: 7 keys in about 1.9 s instead of about 3.6 s. Nothing is checked while it taps, so if a tap navigates, the remaining points still land; check the result with a screenshot or elements afterwards")} - })), - &["steps"], - ), - acting(ictl_l10n::tr!("批量操作", "Batch"), true, false), - ), - ] -} - -struct Args<'a>(&'a Map); - -/// 数字,或写成字符串的数字(toolkit 的 pydantic 也接受 "3") -fn number(v: &Value) -> Option { - v.as_f64().or_else(|| v.as_str()?.trim().parse().ok()).filter(|x: &f64| x.is_finite()) -} - -/// 参数给了但类型不对就报错,不再悄悄用默认值(例如 index: -1 原来会点第 0 个) -impl Args<'_> { - fn get(&self, k: &str) -> Option<&Value> { - self.0.get(k).filter(|v| !v.is_null()) - } - fn f(&self, k: &str) -> Result { - self.opt_f(k)?.ok_or_else(|| ictl_l10n::trf!("缺少数字参数 {k}", "missing number parameter {k}")) - } - fn f_or(&self, k: &str, d: f64) -> Result { - Ok(self.opt_f(k)?.unwrap_or(d)) - } - fn opt_f(&self, k: &str) -> Result, String> { - self.get(k) - .map(|v| number(v).ok_or_else(|| ictl_l10n::trf!("参数 {k} 要是数字", "parameter {k} must be a number"))) - .transpose() - } - fn s(&self, k: &str) -> Result { - self.get(k) - .and_then(Value::as_str) - .map(str::to_owned) - .ok_or_else(|| ictl_l10n::trf!("缺少文字参数 {k}", "missing text parameter {k}")) - } - fn s_or(&self, k: &str, d: &str) -> Result { - match self.get(k) { - None => Ok(d.to_owned()), - Some(v) => v - .as_str() - .map(str::to_owned) - .ok_or_else(|| ictl_l10n::trf!("参数 {k} 要是文字", "parameter {k} must be text")), - } - } - fn u_or(&self, k: &str, d: usize) -> Result { - match self.get(k) { - None => Ok(d), - Some(v) => number(v).filter(|x| *x >= 0.0 && x.fract() == 0.0).map(|x| x as usize).ok_or_else(|| { - ictl_l10n::trf!("参数 {k} 要是非负整数", "parameter {k} must be a non-negative integer") - }), - } - } - /// 连点次数:不给是 1,给了要是 1 到 [`MAX_TAP_COUNT`] 的整数 - fn count(&self, k: &str) -> Result { - match self.u_or(k, 1)? { - n @ 1.. if n <= MAX_TAP_COUNT as usize => Ok(n as u32), - _ => Err(ictl_l10n::trf!( - "参数 {k} 要是 1 到 {MAX_TAP_COUNT} 的整数", - "parameter {k} must be a whole number from 1 to {MAX_TAP_COUNT}" - )), - } - } - fn b_or(&self, k: &str, d: bool) -> Result { - match self.get(k) { - None => Ok(d), - Some(Value::Bool(b)) => Ok(*b), - Some(Value::String(s)) if s.eq_ignore_ascii_case("true") => Ok(true), - Some(Value::String(s)) if s.eq_ignore_ascii_case("false") => Ok(false), - Some(_) => Err(ictl_l10n::trf!("参数 {k} 要是 true 或 false", "parameter {k} must be true or false")), - } - } -} - -/// 工具调用 → 守护进程请求 -/// `iphone_tap_element` 的 `scroll` / `max_scrolls`:没给 scroll 时不滑 -fn scroll_search(a: &Args) -> Result, String> { - let dir = a.s_or("scroll", "")?; - let max = a.u_or("max_scrolls", 8)?; - if dir.is_empty() { - return Ok(None); - } - checked_scroll(&dir, max).map(Some) -} - -fn checked_scroll(dir: &str, max: usize) -> Result { - let down = match dir { - "down" => true, - "up" => false, - _ => return Err(ictl_l10n::trf!("参数 scroll 要是 down 或 up", "parameter scroll must be down or up")), - }; - if max == 0 || max > ictl_protocol::MAX_SEARCH_SCROLLS as usize { - return Err(ictl_l10n::trf!( - "参数 max_scrolls 要在 1 到 {} 之间", - "parameter max_scrolls must be between 1 and {}", - ictl_protocol::MAX_SEARCH_SCROLLS - )); - } - Ok(protocol::ScrollSearch { down, max: max as u32 }) -} - -pub fn to_request(name: &str, args: &Map) -> Result { - let a = Args(args); - Ok(match name { - "iphone_status" => Request::Status, - "iphone_screenshot" => { - let r = [a.opt_f("x")?, a.opt_f("y")?, a.opt_f("width")?, a.opt_f("height")?]; - let region = match r { - [None, None, None, None] => None, - [Some(x), Some(y), Some(w), Some(h)] => Some((x, y, w, h)), - _ => { - return Err(ictl_l10n::tr!( - "放大区域要同时给出 x、y、width、height", - "a zoom region needs all of x, y, width and height" - ) - .into()); - } - }; - Request::Screenshot { region } - } - "iphone_list_elements" => Request::ListElements { - filter: a.s_or("filter", "")?, - limit: a.u_or("limit", 150)?, - max_age_ms: 0, - keep_locked: false, - }, - "iphone_scroll_collect" => { - let limit = a.u_or("limit", protocol::MAX_SCROLL_ROWS)?; - if !(1..=protocol::MAX_SCROLL_ROWS).contains(&limit) { - return Err(ictl_l10n::trf!( - "limit 要在 1 到 {} 之间", - "limit must be between 1 and {}", - protocol::MAX_SCROLL_ROWS - )); - } - let scroll = checked_scroll(&a.s_or("scroll", "down")?, a.u_or("max_scrolls", 8)?)?; - let x = a.opt_f("x")?; - if x.is_some_and(|x| !x.is_finite() || x < 0.0) { - return Err(ictl_l10n::tr!("x 不能是负数", "x can't be negative").into()); - } - Request::ScrollCollect(protocol::ScrollCollect { - down: scroll.down, - max_scrolls: scroll.max, - until: a.s_or("until", "")?, - filter: a.s_or("filter", "")?, - limit, - x, - }) - } - "iphone_tap" => Request::Tap { x: a.f("x")?, y: a.f("y")?, count: a.count("count")? }, - "iphone_tap_element" => Request::TapElement { - text: a.s("text")?, - index: a.u_or("index", 0)?, - max_age_ms: 0, - scroll: scroll_search(&a)?, - }, - "iphone_long_press" => Request::LongPress { x: a.f("x")?, y: a.f("y")?, seconds: a.f_or("seconds", 1.0)? }, - "iphone_swipe" => Request::Swipe { - from: (a.f("from_x")?, a.f("from_y")?), - to: (a.f("to_x")?, a.f("to_y")?), - seconds: a.f_or("seconds", 0.3)?, - hold: a.f_or("hold", 0.0)?, - }, - "iphone_type_text" => { - let text = a.s("text")?; - let submit = a.b_or("submit", false)?; - if a.b_or("replace", false)? { - Request::ReplaceText { text, submit } - } else { - Request::TypeText { text, submit } - } - } - "iphone_press_button" => Request::PressButton { button: a.s("button")? }, - "iphone_list_apps" => Request::ListApps { include_system: a.b_or("include_system", false)? }, - "iphone_launch_app" => Request::LaunchApp { app: a.s("app")? }, - "iphone_terminate_app" => Request::TerminateApp { app: a.s("app")? }, - "iphone_open_url" => Request::OpenUrl { url: a.s("url")? }, - "iphone_list_devices" => Request::ListDevices, - "iphone_select_device" => Request::SelectDevice { device: a.s("device")? }, - "iphone_app_logs" => Request::AppLogs { - process: a.s_or("process", "")?, - grep: a.s_or("grep", "")?, - since_secs: a.u_or("since", 60)? as u64, - limit: a.u_or("limit", 100)?, - errors_only: a.b_or("errors_only", false)?, - }, - "iphone_crash_reports" => Request::CrashReports { filter: a.s_or("filter", "")?, name: a.s_or("name", "")? }, - "iphone_install_app" => Request::InstallApp { path: a.s("path")? }, - "iphone_uninstall_app" => Request::UninstallApp { app: a.s("app")? }, - "iphone_web_targets" => Request::WebTargets, - "iphone_web_eval" => { - let secs = a.f_or("timeout", 10.0)?; - if !(0.0..=60.0).contains(&secs) { - return Err( - ictl_l10n::tr!("timeout 要在 0 到 60 秒之间", "timeout must be between 0 and 60 seconds").into() - ); - } - Request::WebEval { - target: a.s_or("target", "")?, - expression: a.s("expression")?, - timeout_ms: (secs * 1000.0) as u64, - } - } - "iphone_wait_for" => { - let secs = a.f_or("timeout", 5.0)?; - if !(0.0..=30.0).contains(&secs) { - return Err( - ictl_l10n::tr!("timeout 要在 0 到 30 秒之间", "timeout must be between 0 and 30 seconds").into() - ); - } - let text = a.s("text")?; - let timeout_ms = (secs * 1000.0) as u64; - match a.s_or("state", "appeared")?.as_str() { - "appeared" => Request::WaitFor { text, timeout_ms }, - "disappeared" => Request::WaitForDisappearance { text, timeout_ms }, - _ => { - return Err(ictl_l10n::tr!( - "state 只能是 appeared 或 disappeared", - "state must be appeared or disappeared" - ) - .into()); - } - } - } - other => return Err(ictl_l10n::trf!("未知工具 {other}", "unknown tool {other}")), - }) -} - -/// 操作后顺带返回什么 -#[derive(Debug, Clone, PartialEq)] -pub enum Then { - None, - Elements(String), - Screenshot(Option<(f64, f64, f64, f64)>), -} - -/// then 带的选项:返回什么 + 最多等多久让界面稳定 -#[derive(Debug, Clone, PartialEq)] -pub struct ThenOpts { - pub then: Then, - pub settle_ms: u64, -} - -pub fn parse_then(args: &Map) -> Result { - let a = Args(args); - let then = match a.s_or("then", "none")?.as_str() { - "none" | "" => Then::None, - "elements" => Then::Elements(a.s_or("then_filter", "")?), - "screenshot" => { - let region = - match a.get("then_region") { - None => None, - Some(v) => { - let xs: Option> = v.as_array().map(|arr| arr.iter().filter_map(number).collect()); - match xs.as_deref() { - Some([x, y, w, h]) if *w > 0.0 && *h > 0.0 => Some((*x, *y, *w, *h)), - _ => return Err(ictl_l10n::tr!( - "then_region 要是 [x, y, width, height] 四个数,宽高大于 0", - "then_region must be four numbers [x, y, width, height], with width and height above 0" - ) - .into()), - } - } - }; - Then::Screenshot(region) - } - other => { - return Err(ictl_l10n::trf!( - "then 只能是 none / elements / screenshot,不是 {other}", - "then must be none / elements / screenshot, not {other}" - )); - } - }; - let secs = a.f_or("then_settle", THEN_SETTLE_MS as f64 / 1000.0)?; - if !(0.0..=10.0).contains(&secs) { - return Err( - ictl_l10n::tr!("then_settle 要在 0 到 10 秒之间", "then_settle must be between 0 and 10 seconds").into() - ); - } - Ok(ThenOpts { then, settle_ms: (secs * 1000.0) as u64 }) -} - -/// Each tool's argument names: the properties of its input schema, the developer tools' and -/// [`task::CONFIRM_TOOL`]'s included -static ARG_NAMES: std::sync::LazyLock>> = - std::sync::LazyLock::new(|| { - tools_with(true) - .into_iter() - .chain([confirm_tool()]) - .map(|t| { - let names = t - .input_schema - .get("properties") - .and_then(Value::as_object) - .map(|p| p.keys().cloned().collect()) - .unwrap_or_default(); - (t.name.to_string(), names) - }) - .collect() - }); - -/// Refuses an argument `tool` doesn't take, before anything is done. Unknown arguments used to be dropped: a call -/// with a misspelt name, or with one this version doesn't have yet, ran with the default instead and reported success -/// (`iphone_wait_for` with `state: "disappeared"` answered “appeared” at once, #158). `extra`: names taken besides the -/// schema's (a batch step's `tool`); `then` and the like are only taken where the schema lists them, so not in a -/// batch's steps (the batch's own then applies). A tool this server doesn't know is left to the call to refuse -pub fn check_args(tool: &str, args: &Map, extra: &[&str], then: bool) -> Result<(), String> { - let Some(names) = ARG_NAMES.get(tool) else { return Ok(()) }; - let then_names = ["then", "then_filter", "then_region", "then_settle"]; - let takes = |k: &str| (names.iter().any(|n| n == k) && (then || !then_names.contains(&k))) || extra.contains(&k); - let mut unknown: Vec<&str> = args.keys().map(String::as_str).filter(|k| !takes(k)).collect(); - if unknown.is_empty() { - return Ok(()); - } - unknown.sort_unstable(); - let mut known: Vec<&str> = - names.iter().map(String::as_str).filter(|k| takes(k)).chain(extra.iter().copied()).collect(); - known.sort_unstable(); - known.dedup(); - let sep = ictl_l10n::tr!("、", ", "); - let known = if known.is_empty() { ictl_l10n::tr!("(无)", "(none)").to_owned() } else { known.join(sep) }; - Err(ictl_l10n::trf!( - "{tool} 没有参数 {},什么都没做;它的参数:{known}", - "{tool} has no argument {}, nothing was done; its arguments: {known}", - unknown.join(sep) - )) -} - -/// 批量里的一步 -#[derive(Debug, Clone, PartialEq)] -pub enum Step { - Request { tool: String, req: Request }, - Wait(std::time::Duration), -} - -/// 检查并转换批量步骤(一步都不执行就先把参数错误全挡掉) -pub fn batch_steps(args: &Map) -> Result, String> { - let steps = args - .get("steps") - .and_then(Value::as_array) - .ok_or(ictl_l10n::tr!("缺少 steps(数组)", "missing steps (array)"))?; - let reuse = Args(args).b_or("reuse_elements", false)?; - let one_gesture = Args(args).b_or("one_gesture", false)?; - if steps.is_empty() || steps.len() > BATCH_MAX_STEPS { - return Err(ictl_l10n::trf!( - "steps 要有 1 到 {BATCH_MAX_STEPS} 步", - "steps must have 1 to {BATCH_MAX_STEPS} steps" - )); - } - let steps: Vec = steps - .iter() - .enumerate() - .map(|(i, s)| { - let n = i + 1; - let obj = s.as_object().ok_or_else(|| ictl_l10n::trf!("第 {n} 步不是对象", "step {n} is not an object"))?; - let tool = obj - .get("tool") - .and_then(Value::as_str) - .ok_or_else(|| ictl_l10n::trf!("第 {n} 步缺少 tool", "step {n} has no tool"))?; - if !BATCH_TOOLS.contains(&tool) { - return Err(ictl_l10n::trf!( - "第 {n} 步:批量里不能用 {tool},可用:{}", - "step {n}: {tool} can't be used in a batch; allowed: {}", - BATCH_TOOLS.join(ictl_l10n::tr!("、", ", ")) - )); - } - if tool == "wait" { - if let Some(k) = obj.keys().find(|k| !matches!(k.as_str(), "tool" | "seconds")) { - return Err(ictl_l10n::trf!( - "第 {n} 步:wait 没有参数 {k},它的参数:tool、seconds", - "step {n}: wait has no argument {k}; its arguments: tool, seconds" - )); - } - let secs = Args(obj).f("seconds").map_err(|e| ictl_l10n::trf!("第 {n} 步:{e}", "step {n}: {e}"))?; - if !(0.0..=5.0).contains(&secs) { - return Err(ictl_l10n::trf!( - "第 {n} 步:wait 的 seconds 要在 0 到 5 之间", - "step {n}: wait's seconds must be between 0 and 5" - )); - } - return Ok(Step::Wait(std::time::Duration::from_secs_f64(secs))); - } - let req = match check_args(tool, obj, &["tool"], false) - .and_then(|()| to_request(tool, obj)) - .map_err(|e| ictl_l10n::trf!("第 {n} 步({tool}):{e}", "step {n} ({tool}): {e}"))? - { - Request::TapElement { text, index, scroll, .. } if reuse => { - Request::TapElement { text, index, max_age_ms: BATCH_REUSE_MS, scroll } - } - other => other, - }; - req.check_required_text() - .map_err(|e| ictl_l10n::trf!("第 {n} 步({tool}):{e}", "step {n} ({tool}): {e}"))?; - Ok(Step::Request { tool: tool.to_owned(), req }) - }) - .collect::>()?; - if !one_gesture { - return Ok(steps); - } - // 全是坐标点击才能并成一个手势:别的步骤(按名字点、等待、输入)都要在点之间看界面或花时间 - let points = steps - .iter() - .map(|s| match s { - Step::Request { req: Request::Tap { x, y, count }, .. } => Some((*x, *y, *count)), - _ => None, - }) - .collect::>>() - .ok_or(ictl_l10n::tr!( - "one_gesture 只能用于步骤全是 iphone_tap(按坐标点)的批量", - "one_gesture only works when every step is iphone_tap (tap by coordinates)" - ))?; - // 一个手势里每个点只点一下;要连点用 iphone_tap 的 count,不悄悄当成点一下 - if points.iter().any(|p| p.2 != 1) { - return Err(ictl_l10n::tr!( - "one_gesture 里的 iphone_tap 不能带 count;要在一个点连点,单独调用 iphone_tap 并给 count", - "iphone_tap steps under one_gesture can't take count; to tap one point several times, call iphone_tap on its own with count" - ) - .into()); - } - let points = points.into_iter().map(|(x, y, _)| (x, y)).collect(); - Ok(vec![Step::Request { tool: "iphone_tap".into(), req: Request::TapSequence { points } }]) -} - -/// tap_element 的结果是不是「没点到」(没找到、index 超出匹配个数、或整个被别的东西盖住) -pub fn tap_missed(text: &str, outcome: Option) -> bool { - protocol::tapped_nothing(text, outcome) -} - -/// 不带 then 的操作做完后要不要查系统弹窗(弹窗挡着时操作都落在弹窗上,WDA 照样报成功)。 -/// 按键自己处理(Home 先查弹窗;锁屏后不用查),结束 App 后前台是主屏,不会冒出新弹窗 -/// Every variant is listed (no `_`), so a new request type has to be decided here -pub fn wants_alert_check(req: &Request) -> bool { - match req { - Request::Tap { .. } - | Request::TapSequence { .. } - | Request::TapElement { .. } - | Request::LongPress { .. } - | Request::Swipe { .. } - | Request::TypeText { .. } - | Request::ReplaceText { .. } - | Request::LaunchApp { .. } - | Request::OpenUrl { .. } => true, - // 按键见 PressButton 自己的弹窗处理;切换设备后新设备的 WDA 还没起来,查不了弹窗; - // 安装、卸载、Web Inspector 不碰屏幕(Web Inspector 也不该为它排队等设备锁) - // the web viewer's finger isn't an MCP tool; the person watching sees any alert - Request::PressButton { .. } - | Request::Touch { .. } - | Request::TerminateApp { .. } - | Request::SelectDevice { .. } - | Request::InstallApp { .. } - | Request::UninstallApp { .. } - | Request::WebEval { .. } - | Request::Status - | Request::ScreenStream - | Request::Screenshot { .. } - | Request::ScrollCollect(_) - | Request::ListElements { .. } - | Request::ListApps { .. } - | Request::Settle { .. } - | Request::AlertCheck - | Request::WaitFor { .. } - | Request::WaitForDisappearance { .. } - | Request::Daemon - | Request::Doctor - | Request::Resign { .. } - | Request::UnlockReset - | Request::ListDevices - | Request::AppLogs { .. } - | Request::CrashReports { .. } - | Request::WebTargets - // tasks: not tools, nothing on the screen - | Request::TaskOpen { .. } - | Request::TaskEvents { .. } - | Request::TaskList - | Request::TaskControl { .. } - | Request::TaskAgent - | Request::TaskCheck - | Request::TaskStep { .. } - | Request::TaskStepDone { .. } - | Request::TaskConfirm { .. } - | Request::TaskNote { .. } - | Request::TaskFinish { .. } => false, - } -} - -/// The shape of [`with_element_data`]' structured content, declared as `iphone_list_elements`' output schema (action -/// tools give it with then=elements, but not always: a declared schema would oblige every result to carry it). -/// `matched_count` and `truncated` are left out by a daemon older than them -fn elements_output_schema() -> Map { - let element = json!({ - "type": "object", - "properties": { - "type": {"type": "string"}, "label": {"type": "string"}, - "x": {"type": "number"}, "y": {"type": "number"}, "width": {"type": "number"}, "height": {"type": "number"} - } - }); - let v = json!({ - "type": "object", - "properties": { - "type": {"const": "elements"}, - "elements": {"type": "array", "items": element, - "description": "the elements listed, at most limit; x/y the top left corner in points"}, - "matched_count": {"type": "integer", "description": "how many elements matched filter in this read, before limit"}, - "truncated": {"type": "boolean", "description": "matched_count is more than limit: some weren't listed"} - }, - "required": ["elements"] - }); - v.as_object().cloned().unwrap_or_default() -} - -fn with_element_data(mut result: CallToolResult, data: Option) -> CallToolResult { - if let Some(data @ (protocol::Data::Elements { .. } | protocol::Data::ScrollCollection { .. })) = data { - result.structured_content = serde_json::to_value(data).ok(); - } - result -} - -/// 守护进程响应 → MCP 结果。错误走工具错误(is_error),文字原样给客户端 -pub fn to_result(r: Response) -> CallToolResult { - match r { - Response::Text { text, data, .. } => { - with_element_data(CallToolResult::success(vec![ContentBlock::text(text)]), data) - } - Response::Image { jpeg_base64, caption } => { - CallToolResult::success(vec![ContentBlock::image(jpeg_base64, "image/jpeg"), ContentBlock::text(caption)]) - } - Response::Error { message, .. } => CallToolResult::error(vec![ContentBlock::text(message)]), - } -} - -/// Tools that expose delivery of their primary tap, gesture, or text input. -pub fn reports_input(name: &str) -> bool { - matches!(name, "iphone_tap" | "iphone_tap_element" | "iphone_type_text" | "iphone_swipe" | "iphone_long_press") -} - -fn input_error( - message: impl Into, - name: &str, - delivery: Delivery, - stage: Option, -) -> CallToolResult { - let mut message = message.into(); - if !reports_input(name) { - return to_result(Response::error(message)); - } - if delivery == Delivery::Unknown { - message += ictl_l10n::tr!( - "。输入可能已送达,请先查看屏幕再决定下一步。", - ". Input may have reached the phone. Inspect the screen before retrying." - ); - } - let mut result = to_result(Response::error(message)); - result.structured_content = - Some(json!({"delivery": delivery, "readback": {"screen": "not_requested", "settle": "not_requested"}})); - if let Some(stage) = stage { - result.structured_content.as_mut().unwrap()["stage"] = json!(stage); - } - result -} - -fn add_delivery_hint(message: &mut String, delivery: Delivery) { - let lower = message.to_ascii_lowercase(); - let already_guided = - ["inspect the screen", "take a screenshot", "check with a screenshot", "查看屏幕", "截图确认", "截图看看"] - .iter() - .any(|hint| lower.contains(hint)); - message.truncate(message.trim_end().trim_end_matches(['.', '。']).len()); - message.push_str(match delivery { - Delivery::NotSent => ictl_l10n::tr!("。目标输入未发出。", ". The requested input was not sent."), - Delivery::Unknown => ictl_l10n::tr!("。输入可能已送达。", ". Input may have reached the phone."), - Delivery::Sent => ictl_l10n::tr!("。输入已发出。", ". Input was sent."), - }); - if !already_guided && delivery != Delivery::NotSent { - message.push_str(ictl_l10n::tr!("请先查看屏幕再决定下一步。", " Inspect the screen before retrying.")); - } -} - -struct InputResult<'a> { - delivery: Delivery, - stage: Option, - field: Option<&'static str>, - udid: Option<&'a str>, -} - -#[derive(Debug, Clone)] -pub struct McpServer { - pub socket: PathBuf, - /// This process works for a task (`IPHONE_CONTROL_TASK_TOKEN`, see [`task`]); over HTTP a request may instead - /// carry a task's token in [`protocol::TASK_TOKEN_HEADER`] ([`request_token`]) - pub task: bool, - /// Held for the length of each tool call ([`serve_stdio`]); `None` where the process holds one of its own - pub lease: Option, -} - -/// Takes the host's shared maintenance lease (`ictl_daemon::maintenance::shared`): an update waits while it is held -pub type Lease = fn() -> std::io::Result; - -/// How long a tool call waits for an update that holds the maintenance lock before it goes on without the lease -/// (the daemon then answers, or `protocol::connect` waits for it to be back) -const LEASE_WAIT: std::time::Duration = std::time::Duration::from_secs(15); - -/// The lease for one tool call: taken, waited for while an update runs, or `None` (going on without) -async fn hold(take: Lease) -> Option { - let started = std::time::Instant::now(); - loop { - match take() { - Ok(f) => return Some(f), - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock && started.elapsed() < LEASE_WAIT => { - tokio::time::sleep(std::time::Duration::from_millis(200)).await; - } - Err(_) => return None, - } - } -} - -/// The task token an HTTP request carries ([`protocol::TASK_TOKEN_HEADER`]); `None` over stdio -fn request_token(context: &RequestContext) -> Option { - let parts = context.extensions.get::()?; - let t = parts.headers.get(protocol::TASK_TOKEN_HEADER)?.to_str().ok()?.trim(); - (!t.is_empty()).then(|| t.to_owned()) -} - -/// MCP over HTTP (Streamable HTTP, one session per client) for the viewer's `/mcp` -pub type HttpService = rmcp::transport::streamable_http_server::StreamableHttpService< - McpServer, - rmcp::transport::streamable_http_server::session::local::LocalSessionManager, ->; - -/// The service behind `/mcp`. It doesn't check `Host` or `Origin`: the viewer does, with the names of its page -pub fn http_service(socket: PathBuf) -> HttpService { - use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService}; - let config = StreamableHttpServerConfig::default().with_allowed_hosts(Vec::::new()); - StreamableHttpService::new( - move || Ok(McpServer { socket: socket.clone(), task: false, lease: None }), - std::sync::Arc::default(), - config, - ) -} - -impl ServerHandler for McpServer { - fn get_info(&self) -> InitializeResult { - InitializeResult::new(ServerCapabilities::builder().enable_tools().build()).with_instructions(instructions()) - } - - async fn list_tools( - &self, - _request: Option, - context: RequestContext, - ) -> Result { - let mut t = tools(); - if self.task || request_token(&context).is_some() { - t.push(confirm_tool()); - } - Ok(ListToolsResult::with_all_items(t)) - } - - async fn call_tool( - &self, - request: CallToolRequestParams, - context: RequestContext, - ) -> Result { - // an idle server holds nothing (an update can go ahead between calls); a call holds the lease to its end - let _lease = match self.lease { - Some(take) => hold(take).await, - None => None, - }; - let token = request_token(&context); - if !self.task && token.is_none() { - return self.call_tool_cancellable(request, &context).await; - } - // every request of this call goes out with the HTTP request's token (over stdio: the process's) - protocol::as_task(token, None, self.call_tool_in_task(request, context)).await - } -} - -impl McpServer { - /// [`ServerHandler::call_tool`] for a task's agent - async fn call_tool_in_task( - &self, - request: CallToolRequestParams, - context: RequestContext, - ) -> Result { - // working for a task: the daemon holds or refuses the calls; announce each so the page shows the tool - let name = request.name.clone(); - let args = request.arguments.clone().unwrap_or_default(); - let work = async { - if request.name == task::CONFIRM_TOOL { - if let Err(e) = check_args(&request.name, &args, &[], false) { - return Ok(CallToolResult::error(vec![ContentBlock::text(e)]).into()); - } - let r = match task::confirm(&self.socket, &args).await { - Ok(m) => CallToolResult::success(vec![ContentBlock::text(m)]), - Err(m) => CallToolResult::error(vec![ContentBlock::text(m)]), - }; - return Ok(r.into()); - } - match task::before(&self.socket, &request.name, &args).await { - task::Before::Go(step) => { - let t0 = std::time::Instant::now(); - let r = protocol::as_task(None, Some(step), self.call_tool_inner(request)).await; - if let Ok(CallToolResponse::Complete(c)) = &r { - let v = serde_json::to_value(c).unwrap_or_default(); - task::after(&self.socket, step, &v, t0.elapsed().as_millis() as u64).await; - } - r - } - task::Before::Refuse(m) => { - Ok(input_error(m, &name, Delivery::NotSent, Some(FailureStage::Preflight)).into()) - } - } - }; - tokio::select! { - r = work => r, - _ = context.ct.cancelled() => Ok(input_error(ictl_l10n::tr!("调用已取消", "Call cancelled"), &name, Delivery::Unknown, None).into()), - } - } - - async fn call_tool_cancellable( - &self, - request: CallToolRequestParams, - context: &RequestContext, - ) -> Result { - // rmcp 收到取消通知只是置这个令牌,不会中止处理:自己停下。丢掉进行中的调用会断开到守护进程的连接, - // 守护进程那边还在排队的请求随之放弃(protocol::call),iphone_batch 剩下的步骤也不再执行 - let name = request.name.clone(); - tokio::select! { - r = self.call_tool_inner(request) => r, - _ = context.ct.cancelled() => Ok(input_error(ictl_l10n::tr!("调用已取消", "Call cancelled"), &name, Delivery::Unknown, None).into()), - } - } - - async fn call_tool_inner(&self, request: CallToolRequestParams) -> Result { - let args = request.arguments.unwrap_or_default(); - if let Err(e) = check_args(&request.name, &args, &[], true) { - return Ok(input_error(e, &request.name, Delivery::NotSent, Some(FailureStage::Preflight)).into()); - } - let then = match parse_then(&args) { - Ok(t) => t, - Err(e) => return Ok(input_error(e, &request.name, Delivery::NotSent, Some(FailureStage::Preflight)).into()), - }; - if request.name == "iphone_batch" { - return Ok(self.batch(&args, then).await.into()); - } - if DEV_TOOLS.contains(&&*request.name) && !dev_tools_enabled() { - let name = &request.name; - return Ok(to_result(Response::error(ictl_l10n::trf!( - "{name} 是开发者工具,要先设 IPHONE_CONTROL_DEV_TOOLS=1", - "{name} is a developer tool; set IPHONE_CONTROL_DEV_TOOLS=1 first" - ))) - .into()); - } - let req = match to_request(&request.name, &args) { - Ok(r) => r, - Err(e) => return Ok(input_error(e, &request.name, Delivery::NotSent, Some(FailureStage::Preflight)).into()), - }; - // then 只对操作类工具有意义;看界面的工具本身就是返回界面 - // A single input and its readbacks must all apply to the same device. Tasks already pin theirs. - let udid = if req.reports_delivery() && !protocol::in_task() { - match self.controlled_udid().await { - Ok(id) => Some(id), - Err((message, stage)) => { - return Ok(input_error(message, &request.name, Delivery::NotSent, Some(stage)).into()); - } - } - } else { - None - }; - let resp = self.call_on(&req, udid.as_deref()).await; - let input = req.reports_delivery().then(|| InputResult { - delivery: resp.delivery(&req), - stage: resp.failure_stage(), - field: resp.field_readback(&req), - udid: udid.as_deref(), - }); - if matches!(req, Request::ScrollCollect(_)) { - return Ok(to_result(resp).into()); - } - Ok(match (resp, input) { - (Response::Error { mut message, .. }, Some(input)) => { - add_delivery_hint(&mut message, input.delivery); - self.finish(message, true, then, false, false, Some(input)).await - } - (Response::Text { text, outcome, .. }, input) if req.is_device_action() => { - // 结果里已经说了有弹窗(启动 App 被挡)就不再查 - let check = wants_alert_check(&req) && !protocol::alert_reported(&text, outcome); - // 按名字没点到东西:界面没动过,不用等它稳定,直接给界面(按名字点击刚读过的树) - let settle = !tap_missed(&text, outcome); - self.finish(text, false, then, check, settle, input).await - } - (resp, _) => to_result(resp), - } - .into()) - } - - async fn call(&self, req: &Request) -> Response { - self.call_on(req, None).await - } - - /// `expect_udid`:守护进程正在控制的不是这台就不执行(见 [`protocol::EXPECT_UDID`]) - async fn call_on(&self, req: &Request, expect_udid: Option<&str>) -> Response { - // 守护进程正忙(例如在自动解锁)时会排队;最多等 150 秒,免得 agent 一直挂着。An install uploads the package and - // can take several minutes on its own - let wait = if matches!(req, Request::InstallApp { .. }) { 660 } else { 150 }; - // in a task the daemon holds calls while the user has paused or taken over, as long as that takes - let wait = (!protocol::in_task()).then(|| Duration::from_secs(wait)); - protocol::exchange_on(&self.socket, req, wait, expect_udid, None, None).await.unwrap_or_else(|e| { - let reason = e.source; - let message = if e.failure.stage == FailureStage::Connect { - ictl_l10n::trf!( - "连不上守护进程({}):{reason};确认守护进程在运行(iphone-control status)", - "Can't reach the daemon ({}): {reason}; make sure the daemon is running (iphone-control status)", - self.socket.display() - ) - } else { - ictl_l10n::trf!("守护进程请求失败: {reason}", "Daemon request failed: {reason}") - }; - Response::error(message).with_failure(e.failure.delivery, e.failure.stage) - }) - } - - /// 操作完成后:按 then 等界面稳定,再附上元素列表或截图(等稳定时顺带提醒弹窗)。 - /// 不带 then 时,`alert_check` 为真就查一下有没有系统弹窗挡着。`settle` 为假(什么都没点)时不等稳定 - async fn finish( - &self, - mut text: String, - failed: bool, - opts: ThenOpts, - alert_check: bool, - settle: bool, - input: Option>, - ) -> CallToolResult { - let expect_udid = input.as_ref().and_then(|i| i.udid); - let mut elements = None; - let mut readback = json!({"settle": "not_requested", "screen": "not_requested"}); - let mut image = None; - if opts.then == Then::None { - if alert_check { - match self.call_on(&Request::AlertCheck, expect_udid).await { - Response::Text { text: t, .. } => { - text += &t; - readback["alert"] = "ok".into(); - } - Response::Error { message, .. } if input.is_some() => { - text += &ictl_l10n::trf!("\n(检查弹窗失败:{message})", "\n(alert check failed: {message})"); - readback["alert"] = "failed".into(); - } - _ => readback["alert"] = "failed".into(), - } - } - } else { - if settle { - match self.call_on(&Request::Settle { max_ms: opts.settle_ms }, expect_udid).await { - Response::Text { text: t, .. } => { - text += &format!("\n{t}"); - readback["settle"] = "ok".into(); - } - Response::Error { message, .. } => { - text += &ictl_l10n::trf!( - "\n(等界面稳定失败:{message})", - "\n(waiting for the screen to settle failed: {message})" - ); - readback["settle"] = "failed".into(); - } - _ => readback["settle"] = "failed".into(), - } - } - let read = match opts.then { - Then::Elements(filter) => { - Request::ListElements { filter, limit: THEN_LIMIT, max_age_ms: THEN_SETTLE_MS, keep_locked: false } - } - Then::Screenshot(region) => Request::Screenshot { region }, - Then::None => unreachable!(), - }; - let screen = match self.call_on(&read, expect_udid).await { - Response::Text { text: t, data, .. } if matches!(read, Request::ListElements { .. }) => { - elements = data; - text += &ictl_l10n::trf!("\n--- 操作后的界面 ---\n{t}", "\n--- Screen after the action ---\n{t}"); - "ok" - } - Response::Image { jpeg_base64, caption } if matches!(read, Request::Screenshot { .. }) => { - image = Some((jpeg_base64, caption)); - "ok" - } - Response::Error { message, .. } => { - text += &ictl_l10n::trf!("\n(读界面失败:{message})", "\n(reading the screen failed: {message})"); - "failed" - } - _ => { - text += ictl_l10n::tr!("\n(未收到请求的界面)", "\n(The requested screen was not returned.)"); - "failed" - } - }; - readback["screen"] = screen.into(); - } - let read_failed = readback.as_object().unwrap().values().any(|v| v == "failed"); - if input.is_some() && read_failed && !failed { - text += ictl_l10n::tr!( - "\n请单独读取屏幕确认结果,避免重复之前的输入。", - "\nRead the screen separately before repeating any input." - ); - } - let mut blocks = vec![ContentBlock::text(text)]; - if let Some((jpeg, caption)) = image { - blocks.push(ContentBlock::image(jpeg, "image/jpeg")); - blocks.push(ContentBlock::text(caption)); - } - let mut result = if failed { CallToolResult::error(blocks) } else { CallToolResult::success(blocks) }; - result = with_element_data(result, elements); - if let Some(input) = input { - let data = result.structured_content.get_or_insert_with(|| json!({})); - data["delivery"] = json!(input.delivery); - data["readback"] = readback; - if let Some(field) = input.field { - data["readback"]["field"] = field.into(); - } - if let Some(stage) = input.stage.or_else(|| (read_failed && !failed).then_some(FailureStage::Readback)) { - data["stage"] = json!(stage); - } - } - result - } - - /// The cached daemon snapshot includes device.udid on older daemons as well. - async fn controlled_udid(&self) -> Result { - match self.call(&Request::Daemon).await { - Response::Text { text, .. } => { - if let Ok(snapshot) = serde_json::from_str::(&text) - && let Some(id) = snapshot["device"]["udid"].as_str().filter(|id| !id.is_empty()) - { - return Ok(id.to_owned()); - } - } - Response::Error { message, failure, .. } => { - return Err((message, failure.map_or(FailureStage::Preflight, |f| f.stage))); - } - Response::Image { .. } => {} - } - Err(( - ictl_l10n::tr!( - "无法确定当前控制的设备,操作未执行", - "Cannot identify the controlled device; action not sent" - ) - .into(), - FailureStage::Preflight, - )) - } - - /// 按顺序执行;某一步出错就停,说明是第几步、后面几步没执行。出错时也按 then 附上当前界面,方便看停在哪 - async fn batch(&self, args: &Map, then: ThenOpts) -> CallToolResult { - let steps = match batch_steps(args) { - Ok(s) => s, - Err(e) => return to_result(Response::error(e)), - }; - let total = steps.len(); - // 每一步都要求还是开始时控制的那台:自动选设备时拔掉它会改控另一台,剩下的步骤不能落到那台上 - let udid = self.controlled_udid().await.ok(); - let mut lines = Vec::new(); - // 最后一步是不是需要查弹窗的操作 - let mut check = false; - for (i, step) in steps.into_iter().enumerate() { - let n = i + 1; - match step { - Step::Wait(d) => { - tokio::time::sleep(d).await; - lines.push(ictl_l10n::trf!("{n}. wait → 等了 {} 秒", "{n}. wait → waited {} s", d.as_secs_f64())); - } - Step::Request { tool, req } => match self.call_on(&req, udid.as_deref()).await { - // 按名字没点到(toolkit 兼容:单独调用时是普通结果)在批量里要停下:后面的步骤都建立在它点中的前提上 - Response::Text { text, outcome, .. } - if tool == "iphone_tap_element" && tap_missed(&text, outcome) => - { - lines.push(format!("{n}. {tool} → {text}")); - if n < total { - lines.push(ictl_l10n::trf!( - "第 {n} 步没点到,后面 {} 步没有执行", - "Step {n} tapped nothing, the remaining {} step(s) didn't run", - total - n - )); - } - return self.finish(lines.join("\n"), true, then, false, true, None).await; - } - Response::Text { text, outcome, .. } => { - check = wants_alert_check(&req) && !protocol::alert_reported(&text, outcome); - lines.push(format!("{n}. {tool} → {text}")); - } - Response::Image { caption, .. } => lines.push(format!("{n}. {tool} → {caption}")), - Response::Error { message, .. } => { - lines.push(ictl_l10n::trf!("{n}. {tool} → 出错:{message}", "{n}. {tool} → error: {message}")); - if n < total { - lines.push(ictl_l10n::trf!( - "第 {n} 步出错,后面 {} 步没有执行", - "Step {n} failed, the remaining {} step(s) didn't run", - total - n - )); - } - return self.finish(lines.join("\n"), true, then, true, true, None).await; - } - }, - } - } - self.finish(lines.join("\n"), false, then, check, true, None).await - } -} - -/// 在 stdin/stdout 上运行 MCP 服务直到客户端断开 -/// The MCP server on stdin/stdout. `lease` is taken for each tool call, not for the life of the process: agents keep -/// this process running for hours, and an update has to wait only for calls under way -pub async fn serve_stdio(socket: PathBuf, lease: Option) -> anyhow::Result<()> { - let running = McpServer { socket, task: task::join_from_env(), lease }.serve(rmcp::transport::stdio()).await?; - running.waiting().await?; - Ok(()) -} +mod args; +mod batch; +mod result; +mod schema; +mod server; +pub use args::*; +pub use batch::*; +pub use result::*; +pub use schema::*; +pub use server::*; #[cfg(test)] -mod tests { - use super::*; - - fn args(v: Value) -> Map { - v.as_object().cloned().unwrap() - } - - #[tokio::test] - async fn input_delivery_is_independent_of_field_and_screen_readback() { - use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; - let socket = PathBuf::from(format!("/tmp/ictl-single-input-{}.sock", std::process::id())); - let server = McpServer { socket: socket.clone(), task: false, lease: None }; - let call = |name, args: Value| { - let req = CallToolRequestParams::new(name).with_arguments(args.as_object().unwrap().clone()); - let server = &server; - async move { - let CallToolResponse::Complete(result) = server.call_tool_inner(req).await.unwrap() else { panic!() }; - result - } - }; - let tap = json!({"x": 1, "y": 2}); - let unavailable = call("iphone_tap", tap.clone()).await; - let data = unavailable.structured_content.unwrap(); - assert_eq!(data["delivery"], "not_sent"); - assert_eq!(data["stage"], "connect"); - - let listener = tokio::net::UnixListener::bind(&socket).unwrap(); - let exchanges = [ - ("tap", None), // request reached daemon, reply lost - ("tap", Some(Response::text("Tapped"))), - ("settle", Some(Response::text("Settled"))), - ("screenshot", Some(Response::error("controlled device changed to phone-B"))), - ("tap", Some(Response::text("Tapped"))), - ("settle", Some(Response::error("lost settle"))), - ( - "list_elements", - Some(Response::text_data( - "items", - Default::default(), - Some(protocol::Data::Elements { elements: vec![], matched_count: Some(3), truncated: Some(true) }), - )), - ), - ( - "type_text", - Some(Response::text_with( - "Typed", - protocol::Outcome { field_verified: Some(false), ..Default::default() }, - )), - ), - ("alert_check", Some(Response::text(""))), - ("type_text", Some(Response::error("field mismatch").with_failure(Delivery::Sent, FailureStage::Readback))), - ( - "tap_element", - Some(Response::text_with("No match", protocol::Outcome { tapped_nothing: true, ..Default::default() })), - ), - ("alert_check", Some(Response::text(""))), - ]; - let daemon = async { - let mut first_snapshot = true; - for (op, reply) in exchanges { - let mut peer = loop { - let (mut peer, _) = listener.accept().await.unwrap(); - let mut line = String::new(); - BufReader::new(&mut peer).read_line(&mut line).await.unwrap(); - let request: Value = serde_json::from_str(&line).unwrap(); - if request["op"] == "daemon" { - // Old daemon snapshot: only the controlled device's UDID is needed. - let snapshot = if std::mem::take(&mut first_snapshot) { - Response::text(r#"{"device":null}"#) - } else { - Response::text(r#"{"device":{"udid":"phone-A"}}"#) - }; - peer.write_all(format!("{}\n", json!(snapshot)).as_bytes()).await.unwrap(); - continue; - } - assert_eq!(request["op"], op); - assert_eq!(request[protocol::EXPECT_UDID], "phone-A", "{request}"); - break peer; - }; - if let Some(reply) = reply { - peer.write_all(format!("{}\n", json!(reply)).as_bytes()).await.unwrap(); - } - } - }; - let actions = async { - let missing = call("iphone_tap", tap.clone()).await; - let data = missing.structured_content.unwrap(); - assert_eq!(data["delivery"], "not_sent"); - assert_eq!(data["stage"], "preflight"); - - let lost = call("iphone_tap", tap).await; - assert_eq!(lost.is_error, Some(true)); - let data = lost.structured_content.unwrap(); - assert_eq!(data["delivery"], "unknown"); - assert_eq!(data["stage"], "reply"); - - let tapped = call("iphone_tap", json!({"x":1,"y":2,"then":"screenshot"})).await; - assert_ne!(tapped.is_error, Some(true)); - let data = tapped.structured_content.unwrap(); - assert_eq!(data["delivery"], "sent"); - assert_eq!(data["stage"], "readback"); - assert_eq!(data["readback"], json!({"settle":"ok", "screen":"failed"})); - - let listed = call("iphone_tap", json!({"x":1,"y":2,"then":"elements"})).await; - assert_ne!(listed.is_error, Some(true)); - let data = listed.structured_content.unwrap(); - assert_eq!(data["delivery"], "sent"); - assert_eq!(data["readback"], json!({"settle":"failed", "screen":"ok"})); - assert_eq!(data["matched_count"], 3); - assert_eq!(data["truncated"], true); - - let text = json!({"text":"x"}); - let typed = call("iphone_type_text", text.clone()).await.structured_content.unwrap(); - assert_eq!(typed["delivery"], "sent"); - assert_eq!(typed["readback"]["field"], "unverified"); - let mismatch = call("iphone_type_text", text.clone()).await; - assert_eq!(mismatch.is_error, Some(true)); - let data = mismatch.structured_content.unwrap(); - assert_eq!(data["delivery"], "sent"); - assert_eq!(data["readback"]["field"], "failed"); - - let missed = call("iphone_tap_element", text).await; - assert_ne!(missed.is_error, Some(true)); - assert_eq!(missed.structured_content.unwrap()["delivery"], "not_sent"); - }; - tokio::time::timeout(Duration::from_secs(4), async { tokio::join!(daemon, actions) }).await.unwrap(); - std::fs::remove_file(socket).unwrap(); - } - - fn has_cjk(s: &str) -> bool { - s.chars().any(|c| matches!(c, '\u{3000}'..='\u{303f}' | '\u{4e00}'..='\u{9fff}' | '\u{ff00}'..='\u{ffef}')) - } - - /// With IPHONE_CONTROL_LANG=en nothing the agent reads up front is Chinese: instructions, tool - /// descriptions, titles and parameter docs (only examples of Chinese input may stay) - #[test] - fn delivery_hints_do_not_repeat_punctuation_or_existing_screen_guidance() { - ictl_l10n::with_lang(ictl_l10n::Lang::En, || { - let mut message = "Focus changed. Inspect the screen.".to_owned(); - add_delivery_hint(&mut message, Delivery::Sent); - assert_eq!(message, "Focus changed. Inspect the screen. Input was sent."); - }); - ictl_l10n::with_lang(ictl_l10n::Lang::Zh, || { - let mut message = "请求超时,请先截图确认。".to_owned(); - add_delivery_hint(&mut message, Delivery::Unknown); - assert_eq!(message, "请求超时,请先截图确认。输入可能已送达。"); - }); - } - - #[test] - fn english_tool_definitions_have_no_chinese() { - use ictl_l10n::{Lang, with_lang}; - with_lang(Lang::En, || { - assert!(!has_cjk(instructions()), "{}", instructions()); - for t in tools_with(true) { - let json = serde_json::to_string(&t).unwrap(); - assert!(!has_cjk(&json), "{}: {json}", t.name); - } - }); - with_lang(Lang::Zh, || assert!(has_cjk(instructions()))); - } - - /// scroll 是可选的:不给就和以前一样只看当前屏幕;方向只认 down / up,次数 1 到上限 - #[test] - fn tap_element_scroll_search_is_optional_and_checked() { - let req = |v: Value| to_request("iphone_tap_element", &args(v)); - let plain = req(json!({"text": "隐私"})).unwrap(); - assert_eq!(plain, Request::TapElement { text: "隐私".into(), index: 0, max_age_ms: 0, scroll: None }); - let down = req(json!({"text": "隐私", "scroll": "down"})).unwrap(); - let s = |down, max| Some(protocol::ScrollSearch { down, max }); - assert_eq!(down, Request::TapElement { text: "隐私".into(), index: 0, max_age_ms: 0, scroll: s(true, 8) }); - let up = req(json!({"text": "隐私", "scroll": "up", "max_scrolls": 3})).unwrap(); - assert_eq!(up, Request::TapElement { text: "隐私".into(), index: 0, max_age_ms: 0, scroll: s(false, 3) }); - for bad in [ - json!({"text": "x", "scroll": "left"}), - json!({"text": "x", "scroll": "down", "max_scrolls": 0}), - json!({"text": "x", "scroll": "down", "max_scrolls": 16}), - json!({"text": "x", "scroll": true}), - ] { - assert!(req(bad).is_err()); - } - // reused in a batch, the scroll search stays - let steps = batch_steps(&args( - json!({"reuse_elements": true, "steps": [{"tool": "iphone_tap_element", "text": "x", "scroll": "down"}]}), - )); - assert!(matches!(&steps.unwrap()[0], Step::Request { req: Request::TapElement { scroll: Some(_), .. }, .. })); - } - - /// hold defaults to 0 (a plain swipe, same request as before) and is passed through when given - #[test] - fn swipe_hold_defaults_to_zero() { - let plain = to_request("iphone_swipe", &args(json!({"from_x": 1, "from_y": 2, "to_x": 3, "to_y": 4}))).unwrap(); - assert_eq!(plain, Request::Swipe { from: (1.0, 2.0), to: (3.0, 4.0), seconds: 0.3, hold: 0.0 }); - let held = json!({"from_x": 1, "from_y": 2, "to_x": 3, "to_y": 4, "seconds": 0.7, "hold": 0.6}); - let held = to_request("iphone_swipe", &args(held)).unwrap(); - assert_eq!(held, Request::Swipe { from: (1.0, 2.0), to: (3.0, 4.0), seconds: 0.7, hold: 0.6 }); - assert!( - to_request("iphone_swipe", &args(json!({"from_x": 1, "from_y": 2, "to_x": 3, "to_y": 4, "hold": "x"}))) - .is_err() - ); - } - - /// one_gesture 把全是坐标点击的批量并成一个 TapSequence;混了别的步骤就报错,一步都不执行 - #[test] - fn one_gesture_turns_taps_into_one_sequence() { - let steps = batch_steps(&args(json!({"one_gesture": true, "steps": [ - {"tool": "iphone_tap", "x": 60, "y": 548}, - {"tool": "iphone_tap", "x": 23, "y": 548.5} - ]}))); - let req = Request::TapSequence { points: vec![(60.0, 548.0), (23.0, 548.5)] }; - assert_eq!(steps, Ok(vec![Step::Request { tool: "iphone_tap".into(), req }])); - for other in [ - json!({"tool": "iphone_tap_element", "text": "1"}), - json!({"tool": "wait", "seconds": 0.1}), - json!({"tool": "iphone_type_text", "text": "1"}), - ] { - let steps = json!({"one_gesture": true, "steps": [{"tool": "iphone_tap", "x": 1, "y": 2}, other]}); - assert!(batch_steps(&args(steps)).is_err()); - } - // without it a batch of taps stays step by step - let steps = batch_steps(&args(json!({"steps": [{"tool": "iphone_tap", "x": 1, "y": 2}]}))).unwrap(); - assert_eq!( - steps, - vec![Step::Request { tool: "iphone_tap".into(), req: Request::Tap { x: 1.0, y: 2.0, count: 1 } }] - ); - // a step's count can't go into one gesture: an error, not one tap - let steps = json!({"one_gesture": true, "steps": [{"tool": "iphone_tap", "x": 1, "y": 2, "count": 2}]}); - assert!(batch_steps(&args(steps)).is_err()); - } - - /// iphone_tap 不带 count 是点一下;count 要是 1 到 MAX_TAP_COUNT 的整数,给错了报错、不点,不悄悄改成 1 - #[test] - fn tap_count_defaults_to_one_and_rejects_out_of_range() { - let tap = |v: Value| to_request("iphone_tap", &args(v)); - assert_eq!(tap(json!({"x": 1, "y": 2})), Ok(Request::Tap { x: 1.0, y: 2.0, count: 1 })); - assert_eq!(tap(json!({"x": 1, "y": 2, "count": 5})), Ok(Request::Tap { x: 1.0, y: 2.0, count: 5 })); - for bad in [json!(0), json!(11), json!(2.5), json!(-1), json!("two")] { - assert!(tap(json!({"x": 1, "y": 2, "count": bad})).is_err(), "{bad}"); - } - // a batch step takes it too - let steps = batch_steps(&args(json!({"steps": [{"tool": "iphone_tap", "x": 1, "y": 2, "count": 2}]}))); - let req = Request::Tap { x: 1.0, y: 2.0, count: 2 }; - assert_eq!(steps, Ok(vec![Step::Request { tool: "iphone_tap".into(), req }])); - } - - #[test] - fn scroll_collection_is_bounded_and_changes_the_viewport() { - let req = |v| { - let args = args(v); - check_args("iphone_scroll_collect", &args, &[], true)?; - to_request("iphone_scroll_collect", &args) - }; - let r = - req(json!({"scroll": "up", "max_scrolls": 1, "filter": "Cell", "until": "General", "limit": 3})).unwrap(); - assert_eq!( - r, - Request::ScrollCollect(protocol::ScrollCollect { - down: false, - max_scrolls: 1, - filter: "Cell".into(), - until: "General".into(), - limit: 3, - x: None, - }) - ); - // an iPad split view's sidebar - let Request::ScrollCollect(scan) = req(json!({"x": 160})).unwrap() else { panic!() }; - assert_eq!(scan.x, Some(160.0)); - assert!(r.is_device_action()); - assert!(req(json!({})).is_ok()); - for bad in [ - json!({"scroll":"left"}), - json!({"max_scrolls":0}), - json!({"max_scrolls":16}), - json!({"limit":0}), - json!({"limit":151}), - json!({"limit":2.5}), - json!({"x":-1}), - json!({"x":"sidebar"}), - json!({"max_scroll":2}), - ] { - assert!(req(bad.clone()).is_err(), "{bad}"); - } - let result = to_result(Response::text_data( - "row limit reached", - Default::default(), - Some(protocol::Data::ScrollCollection { - stop_reason: protocol::ScrollStop::Limit, - scrolls: 2, - rows: vec![protocol::ScrollRow { - kind: "Cell".into(), - label: "One".into(), - name: "".into(), - value: "".into(), - }], - matched: None, - }), - )); - let data = result.structured_content.unwrap(); - assert_eq!(data["stop_reason"], "limit"); - assert_eq!(data["rows"][0]["label"], "One"); - assert!(data["matched"].is_null()); - } - - #[test] - fn alert_check_after_actions_but_not_buttons_or_reads() { - assert!(wants_alert_check(&Request::Swipe { from: (0.0, 0.0), to: (1.0, 1.0), seconds: 0.3, hold: 0.0 })); - assert!(wants_alert_check(&Request::LaunchApp { app: "微信".into() })); - assert!(!wants_alert_check(&Request::PressButton { button: "home".into() })); - assert!(!wants_alert_check(&Request::TerminateApp { app: "微信".into() })); - assert!(!wants_alert_check(&Request::Status)); - } - - #[test] - fn toolkit_tools_plus_wait_for_batch_and_devices() { - let names: Vec<_> = tools().iter().map(|t| t.name.to_string()).collect(); - assert_eq!(names.len(), 18); - // the developer tools only with IPHONE_CONTROL_DEV_TOOLS - let dev: Vec<_> = tools_with(true).iter().skip(18).map(|t| t.name.to_string()).collect(); - assert_eq!(dev, DEV_TOOLS); - assert_eq!(tools_with(false).len(), 18); - for n in [ - "iphone_status", - "iphone_screenshot", - "iphone_scroll_collect", - "iphone_tap_element", - "iphone_open_url", - "iphone_list_devices", - "iphone_select_device", - ] { - assert!(names.contains(&n.to_owned()), "{n}"); - } - for t in tools_with(true).into_iter().filter(|t| t.name != "iphone_batch") { - let no_required = t.input_schema.get("required").unwrap().as_array().unwrap().is_empty(); - assert_eq!(to_request(&t.name, &Map::new()).is_ok(), no_required, "{}", t.name); - } - } - - /// 注解与工具实际行为一致:看界面的只读,改界面的不是;每个参数都有说明 - #[test] - fn annotations_and_param_docs() { - for t in tools_with(true) { - let a = t.annotations.as_ref().unwrap_or_else(|| panic!("{} 没有注解", t.name)); - assert!(a.title.is_some(), "{}", t.name); - let probe = || { - let props = t.input_schema["properties"].as_object().unwrap(); - let mut m = Map::new(); - for k in t.input_schema["required"].as_array().unwrap() { - let k = k.as_str().unwrap(); - let v = match props[k]["type"].as_str() { - Some("number") => json!(1), - Some("array") => json!([{"tool": "wait", "seconds": 0}]), - _ if k == "button" => json!("home"), - _ => json!("x"), - }; - m.insert(k.to_owned(), v); - } - m - }; - let read_only = match to_request(&t.name, &probe()) { - Ok(r) => !r.is_device_action(), - Err(_) => false, // iphone_batch - }; - assert_eq!(a.read_only_hint, Some(read_only), "{}", t.name); - for (k, v) in t.input_schema["properties"].as_object().unwrap() { - let d = v["description"].as_str().unwrap_or_default(); - assert!(!d.is_empty(), "{}.{k} 缺少说明", t.name); - } - } - } - - #[test] - fn defaults_match_toolkit() { - assert_eq!( - to_request("iphone_list_elements", &Map::new()).unwrap(), - Request::ListElements { filter: String::new(), limit: 150, max_age_ms: 0, keep_locked: false } - ); - assert_eq!( - to_request("iphone_swipe", &args(json!({"from_x": 1, "from_y": 2, "to_x": 3, "to_y": 4}))).unwrap(), - Request::Swipe { from: (1.0, 2.0), to: (3.0, 4.0), seconds: 0.3, hold: 0.0 } - ); - assert_eq!( - to_request("iphone_long_press", &args(json!({"x": 1, "y": 2}))).unwrap(), - Request::LongPress { x: 1.0, y: 2.0, seconds: 1.0 } - ); - assert_eq!( - to_request("iphone_type_text", &args(json!({"text": "设置"}))).unwrap(), - Request::TypeText { text: "设置".into(), submit: false } - ); - } - - #[test] - fn then_is_offered_on_actions_only() { - let has_then = |name: &str| { - let t = tools().into_iter().find(|t| t.name == name).unwrap(); - t.input_schema["properties"].get("then").is_some() - }; - for n in [ - "iphone_tap", - "iphone_tap_element", - "iphone_swipe", - "iphone_type_text", - "iphone_launch_app", - "iphone_batch", - ] { - assert!(has_then(n), "{n}"); - } - for n in ["iphone_status", "iphone_screenshot", "iphone_list_elements", "iphone_wait_for"] { - assert!(!has_then(n), "{n}"); - } - let then = |v: Value| parse_then(&args(v)).map(|o| o.then); - assert_eq!(parse_then(&Map::new()).unwrap(), ThenOpts { then: Then::None, settle_ms: THEN_SETTLE_MS }); - assert_eq!(then(json!({"then": "elements", "then_filter": "设置"})).unwrap(), Then::Elements("设置".into())); - assert_eq!(then(json!({"then": "screenshot"})).unwrap(), Then::Screenshot(None)); - assert_eq!( - then(json!({"then": "screenshot", "then_region": [0, 295, 430, 460]})).unwrap(), - Then::Screenshot(Some((0.0, 295.0, 430.0, 460.0))) - ); - assert!(then(json!({"then": "screenshot", "then_region": [0, 1, 2]})).is_err()); - assert!(then(json!({"then": "screenshot", "then_region": [0, 1, 0, 5]})).is_err()); - assert!(then(json!({"then": "video"})).is_err()); - assert_eq!(parse_then(&args(json!({"then": "screenshot", "then_settle": 5}))).unwrap().settle_ms, 5000); - assert!(parse_then(&args(json!({"then_settle": 30}))).is_err()); - } - - /// #158: an argument the tool doesn't take is refused, not dropped (a wait for disappearance ran as a wait for - /// appearance and answered at once) - #[test] - fn unknown_arguments_are_refused() { - // an argument from another version (here: misspelt) is refused and the tool's own are listed - let e = check_args("iphone_wait_for", &args(json!({"text": "飞行模式", "until": "disappeared"})), &[], true) - .unwrap_err(); - assert!(e.contains("until") && e.contains("state") && e.contains("timeout"), "{e}"); - assert!(check_args("iphone_wait_for", &args(json!({"text": "x", "state": "disappeared"})), &[], true).is_ok()); - assert!(check_args("iphone_type_text", &args(json!({"text": "", "replace": true})), &[], true).is_ok()); - // misspelt - assert!(check_args("iphone_type_text", &args(json!({"text": "a", "sumbit": true})), &[], true).is_err()); - // every documented argument, then on an action, null for a default - assert!( - check_args( - "iphone_type_text", - &args(json!({"text": "a", "submit": true, "then": "elements", - "then_filter": "x", "then_settle": 1})), - &[], - true - ) - .is_ok() - ); - assert!(check_args("iphone_list_elements", &args(json!({"limit": null})), &[], true).is_ok()); - // then only where the schema lists it - assert!(check_args("iphone_screenshot", &args(json!({"then": "elements"})), &[], true).is_err()); - assert!(check_args("iphone_status", &args(json!({})), &[], true).is_ok()); - assert!(check_args("iphone_batch", &args(json!({"steps": [], "then": "screenshot"})), &[], true).is_ok()); - // developer tools and the confirm tool have their own; a tool this server doesn't know is left alone - assert!(check_args("iphone_web_eval", &args(json!({"expression": "1", "timeout": 2})), &[], true).is_ok()); - assert!( - check_args(task::CONFIRM_TOOL, &args(json!({"action": "a", "detail": "b", "x": 1})), &[], false).is_err() - ); - assert!(check_args("no_such_tool", &args(json!({"x": 1})), &[], true).is_ok()); - } - - #[test] - fn batch_steps_refuse_unknown_arguments() { - let bad = |step: Value| batch_steps(&args(json!({"steps": [step]}))).unwrap_err(); - let e = bad(json!({"tool": "iphone_wait_for", "text": "x", "until": "disappeared"})); - assert!(e.contains("第 1 步") && e.contains("until"), "{e}"); - // a step's then would be ignored (the batch's then applies): refused, not dropped - assert!(bad(json!({"tool": "iphone_tap", "x": 1, "y": 2, "then": "elements"})).contains("then")); - assert!(bad(json!({"tool": "wait", "seconds": 1, "secs": 2})).contains("secs")); - } - - #[test] - fn element_lists_declare_their_output_schema() { - let tools = standard_tools(); - let declared: Vec<_> = tools.iter().filter(|t| t.output_schema.is_some()).map(|t| &*t.name).collect(); - assert_eq!(declared, ["iphone_list_elements"]); - let schema = tools.iter().find(|t| t.name == "iphone_list_elements").and_then(|t| t.output_schema.clone()); - assert_eq!(schema.unwrap()["required"], json!(["elements"])); - } - - #[test] - fn batch_steps_are_checked_before_anything_runs() { - let steps = batch_steps(&args(json!({"steps": [ - {"tool": "iphone_tap_element", "text": "One"}, - {"tool": "wait", "seconds": 0.5}, - {"tool": "iphone_tap", "x": 1, "y": 2}, - {"tool": "iphone_wait_for", "text": "完成", "timeout": 3} - ]}))) - .unwrap(); - assert_eq!(steps.len(), 4); - assert_eq!(steps[1], Step::Wait(std::time::Duration::from_millis(500))); - assert_eq!( - steps[3], - Step::Request { - tool: "iphone_wait_for".into(), - req: Request::WaitFor { text: "完成".into(), timeout_ms: 3000 } - } - ); - // 第 2 步参数错:一步都不执行,报出是第几步 - let e = batch_steps(&args( - json!({"steps": [{"tool": "iphone_tap", "x": 1, "y": 2}, {"tool": "iphone_tap", "x": 1}]}), - )) - .unwrap_err(); - assert!(e.contains("第 2 步"), "{e}"); - // 看界面的工具、未知工具、批量套批量都不行 - for bad in ["iphone_screenshot", "iphone_batch", "rm"] { - assert!(batch_steps(&args(json!({"steps": [{"tool": bad}]}))).is_err(), "{bad}"); - } - assert!(batch_steps(&args(json!({"steps": [{"tool": "wait", "seconds": 9}]}))).is_err()); - assert!(batch_steps(&args(json!({"steps": []}))).is_err()); - let many: Vec = (0..21).map(|_| json!({"tool": "wait", "seconds": 0})).collect(); - assert!(batch_steps(&args(json!({"steps": many}))).is_err()); - } - - #[test] - fn reuse_elements_only_affects_tap_element_steps() { - let steps = |reuse: bool| { - batch_steps(&args(json!({"reuse_elements": reuse, "steps": [ - {"tool": "iphone_tap_element", "text": "One"}, - {"tool": "iphone_tap", "x": 1, "y": 2} - ]}))) - .unwrap() - }; - assert_eq!( - steps(true)[0], - Step::Request { - tool: "iphone_tap_element".into(), - req: Request::TapElement { text: "One".into(), index: 0, max_age_ms: BATCH_REUSE_MS, scroll: None } - } - ); - assert!(matches!(&steps(false)[0], Step::Request { req: Request::TapElement { max_age_ms: 0, .. }, .. })); - assert_eq!(steps(true)[1], steps(false)[1]); - } - - #[test] - fn missed_tap_texts_are_recognised() { - // 旧版本守护进程:没有 outcome,只能认中文开头 - assert!(tap_missed("没找到包含 \"x\" 的元素,先用 iphone_list_elements 或截图看看屏幕", None)); - assert!(tap_missed("只匹配到 1 个:\nButton \"x\"", None)); - assert!(!tap_missed("已点击 Button \"x\"", None)); - assert!(tap_missed("被挡住:Button \"x\" 整个被「浮层」盖住,没有点", None)); - assert!(!tap_missed("已点击 Button \"x\";它的中心被「搜索」盖住,改点没被盖住的 (215,848)", None)); - // 新版本:看 outcome,与语言无关 - let missed = protocol::Outcome { tapped_nothing: true, ..Default::default() }; - assert!(tap_missed("Covered: Button \"x\" is completely covered", Some(missed))); - assert!(!tap_missed("Tapped Button \"Not found\"", Some(protocol::Outcome::default()))); - } - - #[test] - fn wait_for_timeout_is_bounded() { - assert_eq!( - to_request("iphone_wait_for", &args(json!({"text": "x"}))).unwrap(), - Request::WaitFor { text: "x".into(), timeout_ms: 5000 } - ); - assert!(to_request("iphone_wait_for", &args(json!({"text": "x", "timeout": 60}))).is_err()); - } - - #[test] - fn text_replacement_is_forwarded_only_when_requested() { - let changed = to_request("iphone_type_text", &args(json!({"text": "蓝牙", "replace": true}))).unwrap(); - assert_eq!(serde_json::to_value(changed).unwrap()["op"], "replace_text"); - let default = to_request("iphone_type_text", &args(json!({"text": "蓝牙"}))).unwrap(); - assert_eq!(serde_json::to_value(default).unwrap()["op"], "type_text"); - } - - #[test] - fn wait_for_accepts_disappeared_and_rejects_unknown_state() { - let req = to_request("iphone_wait_for", &args(json!({"text": "设置", "state": "disappeared"}))).unwrap(); - assert_eq!(serde_json::to_value(req).unwrap()["op"], "wait_for_disappearance"); - assert!(to_request("iphone_wait_for", &args(json!({"text": "设置", "state": "any"}))).is_err()); - } - - #[test] - fn element_limit_is_reported_in_structured_content() { - let reply: Response = serde_json::from_value(json!({ - "kind": "text", "text": "one element, 16 more", - "data": { - "type": "elements", - "elements": [{"type":"Button","label":"设置","x":16,"y":16,"width":44,"height":44}], - "matched_count": 17, "truncated": true - } - })) - .unwrap(); - let result = serde_json::to_value(to_result(reply)).unwrap(); - assert_eq!(result["structuredContent"]["elements"].as_array().unwrap().len(), 1); - assert_eq!(result["structuredContent"]["matched_count"], 17); - assert_eq!(result["structuredContent"]["truncated"], true); - } - - #[test] - fn wrong_typed_parameters_are_errors_not_defaults() { - let args = |v: Value| v.as_object().unwrap().clone(); - assert!(to_request("iphone_tap_element", &args(json!({"text": "设置", "index": -1}))).is_err()); - assert!(to_request("iphone_list_elements", &args(json!({"limit": 1.5}))).is_err()); - assert!(to_request("iphone_swipe", &args(json!({"from_x": 1, "from_y": 2, "to_x": "x", "to_y": 4}))).is_err()); - // 写成字符串的数字照收(toolkit 的 pydantic 也收) - assert_eq!( - to_request("iphone_tap_element", &args(json!({"text": "设置", "index": "2"}))).unwrap(), - Request::TapElement { text: "设置".into(), index: 2, max_age_ms: 0, scroll: None } - ); - assert_eq!( - to_request("iphone_list_elements", &args(json!({"limit": null}))).unwrap(), - Request::ListElements { filter: String::new(), limit: 150, max_age_ms: 0, keep_locked: false } - ); - } - - #[test] - fn screenshot_region_needs_all_four() { - assert_eq!(to_request("iphone_screenshot", &Map::new()).unwrap(), Request::Screenshot { region: None }); - assert_eq!( - to_request("iphone_screenshot", &args(json!({"x": 0, "y": 55, "width": 430, "height": 40}))).unwrap(), - Request::Screenshot { region: Some((0.0, 55.0, 430.0, 40.0)) } - ); - assert_eq!( - to_request("iphone_screenshot", &args(json!({"x": 10, "y": 10}))).unwrap_err(), - "放大区域要同时给出 x、y、width、height" - ); - } - - /// 回归用例 #17:预期内的错误要作为工具错误、带可读文字返回 - #[test] - fn errors_become_tool_errors_with_text() { - let r = to_result(Response::error("button 只能是 home / volume_up / volume_down / lock")); - assert_eq!(r.is_error, Some(true)); - assert!(matches!(&r.content[0], ContentBlock::Text(t) if t.text.contains("button 只能是"))); - let img = to_result(Response::Image { jpeg_base64: "AAAA".into(), caption: "430x932 点".into() }); - assert_eq!(img.content.len(), 2); - assert!(to_request("iphone_nope", &Map::new()).is_err()); - } -} +mod tests; diff --git a/crates/ictl-mcp/src/result.rs b/crates/ictl-mcp/src/result.rs new file mode 100644 index 0000000..ed72f6f --- /dev/null +++ b/crates/ictl-mcp/src/result.rs @@ -0,0 +1,162 @@ +use super::*; + +/// tap_element 的结果是不是「没点到」(没找到、index 超出匹配个数、或整个被别的东西盖住) +pub fn tap_missed(text: &str, outcome: Option) -> bool { + protocol::tapped_nothing(text, outcome) +} + +/// 不带 then 的操作做完后要不要查系统弹窗(弹窗挡着时操作都落在弹窗上,WDA 照样报成功)。 +/// 按键自己处理(Home 先查弹窗;锁屏后不用查),结束 App 后前台是主屏,不会冒出新弹窗 +/// Every variant is listed (no `_`), so a new request type has to be decided here +pub fn wants_alert_check(req: &Request) -> bool { + match req { + Request::Tap { .. } + | Request::TapSequence { .. } + | Request::TapElement { .. } + | Request::LongPress { .. } + | Request::Swipe { .. } + | Request::TypeText { .. } + | Request::ReplaceText { .. } + | Request::LaunchApp { .. } + | Request::OpenUrl { .. } => true, + // 按键见 PressButton 自己的弹窗处理;切换设备后新设备的 WDA 还没起来,查不了弹窗; + // 安装、卸载、Web Inspector 不碰屏幕(Web Inspector 也不该为它排队等设备锁) + // the web viewer's finger isn't an MCP tool; the person watching sees any alert + Request::PressButton { .. } + | Request::Touch { .. } + | Request::TerminateApp { .. } + | Request::SelectDevice { .. } + | Request::InstallApp { .. } + | Request::UninstallApp { .. } + | Request::WebEval { .. } + | Request::Status + | Request::ScreenStream + | Request::Screenshot { .. } + | Request::ScrollCollect(_) + | Request::ListElements { .. } + | Request::ListApps { .. } + | Request::Settle { .. } + | Request::AlertCheck + | Request::WaitFor { .. } + | Request::WaitForDisappearance { .. } + | Request::Daemon + | Request::Doctor + | Request::Resign { .. } + | Request::UnlockReset + | Request::ListDevices + | Request::AppLogs { .. } + | Request::CrashReports { .. } + | Request::WebTargets + // tasks: not tools, nothing on the screen + | Request::TaskOpen { .. } + | Request::TaskEvents { .. } + | Request::TaskList + | Request::TaskControl { .. } + | Request::TaskAgent + | Request::TaskCheck + | Request::TaskStep { .. } + | Request::TaskStepDone { .. } + | Request::TaskConfirm { .. } + | Request::TaskNote { .. } + | Request::TaskFinish { .. } => false, + } +} + +/// The shape of [`with_element_data`]' structured content, declared as `iphone_list_elements`' output schema (action +/// tools give it with then=elements, but not always: a declared schema would oblige every result to carry it). +/// `matched_count` and `truncated` are left out by a daemon older than them +pub(crate) fn elements_output_schema() -> Map { + let element = json!({ + "type": "object", + "properties": { + "type": {"type": "string"}, "label": {"type": "string"}, + "x": {"type": "number"}, "y": {"type": "number"}, "width": {"type": "number"}, "height": {"type": "number"} + } + }); + let v = json!({ + "type": "object", + "properties": { + "type": {"const": "elements"}, + "elements": {"type": "array", "items": element, + "description": "the elements listed, at most limit; x/y the top left corner in points"}, + "matched_count": {"type": "integer", "description": "how many elements matched filter in this read, before limit"}, + "truncated": {"type": "boolean", "description": "matched_count is more than limit: some weren't listed"} + }, + "required": ["elements"] + }); + v.as_object().cloned().unwrap_or_default() +} + +pub(crate) fn with_element_data(mut result: CallToolResult, data: Option) -> CallToolResult { + if let Some(data @ (protocol::Data::Elements { .. } | protocol::Data::ScrollCollection { .. })) = data { + result.structured_content = serde_json::to_value(data).ok(); + } + result +} + +/// 守护进程响应 → MCP 结果。错误走工具错误(is_error),文字原样给客户端 +pub fn to_result(r: Response) -> CallToolResult { + match r { + Response::Text { text, data, .. } => { + with_element_data(CallToolResult::success(vec![ContentBlock::text(text)]), data) + } + Response::Image { jpeg_base64, caption } => { + CallToolResult::success(vec![ContentBlock::image(jpeg_base64, "image/jpeg"), ContentBlock::text(caption)]) + } + Response::Error { message, .. } => CallToolResult::error(vec![ContentBlock::text(message)]), + } +} + +/// Tools that expose delivery of their primary tap, gesture, or text input. +pub fn reports_input(name: &str) -> bool { + matches!(name, "iphone_tap" | "iphone_tap_element" | "iphone_type_text" | "iphone_swipe" | "iphone_long_press") +} + +pub(crate) fn input_error( + message: impl Into, + name: &str, + delivery: Delivery, + stage: Option, +) -> CallToolResult { + let mut message = message.into(); + if !reports_input(name) { + return to_result(Response::error(message)); + } + if delivery == Delivery::Unknown { + message += ictl_l10n::tr!( + "。输入可能已送达,请先查看屏幕再决定下一步。", + ". Input may have reached the phone. Inspect the screen before retrying." + ); + } + let mut result = to_result(Response::error(message)); + result.structured_content = + Some(json!({"delivery": delivery, "readback": {"screen": "not_requested", "settle": "not_requested"}})); + if let Some(stage) = stage { + result.structured_content.as_mut().unwrap()["stage"] = json!(stage); + } + result +} + +pub(crate) fn add_delivery_hint(message: &mut String, delivery: Delivery) { + let lower = message.to_ascii_lowercase(); + let already_guided = + ["inspect the screen", "take a screenshot", "check with a screenshot", "查看屏幕", "截图确认", "截图看看"] + .iter() + .any(|hint| lower.contains(hint)); + message.truncate(message.trim_end().trim_end_matches(['.', '。']).len()); + message.push_str(match delivery { + Delivery::NotSent => ictl_l10n::tr!("。目标输入未发出。", ". The requested input was not sent."), + Delivery::Unknown => ictl_l10n::tr!("。输入可能已送达。", ". Input may have reached the phone."), + Delivery::Sent => ictl_l10n::tr!("。输入已发出。", ". Input was sent."), + }); + if !already_guided && delivery != Delivery::NotSent { + message.push_str(ictl_l10n::tr!("请先查看屏幕再决定下一步。", " Inspect the screen before retrying.")); + } +} + +pub(crate) struct InputResult<'a> { + pub(crate) delivery: Delivery, + pub(crate) stage: Option, + pub(crate) field: Option<&'static str>, + pub(crate) udid: Option<&'a str>, +} diff --git a/crates/ictl-mcp/src/schema.rs b/crates/ictl-mcp/src/schema.rs new file mode 100644 index 0000000..5d1519c --- /dev/null +++ b/crates/ictl-mcp/src/schema.rs @@ -0,0 +1,571 @@ +use super::*; + +/// 服务说明(发给客户端的 instructions):toolkit 的那段,加上自动解锁范围、多设备的说明 +pub fn instructions() -> &'static str { + ictl_l10n::tr!( + "控制一台通过 USB 连接的真实 iPhone(或 iPad)。坐标单位是点(pt),与 iphone_screenshot 图像像素一致。\ +操作前先用 iphone_screenshot 或 iphone_list_elements 看清屏幕;能按名字点就优先用 iphone_tap_element。\ +游戏、地图等界面没有元素树,只能看截图按坐标操作;小图标、小字看不清时用 iphone_screenshot 的区域放大。\ +配置了锁屏密码时,截图、读元素和操作类工具会先自动解锁(iphone_status、列 App、列设备、切换设备和开发者工具不会,按 lock 键也不会)。每次操作后再截图确认结果。\ +涉及付款、删除、发送消息、修改账号或隐私设置的操作,先向用户确认。\ +省时间:操作类工具可带 then=elements 或 then=screenshot,等界面稳定后顺带返回操作后的界面,不用再单独调一次;\ +几步确定的连续操作(按键、逐级点菜单、填表)用 iphone_batch 一次发完;等页面加载用 iphone_wait_for,不要反复截图。\ +接着多台 iPhone/iPad 时同一时间只控制一台:用 iphone_list_devices 查看,iphone_select_device 切换。", + "Controls a real iPhone (or iPad) connected over USB. Coordinates are in points (pt), the same as the pixels of an iphone_screenshot image. Before acting, look at the screen with iphone_screenshot or iphone_list_elements; prefer iphone_tap_element whenever the target has text. Games, maps and similar screens have no element tree: work from screenshots and coordinates, and zoom into small icons or text with an iphone_screenshot region. If a passcode is configured, screenshots, reading elements and the action tools unlock the phone first (iphone_status, listing apps or devices, switching devices and the developer tools don't, nor does pressing lock). Check the result with a screenshot after each action. Ask the user before anything that pays, deletes, sends a message, or changes account or privacy settings. Save time: action tools accept then=elements or then=screenshot to return the screen once it has settled, without a separate call; send a few predictable steps in a row (keys, menu levels, forms) as one iphone_batch; wait for a page with iphone_wait_for instead of repeated screenshots. With several iPhones/iPads connected only one is controlled at a time: see them with iphone_list_devices, switch with iphone_select_device." + ) +} + +pub(crate) fn num(desc: &str) -> Value { + json!({"type": "number", "description": desc}) +} + +pub(crate) fn schema(props: Value, required: &[&str]) -> Map { + let v = json!({"type": "object", "properties": props, "required": required}); + v.as_object().cloned().unwrap_or_default() +} + +/// 操作后顺带返回界面时最多列多少个元素(每步都带太多会占满上下文) +pub const THEN_LIMIT: usize = 80; +/// 顺带返回界面前等界面稳定的上限 +pub const THEN_SETTLE_MS: u64 = 1500; +/// 一次批量最多几步 +pub const BATCH_MAX_STEPS: usize = 20; +/// reuse_elements 时按名字点击复用多旧的元素树(毫秒) +pub const BATCH_REUSE_MS: u64 = 10_000; +/// 批量里能用的工具:改变界面的操作和等待;看界面用 then +pub const BATCH_TOOLS: [&str; 11] = [ + "iphone_tap", + "iphone_tap_element", + "iphone_long_press", + "iphone_swipe", + "iphone_type_text", + "iphone_press_button", + "iphone_launch_app", + "iphone_terminate_app", + "iphone_open_url", + "iphone_wait_for", + "wait", +]; + +/// 操作类工具共有的可选参数:操作后顺带返回界面 +pub(crate) fn then_props() -> Value { + json!({ + "then": {"type": "string", "enum": ["none", "elements", "screenshot"], "default": "none", + "description": ictl_l10n::tr!("操作后等界面稳定,再顺带返回界面:elements=元素列表(最多 80 个),screenshot=截图。省一次单独的调用。操作前看过界面(截图、读元素)时,还会说明和操作前相比界面变没变;没变说明操作可能没生效", "After the action, wait for the screen to settle and return it: elements = element list (up to 80), screenshot = screenshot. Saves a separate call. If the screen was looked at before the action (screenshot, element list), it also says whether the screen changed since; no change means the action may not have taken effect")}, + "then_filter": {"type": "string", "default": "", "description": ictl_l10n::tr!("then=elements 时只列包含这段文字的元素", "With then=elements: only list elements containing this text")}, + "then_region": {"type": "array", "items": {"type": "number"}, "minItems": 4, "maxItems": 4, + "description": ictl_l10n::tr!("then=screenshot 时只返回这块区域的放大图 [x, y, width, height](点),例如游戏棋盘", "With then=screenshot: only return this region, enlarged, as [x, y, width, height] (points), e.g. a game board")}, + "then_settle": {"type": "number", "default": 1.5, + "description": ictl_l10n::tr!("顺带返回界面前最多等几秒让界面稳定(不超过 10)。游戏、地图按画面是否静止判断,消除连锁等长动画可调大,画面一静止就返回", "Maximum seconds to wait for the screen to settle before returning it (up to 10). Games and maps are judged by whether the picture is still; raise it for long animations such as chain reactions, it returns as soon as the picture is still")} + }) +} + +/// 在参数 schema 里加上 then / then_filter +pub(crate) fn with_then(props: Value) -> Value { + let mut p = props; + if let (Some(o), Value::Object(extra)) = (p.as_object_mut(), then_props()) { + o.extend(extra); + } + p +} + +/// 操作类工具描述的共同结尾:返回什么、then 能做什么、自动解锁。 +/// `alert`:不带 then 时会不会查系统弹窗(见 [`wants_alert_check`]) +pub(crate) fn action_desc(body: &str, example: &str, alert: bool) -> String { + let mut s = ictl_l10n::trf!( + "{body}\n\n返回:一行结果文字,例如「{example}」。", + "{body}\n\nReturns: one line of result text, e.g. “{example}”." + ); + if alert { + s += ictl_l10n::tr!( + "不带 then 时,如果系统弹窗挡着屏幕,结果里会提醒(这时操作落在了弹窗上)。", + " Without then, the result warns if a system alert covers the screen (the action then landed on the alert)." + ); + } + s += ictl_l10n::tr!( + "传 then=elements 或 then=screenshot 会等界面稳定后附上操作后的元素列表或截图,省一次单独的调用。\ +配置了锁屏密码时会先自动解锁。", + " With then=elements or then=screenshot it waits for the screen to settle and attaches the element list or screenshot after the action, saving a separate call. If a passcode is configured, the phone is unlocked first." + ); + s +} + +/// 只看不改的工具 +pub(crate) fn looking(title: &str) -> ToolAnnotations { + ToolAnnotations::with_title(title).read_only(true).open_world(false) +} + +/// 改变手机状态的工具。open_world:点击、输入可能经 App 触达外部(发消息、下单),所以都标 true +pub(crate) fn acting(title: &str, destructive: bool, idempotent: bool) -> ToolAnnotations { + ToolAnnotations::with_title(title).read_only(false).destructive(destructive).idempotent(idempotent).open_world(true) +} + +/// Names of the developer tools, listed only with [`dev_tools_enabled`] +pub const DEV_TOOLS: [&str; 6] = [ + "iphone_app_logs", + "iphone_crash_reports", + "iphone_install_app", + "iphone_uninstall_app", + "iphone_web_targets", + "iphone_web_eval", +]; + +/// `IPHONE_CONTROL_DEV_TOOLS=1` (or true/yes/on) adds the developer tools; off by default, so agents that don't +/// need them don't pay for their descriptions +pub fn dev_tools_enabled() -> bool { + std::env::var(ictl_protocol::env::DEV_TOOLS) + .is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on")) +} + +/// The tools this server lists: the 18 standard ones, plus the developer tools when switched on +pub fn tools() -> Vec { + tools_with(dev_tools_enabled()) +} + +pub fn tools_with(dev: bool) -> Vec { + let mut v = standard_tools(); + if dev { + v.extend(dev_tools()); + } + v +} + +/// [`task::CONFIRM_TOOL`], listed only while working for a task (see [`task`]) +pub fn confirm_tool() -> Tool { + Tool::new( + task::CONFIRM_TOOL, + ictl_l10n::tr!( + "请用户确认一步操作(在控制台页面或发起任务的地方),一直等到用户回答。\n\n何时用:付款、购买、下单、转账;删除或清空数据;发送消息、邮件、评论、帖子;\ +修改账号、密码、隐私或安全设置;其他不可撤销的操作。在真正点下那一步之前调用。\n\n\ +返回:用户同意时是普通结果,接着执行;用户拒绝时是错误结果,这时不要执行这一步,也不要换个方式绕过,停下来说明情况。", + "Ask the user to confirm one action (on the control page or wherever the task was started), and wait for the answer.\n\nWhen to use: payments, purchases, orders, transfers; deleting or clearing data; sending messages, emails, comments, posts; changing account, password, privacy or security settings; anything else that can't be undone. Call it right before the step that does it.\n\nReturns: a normal result when the user approves, then go ahead; an error when the user rejects, then don't do that step or work around it: stop and explain." + ) + .to_owned(), + schema( + json!({ + "action": {"type": "string", "description": ictl_l10n::tr!("要做的事,一句话,例如「发送消息」「删除照片」", "what is about to happen, in a few words, e.g. “Send message”, “Delete photo”")}, + "detail": {"type": "string", "description": ictl_l10n::tr!("具体内容:发给谁、发什么、删哪几项、付多少钱", "the specifics: to whom, what, which items, how much")} + }), + &["action", "detail"], + ), + ) + .with_annotations(ToolAnnotations::with_title(ictl_l10n::tr!("请用户确认", "Ask the user")).read_only(true).open_world(false)) +} + +pub(crate) fn dev_tools() -> Vec { + let t = |name: &'static str, desc: &str, s: Map, a: ToolAnnotations| { + Tool::new(name, desc.to_owned(), s).with_annotations(a) + }; + vec![ + t( + "iphone_app_logs", + ictl_l10n::tr!( + "读手机的系统日志(os_log,默认、Error、Fault 级别;Debug、Info 不记录,记录它们会拖慢手机),可按 App 或进程、关键词、时间筛选,每行:多少秒前、进程[pid]、级别、子系统、内容。\n\n\ +何时用:App 崩溃、报错、请求失败、界面没反应时,不靠截图找原因。第一次调用才开始记录(之前的拿不到):先调一次,复现问题,再调一次。\ +记录在 15 分钟没有调用后自动停止。只读。", + "Read the phone's system log (os_log, default, Error and Fault levels; Debug and Info aren't recorded, since streaming them slows the phone down), filtered by app or process, keyword and time; one line per entry: seconds ago, process[pid], level, subsystem, message.\n\nWhen to use: when an app crashes, shows an error, a request fails or the UI doesn't respond, to find the cause without screenshots. Recording starts with the first call (earlier lines aren't available): call it once, reproduce the problem, then call it again. Recording stops by itself after 15 minutes without a call. Read-only." + ), + schema( + json!({ + "process": {"type": "string", "default": "", "description": ictl_l10n::tr!("App 的显示名或 Bundle ID,或进程名(如 SpringBoard);空为全部", "app display name or bundle ID, or a process name (e.g. SpringBoard); empty for all")}, + "grep": {"type": "string", "default": "", "description": ictl_l10n::tr!("只要内容或子系统包含这段文字的行(不分大小写)", "only lines whose message or subsystem contains this text (case-insensitive)")}, + "since": {"type": "number", "default": 60, "description": ictl_l10n::tr!("只看最近多少秒,最多 3600", "only the last this many seconds, at most 3600")}, + "limit": {"type": "integer", "default": 100, "description": ictl_l10n::tr!("最多返回多少行(最新的),1 到 1000", "at most this many lines (the newest), 1 to 1000")}, + "errors_only": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("只看 Error 和 Fault 级别", "only Error and Fault levels")} + }), + &[], + ), + looking(ictl_l10n::tr!("读日志", "Read logs")), + ), + t( + "iphone_crash_reports", + ictl_l10n::tr!( + "列出手机上的崩溃报告(新的在前,最多 50 个),或用 name 读取其中一份(.ips,开头是异常类型、崩溃的线程和 App 版本)。\n\n\ +何时用:App 闪退后找原因。只读。", + "List the crash reports on the phone (newest first, at most 50), or read one with name (.ips; the start has the exception type, the crashed thread and the app version).\n\nWhen to use: to find out why an app quit unexpectedly. Read-only." + ), + schema( + json!({ + "filter": {"type": "string", "default": "", "description": ictl_l10n::tr!("只列文件名包含这段文字的(如进程名)", "only list file names containing this text (e.g. the process name)")}, + "name": {"type": "string", "default": "", "description": ictl_l10n::tr!("要读取的报告文件名(来自列表);给了就返回内容", "file name of the report to read (from the list); if given, returns its content")} + }), + &[], + ), + looking(ictl_l10n::tr!("崩溃报告", "Crash reports")), + ), + t( + "iphone_install_app", + ictl_l10n::tr!( + "安装签好名的 .ipa 或 .app(覆盖已装的同一 App)。path 是运行守护进程的机器上的路径。\ +大的包要一两分钟。", + "Install a signed .ipa or .app (replacing the same app if installed). path is on the machine that runs the daemon. Large packages take a minute or two." + ), + schema( + json!({"path": {"type": "string", "description": ictl_l10n::tr!(".ipa 文件或 .app 目录的路径", "path of the .ipa file or .app directory")}}), + &["path"], + ), + acting(ictl_l10n::tr!("安装 App", "Install app"), true, true), + ), + t( + "iphone_uninstall_app", + ictl_l10n::tr!( + "卸载 App,连同它的数据。不会卸载 WebDriverAgent(iphone-control 靠它控制手机)。卸载前先问用户。", + "Uninstall an app, together with its data. Refuses to remove WebDriverAgent, which iphone-control needs to control the phone. Ask the user before uninstalling." + ), + schema( + json!({"app": {"type": "string", "description": ictl_l10n::tr!("Bundle ID 或显示名", "bundle ID or display name")}}), + &["app"], + ), + acting(ictl_l10n::tr!("卸载 App", "Uninstall app"), true, true), + ), + t( + "iphone_web_targets", + ictl_l10n::tr!( + "列出可检查的网页和 WebView(Web Inspector):Safari 标签页、App 里可检查的 WebView(Capacitor、Cordova、React Native 等的调试构建)。每行:id、类型、所属 App、标题和网址。\n\n\ +何时用:页面内容在网页里时,用 iphone_web_eval 直接读 DOM,比截图和元素树快、省 token、也更准。需要手机上 设置 → Safari → 高级 → 网页检查器 打开。只读。", + "List inspectable web pages and WebViews (Web Inspector): Safari tabs and inspectable WebViews in apps (debug builds of Capacitor, Cordova, React Native and similar). One line each: id, type, app, title and URL.\n\nWhen to use: when the content is a web page, read the DOM with iphone_web_eval instead; that is faster, cheaper in tokens and more accurate than screenshots or the element tree. Needs Settings → Safari → Advanced → Web Inspector on. Read-only." + ), + schema(json!({}), &[]), + looking(ictl_l10n::tr!("列出网页", "List web pages")), + ), + t( + "iphone_web_eval", + ictl_l10n::tr!( + "在网页或 WebView 里执行 JavaScript,返回结果的 JSON(Promise 会等它完成)。例如 document.title、\ +[...document.querySelectorAll('button')].map(b => b.innerText)、document.querySelector('#email').value = 'a@b.c'。\n\n\ +何时用:读网页内容、表单状态、控制台变量,或直接操作页面。只取需要的部分,结果超过 5 万字会被截断。\ +脚本能改页面(提交表单、发请求),和点击一样要小心。", + "Run JavaScript in a web page or WebView and return the result as JSON (a promise is awaited). For example document.title, [...document.querySelectorAll('button')].map(b => b.innerText), document.querySelector('#email').value = 'a@b.c'.\n\nWhen to use: to read page content, form state or JavaScript variables, or to act on the page directly. Select just what you need; results over 50,000 characters are cut. A script can change the page (submit forms, send requests), so take the same care as with taps." + ), + schema( + json!({ + "expression": {"type": "string", "description": ictl_l10n::tr!("要执行的 JavaScript 表达式", "the JavaScript expression to run")}, + "target": {"type": "string", "default": "", "description": ictl_l10n::tr!("iphone_web_targets 列出的 id,或网址、标题里的一段文字;只有一个页面时可以不填", "an id from iphone_web_targets, or text in the page's URL or title; may be left out when there is only one page")}, + "timeout": {"type": "number", "default": 10, "description": ictl_l10n::tr!("最多等多少秒,最多 60", "maximum seconds to wait, at most 60")} + }), + &["expression"], + ), + acting(ictl_l10n::tr!("执行 JavaScript", "Run JavaScript"), true, false), + ), + ] +} + +/// 18 个工具的定义(toolkit 的 13 个 + iphone_wait_for、iphone_batch、iphone_list_devices、iphone_select_device、iphone_scroll_collect)。 +/// 描述可以改写,但工具名、参数、默认返回不改(docs/decisions.md D10) +pub(crate) fn standard_tools() -> Vec { + let t = |name: &'static str, desc: String, s: Map, a: ToolAnnotations| { + Tool::new(name, desc, s).with_annotations(a) + }; + let app = || { + json!({"app": {"type": "string", + "description": ictl_l10n::tr!("Bundle ID(如 com.apple.Preferences)或显示名(如「设置」「微信」)", "Bundle ID (e.g. com.apple.Preferences) or display name (e.g. “Settings”)")}}) + }; + vec![ + t( + "iphone_status", + ictl_l10n::tr!("查看手机和服务的状态:WDA(WebDriverAgent)是否就绪、是否锁屏、能否自动解锁、当前前台 App 的 Bundle ID、\ +屏幕尺寸(点)、守护进程状态。\n\n何时用:开始操作前确认手机可用;操作报错、怀疑 WDA 掉线或手机锁屏时排查。\ +WDA 不可用时会说明哪些功能受影响(读元素、按名字点击、启动 App)。只读,不改变手机状态。", "Show the state of the phone and the service: whether WDA (WebDriverAgent) is ready, whether the phone is locked and can be auto-unlocked, the bundle ID of the foreground app, the screen size (points) and the daemon state.\n\nWhen to use: to check that the phone is usable before starting; to investigate when actions fail or WDA or the lock screen seem to be in the way. If WDA is unavailable it says which features are affected (reading elements, tapping by text, launching apps). Read-only, doesn't change the phone.") + .into(), + schema(json!({}), &[]), + looking(ictl_l10n::tr!("查看状态", "Show status")), + ), + t( + "iphone_screenshot", + ictl_l10n::tr!("截取当前屏幕,返回 JPEG 图像和一行说明。图像已缩放到点尺寸,图中像素坐标可直接用于 iphone_tap、iphone_swipe。\n\n\ +看不清小图标、小字时,传 x/y/width/height(点,四个要一起给)放大这块区域:从原始高清截图裁剪,小区域再额外放大。\ +返回文字里有放大倍数,图中坐标换算回屏幕点:x + 像素/倍数。\n\n\ +何时用:游戏、地图、图片等没有元素树的界面,或要确认画面效果时。只想知道有哪些按钮、文字,iphone_list_elements 更快更省上下文。\ +操作后要看结果时,优先给操作工具带 then=screenshot。WDA 不可用时改用 CoreDevice 截图(iOS 27 起,说明里注明「HID」)。\ +只读:不改变界面,但配置了锁屏密码时会先解锁。", "Capture the current screen and return a JPEG image plus a line of explanation. The image is scaled to points, so its pixel coordinates can be used directly with iphone_tap and iphone_swipe.\n\nTo read small icons or text, pass x/y/width/height (points, all four together) to zoom into that region: it is cropped from the full-resolution capture, and small regions are enlarged further. The text gives the zoom factor; convert image coordinates back to screen points with x + pixel / factor.\n\nWhen to use: screens without an element tree (games, maps, images), or to check how something looks. To find out which buttons and texts are there, iphone_list_elements is faster and uses less context. To see the result of an action, prefer then=screenshot on the action tool. If WDA is unavailable it uses a CoreDevice screenshot instead (iOS 27+, marked “HID”). Read-only: doesn't change the screen, but unlocks the phone first if a passcode is configured.") + .into(), + schema( + json!({"x": num(ictl_l10n::tr!("区域左上角 x(点)", "left edge x of the region (points)")), "y": num(ictl_l10n::tr!("区域左上角 y(点)", "top edge y of the region (points)")), "width": num(ictl_l10n::tr!("区域宽(点)", "region width (points)")), "height": num(ictl_l10n::tr!("区域高(点)", "region height (points)"))}), + &[], + ), + looking(ictl_l10n::tr!("截图", "Screenshot")), + ), + t( + "iphone_list_elements", + ictl_l10n::tr!("列出屏幕上带文字的界面元素,每行一个:类型、标签、名字、值、中心点坐标、尺寸(点)。\n\n\ +何时用:找按钮、输入框、列表项的文字和位置,比截图快、省上下文;找到后用 iphone_tap_element 按文字点。\ +游戏、地图等没有元素树的界面这里是空的,改用 iphone_screenshot。\n\n\ +注意:按坐标判断是否在屏幕内,被弹窗遮住的元素也可能列出来,不确定时截图核对。需要 WDA。\ +只读:不改变界面,但配置了锁屏密码时会先解锁。", "List the UI elements on screen that carry text, one per line: type, label, name, value, center point and size (points).\n\nWhen to use: to find buttons, text fields and list items with their text and position; faster than a screenshot and uses less context. Then tap one by its text with iphone_tap_element. Games, maps and other screens without an element tree return nothing here; use iphone_screenshot.\n\nNote: visibility is judged by position, so elements hidden behind an alert can still be listed; check with a screenshot when in doubt. Needs WDA. Read-only: doesn't change the screen, but unlocks the phone first if a passcode is configured.") + .into(), + schema( + json!({ + "filter": {"type": "string", "default": "", + "description": ictl_l10n::tr!("只返回类型/标签/名字/值里包含这段文字的元素(不区分大小写),例如 SearchField、Button、登录", "Only return elements whose type/label/name/value contains this text (case-insensitive), e.g. SearchField, Button, Login")}, + "limit": {"type": "integer", "default": 150, "description": ictl_l10n::tr!("最多列几个,结构化结果包含匹配总数和截断标记", "Maximum number of elements to return; structured output reports the count and whether it was truncated")} + }), + &[], + ), + looking(ictl_l10n::tr!("列出界面元素", "List UI elements")), + ) + .with_raw_output_schema(std::sync::Arc::new(elements_output_schema())), + t( + "iphone_scroll_collect", + ictl_l10n::tr!("收集连续几屏里可见的文字行,合并相邻屏的重叠内容。可用 until 找到文字就停在当前屏。只滑动,不点击。返回 rows、scrolls、stop_reason,以及找到时当前屏上的 matched。", + "Collect visible text rows across overlapping viewports. Use until to stop with a matching element on screen. Only scrolls, never taps. Returns rows, scrolls, stop_reason and the matched element on the final viewport.").into(), + schema(json!({ + "scroll": {"type": "string", "enum": ["down", "up"], "default": "down", "description": ictl_l10n::tr!("往下或往上找", "look further down or up the list")}, + "until": {"type": "string", "description": ictl_l10n::tr!("可见元素的文字、标识或值包含这段文字时停止,不区分大小写", "stop at a visible label, name or value containing this text, case-insensitive")}, + "filter": {"type": "string", "description": ictl_l10n::tr!("只收集类型或文字包含它的行。与 until 独立", "collect rows whose type or text contains this string, independent of until")}, + "limit": {"type": "integer", "minimum": 1, "maximum": protocol::MAX_SCROLL_ROWS, "default": protocol::MAX_SCROLL_ROWS, "description": ictl_l10n::tr!("最多收集几行", "stop after collecting this many rows")}, + "max_scrolls": {"type": "integer", "minimum": 1, "maximum": protocol::MAX_SEARCH_SCROLLS, "default": 8, "description": ictl_l10n::tr!("最多滚动几次", "maximum number of scrolls")}, + "x": {"type": "number", "minimum": 0, "description": ictl_l10n::tr!("在哪个横坐标上下滑(点),默认屏幕正中。iPad 分栏界面(设置、邮件)只滚动手指所在的那一栏:要滚左栏,给左栏里的横坐标", "where to swipe across, in points from the left; the middle of the screen by default. An iPad split view (Settings, Mail) scrolls only the column swiped in: for the sidebar, an x inside it")} + }), &[]), + acting(ictl_l10n::tr!("滚动收集文字", "Scroll and collect text"), false, false), + ), + t( + "iphone_tap", + action_desc( + ictl_l10n::tr!("点击屏幕上的一个坐标(单位是点,与 iphone_screenshot 全屏图的像素一致,左上角为原点)。\n\n\ +何时用:目标没有文字(图标、图片)、在游戏或地图里,或 iphone_list_elements 里找不到它时。\ +带文字的按钮、列表项优先用 iphone_tap_element,界面布局变了也点得准。按住用 iphone_long_press,滚动用 iphone_swipe。\n\n\ +行为:单指按下约 0.05 秒后抬起,点一次(count 大于 1 时在同一点连点)。不检查坐标上是什么,点之前先截图确认位置。\ +WDA 不可用时改用 CoreDevice HID(iOS 27 起;结果里注明「经 HID」)。", "Tap a point on the screen (in points, the same as the pixels of a full-screen iphone_screenshot, origin at the top left).\n\nWhen to use: the target has no text (icon, image), is in a game or map, or can't be found with iphone_list_elements. For buttons and list items with text prefer iphone_tap_element, which keeps working when the layout changes. Use iphone_long_press to hold and iphone_swipe to scroll.\n\nBehavior: one finger down for about 0.05 s, then up; a single tap (several at the same point with count above 1). It doesn't check what is at that point, so look at a screenshot first. If WDA is unavailable it uses CoreDevice HID instead (iOS 27+; the result says “via HID”)."), + ictl_l10n::tr!("已点击 (120,300)", "Tapped (120,300)"), + true, + ), + schema( + with_then(json!({ + "x": num(ictl_l10n::tr!("x(点)", "x (points)")), + "y": num(ictl_l10n::tr!("y(点)", "y (points)")), + "count": {"type": "integer", "default": 1, "minimum": 1, "maximum": MAX_TAP_COUNT, + "description": ictl_l10n::tr!("在这一点连点几下,一个手势里点完(每下间隔约 0.1 秒):2 是双击;也用于要在短时间内连点几下的入口。分开调用赶不上这类时间窗", "how many times to tap this point, all in one gesture (about 0.1 s apart): 2 is a double tap; also for entries that need several taps in a short time, which separate calls are too slow for")} + })), + &["x", "y"], + ), + acting(ictl_l10n::tr!("点击坐标", "Tap point"), true, false), + ), + t( + "iphone_tap_element", + action_desc( + ictl_l10n::tr!("按文字点击界面元素:先找标签/名字与 text 完全相同的,找不到再找包含 text 的。\ +中心被悬浮栏、键盘等盖住时改点没被盖住的部分,整个被盖住就不点。\n\n\ +何时用:按钮、列表项、标签页等带文字的元素,优先用它而不是按坐标点。不确定文字怎么写时先 iphone_list_elements。\ +没有文字的图标、游戏、地图用 iphone_tap。\n\n\ +行为:没找到、index 超出匹配个数或整个被盖住时不点,返回原因(不算出错;在 iphone_batch 里会让批量停下)。需要 WDA。", "Tap a UI element by its text: first an exact match of label or name with text, otherwise one that contains text. If its center is covered by a floating bar, the keyboard or similar, it taps an uncovered part; if it is completely covered, it doesn't tap.\n\nWhen to use: buttons, list items, tabs and other elements with text; prefer this over coordinates. If unsure how the text is written, use iphone_list_elements first. For icons without text, games and maps use iphone_tap.\n\nBehavior: when nothing matches, index is beyond the number of matches, or the element is completely covered, it doesn't tap and says why (not an error; inside iphone_batch it stops the batch). Needs WDA."), + ictl_l10n::tr!("已点击 Button \"通用\"", "Tapped Button \"General\""), + true, + ), + schema( + with_then(json!({ + "text": {"type": "string", "description": ictl_l10n::tr!("元素的文字(标签或名字),先精确匹配再按包含匹配", "the element's text (label or name); exact match first, then substring")}, + "index": {"type": "integer", "default": 0, + "description": ictl_l10n::tr!("匹配到多个时点第几个(从 0 开始,顺序同 iphone_list_elements)", "which match to tap if there are several (from 0, same order as iphone_list_elements)")}, + "scroll": {"type": "string", "enum": ["down", "up"], + "description": ictl_l10n::tr!("当前屏幕上没有时边滑边找:down 往下找(看下面的内容),up 往上找。每次慢滑约三分之一屏、不带惯性,找到文字完全相同的就点(当前屏只有包含它的不算,接着滑;滑完都没有完全相同的才点包含它的),滑到底(界面不再变)或滑满 max_scrolls 次还没有就停下说明。用于长列表、设置页里不在当前屏的项;不给就只在当前屏幕上找", "If it isn't on the current screen, scroll and look again: down looks further down (the content below), up further up. Each scroll is a slow third of the screen without momentum; it taps as soon as the exact text is found (a row that only contains it doesn't stop the search; if no exact match turns up, one that contains it is tapped), and stops and says so at the end of the list (the screen no longer changes) or after max_scrolls. For items of long lists and settings pages that are off screen; without it only the current screen is searched")}, + "max_scrolls": {"type": "integer", "default": 8, "minimum": 1, "maximum": ictl_protocol::MAX_SEARCH_SCROLLS, + "description": ictl_l10n::tr!("带 scroll 时最多滑几次,默认 8", "with scroll: at most this many scrolls, default 8")} + })), + &["text"], + ), + acting(ictl_l10n::tr!("按文字点击", "Tap by text"), true, false), + ), + t( + "iphone_long_press", + action_desc( + ictl_l10n::tr!("在屏幕坐标(点)上单指按住 seconds 秒再抬起,手指不移动。\n\n\ +何时用:要长按才出现的操作,例如主屏图标的快捷菜单、消息或图片的上下文菜单、选中文字。\ +普通点击用 iphone_tap 或 iphone_tap_element;要移动手指(滚动、拖滑块)用 iphone_swipe。\n\n\ +行为:只按一次。按得太短(不到约 0.5 秒)系统可能当成普通点击。长按弹出的菜单不会自己消失,\ +下一步先看屏幕(或直接带 then=screenshot)。需要 WDA。", "Hold one finger still at a screen point (points) for seconds, then lift.\n\nWhen to use: actions that need a long press, such as home-screen quick actions, context menus on messages or images, or selecting text. For normal taps use iphone_tap or iphone_tap_element; to move the finger (scroll, drag a slider) use iphone_swipe.\n\nBehavior: a single press. Too short a press (under about 0.5 s) may count as a normal tap. Menus opened by a long press stay open, so look at the screen next (or pass then=screenshot). Needs WDA."), + ictl_l10n::tr!("已长按 (200,400) 1 秒", "Long-pressed (200,400) for 1 s"), + true, + ), + schema( + with_then(json!({ + "x": num(ictl_l10n::tr!("x(点)", "x (points)")), + "y": num(ictl_l10n::tr!("y(点)", "y (points)")), + "seconds": {"type": "number", "default": 1.0, "description": ictl_l10n::tr!("按住几秒,默认 1", "seconds to hold, default 1")} + })), + &["x", "y"], + ), + acting(ictl_l10n::tr!("长按", "Long press"), true, false), + ), + t( + "iphone_swipe", + action_desc( + ictl_l10n::tr!("单指从 (from_x, from_y) 按下,用 seconds 秒移到 (to_x, to_y) 后抬起(坐标单位是点)。\n\n\ +何时用:滚动列表或页面、左右翻页、拖动滑块。向上滑看下面的内容:from_y 大、to_y 小(例如 y 从 700 滑到 300);\ +向左滑看右边的内容:from_x 大、to_x 小。点击用 iphone_tap,原地按住用 iphone_long_press。\n\n\ +行为:seconds 越小滑得越快,快滑会带惯性多滚一段;要精确移动(滑块)把 seconds 调到 1 秒左右。\ +滑完会等列表停止滚动(最多 2.5 秒)再返回,还在滚就在结果里说明。WDA 不可用时改用 CoreDevice HID(iOS 27 起)。", "One finger down at (from_x, from_y), moving to (to_x, to_y) over seconds, then up (coordinates in points).\n\nWhen to use: scroll a list or page, page left or right, drag a slider. To see content further down, swipe up: from_y large, to_y small (e.g. y from 700 to 300); to see content to the right, swipe left: from_x large, to_x small. Use iphone_tap to tap and iphone_long_press to hold in place.\n\nBehavior: the smaller seconds, the faster the swipe; a fast swipe keeps scrolling with momentum. For precise moves (sliders) use about 1 second. It waits until the list stops scrolling (up to 2.5 s) before returning and says so if it is still moving. If WDA is unavailable it uses CoreDevice HID instead (iOS 27+)."), + ictl_l10n::tr!("已滑动 (215,700) → (215,300)", "Swiped (215,700) → (215,300)"), + true, + ), + schema( + with_then(json!({ + "from_x": num(ictl_l10n::tr!("起点 x(点)", "start x (points)")), + "from_y": num(ictl_l10n::tr!("起点 y(点)", "start y (points)")), + "to_x": num(ictl_l10n::tr!("终点 x(点)", "end x (points)")), + "to_y": num(ictl_l10n::tr!("终点 y(点)", "end y (points)")), + "seconds": {"type": "number", "default": 0.3, "description": ictl_l10n::tr!("滑动用时(秒),默认 0.3;越小越快、惯性越大", "swipe duration (seconds), default 0.3; smaller is faster with more momentum")}, + "hold": {"type": "number", "default": 0, "minimum": 0, "description": ictl_l10n::tr!("先在起点按住几秒再移动,默认 0(普通滑动)。拖动要先长按才拿得起来的东西时用,例如主屏幕图标、可排序的列表项、文件:hold 0.6~1,seconds 0.7 左右。少于 0.5 秒通常拿不起来,只会滑动或翻页", "seconds to hold still at the start before moving, default 0 (a plain swipe). For dragging things that have to be long-pressed before they can be picked up, such as home-screen icons, reorderable list rows or files: hold 0.6-1, seconds about 0.7. Under 0.5 s usually doesn't pick anything up and just swipes or pages")} + })), + &["from_x", "from_y", "to_x", "to_y"], + ), + acting(ictl_l10n::tr!("滑动", "Swipe"), false, false), + ), + t( + "iphone_type_text", + action_desc( + ictl_l10n::tr!("在当前获得焦点的输入框里输入文字(支持中文),默认从光标处输入。replace=true 替换当前聚焦的普通输入框的全文(text 为空时清空),读回全文一致才按回车。submit=true 时末尾按回车。\n\n\ +何时用:搜索框、表单、聊天框等。要先点中输入框让键盘弹出;屏幕上没有键盘时报错,什么都不输。\ +回车可能会发送消息或提交表单,发送前先向用户确认。\n\n\ +行为:输完会读回输入框核对,少了结尾几个字会自动补上;对不上就报错,也不按回车。\ +WDA 不可用时改用 HID(iOS 27 起):美式键盘上的英文和符号直接按键;中文等经剪贴板粘贴,手机会弹「允许粘贴」,要截图后点它才粘得进去(剪贴板 45 秒后还原)。", "Type text into the focused text field (any language, including Chinese) at the cursor by default. replace=true replaces the contents of a readable focused field (empty text empties it), and presses Return only once the field reads back as exactly the text. With submit=true it presses Return at the end.\n\nWhen to use: search boxes, forms, chat fields. Tap the field first so the keyboard comes up; with no keyboard on screen it fails and types nothing. Return may send a message or submit a form, so ask the user before sending.\n\nBehavior: it reads the field back afterwards; dropped trailing characters are typed again. If it still doesn't match, it reports an error and doesn't press Return. If WDA is unavailable it uses HID instead (iOS 27+): English letters and symbols of a US keyboard are typed as keys, anything else is pasted through the pasteboard, and the phone asks to “Allow Paste”: take a screenshot and tap it to let the text in (the pasteboard is put back after 45 s)."), + ictl_l10n::tr!("已输入 4 个字符,并按了回车", "Typed 4 characters and pressed Return"), + true, + ), + schema( + with_then(json!({ + "text": {"type": "string", "description": ictl_l10n::tr!("要输入的文字", "the text to type")}, + "replace": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("替换当前聚焦输入框的全文,text 为空时清空输入框。仅普通可读输入框(不含密码框);经 WDA 时先清空再输入,失败时原来的文字已删掉;默认在光标处输入", "replace all text in the focused field; with empty text, empty it. Readable fields only (not password fields); through WDA the field is emptied first, so after a failure the old text is gone; defaults to typing at the cursor")}, + "submit": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("输完后按回车(搜索、发送、提交)", "press Return afterwards (search, send, submit)")} + })), + &["text"], + ), + acting(ictl_l10n::tr!("输入文字", "Type text"), false, false), + ), + t( + "iphone_press_button", + action_desc( + ictl_l10n::tr!("按硬件键:home(回主屏幕)、volume_up、volume_down、lock(锁屏)。\n\n\ +何时用:离开当前 App 回主屏幕用 home(App 留在后台,要彻底关掉用 iphone_terminate_app);调音量;锁屏。\ +锁屏后配置了密码的话,下一个操作会先自动解锁。\n\n\ +行为:系统弹窗挡着时按 home 不会生效,这时不按,并提示先点弹窗上的按钮。按 home 会等主屏真的到前台再返回。", "Press a hardware button: home (go to the home screen), volume_up, volume_down, lock (lock the screen).\n\nWhen to use: leave the current app with home (the app stays in the background; use iphone_terminate_app to quit it); change the volume; lock the phone. After locking, if a passcode is configured, the next action unlocks first.\n\nBehavior: while a system alert covers the screen home has no effect, so it isn't pressed and the result says to tap a button on the alert first. home waits until the home screen is really in front before returning."), + ictl_l10n::tr!("已按 home", "Pressed home"), + false, + ), + schema( + with_then(json!({"button": {"type": "string", "enum": ["home", "volume_up", "volume_down", "lock"], + "description": ictl_l10n::tr!("home、volume_up、volume_down 或 lock", "home, volume_up, volume_down or lock")}})), + &["button"], + ), + acting(ictl_l10n::tr!("按硬件键", "Press button"), false, false), + ), + t( + "iphone_list_apps", + ictl_l10n::tr!("列出已安装的 App,每行一个:显示名和 Bundle ID。\n\n\ +何时用:iphone_launch_app、iphone_terminate_app 报「找不到名为…的 App」时,查准确的名字或 Bundle ID。\ +默认只列用户装的 App;设置、相机等系统 App 要 include_system=true(要多花几秒)。结果有缓存。只读。", "List installed apps, one per line: display name and bundle ID.\n\nWhen to use: when iphone_launch_app or iphone_terminate_app report “No app named …”, to look up the exact name or bundle ID. By default only user-installed apps; system apps such as Settings or Camera need include_system=true (takes a few seconds longer). Results are cached. Read-only.") + .into(), + schema( + json!({"include_system": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("同时列出系统 App", "also list system apps")}}), + &[], + ), + looking(ictl_l10n::tr!("列出 App", "List apps")), + ), + t( + "iphone_launch_app", + action_desc( + ictl_l10n::tr!("启动 App 并切到前台。app 是显示名时按已安装的 App 查找,找不到会报错,提示用 iphone_list_apps 查看。\n\n\ +何时用:打开某个 App。要直接进网页或 App 里的某个页面用 iphone_open_url。\ +想从首页重新开始(而不是回到上次的页面),先用 iphone_terminate_app 结束它再启动。\n\n\ +行为:App 已在后台运行时只切回前台,停在上次的页面;没在运行就冷启动。等 App 真的到前台才返回(最多约 8 秒);\ +被系统弹窗(如权限请求)挡住或启动慢时,结果里会说明。需要 WDA。", "Launch an app and bring it to the foreground. A display name is looked up among the installed apps; if not found it fails and suggests iphone_list_apps.\n\nWhen to use: to open an app. To go straight to a web page or a screen inside an app, use iphone_open_url. To start from the app's first screen (instead of where it was), quit it with iphone_terminate_app first.\n\nBehavior: an app already running in the background is only brought back to the front, on the screen it was on; otherwise it cold-starts. It returns once the app is really in front (up to about 8 s); if a system alert (such as a permission prompt) blocks it or it starts slowly, the result says so. Needs WDA."), + ictl_l10n::tr!("已启动 com.apple.Preferences", "Launched com.apple.Preferences"), + true, + ), + schema(with_then(app()), &["app"]), + acting(ictl_l10n::tr!("启动 App", "Launch app"), false, true), + ), + t( + "iphone_terminate_app", + action_desc( + ictl_l10n::tr!("强制结束 App 进程,相当于在多任务界面里把它划掉。app 是显示名时按已安装的 App 查找,找不到会报错。\n\n\ +何时用:App 卡住或状态不对,或者想让下次 iphone_launch_app 从首页冷启动。只想离开 App 用 iphone_press_button 按 home,App 留在后台。\n\n\ +行为:App 里没保存的输入、正在播放的内容会丢失。App 本来没在运行也不报错。结束的是前台 App 时会回到主屏幕。需要 WDA。", "Force-quit an app, like swiping it away in the app switcher. A display name is looked up among the installed apps; if not found it fails.\n\nWhen to use: the app is stuck or in a wrong state, or the next iphone_launch_app should cold-start it on its first screen. To just leave the app, press home with iphone_press_button; the app stays in the background.\n\nBehavior: unsaved input and anything playing is lost. No error if the app wasn't running. Quitting the foreground app returns to the home screen. Needs WDA."), + ictl_l10n::tr!("已结束 com.apple.Preferences", "Terminated com.apple.Preferences"), + false, + ), + schema(with_then(app()), &["app"]), + acting(ictl_l10n::tr!("结束 App", "Quit app"), true, true), + ), + t( + "iphone_open_url", + action_desc( + ictl_l10n::tr!("用系统默认方式打开网址或 URL Scheme:http/https 网页在 Safari 打开,URL Scheme 打开对应的 App。\n\n\ +何时用:直接进入某个网页或 App 里的某个页面,比启动 App 再一级级点快。只想打开 App 用 iphone_launch_app。\n\n\ +行为:有的 URL Scheme 系统会先弹窗问要不要打开,带 then=screenshot 确认。需要 WDA。", "Open a web address or URL scheme the way the system does: http/https pages open in the default browser, URL schemes open their app.\n\nWhen to use: to go straight to a web page or a screen inside an app, faster than launching the app and tapping through. To just open an app use iphone_launch_app.\n\nBehavior: for some URL schemes the system first asks whether to open them; check with then=screenshot. Needs WDA."), + ictl_l10n::tr!("已打开 https://example.com", "Opened https://example.com"), + true, + ), + schema( + with_then(json!({"url": {"type": "string", "description": ictl_l10n::tr!("完整网址(含 https://)或 URL Scheme", "full address (including https://) or URL scheme")}})), + &["url"], + ), + acting(ictl_l10n::tr!("打开链接", "Open URL"), false, false), + ), + t( + "iphone_wait_for", + ictl_l10n::tr!("等含指定文字的元素出现或消失。默认等出现;state=disappeared 时等当前界面没有匹配项。超时报错。\n\n\ +何时用:操作后要等加载时代替反复截图轮询,每 0.3 秒查一次,不占上下文。输入框里的字不算(刚输入的搜索词不会被当成结果)。\ +只读:不改变界面,但配置了锁屏密码时会先解锁。", "Wait for visible UI text to appear (the default), or use state=disappeared to wait for a screen without a match. Returns an error on timeout.\n\nWhen to use: after an action, to wait for loading instead of polling with screenshots; it checks every 0.3 s and uses no context meanwhile. Text inside input fields doesn't count (a search term just typed isn't taken for a result). Read-only: doesn't change the screen, but unlocks the phone first if a passcode is configured.") + .into(), + schema( + json!({ + "text": {"type": "string", "description": ictl_l10n::tr!("要等的文字,元素的标签/名字/值包含它就算出现", "the text to wait for; it counts as appeared when an element's label/name/value contains it")}, + "timeout": {"type": "number", "default": 5, "description": ictl_l10n::tr!("最多等几秒(不超过 30)", "maximum seconds to wait (up to 30)")}, + "state": {"type": "string", "enum": ["appeared", "disappeared"], "default": "appeared", "description": ictl_l10n::tr!("等文字出现或从当前界面消失", "wait for the text to appear or disappear from the visible screen")} + }), + &["text"], + ), + looking(ictl_l10n::tr!("等文字出现", "Wait for text")), + ), + t( + "iphone_list_devices", + ictl_l10n::tr!("列出 USB 上接着的全部 iPhone/iPad,每行一台:设备名、型号、iOS 版本、UDID,标出正在控制哪台、有没有设自动解锁密码。\n\n\ +何时用:接着多台设备、要确认操作落在哪台,或切换前查设备名和 UDID。同一时间只控制一台,其他工具都作用在正在控制的那台上。只读。", "List all iPhones/iPads connected over USB, one per line: device name, model, iOS version, UDID; marks the one being controlled and whether it has an auto-unlock passcode.\n\nWhen to use: with several devices connected, to check which one actions go to, or to look up names and UDIDs before switching. Only one device is controlled at a time; all other tools act on it. Read-only.") + .into(), + schema(json!({}), &[]), + looking(ictl_l10n::tr!("列出设备", "List devices")), + ), + t( + "iphone_select_device", + ictl_l10n::tr!("改为控制另一台设备,之后所有工具都作用在它上面,守护进程重启后还记得。device 是 UDID 或设备名(设备名包含这段文字且只有一台也行),\ +auto 表示取消选定、改回自动选(正在控制的那台断开才换)。\n\n\ +何时用:接着多台设备、要操作的不是正在控制的那台。先用 iphone_list_devices 看有哪几台。\n\n\ +行为:切换后要在新设备上拉起 WDA(10~60 秒),期间读界面、按名字点击等用不了,先用 iphone_status 确认就绪;\ +这台从没装过 WDA 时起不来,要请用户运行 iphone-control setup。\ +自动解锁按设备分开存密码,新设备没设就不会自动解锁。设了 IPHONE_UDID 时不能切换。\n\n\ +返回:一行结果文字,例如「已切换到 Derrors 的 iPad(iPad11,1 iOS 26.6.1,00008020-…)」。", "Control another device from now on: all tools act on it, and the daemon remembers it across restarts. device is a UDID or device name (part of the name works if only one device matches); auto clears the selection and goes back to automatic (switches only when the controlled device disconnects).\n\nWhen to use: with several devices connected, when the one to operate isn't the one being controlled. Look at them with iphone_list_devices first.\n\nBehavior: after switching, WDA has to start on the new device (10-60 s); until then reading the screen, tapping by text etc. don't work, so check readiness with iphone_status. If WDA was never installed on that device it won't start; ask the user to run iphone-control setup. Auto-unlock passcodes are stored per device, so a new device without one isn't auto-unlocked. Not possible while IPHONE_UDID is set.\n\nReturns: one line of result text, e.g. “Switched to Derrors's iPad (iPad11,1 iOS 26.6.1, 00008020-…)”.") + .into(), + schema( + json!({"device": {"type": "string", "description": ictl_l10n::tr!("UDID、设备名,或 auto(改回自动选)", "UDID, device name, or auto (back to automatic)")}}), + &["device"], + ), + ToolAnnotations::with_title(ictl_l10n::tr!("切换设备", "Switch device")).read_only(false).destructive(false).idempotent(true).open_world(false), + ), + t( + "iphone_batch", + action_desc( + ictl_l10n::tr!("按顺序执行几步操作,一次调用完成(最多 20 步),某一步出错就停下,说明停在第几步、后面几步没执行。\n\n\ +steps 每项是 {\"tool\": 工具名, 其余是该工具的参数},可用:iphone_tap、iphone_tap_element、iphone_long_press、\ +iphone_swipe、iphone_type_text、iphone_press_button、iphone_launch_app、iphone_terminate_app、iphone_open_url、\ +iphone_wait_for,以及 {\"tool\": \"wait\", \"seconds\": 秒数}(不超过 5)。iphone_tap_element 没点到也会停下。\ +执行前先检查全部参数,有错一步都不执行。\n\n\ +何时用:结果确定的连续操作(按键、逐级点菜单、填表),每步省一轮往返。每步的结果不确定(点了以后不知道会跳到哪)时,还是一步步来。\ +then 在全部做完(或停下)后返回一次界面。", "Run several steps in order in one call (up to 20); stops at the first error and says which step it stopped at and how many didn't run.\n\nEach item of steps is {\"tool\": tool name, plus that tool's parameters}; allowed: iphone_tap, iphone_tap_element, iphone_long_press, iphone_swipe, iphone_type_text, iphone_press_button, iphone_launch_app, iphone_terminate_app, iphone_open_url, iphone_wait_for, and {\"tool\": \"wait\", \"seconds\": n} (up to 5). An iphone_tap_element that taps nothing also stops it. All parameters are checked first; if any is wrong, no step runs.\n\nWhen to use: sequences with predictable results (keys, menu levels, forms), saving a round trip per step. When the outcome of a step is uncertain (you don't know where a tap leads), go step by step. then returns the screen once, after the last step (or where it stopped)."), + ictl_l10n::tr!("1. iphone_launch_app → 已启动 com.apple.Preferences(每步一行)", "1. iphone_launch_app → Launched com.apple.Preferences (one line per step)"), + true, + ), + schema( + with_then(json!({ + "steps": {"type": "array", "items": {"type": "object"}, + "description": ictl_l10n::tr!("要执行的步骤,1 到 20 个,例如 [{\"tool\": \"iphone_tap_element\", \"text\": \"通用\"}]", "the steps to run, 1 to 20, e.g. [{\"tool\": \"iphone_tap_element\", \"text\": \"General\"}]")}, + "reuse_elements": {"type": "boolean", "default": false, + "description": ictl_l10n::tr!("这批操作不改变界面布局时(例如在同一个键盘上连按)设为 true:按名字点击复用最近读到的元素树,每步省 0.3~0.8 秒。会跳转页面的不要用,否则可能点到旧位置", "Set to true when the steps don't change the layout (e.g. pressing keys on the same keypad): tapping by text reuses the most recent element tree, saving 0.3-0.8 s per step. Don't use it for steps that navigate, or it may tap where things used to be")}, + "one_gesture": {"type": "boolean", "default": false, + "description": ictl_l10n::tr!("步骤全是 iphone_tap 时可设为 true:这些点在一个手势里依次点完(每个点一根手指,间隔约 0.04 秒),中间不等界面空闲。用于在同一个键盘上连按,例如输入框不接受 iphone_type_text 时逐个点数字键:7 个键约 1.9 秒,分开点约 3.6 秒。点的过程中不看界面,中途跳了页面后面的点也照样点下去;点完截图或读元素核对", "Only when every step is iphone_tap: set to true to tap the points one after another in a single gesture (one finger per point, about 0.04 s apart) without waiting for the interface in between. For pressing keys on the same keyboard, e.g. digit keys one by one when a field doesn't take iphone_type_text: 7 keys in about 1.9 s instead of about 3.6 s. Nothing is checked while it taps, so if a tap navigates, the remaining points still land; check the result with a screenshot or elements afterwards")} + })), + &["steps"], + ), + acting(ictl_l10n::tr!("批量操作", "Batch"), true, false), + ), + ] +} diff --git a/crates/ictl-mcp/src/server.rs b/crates/ictl-mcp/src/server.rs new file mode 100644 index 0000000..aa30b96 --- /dev/null +++ b/crates/ictl-mcp/src/server.rs @@ -0,0 +1,430 @@ +use super::*; + +#[derive(Debug, Clone)] +pub struct McpServer { + pub socket: PathBuf, + /// This process works for a task (`IPHONE_CONTROL_TASK_TOKEN`, see [`task`]); over HTTP a request may instead + /// carry a task's token in [`protocol::TASK_TOKEN_HEADER`] ([`request_token`]) + pub task: bool, + /// Held for the length of each tool call ([`serve_stdio`]); `None` where the process holds one of its own + pub lease: Option, +} + +/// Takes the host's shared maintenance lease (`ictl_daemon::maintenance::shared`): an update waits while it is held +pub type Lease = fn() -> std::io::Result; + +/// How long a tool call waits for an update that holds the maintenance lock before it goes on without the lease +/// (the daemon then answers, or `protocol::connect` waits for it to be back) +pub(crate) const LEASE_WAIT: std::time::Duration = std::time::Duration::from_secs(15); + +/// The lease for one tool call: taken, waited for while an update runs, or `None` (going on without) +pub(crate) async fn hold(take: Lease) -> Option { + let started = std::time::Instant::now(); + loop { + match take() { + Ok(f) => return Some(f), + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock && started.elapsed() < LEASE_WAIT => { + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + } + Err(_) => return None, + } + } +} + +/// The task token an HTTP request carries ([`protocol::TASK_TOKEN_HEADER`]); `None` over stdio +pub(crate) fn request_token(context: &RequestContext) -> Option { + let parts = context.extensions.get::()?; + let t = parts.headers.get(protocol::TASK_TOKEN_HEADER)?.to_str().ok()?.trim(); + (!t.is_empty()).then(|| t.to_owned()) +} + +/// MCP over HTTP (Streamable HTTP, one session per client) for the viewer's `/mcp` +pub type HttpService = rmcp::transport::streamable_http_server::StreamableHttpService< + McpServer, + rmcp::transport::streamable_http_server::session::local::LocalSessionManager, +>; + +/// The service behind `/mcp`. It doesn't check `Host` or `Origin`: the viewer does, with the names of its page +pub fn http_service(socket: PathBuf) -> HttpService { + use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService}; + let config = StreamableHttpServerConfig::default().with_allowed_hosts(Vec::::new()); + StreamableHttpService::new( + move || Ok(McpServer { socket: socket.clone(), task: false, lease: None }), + std::sync::Arc::default(), + config, + ) +} + +impl ServerHandler for McpServer { + fn get_info(&self) -> InitializeResult { + InitializeResult::new(ServerCapabilities::builder().enable_tools().build()).with_instructions(instructions()) + } + + async fn list_tools( + &self, + _request: Option, + context: RequestContext, + ) -> Result { + let mut t = tools(); + if self.task || request_token(&context).is_some() { + t.push(confirm_tool()); + } + Ok(ListToolsResult::with_all_items(t)) + } + + async fn call_tool( + &self, + request: CallToolRequestParams, + context: RequestContext, + ) -> Result { + // an idle server holds nothing (an update can go ahead between calls); a call holds the lease to its end + let _lease = match self.lease { + Some(take) => hold(take).await, + None => None, + }; + let token = request_token(&context); + if !self.task && token.is_none() { + return self.call_tool_cancellable(request, &context).await; + } + // every request of this call goes out with the HTTP request's token (over stdio: the process's) + protocol::as_task(token, None, self.call_tool_in_task(request, context)).await + } +} + +impl McpServer { + /// [`ServerHandler::call_tool`] for a task's agent + async fn call_tool_in_task( + &self, + request: CallToolRequestParams, + context: RequestContext, + ) -> Result { + // working for a task: the daemon holds or refuses the calls; announce each so the page shows the tool + let name = request.name.clone(); + let args = request.arguments.clone().unwrap_or_default(); + let work = async { + if request.name == task::CONFIRM_TOOL { + if let Err(e) = check_args(&request.name, &args, &[], false) { + return Ok(CallToolResult::error(vec![ContentBlock::text(e)]).into()); + } + let r = match task::confirm(&self.socket, &args).await { + Ok(m) => CallToolResult::success(vec![ContentBlock::text(m)]), + Err(m) => CallToolResult::error(vec![ContentBlock::text(m)]), + }; + return Ok(r.into()); + } + match task::before(&self.socket, &request.name, &args).await { + task::Before::Go(step) => { + let t0 = std::time::Instant::now(); + let r = protocol::as_task(None, Some(step), self.call_tool_inner(request)).await; + if let Ok(CallToolResponse::Complete(c)) = &r { + let v = serde_json::to_value(c).unwrap_or_default(); + task::after(&self.socket, step, &v, t0.elapsed().as_millis() as u64).await; + } + r + } + task::Before::Refuse(m) => { + Ok(input_error(m, &name, Delivery::NotSent, Some(FailureStage::Preflight)).into()) + } + } + }; + tokio::select! { + r = work => r, + _ = context.ct.cancelled() => Ok(input_error(ictl_l10n::tr!("调用已取消", "Call cancelled"), &name, Delivery::Unknown, None).into()), + } + } + + async fn call_tool_cancellable( + &self, + request: CallToolRequestParams, + context: &RequestContext, + ) -> Result { + // rmcp 收到取消通知只是置这个令牌,不会中止处理:自己停下。丢掉进行中的调用会断开到守护进程的连接, + // 守护进程那边还在排队的请求随之放弃(protocol::call),iphone_batch 剩下的步骤也不再执行 + let name = request.name.clone(); + tokio::select! { + r = self.call_tool_inner(request) => r, + _ = context.ct.cancelled() => Ok(input_error(ictl_l10n::tr!("调用已取消", "Call cancelled"), &name, Delivery::Unknown, None).into()), + } + } + + pub(crate) async fn call_tool_inner(&self, request: CallToolRequestParams) -> Result { + let args = request.arguments.unwrap_or_default(); + if let Err(e) = check_args(&request.name, &args, &[], true) { + return Ok(input_error(e, &request.name, Delivery::NotSent, Some(FailureStage::Preflight)).into()); + } + let then = match parse_then(&args) { + Ok(t) => t, + Err(e) => return Ok(input_error(e, &request.name, Delivery::NotSent, Some(FailureStage::Preflight)).into()), + }; + if request.name == "iphone_batch" { + return Ok(self.batch(&args, then).await.into()); + } + if DEV_TOOLS.contains(&&*request.name) && !dev_tools_enabled() { + let name = &request.name; + return Ok(to_result(Response::error(ictl_l10n::trf!( + "{name} 是开发者工具,要先设 IPHONE_CONTROL_DEV_TOOLS=1", + "{name} is a developer tool; set IPHONE_CONTROL_DEV_TOOLS=1 first" + ))) + .into()); + } + let req = match to_request(&request.name, &args) { + Ok(r) => r, + Err(e) => return Ok(input_error(e, &request.name, Delivery::NotSent, Some(FailureStage::Preflight)).into()), + }; + // then 只对操作类工具有意义;看界面的工具本身就是返回界面 + // A single input and its readbacks must all apply to the same device. Tasks already pin theirs. + let udid = if req.reports_delivery() && !protocol::in_task() { + match self.controlled_udid().await { + Ok(id) => Some(id), + Err((message, stage)) => { + return Ok(input_error(message, &request.name, Delivery::NotSent, Some(stage)).into()); + } + } + } else { + None + }; + let resp = self.call_on(&req, udid.as_deref()).await; + let input = req.reports_delivery().then(|| InputResult { + delivery: resp.delivery(&req), + stage: resp.failure_stage(), + field: resp.field_readback(&req), + udid: udid.as_deref(), + }); + if matches!(req, Request::ScrollCollect(_)) { + return Ok(to_result(resp).into()); + } + Ok(match (resp, input) { + (Response::Error { mut message, .. }, Some(input)) => { + add_delivery_hint(&mut message, input.delivery); + self.finish(message, true, then, false, false, Some(input)).await + } + (Response::Text { text, outcome, .. }, input) if req.is_device_action() => { + // 结果里已经说了有弹窗(启动 App 被挡)就不再查 + let check = wants_alert_check(&req) && !protocol::alert_reported(&text, outcome); + // 按名字没点到东西:界面没动过,不用等它稳定,直接给界面(按名字点击刚读过的树) + let settle = !tap_missed(&text, outcome); + self.finish(text, false, then, check, settle, input).await + } + (resp, _) => to_result(resp), + } + .into()) + } + + async fn call(&self, req: &Request) -> Response { + self.call_on(req, None).await + } + + /// `expect_udid`:守护进程正在控制的不是这台就不执行(见 [`protocol::EXPECT_UDID`]) + async fn call_on(&self, req: &Request, expect_udid: Option<&str>) -> Response { + // 守护进程正忙(例如在自动解锁)时会排队;最多等 150 秒,免得 agent 一直挂着。An install uploads the package and + // can take several minutes on its own + let wait = if matches!(req, Request::InstallApp { .. }) { 660 } else { 150 }; + // in a task the daemon holds calls while the user has paused or taken over, as long as that takes + let wait = (!protocol::in_task()).then(|| Duration::from_secs(wait)); + protocol::exchange_on(&self.socket, req, wait, expect_udid, None, None).await.unwrap_or_else(|e| { + let reason = e.source; + let message = if e.failure.stage == FailureStage::Connect { + ictl_l10n::trf!( + "连不上守护进程({}):{reason};确认守护进程在运行(iphone-control status)", + "Can't reach the daemon ({}): {reason}; make sure the daemon is running (iphone-control status)", + self.socket.display() + ) + } else { + ictl_l10n::trf!("守护进程请求失败: {reason}", "Daemon request failed: {reason}") + }; + Response::error(message).with_failure(e.failure.delivery, e.failure.stage) + }) + } + + /// 操作完成后:按 then 等界面稳定,再附上元素列表或截图(等稳定时顺带提醒弹窗)。 + /// 不带 then 时,`alert_check` 为真就查一下有没有系统弹窗挡着。`settle` 为假(什么都没点)时不等稳定 + async fn finish( + &self, + mut text: String, + failed: bool, + opts: ThenOpts, + alert_check: bool, + settle: bool, + input: Option>, + ) -> CallToolResult { + let expect_udid = input.as_ref().and_then(|i| i.udid); + let mut elements = None; + let mut readback = json!({"settle": "not_requested", "screen": "not_requested"}); + let mut image = None; + if opts.then == Then::None { + if alert_check { + match self.call_on(&Request::AlertCheck, expect_udid).await { + Response::Text { text: t, .. } => { + text += &t; + readback["alert"] = "ok".into(); + } + Response::Error { message, .. } if input.is_some() => { + text += &ictl_l10n::trf!("\n(检查弹窗失败:{message})", "\n(alert check failed: {message})"); + readback["alert"] = "failed".into(); + } + _ => readback["alert"] = "failed".into(), + } + } + } else { + if settle { + match self.call_on(&Request::Settle { max_ms: opts.settle_ms }, expect_udid).await { + Response::Text { text: t, .. } => { + text += &format!("\n{t}"); + readback["settle"] = "ok".into(); + } + Response::Error { message, .. } => { + text += &ictl_l10n::trf!( + "\n(等界面稳定失败:{message})", + "\n(waiting for the screen to settle failed: {message})" + ); + readback["settle"] = "failed".into(); + } + _ => readback["settle"] = "failed".into(), + } + } + let read = match opts.then { + Then::Elements(filter) => { + Request::ListElements { filter, limit: THEN_LIMIT, max_age_ms: THEN_SETTLE_MS, keep_locked: false } + } + Then::Screenshot(region) => Request::Screenshot { region }, + Then::None => unreachable!(), + }; + let screen = match self.call_on(&read, expect_udid).await { + Response::Text { text: t, data, .. } if matches!(read, Request::ListElements { .. }) => { + elements = data; + text += &ictl_l10n::trf!("\n--- 操作后的界面 ---\n{t}", "\n--- Screen after the action ---\n{t}"); + "ok" + } + Response::Image { jpeg_base64, caption } if matches!(read, Request::Screenshot { .. }) => { + image = Some((jpeg_base64, caption)); + "ok" + } + Response::Error { message, .. } => { + text += &ictl_l10n::trf!("\n(读界面失败:{message})", "\n(reading the screen failed: {message})"); + "failed" + } + _ => { + text += ictl_l10n::tr!("\n(未收到请求的界面)", "\n(The requested screen was not returned.)"); + "failed" + } + }; + readback["screen"] = screen.into(); + } + let read_failed = readback.as_object().unwrap().values().any(|v| v == "failed"); + if input.is_some() && read_failed && !failed { + text += ictl_l10n::tr!( + "\n请单独读取屏幕确认结果,避免重复之前的输入。", + "\nRead the screen separately before repeating any input." + ); + } + let mut blocks = vec![ContentBlock::text(text)]; + if let Some((jpeg, caption)) = image { + blocks.push(ContentBlock::image(jpeg, "image/jpeg")); + blocks.push(ContentBlock::text(caption)); + } + let mut result = if failed { CallToolResult::error(blocks) } else { CallToolResult::success(blocks) }; + result = with_element_data(result, elements); + if let Some(input) = input { + let data = result.structured_content.get_or_insert_with(|| json!({})); + data["delivery"] = json!(input.delivery); + data["readback"] = readback; + if let Some(field) = input.field { + data["readback"]["field"] = field.into(); + } + if let Some(stage) = input.stage.or_else(|| (read_failed && !failed).then_some(FailureStage::Readback)) { + data["stage"] = json!(stage); + } + } + result + } + + /// The cached daemon snapshot includes device.udid on older daemons as well. + async fn controlled_udid(&self) -> Result { + match self.call(&Request::Daemon).await { + Response::Text { text, .. } => { + if let Ok(snapshot) = serde_json::from_str::(&text) + && let Some(id) = snapshot["device"]["udid"].as_str().filter(|id| !id.is_empty()) + { + return Ok(id.to_owned()); + } + } + Response::Error { message, failure, .. } => { + return Err((message, failure.map_or(FailureStage::Preflight, |f| f.stage))); + } + Response::Image { .. } => {} + } + Err(( + ictl_l10n::tr!( + "无法确定当前控制的设备,操作未执行", + "Cannot identify the controlled device; action not sent" + ) + .into(), + FailureStage::Preflight, + )) + } + + /// 按顺序执行;某一步出错就停,说明是第几步、后面几步没执行。出错时也按 then 附上当前界面,方便看停在哪 + async fn batch(&self, args: &Map, then: ThenOpts) -> CallToolResult { + let steps = match batch_steps(args) { + Ok(s) => s, + Err(e) => return to_result(Response::error(e)), + }; + let total = steps.len(); + // 每一步都要求还是开始时控制的那台:自动选设备时拔掉它会改控另一台,剩下的步骤不能落到那台上 + let udid = self.controlled_udid().await.ok(); + let mut lines = Vec::new(); + // 最后一步是不是需要查弹窗的操作 + let mut check = false; + for (i, step) in steps.into_iter().enumerate() { + let n = i + 1; + match step { + Step::Wait(d) => { + tokio::time::sleep(d).await; + lines.push(ictl_l10n::trf!("{n}. wait → 等了 {} 秒", "{n}. wait → waited {} s", d.as_secs_f64())); + } + Step::Request { tool, req } => match self.call_on(&req, udid.as_deref()).await { + // 按名字没点到(toolkit 兼容:单独调用时是普通结果)在批量里要停下:后面的步骤都建立在它点中的前提上 + Response::Text { text, outcome, .. } + if tool == "iphone_tap_element" && tap_missed(&text, outcome) => + { + lines.push(format!("{n}. {tool} → {text}")); + if n < total { + lines.push(ictl_l10n::trf!( + "第 {n} 步没点到,后面 {} 步没有执行", + "Step {n} tapped nothing, the remaining {} step(s) didn't run", + total - n + )); + } + return self.finish(lines.join("\n"), true, then, false, true, None).await; + } + Response::Text { text, outcome, .. } => { + check = wants_alert_check(&req) && !protocol::alert_reported(&text, outcome); + lines.push(format!("{n}. {tool} → {text}")); + } + Response::Image { caption, .. } => lines.push(format!("{n}. {tool} → {caption}")), + Response::Error { message, .. } => { + lines.push(ictl_l10n::trf!("{n}. {tool} → 出错:{message}", "{n}. {tool} → error: {message}")); + if n < total { + lines.push(ictl_l10n::trf!( + "第 {n} 步出错,后面 {} 步没有执行", + "Step {n} failed, the remaining {} step(s) didn't run", + total - n + )); + } + return self.finish(lines.join("\n"), true, then, true, true, None).await; + } + }, + } + } + self.finish(lines.join("\n"), false, then, check, true, None).await + } +} + +/// 在 stdin/stdout 上运行 MCP 服务直到客户端断开 +/// The MCP server on stdin/stdout. `lease` is taken for each tool call, not for the life of the process: agents keep +/// this process running for hours, and an update has to wait only for calls under way +pub async fn serve_stdio(socket: PathBuf, lease: Option) -> anyhow::Result<()> { + let running = McpServer { socket, task: task::join_from_env(), lease }.serve(rmcp::transport::stdio()).await?; + running.waiting().await?; + Ok(()) +} diff --git a/crates/ictl-mcp/src/tests.rs b/crates/ictl-mcp/src/tests.rs new file mode 100644 index 0000000..6f644e4 --- /dev/null +++ b/crates/ictl-mcp/src/tests.rs @@ -0,0 +1,616 @@ +use super::*; + +fn args(v: Value) -> Map { + v.as_object().cloned().unwrap() +} + +#[tokio::test] +async fn input_delivery_is_independent_of_field_and_screen_readback() { + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + let socket = PathBuf::from(format!("/tmp/ictl-single-input-{}.sock", std::process::id())); + let server = McpServer { socket: socket.clone(), task: false, lease: None }; + let call = |name, args: Value| { + let req = CallToolRequestParams::new(name).with_arguments(args.as_object().unwrap().clone()); + let server = &server; + async move { + let CallToolResponse::Complete(result) = server.call_tool_inner(req).await.unwrap() else { panic!() }; + result + } + }; + let tap = json!({"x": 1, "y": 2}); + let unavailable = call("iphone_tap", tap.clone()).await; + let data = unavailable.structured_content.unwrap(); + assert_eq!(data["delivery"], "not_sent"); + assert_eq!(data["stage"], "connect"); + + let listener = tokio::net::UnixListener::bind(&socket).unwrap(); + let exchanges = [ + ("tap", None), // request reached daemon, reply lost + ("tap", Some(Response::text("Tapped"))), + ("settle", Some(Response::text("Settled"))), + ("screenshot", Some(Response::error("controlled device changed to phone-B"))), + ("tap", Some(Response::text("Tapped"))), + ("settle", Some(Response::error("lost settle"))), + ( + "list_elements", + Some(Response::text_data( + "items", + Default::default(), + Some(protocol::Data::Elements { elements: vec![], matched_count: Some(3), truncated: Some(true) }), + )), + ), + ( + "type_text", + Some(Response::text_with("Typed", protocol::Outcome { field_verified: Some(false), ..Default::default() })), + ), + ("alert_check", Some(Response::text(""))), + ("type_text", Some(Response::error("field mismatch").with_failure(Delivery::Sent, FailureStage::Readback))), + ( + "tap_element", + Some(Response::text_with("No match", protocol::Outcome { tapped_nothing: true, ..Default::default() })), + ), + ("alert_check", Some(Response::text(""))), + ]; + let daemon = async { + let mut first_snapshot = true; + for (op, reply) in exchanges { + let mut peer = loop { + let (mut peer, _) = listener.accept().await.unwrap(); + let mut line = String::new(); + BufReader::new(&mut peer).read_line(&mut line).await.unwrap(); + let request: Value = serde_json::from_str(&line).unwrap(); + if request["op"] == "daemon" { + // Old daemon snapshot: only the controlled device's UDID is needed. + let snapshot = if std::mem::take(&mut first_snapshot) { + Response::text(r#"{"device":null}"#) + } else { + Response::text(r#"{"device":{"udid":"phone-A"}}"#) + }; + peer.write_all(format!("{}\n", json!(snapshot)).as_bytes()).await.unwrap(); + continue; + } + assert_eq!(request["op"], op); + assert_eq!(request[protocol::EXPECT_UDID], "phone-A", "{request}"); + break peer; + }; + if let Some(reply) = reply { + peer.write_all(format!("{}\n", json!(reply)).as_bytes()).await.unwrap(); + } + } + }; + let actions = async { + let missing = call("iphone_tap", tap.clone()).await; + let data = missing.structured_content.unwrap(); + assert_eq!(data["delivery"], "not_sent"); + assert_eq!(data["stage"], "preflight"); + + let lost = call("iphone_tap", tap).await; + assert_eq!(lost.is_error, Some(true)); + let data = lost.structured_content.unwrap(); + assert_eq!(data["delivery"], "unknown"); + assert_eq!(data["stage"], "reply"); + + let tapped = call("iphone_tap", json!({"x":1,"y":2,"then":"screenshot"})).await; + assert_ne!(tapped.is_error, Some(true)); + let data = tapped.structured_content.unwrap(); + assert_eq!(data["delivery"], "sent"); + assert_eq!(data["stage"], "readback"); + assert_eq!(data["readback"], json!({"settle":"ok", "screen":"failed"})); + + let listed = call("iphone_tap", json!({"x":1,"y":2,"then":"elements"})).await; + assert_ne!(listed.is_error, Some(true)); + let data = listed.structured_content.unwrap(); + assert_eq!(data["delivery"], "sent"); + assert_eq!(data["readback"], json!({"settle":"failed", "screen":"ok"})); + assert_eq!(data["matched_count"], 3); + assert_eq!(data["truncated"], true); + + let text = json!({"text":"x"}); + let typed = call("iphone_type_text", text.clone()).await.structured_content.unwrap(); + assert_eq!(typed["delivery"], "sent"); + assert_eq!(typed["readback"]["field"], "unverified"); + let mismatch = call("iphone_type_text", text.clone()).await; + assert_eq!(mismatch.is_error, Some(true)); + let data = mismatch.structured_content.unwrap(); + assert_eq!(data["delivery"], "sent"); + assert_eq!(data["readback"]["field"], "failed"); + + let missed = call("iphone_tap_element", text).await; + assert_ne!(missed.is_error, Some(true)); + assert_eq!(missed.structured_content.unwrap()["delivery"], "not_sent"); + }; + tokio::time::timeout(Duration::from_secs(4), async { tokio::join!(daemon, actions) }).await.unwrap(); + std::fs::remove_file(socket).unwrap(); +} + +fn has_cjk(s: &str) -> bool { + s.chars().any(|c| matches!(c, '\u{3000}'..='\u{303f}' | '\u{4e00}'..='\u{9fff}' | '\u{ff00}'..='\u{ffef}')) +} + +/// With IPHONE_CONTROL_LANG=en nothing the agent reads up front is Chinese: instructions, tool +/// descriptions, titles and parameter docs (only examples of Chinese input may stay) +#[test] +fn delivery_hints_do_not_repeat_punctuation_or_existing_screen_guidance() { + ictl_l10n::with_lang(ictl_l10n::Lang::En, || { + let mut message = "Focus changed. Inspect the screen.".to_owned(); + add_delivery_hint(&mut message, Delivery::Sent); + assert_eq!(message, "Focus changed. Inspect the screen. Input was sent."); + }); + ictl_l10n::with_lang(ictl_l10n::Lang::Zh, || { + let mut message = "请求超时,请先截图确认。".to_owned(); + add_delivery_hint(&mut message, Delivery::Unknown); + assert_eq!(message, "请求超时,请先截图确认。输入可能已送达。"); + }); +} + +#[test] +fn english_tool_definitions_have_no_chinese() { + use ictl_l10n::{Lang, with_lang}; + with_lang(Lang::En, || { + assert!(!has_cjk(instructions()), "{}", instructions()); + for t in tools_with(true) { + let json = serde_json::to_string(&t).unwrap(); + assert!(!has_cjk(&json), "{}: {json}", t.name); + } + }); + with_lang(Lang::Zh, || assert!(has_cjk(instructions()))); +} + +/// scroll 是可选的:不给就和以前一样只看当前屏幕;方向只认 down / up,次数 1 到上限 +#[test] +fn tap_element_scroll_search_is_optional_and_checked() { + let req = |v: Value| to_request("iphone_tap_element", &args(v)); + let plain = req(json!({"text": "隐私"})).unwrap(); + assert_eq!(plain, Request::TapElement { text: "隐私".into(), index: 0, max_age_ms: 0, scroll: None }); + let down = req(json!({"text": "隐私", "scroll": "down"})).unwrap(); + let s = |down, max| Some(protocol::ScrollSearch { down, max }); + assert_eq!(down, Request::TapElement { text: "隐私".into(), index: 0, max_age_ms: 0, scroll: s(true, 8) }); + let up = req(json!({"text": "隐私", "scroll": "up", "max_scrolls": 3})).unwrap(); + assert_eq!(up, Request::TapElement { text: "隐私".into(), index: 0, max_age_ms: 0, scroll: s(false, 3) }); + for bad in [ + json!({"text": "x", "scroll": "left"}), + json!({"text": "x", "scroll": "down", "max_scrolls": 0}), + json!({"text": "x", "scroll": "down", "max_scrolls": 16}), + json!({"text": "x", "scroll": true}), + ] { + assert!(req(bad).is_err()); + } + // reused in a batch, the scroll search stays + let steps = batch_steps(&args( + json!({"reuse_elements": true, "steps": [{"tool": "iphone_tap_element", "text": "x", "scroll": "down"}]}), + )); + assert!(matches!(&steps.unwrap()[0], Step::Request { req: Request::TapElement { scroll: Some(_), .. }, .. })); +} + +/// hold defaults to 0 (a plain swipe, same request as before) and is passed through when given +#[test] +fn swipe_hold_defaults_to_zero() { + let plain = to_request("iphone_swipe", &args(json!({"from_x": 1, "from_y": 2, "to_x": 3, "to_y": 4}))).unwrap(); + assert_eq!(plain, Request::Swipe { from: (1.0, 2.0), to: (3.0, 4.0), seconds: 0.3, hold: 0.0 }); + let held = json!({"from_x": 1, "from_y": 2, "to_x": 3, "to_y": 4, "seconds": 0.7, "hold": 0.6}); + let held = to_request("iphone_swipe", &args(held)).unwrap(); + assert_eq!(held, Request::Swipe { from: (1.0, 2.0), to: (3.0, 4.0), seconds: 0.7, hold: 0.6 }); + assert!( + to_request("iphone_swipe", &args(json!({"from_x": 1, "from_y": 2, "to_x": 3, "to_y": 4, "hold": "x"}))) + .is_err() + ); +} + +/// one_gesture 把全是坐标点击的批量并成一个 TapSequence;混了别的步骤就报错,一步都不执行 +#[test] +fn one_gesture_turns_taps_into_one_sequence() { + let steps = batch_steps(&args(json!({"one_gesture": true, "steps": [ + {"tool": "iphone_tap", "x": 60, "y": 548}, + {"tool": "iphone_tap", "x": 23, "y": 548.5} + ]}))); + let req = Request::TapSequence { points: vec![(60.0, 548.0), (23.0, 548.5)] }; + assert_eq!(steps, Ok(vec![Step::Request { tool: "iphone_tap".into(), req }])); + for other in [ + json!({"tool": "iphone_tap_element", "text": "1"}), + json!({"tool": "wait", "seconds": 0.1}), + json!({"tool": "iphone_type_text", "text": "1"}), + ] { + let steps = json!({"one_gesture": true, "steps": [{"tool": "iphone_tap", "x": 1, "y": 2}, other]}); + assert!(batch_steps(&args(steps)).is_err()); + } + // without it a batch of taps stays step by step + let steps = batch_steps(&args(json!({"steps": [{"tool": "iphone_tap", "x": 1, "y": 2}]}))).unwrap(); + assert_eq!( + steps, + vec![Step::Request { tool: "iphone_tap".into(), req: Request::Tap { x: 1.0, y: 2.0, count: 1 } }] + ); + // a step's count can't go into one gesture: an error, not one tap + let steps = json!({"one_gesture": true, "steps": [{"tool": "iphone_tap", "x": 1, "y": 2, "count": 2}]}); + assert!(batch_steps(&args(steps)).is_err()); +} + +/// iphone_tap 不带 count 是点一下;count 要是 1 到 MAX_TAP_COUNT 的整数,给错了报错、不点,不悄悄改成 1 +#[test] +fn tap_count_defaults_to_one_and_rejects_out_of_range() { + let tap = |v: Value| to_request("iphone_tap", &args(v)); + assert_eq!(tap(json!({"x": 1, "y": 2})), Ok(Request::Tap { x: 1.0, y: 2.0, count: 1 })); + assert_eq!(tap(json!({"x": 1, "y": 2, "count": 5})), Ok(Request::Tap { x: 1.0, y: 2.0, count: 5 })); + for bad in [json!(0), json!(11), json!(2.5), json!(-1), json!("two")] { + assert!(tap(json!({"x": 1, "y": 2, "count": bad})).is_err(), "{bad}"); + } + // a batch step takes it too + let steps = batch_steps(&args(json!({"steps": [{"tool": "iphone_tap", "x": 1, "y": 2, "count": 2}]}))); + let req = Request::Tap { x: 1.0, y: 2.0, count: 2 }; + assert_eq!(steps, Ok(vec![Step::Request { tool: "iphone_tap".into(), req }])); +} + +#[test] +fn scroll_collection_is_bounded_and_changes_the_viewport() { + let req = |v| { + let args = args(v); + check_args("iphone_scroll_collect", &args, &[], true)?; + to_request("iphone_scroll_collect", &args) + }; + let r = req(json!({"scroll": "up", "max_scrolls": 1, "filter": "Cell", "until": "General", "limit": 3})).unwrap(); + assert_eq!( + r, + Request::ScrollCollect(protocol::ScrollCollect { + down: false, + max_scrolls: 1, + filter: "Cell".into(), + until: "General".into(), + limit: 3, + x: None, + }) + ); + // an iPad split view's sidebar + let Request::ScrollCollect(scan) = req(json!({"x": 160})).unwrap() else { panic!() }; + assert_eq!(scan.x, Some(160.0)); + assert!(r.is_device_action()); + assert!(req(json!({})).is_ok()); + for bad in [ + json!({"scroll":"left"}), + json!({"max_scrolls":0}), + json!({"max_scrolls":16}), + json!({"limit":0}), + json!({"limit":151}), + json!({"limit":2.5}), + json!({"x":-1}), + json!({"x":"sidebar"}), + json!({"max_scroll":2}), + ] { + assert!(req(bad.clone()).is_err(), "{bad}"); + } + let result = to_result(Response::text_data( + "row limit reached", + Default::default(), + Some(protocol::Data::ScrollCollection { + stop_reason: protocol::ScrollStop::Limit, + scrolls: 2, + rows: vec![protocol::ScrollRow { + kind: "Cell".into(), + label: "One".into(), + name: "".into(), + value: "".into(), + }], + matched: None, + }), + )); + let data = result.structured_content.unwrap(); + assert_eq!(data["stop_reason"], "limit"); + assert_eq!(data["rows"][0]["label"], "One"); + assert!(data["matched"].is_null()); +} + +#[test] +fn alert_check_after_actions_but_not_buttons_or_reads() { + assert!(wants_alert_check(&Request::Swipe { from: (0.0, 0.0), to: (1.0, 1.0), seconds: 0.3, hold: 0.0 })); + assert!(wants_alert_check(&Request::LaunchApp { app: "微信".into() })); + assert!(!wants_alert_check(&Request::PressButton { button: "home".into() })); + assert!(!wants_alert_check(&Request::TerminateApp { app: "微信".into() })); + assert!(!wants_alert_check(&Request::Status)); +} + +#[test] +fn toolkit_tools_plus_wait_for_batch_and_devices() { + let names: Vec<_> = tools().iter().map(|t| t.name.to_string()).collect(); + assert_eq!(names.len(), 18); + // the developer tools only with IPHONE_CONTROL_DEV_TOOLS + let dev: Vec<_> = tools_with(true).iter().skip(18).map(|t| t.name.to_string()).collect(); + assert_eq!(dev, DEV_TOOLS); + assert_eq!(tools_with(false).len(), 18); + for n in [ + "iphone_status", + "iphone_screenshot", + "iphone_scroll_collect", + "iphone_tap_element", + "iphone_open_url", + "iphone_list_devices", + "iphone_select_device", + ] { + assert!(names.contains(&n.to_owned()), "{n}"); + } + for t in tools_with(true).into_iter().filter(|t| t.name != "iphone_batch") { + let no_required = t.input_schema.get("required").unwrap().as_array().unwrap().is_empty(); + assert_eq!(to_request(&t.name, &Map::new()).is_ok(), no_required, "{}", t.name); + } +} + +/// 注解与工具实际行为一致:看界面的只读,改界面的不是;每个参数都有说明 +#[test] +fn annotations_and_param_docs() { + for t in tools_with(true) { + let a = t.annotations.as_ref().unwrap_or_else(|| panic!("{} 没有注解", t.name)); + assert!(a.title.is_some(), "{}", t.name); + let probe = || { + let props = t.input_schema["properties"].as_object().unwrap(); + let mut m = Map::new(); + for k in t.input_schema["required"].as_array().unwrap() { + let k = k.as_str().unwrap(); + let v = match props[k]["type"].as_str() { + Some("number") => json!(1), + Some("array") => json!([{"tool": "wait", "seconds": 0}]), + _ if k == "button" => json!("home"), + _ => json!("x"), + }; + m.insert(k.to_owned(), v); + } + m + }; + let read_only = match to_request(&t.name, &probe()) { + Ok(r) => !r.is_device_action(), + Err(_) => false, // iphone_batch + }; + assert_eq!(a.read_only_hint, Some(read_only), "{}", t.name); + for (k, v) in t.input_schema["properties"].as_object().unwrap() { + let d = v["description"].as_str().unwrap_or_default(); + assert!(!d.is_empty(), "{}.{k} 缺少说明", t.name); + } + } +} + +#[test] +fn defaults_match_toolkit() { + assert_eq!( + to_request("iphone_list_elements", &Map::new()).unwrap(), + Request::ListElements { filter: String::new(), limit: 150, max_age_ms: 0, keep_locked: false } + ); + assert_eq!( + to_request("iphone_swipe", &args(json!({"from_x": 1, "from_y": 2, "to_x": 3, "to_y": 4}))).unwrap(), + Request::Swipe { from: (1.0, 2.0), to: (3.0, 4.0), seconds: 0.3, hold: 0.0 } + ); + assert_eq!( + to_request("iphone_long_press", &args(json!({"x": 1, "y": 2}))).unwrap(), + Request::LongPress { x: 1.0, y: 2.0, seconds: 1.0 } + ); + assert_eq!( + to_request("iphone_type_text", &args(json!({"text": "设置"}))).unwrap(), + Request::TypeText { text: "设置".into(), submit: false } + ); +} + +#[test] +fn then_is_offered_on_actions_only() { + let has_then = |name: &str| { + let t = tools().into_iter().find(|t| t.name == name).unwrap(); + t.input_schema["properties"].get("then").is_some() + }; + for n in + ["iphone_tap", "iphone_tap_element", "iphone_swipe", "iphone_type_text", "iphone_launch_app", "iphone_batch"] + { + assert!(has_then(n), "{n}"); + } + for n in ["iphone_status", "iphone_screenshot", "iphone_list_elements", "iphone_wait_for"] { + assert!(!has_then(n), "{n}"); + } + let then = |v: Value| parse_then(&args(v)).map(|o| o.then); + assert_eq!(parse_then(&Map::new()).unwrap(), ThenOpts { then: Then::None, settle_ms: THEN_SETTLE_MS }); + assert_eq!(then(json!({"then": "elements", "then_filter": "设置"})).unwrap(), Then::Elements("设置".into())); + assert_eq!(then(json!({"then": "screenshot"})).unwrap(), Then::Screenshot(None)); + assert_eq!( + then(json!({"then": "screenshot", "then_region": [0, 295, 430, 460]})).unwrap(), + Then::Screenshot(Some((0.0, 295.0, 430.0, 460.0))) + ); + assert!(then(json!({"then": "screenshot", "then_region": [0, 1, 2]})).is_err()); + assert!(then(json!({"then": "screenshot", "then_region": [0, 1, 0, 5]})).is_err()); + assert!(then(json!({"then": "video"})).is_err()); + assert_eq!(parse_then(&args(json!({"then": "screenshot", "then_settle": 5}))).unwrap().settle_ms, 5000); + assert!(parse_then(&args(json!({"then_settle": 30}))).is_err()); +} + +/// #158: an argument the tool doesn't take is refused, not dropped (a wait for disappearance ran as a wait for +/// appearance and answered at once) +#[test] +fn unknown_arguments_are_refused() { + // an argument from another version (here: misspelt) is refused and the tool's own are listed + let e = check_args("iphone_wait_for", &args(json!({"text": "飞行模式", "until": "disappeared"})), &[], true) + .unwrap_err(); + assert!(e.contains("until") && e.contains("state") && e.contains("timeout"), "{e}"); + assert!(check_args("iphone_wait_for", &args(json!({"text": "x", "state": "disappeared"})), &[], true).is_ok()); + assert!(check_args("iphone_type_text", &args(json!({"text": "", "replace": true})), &[], true).is_ok()); + // misspelt + assert!(check_args("iphone_type_text", &args(json!({"text": "a", "sumbit": true})), &[], true).is_err()); + // every documented argument, then on an action, null for a default + assert!( + check_args( + "iphone_type_text", + &args(json!({"text": "a", "submit": true, "then": "elements", + "then_filter": "x", "then_settle": 1})), + &[], + true + ) + .is_ok() + ); + assert!(check_args("iphone_list_elements", &args(json!({"limit": null})), &[], true).is_ok()); + // then only where the schema lists it + assert!(check_args("iphone_screenshot", &args(json!({"then": "elements"})), &[], true).is_err()); + assert!(check_args("iphone_status", &args(json!({})), &[], true).is_ok()); + assert!(check_args("iphone_batch", &args(json!({"steps": [], "then": "screenshot"})), &[], true).is_ok()); + // developer tools and the confirm tool have their own; a tool this server doesn't know is left alone + assert!(check_args("iphone_web_eval", &args(json!({"expression": "1", "timeout": 2})), &[], true).is_ok()); + assert!(check_args(task::CONFIRM_TOOL, &args(json!({"action": "a", "detail": "b", "x": 1})), &[], false).is_err()); + assert!(check_args("no_such_tool", &args(json!({"x": 1})), &[], true).is_ok()); +} + +#[test] +fn batch_steps_refuse_unknown_arguments() { + let bad = |step: Value| batch_steps(&args(json!({"steps": [step]}))).unwrap_err(); + let e = bad(json!({"tool": "iphone_wait_for", "text": "x", "until": "disappeared"})); + assert!(e.contains("第 1 步") && e.contains("until"), "{e}"); + // a step's then would be ignored (the batch's then applies): refused, not dropped + assert!(bad(json!({"tool": "iphone_tap", "x": 1, "y": 2, "then": "elements"})).contains("then")); + assert!(bad(json!({"tool": "wait", "seconds": 1, "secs": 2})).contains("secs")); +} + +#[test] +fn element_lists_declare_their_output_schema() { + let tools = standard_tools(); + let declared: Vec<_> = tools.iter().filter(|t| t.output_schema.is_some()).map(|t| &*t.name).collect(); + assert_eq!(declared, ["iphone_list_elements"]); + let schema = tools.iter().find(|t| t.name == "iphone_list_elements").and_then(|t| t.output_schema.clone()); + assert_eq!(schema.unwrap()["required"], json!(["elements"])); +} + +#[test] +fn batch_steps_are_checked_before_anything_runs() { + let steps = batch_steps(&args(json!({"steps": [ + {"tool": "iphone_tap_element", "text": "One"}, + {"tool": "wait", "seconds": 0.5}, + {"tool": "iphone_tap", "x": 1, "y": 2}, + {"tool": "iphone_wait_for", "text": "完成", "timeout": 3} + ]}))) + .unwrap(); + assert_eq!(steps.len(), 4); + assert_eq!(steps[1], Step::Wait(std::time::Duration::from_millis(500))); + assert_eq!( + steps[3], + Step::Request { + tool: "iphone_wait_for".into(), + req: Request::WaitFor { text: "完成".into(), timeout_ms: 3000 } + } + ); + // 第 2 步参数错:一步都不执行,报出是第几步 + let e = + batch_steps(&args(json!({"steps": [{"tool": "iphone_tap", "x": 1, "y": 2}, {"tool": "iphone_tap", "x": 1}]}))) + .unwrap_err(); + assert!(e.contains("第 2 步"), "{e}"); + // 看界面的工具、未知工具、批量套批量都不行 + for bad in ["iphone_screenshot", "iphone_batch", "rm"] { + assert!(batch_steps(&args(json!({"steps": [{"tool": bad}]}))).is_err(), "{bad}"); + } + assert!(batch_steps(&args(json!({"steps": [{"tool": "wait", "seconds": 9}]}))).is_err()); + assert!(batch_steps(&args(json!({"steps": []}))).is_err()); + let many: Vec = (0..21).map(|_| json!({"tool": "wait", "seconds": 0})).collect(); + assert!(batch_steps(&args(json!({"steps": many}))).is_err()); +} + +#[test] +fn reuse_elements_only_affects_tap_element_steps() { + let steps = |reuse: bool| { + batch_steps(&args(json!({"reuse_elements": reuse, "steps": [ + {"tool": "iphone_tap_element", "text": "One"}, + {"tool": "iphone_tap", "x": 1, "y": 2} + ]}))) + .unwrap() + }; + assert_eq!( + steps(true)[0], + Step::Request { + tool: "iphone_tap_element".into(), + req: Request::TapElement { text: "One".into(), index: 0, max_age_ms: BATCH_REUSE_MS, scroll: None } + } + ); + assert!(matches!(&steps(false)[0], Step::Request { req: Request::TapElement { max_age_ms: 0, .. }, .. })); + assert_eq!(steps(true)[1], steps(false)[1]); +} + +#[test] +fn missed_tap_texts_are_recognised() { + // 旧版本守护进程:没有 outcome,只能认中文开头 + assert!(tap_missed("没找到包含 \"x\" 的元素,先用 iphone_list_elements 或截图看看屏幕", None)); + assert!(tap_missed("只匹配到 1 个:\nButton \"x\"", None)); + assert!(!tap_missed("已点击 Button \"x\"", None)); + assert!(tap_missed("被挡住:Button \"x\" 整个被「浮层」盖住,没有点", None)); + assert!(!tap_missed("已点击 Button \"x\";它的中心被「搜索」盖住,改点没被盖住的 (215,848)", None)); + // 新版本:看 outcome,与语言无关 + let missed = protocol::Outcome { tapped_nothing: true, ..Default::default() }; + assert!(tap_missed("Covered: Button \"x\" is completely covered", Some(missed))); + assert!(!tap_missed("Tapped Button \"Not found\"", Some(protocol::Outcome::default()))); +} + +#[test] +fn wait_for_timeout_is_bounded() { + assert_eq!( + to_request("iphone_wait_for", &args(json!({"text": "x"}))).unwrap(), + Request::WaitFor { text: "x".into(), timeout_ms: 5000 } + ); + assert!(to_request("iphone_wait_for", &args(json!({"text": "x", "timeout": 60}))).is_err()); +} + +#[test] +fn text_replacement_is_forwarded_only_when_requested() { + let changed = to_request("iphone_type_text", &args(json!({"text": "蓝牙", "replace": true}))).unwrap(); + assert_eq!(serde_json::to_value(changed).unwrap()["op"], "replace_text"); + let default = to_request("iphone_type_text", &args(json!({"text": "蓝牙"}))).unwrap(); + assert_eq!(serde_json::to_value(default).unwrap()["op"], "type_text"); +} + +#[test] +fn wait_for_accepts_disappeared_and_rejects_unknown_state() { + let req = to_request("iphone_wait_for", &args(json!({"text": "设置", "state": "disappeared"}))).unwrap(); + assert_eq!(serde_json::to_value(req).unwrap()["op"], "wait_for_disappearance"); + assert!(to_request("iphone_wait_for", &args(json!({"text": "设置", "state": "any"}))).is_err()); +} + +#[test] +fn element_limit_is_reported_in_structured_content() { + let reply: Response = serde_json::from_value(json!({ + "kind": "text", "text": "one element, 16 more", + "data": { + "type": "elements", + "elements": [{"type":"Button","label":"设置","x":16,"y":16,"width":44,"height":44}], + "matched_count": 17, "truncated": true + } + })) + .unwrap(); + let result = serde_json::to_value(to_result(reply)).unwrap(); + assert_eq!(result["structuredContent"]["elements"].as_array().unwrap().len(), 1); + assert_eq!(result["structuredContent"]["matched_count"], 17); + assert_eq!(result["structuredContent"]["truncated"], true); +} + +#[test] +fn wrong_typed_parameters_are_errors_not_defaults() { + let args = |v: Value| v.as_object().unwrap().clone(); + assert!(to_request("iphone_tap_element", &args(json!({"text": "设置", "index": -1}))).is_err()); + assert!(to_request("iphone_list_elements", &args(json!({"limit": 1.5}))).is_err()); + assert!(to_request("iphone_swipe", &args(json!({"from_x": 1, "from_y": 2, "to_x": "x", "to_y": 4}))).is_err()); + // 写成字符串的数字照收(toolkit 的 pydantic 也收) + assert_eq!( + to_request("iphone_tap_element", &args(json!({"text": "设置", "index": "2"}))).unwrap(), + Request::TapElement { text: "设置".into(), index: 2, max_age_ms: 0, scroll: None } + ); + assert_eq!( + to_request("iphone_list_elements", &args(json!({"limit": null}))).unwrap(), + Request::ListElements { filter: String::new(), limit: 150, max_age_ms: 0, keep_locked: false } + ); +} + +#[test] +fn screenshot_region_needs_all_four() { + assert_eq!(to_request("iphone_screenshot", &Map::new()).unwrap(), Request::Screenshot { region: None }); + assert_eq!( + to_request("iphone_screenshot", &args(json!({"x": 0, "y": 55, "width": 430, "height": 40}))).unwrap(), + Request::Screenshot { region: Some((0.0, 55.0, 430.0, 40.0)) } + ); + assert_eq!( + to_request("iphone_screenshot", &args(json!({"x": 10, "y": 10}))).unwrap_err(), + "放大区域要同时给出 x、y、width、height" + ); +} + +/// 回归用例 #17:预期内的错误要作为工具错误、带可读文字返回 +#[test] +fn errors_become_tool_errors_with_text() { + let r = to_result(Response::error("button 只能是 home / volume_up / volume_down / lock")); + assert_eq!(r.is_error, Some(true)); + assert!(matches!(&r.content[0], ContentBlock::Text(t) if t.text.contains("button 只能是"))); + let img = to_result(Response::Image { jpeg_base64: "AAAA".into(), caption: "430x932 点".into() }); + assert_eq!(img.content.len(), 2); + assert!(to_request("iphone_nope", &Map::new()).is_err()); +} diff --git a/docs/tools.md b/docs/tools.md index ebd9629..56a64f4 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1,6 +1,6 @@ # MCP tools -The MCP server (`iphone-control mcp`) exposes 18 tools (24 with the [developer tools](#developer-tools-opt-in)). The tool descriptions the agent sees, and every result text, are in Simplified Chinese by default, or in English with `IPHONE_CONTROL_LANG=en` (see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration)); this page is the English reference. The definitions live in [`crates/ictl-mcp/src/lib.rs`](../crates/ictl-mcp/src/lib.rs). +The MCP server (`iphone-control mcp`) exposes 18 tools (24 with the [developer tools](#developer-tools-opt-in)). The tool descriptions the agent sees, and every result text, are in Simplified Chinese by default, or in English with `IPHONE_CONTROL_LANG=en` (see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration)); this page is the English reference. The definitions live in [`crates/ictl-mcp/src/schema.rs`](../crates/ictl-mcp/src/schema.rs). Coordinates are in **points**, the same unit as the pixels of a full-screen `iphone_screenshot` (for example 430×932 on an iPhone 15 Pro Max), so an agent can read a position off a screenshot and tap it directly. Coordinates follow the current screen orientation: after a rotation the same spot has different coordinates, so take a new screenshot. Screen sizes differ per device (an iPad mini 5 is 768×1024 in portrait); don't assume 430×932. From 7a8cd47ccae5111edad23ae915b6846603d6c3b9 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:34:12 +0800 Subject: [PATCH 2/5] refactor(wda): split WdaClient's methods into submodules client.rs was 2,100 lines, most of it one 900-line impl block and its tests. The methods now sit in client/ by what they do: session.rs (the transport, the XCTest session, stall detection, idle-wait settings), screen.rs (size, rotation, lock state, the element tree, screenshots, alerts, the keyboard, the passcode field), actions.rs (gestures, buttons, IOHID events, apps, links) and typing.rs (the focused field). The free functions and types stay in client.rs; the tests move to client/tests.rs. A pure move: each of the 68 methods is the same as before with whitespace ignored; methods that were private are `pub(super)` so the sibling modules can call them, and the tests' fixture paths gained a `../` for the deeper directory. Co-authored-by: Claude Opus 5.5 --- crates/ictl-wda/src/client.rs | 1795 +------------------------ crates/ictl-wda/src/client/actions.rs | 277 ++++ crates/ictl-wda/src/client/screen.rs | 340 +++++ crates/ictl-wda/src/client/session.rs | 248 ++++ crates/ictl-wda/src/client/tests.rs | 879 ++++++++++++ crates/ictl-wda/src/client/typing.rs | 54 + 6 files changed, 1805 insertions(+), 1788 deletions(-) create mode 100644 crates/ictl-wda/src/client/actions.rs create mode 100644 crates/ictl-wda/src/client/screen.rs create mode 100644 crates/ictl-wda/src/client/session.rs create mode 100644 crates/ictl-wda/src/client/tests.rs create mode 100644 crates/ictl-wda/src/client/typing.rs diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rs index 7aefa9f..66571c6 100644 --- a/crates/ictl-wda/src/client.rs +++ b/crates/ictl-wda/src/client.rs @@ -332,1793 +332,12 @@ pub struct WdaClient { detection_point_set: bool, } -impl WdaClient { - pub fn new(transport: T) -> Self { - Self { - transport, - session: None, - screen: None, - screen_at: None, - rotation_unsupported: false, - lock_state_trusted: false, - idle_baseline: None, - idle_current: None, - fast_stream: false, - unanswered: AtomicU32::new(0), - snapshot_level: 0, - snapshot_applied: None, - snapshot_read: 0, - detection_point_set: false, - } - } - - async fn call(&self, method: &str, path: &str, body: Option, timeout: Duration) -> Result { - self.call_or_abandon(method, path, body, timeout, None).await - } - - /// [`Self::call`];`abandon` 是会话号时,请求没有应答就先结束这个会话,再判断 WDA 是不是卡死了(见 [`Self::in_session`]) - async fn call_or_abandon( - &self, - method: &str, - path: &str, - body: Option, - timeout: Duration, - abandon: Option<&str>, - ) -> Result { - // `/status` 不经 XCTest:WDA 半死时它照样应答,不能拿它算 WDA 还活着 - if path == "/status" { - return self.send(method, path, body, timeout).await; - } - // 已判定卡死:不再发、不再一次次等超时(一个工具调用里接连几个请求,每个都等满时限的话, - // 设备会被占好几分钟,守护进程没机会重启 WDA) - if let Some(reason) = self.stall_reason() { - let why = reason.describe(); - return Err(WdaError::Unavailable(ictl_l10n::trf!( - "WDA 卡死判定:{why},等守护进程重启它", - "WDA is considered stuck: {why}; waiting for the daemon to restart it" - ))); - } - let r = self.send(method, path, body, timeout).await; - match &r { - Err(e) if e.no_answer() => { - if let Some(sid) = abandon { - self.delete_session(sid).await; - } - let n = self.unanswered.fetch_add(1, Ordering::Relaxed) + 1; - // 长请求未应答,补一次短探测;保留实际计数,不把两个请求写成三次无应答。 - if n < STALL_LIMIT && timeout > XCTEST_PROBE_TIMEOUT { - match self.send("GET", "/wda/activeAppInfo", None, XCTEST_PROBE_TIMEOUT).await { - Err(p) if p.no_answer() => { - self.unanswered.store((n + 1) | UNANSWERED_PROBE, Ordering::Relaxed); - } - reply if answered(&reply) => self.unanswered.store(0, Ordering::Relaxed), - _ => {} - } - } - } - _ if answered(&r) => self.unanswered.store(0, Ordering::Relaxed), - _ => {} - } - r - } - - /// 连续三次无应答,或长请求和其短探测均无应答时,后续请求不再发送,等待守护进程恢复。 - pub fn stalled(&self) -> bool { - self.stall_reason().is_some() - } - - /// 读取一致的计数与判定原因;`/status` 的响应不参与此状态。 - pub fn stall_reason(&self) -> Option { - let state = self.unanswered.load(Ordering::Relaxed); - if state & UNANSWERED_PROBE != 0 { - Some(StallReason::LongRequestAndProbe) - } else if state >= STALL_LIMIT { - Some(StallReason::ConsecutiveRequests(state)) - } else { - None - } - } - - /// 实际连续无应答次数,不含判定标记。 - pub fn unanswered(&self) -> u32 { - self.unanswered.load(Ordering::Relaxed) & !UNANSWERED_PROBE - } - - async fn send(&self, method: &str, path: &str, body: Option, timeout: Duration) -> Result { - let body = body.map(|b| b.to_string().into_bytes()); - let (status, raw) = self.transport.send(method, path, body, timeout).await.map_err(|e| match e.kind() { - std::io::ErrorKind::TimedOut => WdaError::Timeout(e.to_string()), - crate::http::WRITE_FAILED if acts(method, path) => WdaError::Write(e.to_string()), - crate::http::AFTER_SENT => WdaError::Interrupted(e.to_string()), - _ => WdaError::Unavailable(e.to_string()), - })?; - let v: Value = match serde_json::from_slice(&raw) { - Ok(v) => v, - Err(_) if status >= 400 => { - return Err(WdaError::Remote { kind: "http".into(), message: status.to_string() }); - } - Err(e) => { - return Err(WdaError::Interrupted(ictl_l10n::trf!("响应不是 JSON:{e}", "response is not JSON: {e}"))); - } - }; - if let Some(err) = v.get("value").and_then(|x| x.get("error")).and_then(|e| e.as_str()) { - let msg = v["value"].get("message").and_then(|m| m.as_str()).unwrap_or_default(); - return Err(WdaError::Remote { - kind: err.to_owned(), - message: msg.lines().next().unwrap_or_default().to_owned(), - }); - } - // Older runners may return a JSON 404 without a W3C value.error. - if status >= 400 { - return Err(WdaError::Remote { kind: "http".into(), message: status.to_string() }); - } - Ok(v) - } - - async fn get(&self, path: &str) -> Result { - Ok(self.call("GET", path, None, DEFAULT_TIMEOUT).await?["value"].take()) - } - - async fn session_id(&mut self) -> Result { - if let Some(s) = &self.session { - return Ok(s.clone()); - } - let r = - self.call("POST", "/session", Some(json!({"capabilities": {"alwaysMatch": {}}})), DEFAULT_TIMEOUT).await?; - let id = r - .get("sessionId") - .and_then(|s| s.as_str()) - .or_else(|| r["value"].get("sessionId").and_then(|s| s.as_str())) - .ok_or_else(|| { - WdaError::Unavailable( - ictl_l10n::tr!("创建会话没有返回 sessionId", "creating a session returned no sessionId").into(), - ) - })? - .to_owned(); - self.session = Some(id.clone()); - self.idle_current = None; - self.snapshot_applied = Some(0); - if self.fast_stream { - // fixOrientation explicitly off: a WDA left running in the background keeps what an - // older version set - let settings = json!({ - "mjpegServerFramerate": MJPEG_FPS, - "mjpegScalingFactor": MJPEG_SCALE, - "mjpegFixOrientation": false, - }); - let path = format!("/session/{id}/appium/settings"); - if let Err(e) = self.call("POST", &path, Some(json!({"settings": settings})), DEFAULT_TIMEOUT).await { - tracing::debug!("MJPEG settings: {e}"); - } - } - Ok(id) - } - - /// 带会话的请求;会话失效时重建一次再试。 - /// - /// 改变手机状态的请求([`acts`])没有应答时,马上结束这个会话(`DELETE /session/:id`,WDA 16.15.3 不排队处理它): - /// WDA 在主线程上一个一个处理请求,我们不等了它还会接着做。排在慢请求后面的点击、滑动会在报了失败之后很久才落到屏幕上 - /// (Poki 在真机上见过)。结束会话后,这个会话里还在排队的请求 WDA 直接回「会话不存在」,不再执行;正在执行的那个照样做完。 - /// 下一个请求开新会话 - pub async fn in_session( - &mut self, - method: &str, - path: &str, - body: Option, - timeout: Duration, - ) -> Result { - for attempt in 0..2 { - let input = acts(method, path); - let sid = self.session_id().await.map_err(|e| if input { e.before_input() } else { e })?; - let abandon = input.then_some(sid.as_str()); - let r = - self.call_or_abandon(method, &format!("/session/{sid}{path}"), body.clone(), timeout, abandon).await; - match r { - Err(WdaError::Remote { kind, .. }) if attempt == 0 && kind == "invalid session id" => { - self.session = None - } - Err(e) if abandon.is_some() && e.no_answer() => { - self.forget_session(); - return Err(e); - } - other => return other.map(|mut v| v["value"].take()), - } - } - unreachable!() - } - - /// 结束会话,不管结果:结束不了的会话 WDA 下次开会话时也会结束它 - async fn delete_session(&self, sid: &str) { - // send 而不是 call:WDA 卡死时也要发,也不算进卡死计数 - if let Err(e) = self.send("DELETE", &format!("/session/{sid}"), None, SESSION_DELETE_TIMEOUT).await { - tracing::debug!("DELETE /session/{sid}: {e}"); - } - } - - /// 会话已经结束(或要当作结束):下一个请求开新会话,WDA 那时把设置重置成默认 - fn forget_session(&mut self) { - self.session = None; - self.idle_current = None; - } - - async fn post(&mut self, path: &str, body: Value) -> Result { - self.in_session("POST", path, Some(body), DEFAULT_TIMEOUT).await - } - - pub async fn ready(&self) -> Result { - Ok(self.call("GET", "/status", None, Duration::from_secs(5)).await?["value"]["ready"] == true) - } - - /// WDA 还能不能经 XCTest 办事:问一次前台 App,限时 [`XCTEST_PROBE_TIMEOUT`]。 - /// `/status` 不经 XCTest,WDA 半死(iPad 真机:`/status` 照常 200,前台 App、截图、读元素、`/wda/locked` 全部超时)时 - /// 它照样报 ready;这一问才看得出来 - pub async fn xctest_responsive(&self) -> Result<()> { - self.call("GET", "/wda/activeAppInfo", None, XCTEST_PROBE_TIMEOUT).await.map(drop) - } - - /// Read the WDA screen size again, including changes to Display Zoom. - pub async fn measure_screen(&mut self) -> Result { - let v = self.get("/wda/screen").await?; - let s = &v["screenSize"]; - let positive = |key: &str| s[key].as_f64().filter(|n| n.is_finite() && *n > 0.0); - let size = positive("width") - .zip(positive("height")) - .map(|(width, height)| ScreenSize { width, height }) - .ok_or_else(|| { - WdaError::Unavailable(ictl_l10n::tr!("/wda/screen 尺寸无效", "Invalid /wda/screen dimensions").into()) - })?; - self.screen = Some(size); - self.screen_at = Some(Instant::now()); - Ok(size) - } - - pub async fn base_screen_size(&mut self) -> Result { - match self.screen { - Some(s) => Ok(s), - None => self.measure_screen().await, - } - } - - /// 当前方向下的屏幕点尺寸(转屏后宽高跟着变) - pub async fn screen_size(&mut self) -> Result { - Ok(self.view().await?.screen) - } - - /// 当前方向下的屏幕尺寸和方向。尺寸只问一次 `/wda/screen`(约 0.3 秒),方向每次问(约 20 毫秒): - /// 尺寸缓存的是问的那一刻的方向,转屏后不换算的话截图会被压扁、屏幕下半截的元素被当成屏幕外。 - /// 问不到方向(旧版 WDA 等)就按缓存的尺寸、方向未知(不换算元素坐标) - pub async fn view(&mut self) -> Result { - let base = self.base_screen_size().await?; - Ok(match self.orientation().await { - Ok(o) => elements::View { screen: o.orient(base), orientation: Some(o) }, - Err(e) => { - tracing::debug!( - "{}", - ictl_l10n::log_trf!( - "读屏幕方向失败,按缓存的屏幕尺寸算:{e}", - "Reading the screen orientation failed, using the cached screen size: {e}" - ) - ); - elements::View { screen: base, orientation: None } - } - }) - } - - /// 界面相对设备竖放转了多少(`GET /rotation` 的 z)。能分出两个横屏方向,`/orientation` 分不出 - pub async fn rotation(&mut self) -> Result { - let v = self.in_session("GET", "/rotation", None, Duration::from_secs(10)).await?; - v["z"].as_f64().and_then(ictl_device::Rotation::from_degrees).ok_or_else(|| { - WdaError::Unavailable(ictl_l10n::trf!( - "看不懂 WDA 给的旋转角:{v}", - "Can't make sense of the rotation WDA reported: {v}" - )) - }) - } - - /// Older WDA versions lack /rotation. Remember an unsupported route for this runner; - /// the regular /orientation endpoint folds opposite directions into the same string. - async fn interface_rotation(&mut self, fallback: impl Future>) -> Option { - if !self.rotation_unsupported { - match self.rotation().await { - Ok(r) => return Some(r), - Err(WdaError::Remote { kind, message }) - if matches!(kind.as_str(), "unknown command" | "unknown method" | "unsupported operation") - || (kind == "http" && matches!(message.as_str(), "404" | "405")) => - { - self.rotation_unsupported = true; - } - Err(_) => return None, - } - } - fallback.await - } - - /// Poll rotation to detect a changed view. The screen size (a slower request) is measured on acquisition and on - /// rotation, and again once the last measurement is older than [`SCREEN_RECHECK`] (Display Zoom) when - /// `refresh_stale`: a poll while nobody acts, never a gesture's start, which costs only the rotation request. - pub async fn display_sample( - &mut self, - previous: Option, - refresh_stale: bool, - fallback: impl Future>, - ) -> (Option, Option) { - let rotation = self.interface_rotation(fallback).await; - let stale = self.screen_at.is_none_or(|t| t.elapsed() >= SCREEN_RECHECK); - let rotated = rotation.is_some_and(|r| Some(r.degrees()) != previous); - let size = if rotated || (refresh_stale && stale) { - self.measure_screen().await - } else { - self.base_screen_size().await - }; - (size.ok().map(ScreenSize::portrait), rotation) - } - - /// 前台界面的方向 - pub async fn orientation(&mut self) -> Result { - let v = self.in_session("GET", "/orientation", None, Duration::from_secs(10)).await?; - v.as_str().and_then(elements::Orientation::from_wda).ok_or_else(|| { - WdaError::Unavailable(ictl_l10n::trf!( - "看不懂 WDA 给的方向:{v}", - "Can't make sense of the orientation WDA reported: {v}" - )) - }) - } - - /// 是否锁屏。WDA 的 `/wda/locked` 只靠 `com.apple.springboard.lockstate` 的变化通知维护 - /// (WebDriverAgent `XCUIDevice+FBHelpers.m`),有两处误报,用元素树纠正([`elements::cover_sheet`]): - /// - 初值为 false:WDA 在手机锁着时启动就一直报未锁屏,直到下一次锁屏/解锁。确认过一次「确实没锁屏」之后 - /// WDA 就跟上了,此后它说没锁就直接信,不多发请求 - /// - 下拉通知中心时报 true(和锁屏同一个界面):WDA 说锁了时核对一次,是通知中心就算没锁 - /// - /// 核对失败时按 WDA 的结果;需要「拿不准就算锁着」时用 [`Self::check_lock`] 的 strict 模式 - pub async fn locked(&mut self) -> Result { - Ok(self.check_lock(None, false).await?.locked) - } - - /// 锁屏判断,并带回核对时取到的元素树(解锁流程接着用,省一次 `/source`)。 - /// - `reported`:调用方刚问过的 `/wda/locked`,省一次请求 - /// - `strict`:拿不准就算锁着。确认整串密码是否解开时用:把仍锁着误判成已解锁,下一次会把同一个错误密码再输一遍 - pub async fn check_lock(&mut self, reported: Option, strict: bool) -> Result { - let wda_locked = match reported { - Some(v) => v, - None => self.wda_reports_locked().await?, - }; - if self.lock_state_trusted && (!wda_locked || strict) { - // 已同步过:WDA 说没锁就是没锁;strict 场景在密码键盘上,WDA 说锁了也不会是通知中心 - return Ok(LockCheck { locked: wda_locked, uncertain: false, tree: None }); - } - let (sheet, tree) = match self.cover_tree().await { - Ok(x) => x, - Err(e) => { - tracing::debug!( - "{}", - ictl_l10n::log_trf!( - "核对锁屏界面失败,按{}处理:{e}", - "Checking the lock screen failed, going by {}: {e}", - if strict { - ictl_l10n::tr!("锁着", "locked") - } else { - ictl_l10n::tr!(" WDA 的结果", "what WDA reported") - } - ) - ); - return Ok(LockCheck { locked: strict || wda_locked, uncertain: false, tree: None }); - } - }; - let (locked, uncertain) = match (wda_locked, sheet) { - (true, elements::CoverSheet::NotificationCenter) => (false, false), - (true, _) => (true, false), - (false, elements::CoverSheet::Locked) => { - tracing::info!( - "{}", - ictl_l10n::log_tr!( - "WDA 报未锁屏,但屏幕上是锁屏界面(WDA 在锁屏时启动,状态未同步)", - "WDA says unlocked, but the screen shows the lock screen (WDA started while locked and its state is stale)" - ) - ); - (true, false) - } - // 锁屏样式、却没有锁的标记:可能是通知中心,也可能是 Touch ID 机型熄屏、有通知时的锁屏 - // (iPad mini 5 / iPadOS 26.6.1 真机:没有「按下主屏幕按钮以解锁」那行)。WDA 在锁屏时启动的话一直报 false, - // 不能在这里认定它可信,否则之后再也不核对、永远不会自动解锁 - // 严格核对时拿不准就算锁着(同 `strict` 的说明) - (false, elements::CoverSheet::NotificationCenter) => (strict, !strict), - // 普通界面上确认过一次:WDA 的状态是同步的 - (false, elements::CoverSheet::None) => { - self.lock_state_trusted = true; - (false, false) - } - }; - Ok(LockCheck { locked, uncertain, tree }) - } - - /// WDA 自己报的锁屏状态,不核对。可能误报,见 [`Self::locked`];配合 [`Self::lock_state_trusted`] 做快速判断 - pub async fn wda_reports_locked(&self) -> Result { - Ok(self.call("GET", "/wda/locked", None, Duration::from_secs(10)).await?["value"] == true) - } - - /// 本次 WDA 启动后是否确认过一次没锁屏。确认过且 WDA 说没锁,就确定没锁 - pub fn lock_state_trusted(&self) -> bool { - self.lock_state_trusted - } - - /// 前台是 SpringBoard 时看元素树是锁屏、通知中心还是普通界面,并带回元素树;前台是别的 App 就是普通界面 - async fn cover_tree(&mut self) -> Result<(elements::CoverSheet, Option)> { - if self.active_app().await? != SPRINGBOARD { - return Ok((elements::CoverSheet::None, None)); - } - let xml = self.source_xml().await?; - Ok((elements::cover_sheet(&xml), Some(xml))) - } - - pub async fn active_app(&self) -> Result { - Ok(self.get("/wda/activeAppInfo").await?["bundleId"].as_str().unwrap_or_default().to_owned()) - } - - pub async fn screenshot_png(&self) -> Result> { - // base64 约 11MB:从 JSON 里直接拿走字符串,原地去掉换行,不再另外复制 - let Value::String(mut b64) = self.get("/screenshot").await? else { - return Err(WdaError::Unavailable( - ictl_l10n::tr!("截图响应不是字符串", "screenshot response is not a string").into(), - )); - }; - b64.retain(|c| !c.is_whitespace()); - base64::engine::general_purpose::STANDARD.decode(b64).map_err(|e| { - WdaError::Unavailable(ictl_l10n::trf!("截图不是有效的 base64:{e}", "screenshot is not valid base64: {e}")) - }) - } - - /// 元素树 XML,排除可见性等慢属性(完整树 7~8 秒,排除后约 0.3 秒)。读得慢就收紧快照上限([`SnapshotLimits`]) - pub async fn source_xml(&mut self) -> Result { - let level = self.snapshot_level; - if self.snapshot_applied.unwrap_or(0) != level { - let l = SNAPSHOT_LEVELS[level]; - let body = json!({"settings": { - "snapshotMaxDepth": l.depth, - "snapshotMaxChildren": l.children.unwrap_or(i32::MAX as u32), - }}); - // 设不上照样读,下次再设 - match self.post("/appium/settings", body).await { - Ok(_) => self.snapshot_applied = Some(level), - Err(e) => tracing::debug!("snapshot limits: {e}"), - } - } - let applied = self.snapshot_applied.unwrap_or(0); - let path = format!("/source?format=xml&excluded_attributes={}", elements::SOURCE_EXCLUDED); - let t0 = Instant::now(); - let r = self.call("GET", &path, None, SOURCE_TIMEOUT).await; - let took = match r { - Ok(_) => Some(t0.elapsed()), - Err(WdaError::Timeout(_)) => None, - Err(e) => return Err(e), - }; - let next = next_snapshot_level(applied, took); - if next != applied { - tracing::info!( - "{}", - ictl_l10n::log_trf!( - "读元素树{},快照上限改为 {:?}", - "Reading the element tree {}; snapshot limits now {:?}", - took.map_or_else( - || ictl_l10n::log_tr!("超时", "timed out").to_owned(), - |t| ictl_l10n::log_trf!("用了 {:.1} 秒", "took {:.1} s", t.as_secs_f64()) - ), - SNAPSHOT_LEVELS[next] - ) - ); - } - self.snapshot_level = next; - let v = r?; - self.snapshot_read = applied; - Ok(v["value"].as_str().unwrap_or_default().to_owned()) - } - - /// 上一次读到的元素树受了快照上限([`SnapshotLimits`])的限制时,给人和 agent 看的说明 - pub fn snapshot_note(&self) -> Option { - let l = SNAPSHOT_LEVELS[self.snapshot_read]; - let children = l.children?; - Some(ictl_l10n::trf!( - "(界面元素太多、读得慢,这次只读了 {} 层、每个元素最多 {children} 个子元素:长列表靠后的行、很深的元素可能没列出;读得快了会自动放宽)", - "(This screen has so many elements that reading them was slow, so this read went {} levels deep with at most {children} children per element: rows far down a long list or deeply nested elements may be missing; the limits loosen again once reads are fast)", - l.depth - )) - } - - pub async fn elements(&mut self) -> Result> { - Ok(self.tree().await?.elements) - } - - /// 元素树,带上「谁盖住谁」「有没有加载圈」等信息 - pub async fn tree(&mut self) -> Result { - let view = self.view().await?; - self.move_detection_point(view.screen).await; - let mut tree = elements::parse_tree(&self.source_xml().await?, view); - tree.incomplete |= SNAPSHOT_LEVELS[self.snapshot_read].children.is_some(); - Ok(tree) - } - - /// 把 WDA 判断前台 App 的点(appium setting `activeAppDetectionPoint`)挪到 [`detection_point`],每个客户端做一次。 - /// - /// WDA 读元素树、问前台 App 时,看屏幕上这个点下面的元素属于哪个进程。默认点在离左上角短边 20% 的地方 - /// (WDA 16.15.3 `FBActiveAppDetectionPoint`,430 点宽的 iPhone 上是 (86, 86)),正好在通知横幅底下:横幅弹着时 - /// 读到的是 SpringBoard 的树,按名字点 App 里的按钮就找不到(iPhone16,2 / iOS 27.2.1 的备忘录,「Device Hub」横幅)。 - /// 设不上不影响读树,只是还用默认的点;连不上 WDA 时下次再试 - async fn move_detection_point(&mut self, screen: ScreenSize) { - if self.detection_point_set { - return; - } - let (x, y) = detection_point(screen); - let body = json!({"settings": {"activeAppDetectionPoint": format!("{x},{y}")}}); - match self.post("/appium/settings", body).await { - Ok(_) => self.detection_point_set = true, - Err(e) => { - tracing::debug!("activeAppDetectionPoint: {e}"); - self.detection_point_set = !matches!(e, WdaError::Unavailable(_)); - } - } - } - - /// 点击:一个 W3C actions 单指手势(按下 50ms),期间把等待设置临时调小。真机计时(iOS 27): - /// - `/wda/tap` 先等界面空闲:主屏点图标约 1.7 秒(调小等待也没用),App 里约 0.6 秒,锁屏上约 2.9 秒 - /// - actions 手势做完要等动画冷却(`animationCoolOffTimeout`,默认 2 秒):App 里切标签约 1.9 秒 - /// - actions + 临时调小等待:App 里约 0.7 秒,主屏点图标约 0.9 秒 - /// - 冷却不能是 0.2 秒([`IdleSettings::QUICK`]):界面上一直有动画时(键盘弹着、光标在闪)要等约 26 秒才返回, - /// iPhone 18 Pro Max(iOS 27.2.1)在设置里点搜索结果每次都这样;冷却 0 约 0.4 秒。和滑动一样用 - /// [`IdleSettings::NO_COOL_OFF`] - /// - /// 和 `/wda/tap` 一样不等点击引起的动画结束,调用方要看结果就再截图 - pub async fn tap(&mut self, x: f64, y: f64) -> Result<()> { - self.quick_gesture(&tap_steps(x, y, TAP_PRESS_MS), IdleSettings::NO_COOL_OFF).await - } - - /// 依次点几个点,一个手势([`tap_sequence_body`]):同一个键盘、键盘上连按时用。分开点每下都要等界面空闲, - /// 数字键盘上点 7 个键约 3.6 秒,一个手势约 1.9 秒。点的过程中界面变了(跳了页面)后面的点也照样点下去, - /// 所以只给点的时候布局不变的一串点用 - pub async fn tap_sequence(&mut self, points: &[(f64, f64)]) -> Result<()> { - let body = tap_sequence_body(points, TAP_PRESS_MS, SEQUENCE_GAP_MS); - self.quick_actions(body, IdleSettings::NO_COOL_OFF).await - } - - /// 同一点连点 `count` 下(双击、「短时间内连点 N 下」的隐藏入口),一个 actions 手势,每下之间停 - /// [`MULTI_TAP_GAP_MS`]。分开点每下都要等界面空闲(约 0.6 秒),`iphone_batch` 连点 5 下约 2.9 秒,赶不上这类入口的时间窗 - pub async fn multi_tap(&mut self, x: f64, y: f64, count: u32) -> Result<()> { - let steps = multi_tap_steps(x, y, count, TAP_PRESS_MS, MULTI_TAP_GAP_MS); - self.quick_gesture(&steps, IdleSettings::NO_COOL_OFF).await - } - - /// 长按:按下、停 `seconds` 秒、抬起,一个 actions 手势。`/wda/touchAndHold` 前后都等界面空闲, - /// 真机上主屏长按图标 1.2 秒要约 12 秒才返回。等待设置同 [`Self::tap`] - pub async fn touch_and_hold(&mut self, x: f64, y: f64, seconds: f64) -> Result<()> { - self.quick_gesture(&tap_steps(x, y, (seconds * 1000.0) as u64), IdleSettings::NO_COOL_OFF).await - } - - /// 滑动:一个 actions 手势,期间用 [`IdleSettings::NO_COOL_OFF`]。做完时列表可能还在惯性滚动, - /// 要看结果的调用方自己等界面稳定 - pub async fn swipe(&mut self, from: (f64, f64), to: (f64, f64), ms: u64) -> Result<()> { - self.quick_gesture(&swipe_steps(from, to, ms), IdleSettings::NO_COOL_OFF).await - } - - /// The MJPEG stream (the live viewer) at up to [`MJPEG_FPS`] frames a second instead of WDA's 10, at full size - /// ([`MJPEG_SCALE`], why not smaller) and never turned upright, set with each new session: the picture follows a - /// drag closely. In landscape the frames stay portrait with the content sideways (on an iPhone; an iPad's are - /// already landscape) and the viewer page turns them by the interface rotation, as it does the phone's own video: - /// `mjpegFixOrientation` makes WDA decode, rotate and re-encode every frame, 92 % of a core on an iPhone 15 Pro Max - /// in landscape, and iOS killed it within two minutes. WDA only captures while a client is connected - pub fn fast_stream(&mut self) { - self.fast_stream = true; - } - - /// Swipes and stays in polling mode for the caller, who ends it with [`Self::end_polling`]: restoring the settings - /// only to change them again right after would cost two round trips - /// `hold_ms` > 0 holds the finger still at `from` first ([`drag_steps`]) - pub async fn swipe_into_polling(&mut self, from: (f64, f64), to: (f64, f64), hold_ms: u64, ms: u64) -> Result<()> { - self.baseline().await.map_err(WdaError::before_input)?; - self.set_idle_settings(IdleSettings::NO_COOL_OFF).await.map_err(WdaError::before_input)?; - let r = self.actions(&drag_steps(from, to, hold_ms, ms)).await; - if r.is_err() { - self.end_polling().await; - } - r - } - - /// 开始轮询界面:读元素树时不等界面空闲、动画冷却(约 0.2 秒一次),由调用方比较前后两次判断稳定。 - /// 用完调 [`Self::end_polling`] 恢复 - pub async fn begin_polling(&mut self) -> Result<()> { - self.baseline().await?; - self.set_idle_settings(IdleSettings::NO_COOL_OFF).await - } - - pub async fn end_polling(&mut self) { - let b = self.idle_baseline.unwrap_or(IdleSettings::DEFAULT); - if let Err(e) = self.set_idle_settings(b).await { - tracing::warn!( - "{}", - ictl_l10n::log_trf!( - "轮询后恢复 WDA 等待设置失败:{e}", - "Restoring the WDA wait settings after polling failed: {e}" - ) - ); - } - } - - /// 平时的等待设置(第一次用时读一次)。临时调小、改回之前都按它恢复 - pub async fn baseline(&mut self) -> Result { - if let Some(b) = self.idle_baseline { - return Ok(b); - } - // 上次没恢复成功的话读到的就是调小的值:按 WDA 默认值算 - let b = match self.idle_settings().await? { - s if s == IdleSettings::QUICK || s == IdleSettings::NO_COOL_OFF => IdleSettings::DEFAULT, - s => s, - }; - self.idle_baseline = Some(b); - Ok(b) - } - - /// 发一个手势,期间把等待设置临时换成 `during`(见 [`Self::tap`]),做完恢复 - async fn quick_gesture(&mut self, steps: &[PointerStep], during: IdleSettings) -> Result<()> { - self.quick_actions(actions_body(steps), during).await - } - - async fn quick_actions(&mut self, body: Value, during: IdleSettings) -> Result<()> { - let baseline = self.baseline().await.map_err(WdaError::before_input)?; - self.set_idle_settings(during).await.map_err(WdaError::before_input)?; - let r = self.post("/actions", body).await.map(drop); - if let Err(e) = self.set_idle_settings(baseline).await { - tracing::warn!( - "{}", - ictl_l10n::log_trf!( - "手势后恢复 WDA 等待设置失败:{e}", - "Restoring the WDA wait settings after the gesture failed: {e}" - ) - ); - } - r - } - - /// 一次 W3C actions 请求。注意:多次点击合并成一个请求会漏键,解锁时每位单独发 - pub async fn actions(&mut self, steps: &[PointerStep]) -> Result<()> { - self.post("/actions", actions_body(steps)).await.map(drop) - } - - /// 屏幕上的系统弹窗(定位权限、通知权限等)的文字;没有弹窗返回 None。 - /// 弹窗挡着时 Home 不生效、App 也到不了前台,WDA 却照样报成功 - pub async fn alert_text(&mut self) -> Result> { - match self.in_session("GET", "/alert/text", None, DEFAULT_TIMEOUT).await { - Ok(v) => Ok(v.as_str().map(str::to_owned).filter(|t| !t.is_empty())), - Err(WdaError::Remote { kind, .. }) if kind.contains("alert") => Ok(None), - Err(e) => Err(e), - } - } - - /// 屏幕上有没有软键盘(有输入框获得了焦点)。`/wda/keys` 在没有焦点时也返回成功,什么都没输进去 - pub async fn keyboard_shown(&mut self) -> Result { - let v = self.post("/elements", json!({"using": "class name", "value": "XCUIElementTypeKeyboard"})).await?; - Ok(v.as_array().is_some_and(|a| !a.is_empty())) - } - - /// The element with keyboard focus (`GET /element/active`); None when no element has it - pub async fn focused_field(&mut self) -> Result> { - let Some(id) = self.active_element().await? else { return Ok(None) }; - let kind = self.attribute(&id, "type").await?; - let kind = kind.strip_prefix("XCUIElementType").unwrap_or(&kind).to_owned(); - let placeholder = self.attribute(&id, "placeholderValue").await?; - Ok(Some(FocusedField { id, kind, placeholder })) - } - - /// The id of the element with keyboard focus (`GET /element/active`), one request; nothing has focus: `None`. - /// Rereading a field already known ([`Self::focused_field`] takes three) only needs this and its value - pub async fn active_element(&mut self) -> Result> { - match self.in_session("GET", "/element/active", None, DEFAULT_TIMEOUT).await { - Ok(v) => Ok(element_id(&v)), - Err(WdaError::Remote { kind, .. }) if kind.contains("no such element") => Ok(None), - Err(e) => Err(e), - } - } - - /// An attribute of an element as text; a missing one (`null`) reads as empty - pub async fn attribute(&mut self, id: &str, name: &str) -> Result { - let v = self.in_session("GET", &format!("/element/{id}/attribute/{name}"), None, DEFAULT_TIMEOUT).await?; - Ok(match v { - Value::String(s) => s, - Value::Null => String::new(), - other => other.to_string(), - }) - } - - /// What the field holds: an empty field reads its placeholder as its value (Spotlight's reads «搜索»), so that - /// counts as empty, as with native control - pub async fn field_text(&mut self, f: &FocusedField) -> Result { - let v = self.attribute(&f.id, "value").await?; - Ok(if !f.placeholder.is_empty() && v == f.placeholder { String::new() } else { v }) - } - - /// Empties a field (`POST /element/:id/clear`): WDA deletes the text with the keyboard until the field reads - /// empty, and answers an error when it doesn't (some custom fields) - pub async fn clear(&mut self, id: &str) -> Result<()> { - self.in_session("POST", &format!("/element/{id}/clear"), Some(json!({})), Duration::from_secs(60)) - .await - .map(drop) - } - - pub async fn keys(&mut self, text: &str) -> Result<()> { - let chars: Vec = text.chars().map(String::from).collect(); - self.in_session("POST", "/wda/keys", Some(json!({"value": chars})), Duration::from_secs(120)).await.map(drop) - } - - /// home / volumeUp / volumeDown,走 XCTest 的 `XCUIDevice pressButton`。 - /// iPhone 12 mini(iOS 26.4.1)上 home 不起作用但照样报成功,见 [`Self::press_home_hid`] - pub async fn press_button(&mut self, name: &str) -> Result<()> { - self.post("/wda/pressButton", json!({"name": name})).await.map(drop) - } - - /// 直接发一个 IOHID 按键事件(`/wda/performIoHidEvent`),按住 `seconds` 秒 - pub async fn hid_event(&mut self, page: u32, usage: u32, seconds: f64) -> Result<()> { - self.post("/wda/performIoHidEvent", json!({"page": page, "usage": usage, "duration": seconds})).await.map(drop) - } - - /// 经 IOHID 按 Home(消费者页 AC Home)。iPhone 12 mini(iOS 26.4.1)实测:XCTest 的 home 无效时 - /// 它能从 App 回到主屏、关掉 Spotlight、点亮熄灭的屏幕;同页的 Menu(0x40)没反应 - pub async fn press_home_hid(&mut self) -> Result<()> { - self.hid_event(HID_PAGE_CONSUMER, HID_AC_HOME, 0.05).await - } - - /// 经 IOHID 短按电源键([`POWER_PRESS_SECS`],和手指按一下差不多)。WDA 自己的 `/wda/lock` 在 iOS 27 上按住 0.5 秒, - /// iOS 27 以下用 XCTest 的 `pressLockButton`,iPhone 12 mini(iOS 26.4.1)、iPad mini 5(iPadOS 26.7.3)上锁不了屏。 - /// 屏幕已熄灭时按它会把屏幕点亮,调用方要先确认没锁屏 - pub async fn press_power_hid(&mut self) -> Result<()> { - self.hid_event(HID_PAGE_CONSUMER, HID_POWER, POWER_PRESS_SECS).await - } - - pub async fn lock(&mut self) -> Result<()> { - self.post("/wda/lock", json!({})).await.map(drop) - } - - /// 启动并等到前台、界面稳定(冷启动后立即点击会被吞),最多等 8 秒。 - /// 等待期间查前台出错不算失败(启动命令已经成功了) - pub async fn launch_app(&mut self, bundle_id: &str) -> Result { - let started = tokio::time::Instant::now(); - // 不经 XCTest 启动(LSApplicationWorkspace),发出就返回,到没到前台由下面自己查。`/wda/apps/launch` 要等 XCTest - // 看到 App 在前台:系统 App 第一次打开时隐私说明页盖在上面,它就一直等到 60 秒超时,WDA 也被判卡死重启 - // (iPhone 12 mini,iOS 26.4.1,「备忘录」「提醒事项」都是 65 秒)。这时它回「failed to launch」,说明页已经出来了 - let body = json!({"bundleId": bundle_id}); - match self.call("POST", "/wda/apps/launchUnattached", Some(body.clone()), DEFAULT_TIMEOUT).await { - Ok(_) => {} - Err(WdaError::Remote { message, .. }) if message.contains("failed to launch") => {} - // older WDA without the route: launch as before - Err(WdaError::Remote { kind, message }) if unknown_route(&kind, &message) => { - self.in_session("POST", "/wda/apps/launch", Some(body), Duration::from_secs(60)).await?; - } - Err(e) => return Err(e), - } - let t0 = tokio::time::Instant::now(); - let deadline = t0 + Duration::from_secs(8); - let mut foreground = false; - while tokio::time::Instant::now() < deadline { - match self.active_app().await { - Ok(a) if a == bundle_id => { - foreground = true; - break; - } - Ok(a) if a == PRIVACY_SHEET => { - return Ok(Launch::Blocked( - ictl_l10n::tr!( - "第一次打开时的隐私说明页(点「继续」或「接受并继续」后才进入 App)", - "the privacy notice shown on first launch (tap Continue or Accept & Continue to get into the app)" - ) - .into(), - )); - } - // 系统弹窗(权限请求)挡着时前台一直是 SpringBoard,原来要白等满 8 秒。 - // 刚启动的一瞬间前台也还是 SpringBoard,过 1 秒还是才去查弹窗(查一次约 0.4 秒) - Ok(a) if a == SPRINGBOARD && bundle_id != SPRINGBOARD && t0.elapsed() >= Duration::from_secs(1) => { - if let Ok(Some(text)) = self.alert_text().await { - return Ok(Launch::Blocked(text)); - } - } - _ => {} - } - tokio::time::sleep(Duration::from_millis(500)).await; - } - if !foreground { - return Ok(match self.alert_text().await { - Ok(Some(text)) => Launch::Blocked(text), - _ => Launch::Slow, - }); - } - self.settle_launched(started).await; - Ok(Launch::Foreground) - } - - /// App 到了前台之后再等它画出来。`started`:发出启动请求的时刻 - async fn settle_launched(&mut self, started: tokio::time::Instant) { - // 冷启动后立即点击会被吞(回归用例 #13)。原来固定再等 1 秒;改为等界面稳定:连续两次元素树一样 - // (读元素树时 WDA 本身也等界面空闲),最多仍是 1 秒 - let deadline = tokio::time::Instant::now() + Duration::from_secs(1); - let mut prev = None; - while tokio::time::Instant::now() < deadline { - let cur = self.source_xml().await.ok(); - if cur.is_some() && cur == prev { - break; - } - prev = cur; - } - // 切回已在后台的 App 时元素树马上就稳定了(约 0.4 秒),放大进场的动画还没完,这时点击会被吞(真机:小红书、高德各一次) - if let Some(left) = LAUNCH_MIN.checked_sub(started.elapsed()) { - tokio::time::sleep(left).await; - } - } - - pub async fn terminate_app(&mut self, bundle_id: &str) -> Result<()> { - self.post("/wda/apps/terminate", json!({"bundleId": bundle_id})).await.map(drop) - } - - /// 打开网址或 URL Scheme,等打开它的 App 到前台、画出来再返回(最多约 8 秒),同 [`Self::launch_app`]。 - /// 不等的话 App 冷启动时还是黑屏,紧接着截图会把两帧黑屏当成「画面已静止」(iPad Safari 真机)。 - /// 返回结果和前台 App;在原来的前台 App 里打开(Safari 里开网址)时等 1 秒没换就算打开了 - pub async fn open_url(&mut self, url: &str) -> Result<(Launch, String)> { - let started = tokio::time::Instant::now(); - let before = self.active_app().await.unwrap_or_default(); - self.in_session("POST", "/url", Some(json!({"url": url})), Duration::from_secs(60)).await?; - let deadline = started + Duration::from_secs(8); - // 前台要连续两次是同一个才算:Safari 冷启动的一瞬间前台是 `com.apple.DocumentManager.DockFolderViewService`(iPad 真机) - let mut last = String::new(); - loop { - tokio::time::sleep(Duration::from_millis(300)).await; - let waited = started.elapsed() >= Duration::from_secs(1); - let now = self.active_app().await; - let steady = now.as_ref().is_ok_and(|a| *a == last); - if let Ok(a) = &now { - last.clone_from(a); - } - match now { - Ok(a) if a != before && a != SPRINGBOARD && steady => { - self.settle_launched(started).await; - return Ok((Launch::Foreground, a)); - } - Ok(a) if a == before && a != SPRINGBOARD && waited => { - self.settle_launched(started).await; - return Ok((Launch::Foreground, a)); - } - // 「要在某 App 中打开吗」之类的系统弹窗挡着时前台一直是 SpringBoard - Ok(a) if a == SPRINGBOARD && waited => { - if let Ok(Some(text)) = self.alert_text().await { - return Ok((Launch::Blocked(text), a)); - } - } - _ => {} - } - if tokio::time::Instant::now() >= deadline { - let now = self.active_app().await.unwrap_or_default(); - return Ok((Launch::Slow, now)); - } - } - } - - pub async fn idle_settings(&mut self) -> Result { - let v = self.in_session("GET", "/appium/settings", None, DEFAULT_TIMEOUT).await?; - Ok(IdleSettings { - wait_for_idle_timeout: v["waitForIdleTimeout"].as_f64().unwrap_or(10.0), - animation_cool_off_timeout: v["animationCoolOffTimeout"].as_f64().unwrap_or(2.0), - }) - } - - pub async fn set_idle_settings(&mut self, s: IdleSettings) -> Result<()> { - if self.idle_current == Some(s) { - return Ok(()); - } - // not known if this fails - self.idle_current = None; - let body = json!({"settings": {"waitForIdleTimeout": s.wait_for_idle_timeout, "animationCoolOffTimeout": s.animation_cool_off_timeout}}); - self.post("/appium/settings", body).await?; - self.idle_current = Some(s); - Ok(()) - } - - /// 锁屏密码栏的 (总位数, 已输入位数);找不到密码栏返回 None - pub async fn passcode_field(&mut self) -> Result> { - let els = - self.post("/elements", json!({"using": "class name", "value": "XCUIElementTypeSecureTextField"})).await?; - for e in els.as_array().into_iter().flatten() { - let Some(eid) = e.as_object().and_then(|o| o.values().next()).and_then(|v| v.as_str()) else { continue }; - let v = self.in_session("GET", &format!("/element/{eid}/attribute/value"), None, DEFAULT_TIMEOUT).await?; - if let Some(p) = v.as_str().and_then(elements::parse_passcode_value) { - return Ok(Some(p)); - } - } - Ok(None) - } -} +// WdaClient's methods, by what they do: session (transport, XCTest session, stalls), screen (what is on it), +// actions (gestures, buttons, apps), typing (the focused field) +mod actions; +mod screen; +mod session; +mod typing; #[cfg(test)] -mod tests { - use super::*; - use std::collections::VecDeque; - use std::sync::Mutex; - - /// 按顺序返回预设响应,并记录收到的请求 - #[derive(Default)] - struct Mock { - replies: Mutex>, - seen: Mutex)>>, - } - - impl Mock { - fn with(replies: &[(u16, &str)]) -> Self { - Self { - replies: Mutex::new(replies.iter().map(|(s, b)| (*s, b.to_string())).collect()), - ..Default::default() - } - } - } - - impl Transport for &Mock { - async fn send( - &self, - method: &str, - path: &str, - body: Option>, - _: Duration, - ) -> std::io::Result<(u16, Vec)> { - self.seen.lock().unwrap().push((method.into(), path.into(), body.map(|b| String::from_utf8(b).unwrap()))); - let (s, b) = self.replies.lock().unwrap().pop_front().ok_or_else(|| std::io::Error::other("连接被拒绝"))?; - Ok((s, b.into_bytes())) - } - } - - #[tokio::test] - async fn display_poll_remeasures_size_only_when_needed() { - let session = (200, r#"{"sessionId":"A"}"#); - let size = (200, r#"{"value":{"screenSize":{"width":393,"height":852}}}"#); - let portrait = (200, r#"{"value":{"z":0}}"#); - let landscape = (200, r#"{"value":{"z":90}}"#); - let m = - Mock::with(&[session, portrait, size, portrait, landscape, size, landscape, landscape, landscape, size]); - let mut w = WdaClient::new(&m); - // (previous rotation, a poll that may refresh the size, size older than SCREEN_RECHECK, expected rotation) - for (previous, refresh, stale, expected) in [ - (None, true, false, Rotation::Portrait), - (Some(0), true, false, Rotation::Portrait), - // rotated: measured whatever the caller - (Some(0), false, false, Rotation::TopToRight), - // a touch-down with a recent size: rotation only - (Some(90), false, false, Rotation::TopToRight), - // a touch-down with an old size: still rotation only (0.95 s on an iPad mini 5) - (Some(90), false, true, Rotation::TopToRight), - // a quiet poll with an old size: measured again (Display Zoom) - (Some(90), true, true, Rotation::TopToRight), - ] { - if stale { - w.screen_at = Some(Instant::now() - SCREEN_RECHECK); - } - let (size, rotation) = w.display_sample(previous, refresh, async { panic!("unexpected fallback") }).await; - assert_eq!(rotation, Some(expected)); - assert_eq!(size.unwrap().width, 393.); - } - let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect(); - assert_eq!( - paths, - [ - "/session", - "/session/A/rotation", - "/wda/screen", - "/session/A/rotation", - "/session/A/rotation", - "/wda/screen", - "/session/A/rotation", - "/session/A/rotation", - "/session/A/rotation", - "/wda/screen" - ] - ); - } - - #[tokio::test] - async fn legacy_http_404_is_distinct_from_a_transient_rotation_failure() { - let m = Mock::with(&[ - (200, r#"{"sessionId":"A"}"#), - (500, r#"{"value":"runner busy"}"#), - (200, r#"{"value":{"z":90}}"#), - (404, r#"{"value":{"message":"Unhandled endpoint"}}"#), - ]); - let mut w = WdaClient::new(&m); - assert_eq!(w.interface_rotation(async { panic!("500 is not a missing route") }).await, None); - assert_eq!(w.interface_rotation(async { panic!("supported route") }).await, Some(Rotation::TopToRight)); - assert_eq!(w.interface_rotation(async { Some(Rotation::UpsideDown) }).await, Some(Rotation::UpsideDown)); - } - - #[tokio::test] - async fn legacy_wda_uses_a_fresh_interface_rotation_without_retrying_the_missing_route() { - let m = Mock::with(&[ - (200, r#"{"sessionId":"A"}"#), - (404, r#"{"value":{"error":"unknown command"}}"#), - (200, r#"{"value":{"screenSize":{"width":393,"height":852}}}"#), - ]); - let mut w = WdaClient::new(&m); - let (size, rotation) = w.display_sample(None, false, async { Some(Rotation::UpsideDown) }).await; - assert_eq!(size.unwrap().width, 393.); - assert_eq!(rotation, Some(Rotation::UpsideDown)); - assert_eq!(w.interface_rotation(async { Some(Rotation::TopToLeft) }).await, Some(Rotation::TopToLeft)); - assert_eq!(w.interface_rotation(async { None }).await, None); - assert_eq!(m.seen.lock().unwrap().len(), 3); - } - - #[tokio::test] - async fn session_is_recreated_once_after_invalid_session() { - let m = Mock::with(&[ - (200, r#"{"sessionId":"A","value":{}}"#), - (404, r#"{"value":{"error":"invalid session id","message":"gone\nmore"}}"#), - (200, r#"{"value":{"sessionId":"B"}}"#), - (200, r#"{"value":null}"#), - ]); - let mut c = WdaClient::new(&m); - c.press_button("home").await.unwrap(); - let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect(); - assert_eq!(paths, ["/session", "/session/A/wda/pressButton", "/session", "/session/B/wda/pressButton"]); - } - - #[tokio::test] - async fn hid_buttons_send_consumer_page_events() { - let ok = r#"{"value":null}"#; - let m = Mock::with(&[(200, r#"{"sessionId":"A"}"#), (200, ok), (200, ok)]); - let mut c = WdaClient::new(&m); - c.press_home_hid().await.unwrap(); - c.press_power_hid().await.unwrap(); - let seen = m.seen.lock().unwrap().clone(); - assert_eq!(seen[1].1, "/session/A/wda/performIoHidEvent"); - let body = |i: usize| serde_json::from_str::(seen[i].2.as_deref().unwrap()).unwrap(); - assert_eq!((body(1)["page"].as_u64(), body(1)["usage"].as_u64()), (Some(0x0C), Some(0x223))); - assert_eq!((body(2)["page"].as_u64(), body(2)["usage"].as_u64()), (Some(0x0C), Some(0x30))); - // 0.1 秒在 iPhone 15 Pro Max、iPad mini 5 上锁不了屏,0.5 秒在 iPhone 18 Pro Max 上锁不了(见 POWER_PRESS_SECS) - assert_eq!(body(2)["duration"], 0.15); - } - - #[tokio::test] - async fn tap_is_one_gesture_with_quick_waits_then_restores_baseline() { - let ok = r#"{"value":null}"#; - let m = Mock::with(&[ - (200, r#"{"sessionId":"A"}"#), - (200, r#"{"value":{"waitForIdleTimeout":10,"animationCoolOffTimeout":2}}"#), - (200, ok), - (200, ok), - (200, ok), - // 第二次点击不再读设置 - (200, ok), - (200, ok), - (200, ok), - ]); - let mut c = WdaClient::new(&m); - c.tap(10.0, 20.0).await.unwrap(); - c.tap(30.0, 40.0).await.unwrap(); - let seen = m.seen.lock().unwrap().clone(); - let paths: Vec<_> = seen.iter().map(|s| s.1.as_str()).collect(); - assert_eq!( - paths, - [ - "/session", - "/session/A/appium/settings", - "/session/A/appium/settings", - "/session/A/actions", - "/session/A/appium/settings", - "/session/A/appium/settings", - "/session/A/actions", - "/session/A/appium/settings", - ] - ); - let body = |i: usize| serde_json::from_str::(seen[i].2.as_deref().unwrap()).unwrap(); - assert_eq!(body(2)["settings"]["animationCoolOffTimeout"], 0.0); - assert_eq!(body(4)["settings"]["animationCoolOffTimeout"], 2.0); - let a = body(3); - let steps = a["actions"][0]["actions"].as_array().unwrap(); - assert_eq!(steps.iter().filter(|s| s["type"] == "pointerDown").count(), 1); - } - - /// 启动不经 XCTest(`launchUnattached`),发出就返回;系统 App 第一次打开时它回 failed to launch,前台是隐私说明页, - /// 马上报被挡住,不再等 60 秒 - #[tokio::test] - async fn a_first_launch_privacy_notice_is_reported_at_once() { - let fail = r#"{"value":{"error":"unknown error","message":"LSApplicationWorkspace failed to launch app"}}"#; - let m = Mock::with(&[(500, fail), (200, r#"{"value":{"bundleId":"com.apple.PDUIApp"}}"#)]); - let mut w = WdaClient::new(&m); - let t0 = std::time::Instant::now(); - let r = w.launch_app("com.apple.mobilenotes").await.unwrap(); - assert!(matches!(r, Launch::Blocked(ref t) if !t.is_empty()), "{r:?}"); - assert!(t0.elapsed() < Duration::from_secs(1)); - let seen = m.seen.lock().unwrap(); - assert_eq!(seen[0].1, "/wda/apps/launchUnattached"); - assert!(seen.iter().all(|(_, p, _)| !p.ends_with("/wda/apps/launch"))); - } - - /// 旧版 WDA 没有 launchUnattached:照旧经会话启动 - #[tokio::test] - async fn an_older_wda_without_unattached_launch_launches_as_before() { - let m = Mock::with(&[ - (404, r#"{"value":{"error":"unknown command","message":"Unhandled endpoint"}}"#), - (200, r#"{"sessionId":"A"}"#), - (200, r#"{"value":null}"#), - (200, r#"{"value":{"bundleId":"com.apple.PDUIApp"}}"#), - ]); - let mut w = WdaClient::new(&m); - assert!(matches!(w.launch_app("com.apple.mobilenotes").await.unwrap(), Launch::Blocked(_))); - let seen = m.seen.lock().unwrap(); - assert_eq!(seen[2].1, "/session/A/wda/apps/launch"); - } - - /// 别的错误照样报出来,不当成启动了 - #[tokio::test] - async fn other_launch_errors_are_errors() { - let m = Mock::with(&[(500, r#"{"value":{"error":"invalid argument","message":"bad bundle"}}"#)]); - let mut w = WdaClient::new(&m); - assert!(matches!(w.launch_app("x").await, Err(WdaError::Remote { .. }))); - } - - /// 依次点几个点:每个点一根手指,第 k 根先空等前面的点按完;各手指的节拍数对得上,按下抬起一个接一个、不重叠 - #[test] - fn a_sequence_is_one_finger_per_point_in_turn() { - let body = tap_sequence_body(&[(10.0, 20.0), (30.0, 40.0), (50.0, 60.0)], 50, 40); - let fingers = body["actions"].as_array().unwrap(); - assert_eq!(fingers.len(), 3); - for (k, f) in fingers.iter().enumerate() { - let a = f["actions"].as_array().unwrap(); - assert_eq!(a.len(), 5 * k + 4, "finger {k}"); - // pauses only until its own turn, then move, down, hold, up at its point - assert!(a[..5 * k].iter().all(|s| s["type"] == "pause")); - assert_eq!(a[5 * k]["type"], "pointerMove"); - assert_eq!(a[5 * k]["x"].as_f64(), Some(10.0 + 20.0 * k as f64)); - assert_eq!(a[5 * k + 1]["type"], "pointerDown"); - assert_eq!(a[5 * k + 3]["type"], "pointerUp"); - assert_ne!(fingers[0]["id"], fingers[k.max(1)]["id"]); - } - // finger k waits 5 ticks per earlier point: move, down, hold, up, gap - assert_eq!(fingers[1]["actions"][2]["duration"], 50); - assert_eq!(fingers[1]["actions"][4]["duration"], 40); - } - - /// 连点是一个 actions 请求:一根手指只移动一次,在同一点按下抬起 N 次,两下之间停 MULTI_TAP_GAP_MS; - /// 5 下在 0.8 秒内点完 - #[tokio::test] - async fn multi_tap_is_one_request_at_one_point() { - let ok = r#"{"value":null}"#; - let m = Mock::with(&[ - (200, r#"{"sessionId":"A"}"#), - (200, r#"{"value":{"waitForIdleTimeout":10,"animationCoolOffTimeout":2}}"#), - (200, ok), - (200, ok), - (200, ok), - ]); - let mut c = WdaClient::new(&m); - c.multi_tap(10.0, 20.0, 5).await.unwrap(); - let seen = m.seen.lock().unwrap().clone(); - let actions: Vec<_> = seen.iter().filter(|s| s.1.ends_with("/actions")).collect(); - assert_eq!(actions.len(), 1); - let body = serde_json::from_str::(actions[0].2.as_deref().unwrap()).unwrap(); - let steps = body["actions"][0]["actions"].as_array().unwrap(); - let count = |t: &str| steps.iter().filter(|s| s["type"] == t).count(); - assert_eq!((count("pointerMove"), count("pointerDown"), count("pointerUp")), (1, 5, 5)); - assert_eq!((steps[0]["x"].as_f64(), steps[0]["y"].as_f64()), (Some(10.0), Some(20.0))); - let ms: u64 = steps.iter().filter_map(|s| s["duration"].as_u64()).sum(); - assert_eq!(ms, 5 * TAP_PRESS_MS + 4 * MULTI_TAP_GAP_MS); - assert!(ms < 800); - } - - #[tokio::test] - async fn remote_error_keeps_first_line_and_unreachable_maps_to_unavailable() { - let m = Mock::with(&[ - (200, r#"{"sessionId":"A"}"#), - (500, r#"{"value":{"error":"unknown error","message":"boom\nstack"}}"#), - ]); - let mut c = WdaClient::new(&m); - match c.press_button("home").await { - Err(WdaError::Remote { kind, message }) => { - assert_eq!((kind.as_str(), message.as_str()), ("unknown error", "boom")) - } - other => panic!("{other:?}"), - } - assert!(matches!(c.active_app().await, Err(WdaError::Unavailable(_)))); - } - - /// 传输层报的错误按「请求送没送到」分类:只有没送到的才是 Unavailable(调用方会退到 HID 重做) - #[tokio::test] - async fn errors_after_sending_are_not_unavailable() { - struct Fails(std::io::ErrorKind); - impl Transport for Fails { - async fn send(&self, _: &str, _: &str, _: Option>, _: Duration) -> std::io::Result<(u16, Vec)> { - Err(std::io::Error::new(self.0, "x")) - } - } - let kind = |k| async move { WdaClient::new(Fails(k)).active_app().await }; - assert!(matches!(kind(crate::http::AFTER_SENT).await, Err(WdaError::Interrupted(_)))); - assert!(matches!(kind(crate::http::WRITE_FAILED).await, Err(WdaError::Unavailable(_)))); - let client = WdaClient::new(Fails(crate::http::WRITE_FAILED)); - for (path, acts) in [("/session/1/element", false), ("/session/1/wda/keys", true)] { - let error = client.send("POST", path, None, Duration::from_secs(1)).await.unwrap_err(); - assert!(if acts { matches!(error, WdaError::Write(_)) } else { matches!(error, WdaError::Unavailable(_)) }); - } - assert!(matches!(kind(std::io::ErrorKind::TimedOut).await, Err(WdaError::Timeout(_)))); - assert!(matches!(kind(std::io::ErrorKind::NotConnected).await, Err(WdaError::Unavailable(_)))); - // 应答了但不是 JSON:WDA 收到了请求 - let m = Mock::with(&[(200, "")]); - assert!(matches!(WdaClient::new(&m).active_app().await, Err(WdaError::Interrupted(_)))); - } - - /// 经 XCTest 的请求(工具调用和探测一样算)连续 3 次没有应答就判定卡死:之后不再发,直接报不可用; - /// `/status` 不经 XCTest,既不算数也不受影响;中间有一次应答(哪怕是错误)就从头数。 - /// 长请求没应答时马上问一次前台 App(5 秒):它也没应答就立刻判定卡死,它应答了只是慢 - #[tokio::test] - async fn three_unanswered_requests_mean_stalled() { - type Reply = std::io::Result<(u16, Vec)>; - struct Scripted { - replies: Mutex>, - sent: Mutex>, - } - impl Transport for &Scripted { - async fn send( - &self, - _: &str, - path: &str, - _: Option>, - _: Duration, - ) -> std::io::Result<(u16, Vec)> { - self.sent.lock().unwrap().push(path.to_owned()); - self.replies.lock().unwrap().pop_front().expect("unexpected request") - } - } - let timeout = || Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "t")); - let ok = |b: &str| Ok((200, b.as_bytes().to_vec())); - let t = Scripted { - replies: Mutex::new(VecDeque::from([ - // a long request unanswered, the quick question after it answered: slow, not stuck - timeout(), - ok(r#"{"value":{}}"#), - timeout(), - ok(r#"{"value":{}}"#), - ok(r#"{"value":{"error":"unknown error","message":"busy"}}"#), - // the probe itself is short: no question after it - timeout(), - ok(r#"{"value":{"ready":true}}"#), - // a long request and the quick question both unanswered: stuck at once - timeout(), - timeout(), - ok(r#"{"value":{"ready":true}}"#), - ])), - sent: Mutex::default(), - }; - let c = WdaClient::new(&t); - assert!(c.wda_reports_locked().await.unwrap_err().no_answer()); - assert!(c.active_app().await.unwrap_err().no_answer()); - assert_eq!(c.unanswered(), 0, "两次短探测均获得回答,应清零"); - // 回了错误:还活着,从头数 - assert!(matches!(c.active_app().await, Err(WdaError::Remote { .. }))); - assert_eq!(c.unanswered(), 0); - assert!(c.xctest_responsive().await.unwrap_err().no_answer()); - // /status 应答了也不清零 - assert!(c.ready().await.unwrap()); - assert_eq!(c.unanswered(), 1); - assert!(!c.stalled()); - assert!(c.wda_reports_locked().await.is_err()); - assert!(c.stalled(), "the quick question went unanswered too"); - assert!(t.replies.lock().unwrap().len() == 1, "every scripted reply but /status was used"); - // 卡死后经 XCTest 的请求不再发出,直接报不可用(调用方可以退到 HID);/status 照常 - let sent = t.sent.lock().unwrap().len(); - assert!(matches!(c.screenshot_png().await, Err(WdaError::Unavailable(_)))); - assert!(matches!(c.xctest_responsive().await, Err(WdaError::Unavailable(_)))); - assert_eq!(t.sent.lock().unwrap().len(), sent); - assert!(c.ready().await.unwrap()); - assert!(c.stalled()); - } - - /// 较长请求超时后,短探测的正常回答或远端错误都证明 WDA 仍有响应,应重新计数。 - #[tokio::test] - async fn answered_probe_resets_stall_count_after_each_slow_request() { - for (status, body) in [ - (200, r#"{"value":{}}"#), - (500, r#"{"value":{"error":"unknown error","message":"busy"}}"#), - (404, r#"{"message":"unknown route"}"#), - (502, "temporarily unavailable"), - ] { - let replies = (0..4).flat_map(|_| [timed_out(), Ok((status, body.as_bytes().to_vec()))]).collect(); - let t = Script::new(replies); - let c = WdaClient::new(&t); - for _ in 0..4 { - assert!(c.wda_reports_locked().await.unwrap_err().no_answer()); - assert_eq!(c.unanswered(), 0, "探测返回 {status} {body}"); - assert!(!c.stalled()); - } - assert_eq!(t.sent().len(), 8, "每个慢请求后都应继续做短探测"); - } - } - - /// 连不上不是收到回答,不能抹掉之前已经发生的无应答。 - #[tokio::test] - async fn connection_error_does_not_reset_unanswered_count() { - let t = Script::new(vec![ - timed_out(), - Err(std::io::Error::new(std::io::ErrorKind::NotConnected, "offline")), - Ok((500, br#"{"value":{"error":"unknown error","message":"busy"}}"#.to_vec())), - ]); - let c = WdaClient::new(&t); - assert!(c.xctest_responsive().await.unwrap_err().no_answer()); - assert_eq!(c.unanswered(), 1); - assert!(matches!(c.xctest_responsive().await, Err(WdaError::Unavailable(_)))); - assert_eq!(c.unanswered(), 1); - assert!(matches!(c.xctest_responsive().await, Err(WdaError::Remote { .. }))); - assert_eq!(c.unanswered(), 0); - assert!(!c.stalled()); - } - - /// 两个请求未应答即可触发快速恢复,但实际计数和原因不能伪装成三次无应答。 - #[tokio::test] - async fn long_request_and_failed_probe_keep_the_actual_count_and_reason() { - let t = Script::new(vec![timed_out(), timed_out(), ok(r#"{"value":{"ready":true}}"#)]); - let c = WdaClient::new(&t); - assert!(c.wda_reports_locked().await.unwrap_err().no_answer()); - assert_eq!(c.unanswered(), 2); - assert_eq!(c.stall_reason(), Some(StallReason::LongRequestAndProbe)); - assert!(c.stalled()); - let why = c.stall_reason().unwrap().describe(); - assert!(why.contains("/wda/activeAppInfo")); - assert!(!why.contains("3 次")); - // 本地 /status 的回答不应把已记录的判定抹掉。 - assert!(c.ready().await.unwrap()); - assert_eq!(c.stall_reason(), Some(StallReason::LongRequestAndProbe)); - assert_eq!(t.sent(), ["GET /wda/locked", "GET /wda/activeAppInfo", "GET /status"]); - } - - #[tokio::test] - async fn three_short_unanswered_requests_report_a_consecutive_stall() { - let t = Script::new(vec![timed_out(), timed_out(), timed_out()]); - let c = WdaClient::new(&t); - for n in 1..=STALL_LIMIT { - assert!(c.xctest_responsive().await.unwrap_err().no_answer()); - assert_eq!(c.unanswered(), n); - assert_eq!(c.stalled(), n == STALL_LIMIT); - } - assert_eq!(c.stall_reason(), Some(StallReason::ConsecutiveRequests(STALL_LIMIT))); - // 后续调用仍立即拒绝,不再发送请求。 - assert!(matches!(c.xctest_responsive().await, Err(WdaError::Unavailable(_)))); - assert_eq!(t.sent().len(), STALL_LIMIT as usize); - } - - /// 结束会话的回答只用于清理,不应代替真正的前台响应探测。 - #[tokio::test] - async fn answered_session_delete_does_not_mask_a_failed_probe() { - let t = Script::new(vec![ok(r#"{"sessionId":"A"}"#), timed_out(), ok(r#"{"value":null}"#), timed_out()]); - let mut c = WdaClient::new(&t); - assert!(matches!(c.press_button("home").await, Err(WdaError::Timeout(_)))); - assert_eq!(c.unanswered(), 2); - assert_eq!(c.stall_reason(), Some(StallReason::LongRequestAndProbe)); - assert_eq!(t.sent()[2], "DELETE /session/A"); - } - - /// 经 XCTest 的探测:只有「送到了却没有应答」算卡死的迹象;WDA 回了错误说明它还在办事,连不上归 `/status` 管 - #[tokio::test] - async fn xctest_probe_counts_only_missing_answers() { - struct Fails(std::io::ErrorKind); - impl Transport for Fails { - async fn send(&self, _: &str, _: &str, _: Option>, t: Duration) -> std::io::Result<(u16, Vec)> { - assert_eq!(t, XCTEST_PROBE_TIMEOUT); - Err(std::io::Error::new(self.0, "x")) - } - } - let probe = |k| async move { WdaClient::new(Fails(k)).xctest_responsive().await }; - assert!(probe(std::io::ErrorKind::TimedOut).await.unwrap_err().no_answer()); - assert!(probe(crate::http::AFTER_SENT).await.unwrap_err().no_answer()); - assert!(!probe(std::io::ErrorKind::NotConnected).await.unwrap_err().no_answer()); - let m = Mock::with(&[ - (200, r#"{"value":{"bundleId":"com.apple.springboard","pid":60}}"#), - (500, r#"{"value":{"error":"unknown error","message":"busy"}}"#), - ]); - let c = WdaClient::new(&m); - assert!(c.xctest_responsive().await.is_ok()); - assert!(!c.xctest_responsive().await.unwrap_err().no_answer()); - assert_eq!(m.seen.lock().unwrap()[0].1, "/wda/activeAppInfo"); - } - - #[tokio::test] - async fn screen_size_is_cached_and_status_ready() { - let unknown = r#"{"value":{"error":"unknown command","message":"no"}}"#; - let m = Mock::with(&[ - (200, r#"{"value":{"screenSize":{"width":430,"height":932},"scale":3}}"#), - (200, r#"{"sessionId":"S"}"#), - (404, unknown), - (404, unknown), - (200, r#"{"value":{"ready":true}}"#), - ]); - let mut c = WdaClient::new(&m); - // 问不到方向:按缓存的尺寸 - assert_eq!(c.screen_size().await.unwrap(), ScreenSize { width: 430.0, height: 932.0 }); - assert_eq!(c.screen_size().await.unwrap().width, 430.0); - assert!(c.ready().await.unwrap()); - let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect(); - assert_eq!(paths.iter().filter(|p| *p == "/wda/screen").count(), 1); - } - - #[tokio::test] - async fn rotation_reads_z_angle() { - let m = Mock::with(&[ - (200, r#"{"sessionId":"S"}"#), - (200, r#"{"value":{"x":0,"y":0,"z":270}}"#), - (200, r#"{"value":{"x":0,"y":0,"z":12}}"#), - ]); - let mut c = WdaClient::new(&m); - assert_eq!(c.rotation().await.unwrap(), ictl_device::Rotation::TopToLeft); - assert!(c.rotation().await.is_err()); - assert_eq!(m.seen.lock().unwrap()[1].1, "/session/S/rotation"); - } - - /// WDA 在横屏时启动,缓存的是 1024x768;转成竖屏后要给 768x1024 - #[tokio::test] - async fn screen_size_follows_orientation_after_rotation() { - let m = Mock::with(&[ - (200, r#"{"value":{"screenSize":{"width":1024,"height":768},"scale":2}}"#), - (200, r#"{"sessionId":"S"}"#), - (200, r#"{"value":"LANDSCAPE"}"#), - (200, r#"{"value":"PORTRAIT"}"#), - ]); - let mut c = WdaClient::new(&m); - let v = c.view().await.unwrap(); - assert_eq!( - (v.screen, v.orientation), - (ScreenSize { width: 1024.0, height: 768.0 }, Some(elements::Orientation::LandscapeLeft)) - ); - assert_eq!(c.screen_size().await.unwrap(), ScreenSize { width: 768.0, height: 1024.0 }); - assert_eq!(m.seen.lock().unwrap()[2].1, "/session/S/orientation"); - } - - /// 从主屏打开网址:等 Safari 到前台、元素树稳定才返回,不是发完请求就走;一闪而过的系统服务不算 - #[tokio::test] - async fn open_url_waits_for_the_opening_app() { - let m = Mock::with(&[ - (200, r#"{"value":{"bundleId":"com.apple.springboard"}}"#), - (200, r#"{"sessionId":"S"}"#), - (200, r#"{"value":null}"#), - (200, r#"{"value":{"bundleId":"com.apple.DocumentManager.DockFolderViewService"}}"#), - (200, r#"{"value":{"bundleId":"com.apple.mobilesafari"}}"#), - (200, r#"{"value":{"bundleId":"com.apple.mobilesafari"}}"#), - (200, r#"{"value":""}"#), - (200, r#"{"value":""}"#), - ]); - let mut c = WdaClient::new(&m); - let t0 = std::time::Instant::now(); - let (r, app) = c.open_url("https://example.com").await.unwrap(); - assert_eq!((r, app.as_str()), (Launch::Foreground, "com.apple.mobilesafari")); - assert!(t0.elapsed() >= LAUNCH_MIN); - let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect(); - assert_eq!(paths[2], "/session/S/url"); - assert!(paths[6].starts_with("/source"), "{paths:?}"); - } - - #[tokio::test] - async fn source_request_excludes_slow_attributes() { - let m = Mock::with(&[(200, r#"{"value":""}"#)]); - let mut c = WdaClient::new(&m); - c.source_xml().await.unwrap(); - let path = m.seen.lock().unwrap()[0].1.clone(); - assert!(path.starts_with("/source?format=xml&excluded_attributes=visible,"), "{path}"); - } - - #[tokio::test] - async fn passcode_field_reads_secure_text_field_value() { - let m = Mock::with(&[ - (200, r#"{"sessionId":"S"}"#), - (200, r#"{"value":[{"ELEMENT":"E1","element-6066-11e4-a52e-4f735466cecf":"E1"}]}"#), - (200, r#"{"value":"共6位数,已输入2位"}"#), - ]); - let mut c = WdaClient::new(&m); - assert_eq!(c.passcode_field().await.unwrap(), Some((6, 2))); - assert_eq!(m.seen.lock().unwrap()[2].1, "/session/S/element/E1/attribute/value"); - } - - #[tokio::test] - async fn focused_field_reads_its_type_and_placeholder() { - let m = Mock::with(&[ - (200, r#"{"sessionId":"S"}"#), - (200, r#"{"value":{"ELEMENT":"F1","element-6066-11e4-a52e-4f735466cecf":"F1"}}"#), - (200, r#"{"value":"XCUIElementTypeSearchField"}"#), - (200, r#"{"value":"搜索"}"#), - // empty: reads its placeholder - (200, r#"{"value":"搜索"}"#), - (200, r#"{"value":"wifi"}"#), - ]); - let mut c = WdaClient::new(&m); - let f = c.focused_field().await.unwrap().unwrap(); - assert_eq!(f, FocusedField { id: "F1".into(), kind: "SearchField".into(), placeholder: "搜索".into() }); - assert_eq!(c.field_text(&f).await.unwrap(), ""); - assert_eq!(c.field_text(&f).await.unwrap(), "wifi"); - let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect(); - assert_eq!( - paths[1..4], - [ - "/session/S/element/active", - "/session/S/element/F1/attribute/type", - "/session/S/element/F1/attribute/placeholderValue" - ] - ); - } - - #[tokio::test] - async fn no_focused_element_is_none() { - let m = Mock::with(&[ - (200, r#"{"sessionId":"S"}"#), - (404, r#"{"value":{"error":"no such element","message":"No element is in focus"}}"#), - ]); - assert_eq!(WdaClient::new(&m).focused_field().await.unwrap(), None); - } - - /// Finding elements reads; clearing one changes the phone (its session is ended when it doesn't answer) - #[test] - fn element_finds_read_and_element_edits_act() { - assert!(!acts("POST", "/elements")); - assert!(!acts("POST", "/element")); - assert!(!acts("POST", "/element/E1/elements")); - assert!(!acts("GET", "/element/active")); - assert!(acts("POST", "/element/E1/clear")); - assert!(acts("POST", "/wda/keys")); - } - - #[test] - fn actions_body_is_one_pointer_with_steps() { - let b = actions_body(&tap_steps(10.0, 20.0, 80)); - let a = &b["actions"][0]; - assert_eq!(a["parameters"]["pointerType"], "touch"); - let types: Vec<_> = a["actions"].as_array().unwrap().iter().map(|s| s["type"].as_str().unwrap()).collect(); - assert_eq!(types, ["pointerMove", "pointerDown", "pause", "pointerUp"]); - assert_eq!(a["actions"][2]["duration"], 80); - let s = swipe_steps((1.0, 2.0), (3.0, 4.0), 300); - assert_eq!(s[3], PointerStep::Move { x: 3.0, y: 4.0, ms: 300 }); - } - - /// 按住再拖:按下后原地 move 按住(不是 pause,pause 拖不动图标),再移到终点;不按住就是普通滑动 - #[test] - fn a_held_drag_holds_with_a_move_in_place() { - let s = drag_steps((1.0, 2.0), (3.0, 4.0), 600, 700); - assert_eq!( - s, - [ - PointerStep::Move { x: 1.0, y: 2.0, ms: 0 }, - PointerStep::Down, - PointerStep::Move { x: 1.0, y: 2.0, ms: 600 }, - PointerStep::Move { x: 3.0, y: 4.0, ms: 700 }, - PointerStep::Up, - ] - ); - assert_eq!(drag_steps((1.0, 2.0), (3.0, 4.0), 0, 300), swipe_steps((1.0, 2.0), (3.0, 4.0), 300)); - } - - #[tokio::test] - async fn locked_checks_tree_until_unlocked_once_then_trusts_wda() { - let lock_xml = serde_json::to_string(include_str!("../tests/fixtures/lockscreen-ios27.xml")).unwrap(); - let home_xml = serde_json::to_string(include_str!("../tests/fixtures/home.xml")).unwrap(); - let sb = r#"{"value":{"bundleId":"com.apple.springboard"}}"#; - let no = r#"{"value":false}"#; - let (lock_src, home_src) = (format!(r#"{{"value":{lock_xml}}}"#), format!(r#"{{"value":{home_xml}}}"#)); - let m = Mock::with(&[ - // 1. WDA 在锁屏时启动:/wda/locked 误报 false,元素树是锁屏 - (200, no), - (200, sb), - (200, &lock_src), - // 2. 人工解锁后:主屏幕,确认一次 - (200, no), - (200, sb), - (200, &home_src), - // 3. 之后 WDA 说没锁就直接信 - (200, no), - // 4. WDA 说锁了:核对一次,确实是锁屏 - (200, r#"{"value":true}"#), - (200, sb), - (200, &lock_src), - ]); - let mut c = WdaClient::new(&m); - assert!(c.locked().await.unwrap()); - assert!(!c.locked().await.unwrap()); - assert!(!c.locked().await.unwrap()); - assert!(c.locked().await.unwrap()); - let paths: Vec = m.seen.lock().unwrap().iter().map(|(_, p, _)| p.clone()).collect(); - assert_eq!(paths.iter().filter(|p| p.starts_with("/source")).count(), 3, "{paths:?}"); - } - - #[tokio::test] - async fn notification_center_is_not_locked_even_if_wda_says_so() { - let nc = serde_json::to_string(include_str!("../tests/fixtures/notification-center-ios27.xml")).unwrap(); - let pin = serde_json::to_string(include_str!("../tests/fixtures/passcode-view-ios27.xml")).unwrap(); - let sb = r#"{"value":{"bundleId":"com.apple.springboard"}}"#; - let yes = r#"{"value":true}"#; - let (nc, pin) = (format!(r#"{{"value":{nc}}}"#), format!(r#"{{"value":{pin}}}"#)); - let m = Mock::with(&[(200, yes), (200, sb), (200, &nc), (200, yes), (200, sb), (200, &pin), (200, yes)]); - let mut c = WdaClient::new(&m); - assert!(!c.locked().await.unwrap(), "通知中心"); - assert!(c.locked().await.unwrap(), "密码键盘界面"); - // 核对失败时按 WDA 的结果 - assert!(c.locked().await.unwrap()); - } - - #[tokio::test] - async fn locked_falls_back_to_wda_when_tree_check_fails() { - // 核对失败(例如取元素树超时)不能把可用的手机误判成锁屏,也不能就此信任 WDA - let m = Mock::with(&[(200, r#"{"value":false}"#)]); - let mut c = WdaClient::new(&m); - assert!(!c.locked().await.unwrap()); - assert!(!c.lock_state_trusted); - } - - /// 传输层给出的一个结果:状态码和响应体,或者超时之类的错误 - type Reply = std::io::Result<(u16, Vec)>; - - /// 按顺序给出预设结果(可以是超时),记下每个请求的方法、路径和请求体 - #[derive(Default)] - struct Script { - replies: Mutex>, - sent: Mutex)>>, - } - - impl Script { - fn new(replies: Vec) -> Self { - Self { replies: Mutex::new(replies.into()), ..Default::default() } - } - - fn sent(&self) -> Vec { - self.sent.lock().unwrap().iter().map(|(m, p, _)| format!("{m} {p}")).collect() - } - - fn body(&self, i: usize) -> Value { - self.sent.lock().unwrap()[i].2.clone().expect("a body") - } - } - - impl Transport for &Script { - async fn send( - &self, - method: &str, - path: &str, - body: Option>, - _: Duration, - ) -> std::io::Result<(u16, Vec)> { - let body = body.map(|b| serde_json::from_slice(&b).unwrap()); - self.sent.lock().unwrap().push((method.into(), path.into(), body)); - self.replies.lock().unwrap().pop_front().expect("unexpected request") - } - } - - fn timed_out() -> Reply { - Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "t")) - } - - fn ok(body: &str) -> Reply { - Ok((200, body.as_bytes().to_vec())) - } - - /// 动作没有应答:先结束会话(WDA 不再执行这个会话里还在排队的请求),再问一次前台 App 判断是不是卡死; - /// 下一个动作开新会话 - #[tokio::test] - async fn an_unanswered_action_ends_its_session() { - let t = Script::new(vec![ - ok(r#"{"sessionId":"A"}"#), - timed_out(), - ok(r#"{"value":null}"#), - ok(r#"{"value":{}}"#), - ok(r#"{"sessionId":"B"}"#), - ok(r#"{"value":null}"#), - ]); - let mut c = WdaClient::new(&t); - assert!(matches!(c.press_button("home").await, Err(WdaError::Timeout(_)))); - c.press_button("home").await.unwrap(); - assert_eq!( - t.sent(), - [ - "POST /session", - "POST /session/A/wda/pressButton", - "DELETE /session/A", - "GET /wda/activeAppInfo", - "POST /session", - "POST /session/B/wda/pressButton", - ] - ); - } - - /// 读没有应答不结束会话:排在读后面的不会动手机,结束了只会让下一次开会话也排到它后面 - #[tokio::test] - async fn an_unanswered_read_keeps_its_session() { - let t = Script::new(vec![ - ok(r#"{"sessionId":"A"}"#), - timed_out(), - ok(r#"{"value":{}}"#), - timed_out(), - ok(r#"{"value":{}}"#), - ok(r#"{"value":null}"#), - ]); - let mut c = WdaClient::new(&t); - assert!(c.alert_text().await.unwrap_err().no_answer()); - assert!(c.keyboard_shown().await.unwrap_err().no_answer()); - c.press_button("home").await.unwrap(); - assert_eq!( - t.sent(), - [ - "POST /session", - "GET /session/A/alert/text", - "GET /wda/activeAppInfo", - "POST /session/A/elements", - "GET /wda/activeAppInfo", - "POST /session/A/wda/pressButton", - ] - ); - } - - #[test] - fn snapshot_limits_tighten_when_slow_and_loosen_when_fast() { - let slow = Some(SLOW_SOURCE); - let fast = Some(Duration::from_millis(300)); - let fair = Some(Duration::from_secs(3)); - assert_eq!(next_snapshot_level(0, slow), 1); - assert_eq!(next_snapshot_level(1, None), 2); - assert_eq!(next_snapshot_level(3, None), 3, "never tighter than the last level"); - assert_eq!(next_snapshot_level(2, fair), 2); - assert_eq!(next_snapshot_level(2, fast), 1); - assert_eq!(next_snapshot_level(0, fast), 0); - assert_eq!(next_snapshot_level(0, fair), 0); - // 先限子元素再减层数,都有下限 - assert_eq!(SNAPSHOT_LEVELS[1], SnapshotLimits { depth: 50, children: Some(150) }); - assert!(SNAPSHOT_LEVELS.windows(2).all(|w| w[1].depth <= w[0].depth)); - assert_eq!(SNAPSHOT_LEVELS[3], SnapshotLimits { depth: 12, children: Some(60) }); - } - - /// 读树超时后下一次先设上限再读,读得快了再放宽;新会话里 WDA 是不限的,不为读树专门设 - #[tokio::test] - async fn a_timed_out_tree_is_read_again_with_limits() { - let xml = r#"{"value":""}"#; - let t = Script::new(vec![ - timed_out(), - ok(r#"{"value":{}}"#), - ok(r#"{"sessionId":"A"}"#), - ok(r#"{"value":null}"#), - ok(xml), - ok(r#"{"value":null}"#), - ok(xml), - ok(xml), - ]); - let mut c = WdaClient::new(&t); - assert!(matches!(c.source_xml().await, Err(WdaError::Timeout(_)))); - assert_eq!(c.snapshot_note(), None, "nothing was read with limits yet"); - assert_eq!(c.source_xml().await.unwrap(), ""); - assert!(c.snapshot_note().unwrap().contains("150")); - c.source_xml().await.unwrap(); - assert_eq!(c.snapshot_note(), None); - c.source_xml().await.unwrap(); - let sent = t.sent(); - assert!(sent[0].starts_with("GET /source?")); - assert_eq!(sent[1..4], ["GET /wda/activeAppInfo", "POST /session", "POST /session/A/appium/settings"]); - assert_eq!(t.body(3)["settings"], json!({"snapshotMaxDepth": 50, "snapshotMaxChildren": 150})); - assert_eq!(sent[5], "POST /session/A/appium/settings"); - assert_eq!(t.body(5)["settings"]["snapshotMaxChildren"], i32::MAX); - assert_eq!(sent.len(), 8, "the last read needs no settings: {sent:?}"); - } - - #[test] - fn the_detection_point_is_below_banners_in_either_orientation() { - assert_eq!(detection_point(ScreenSize { width: 430.0, height: 932.0 }), (215, 215)); - assert_eq!(detection_point(ScreenSize { width: 932.0, height: 430.0 }), (215, 215)); - assert_eq!(detection_point(ScreenSize { width: 744.0, height: 1133.0 }), (372, 372)); - } - - /// 第一次读元素树时挪一次判断前台 App 的点,之后不再设 - #[tokio::test] - async fn the_first_tree_read_moves_the_detection_point_once() { - let xml = r#"{"value":""}"#; - let t = Script::new(vec![ - ok(r#"{"value":{"screenSize":{"width":430,"height":932}}}"#), - ok(r#"{"sessionId":"A"}"#), - ok(r#"{"value":"PORTRAIT"}"#), - ok(r#"{"value":null}"#), - ok(xml), - ok(r#"{"value":"PORTRAIT"}"#), - ok(xml), - ]); - let mut c = WdaClient::new(&t); - c.tree().await.unwrap(); - c.tree().await.unwrap(); - let sent = t.sent(); - assert_eq!(sent[3], "POST /session/A/appium/settings", "{sent:?}"); - assert_eq!(t.body(3)["settings"], json!({"activeAppDetectionPoint": "215,215"})); - assert_eq!(sent.len(), 7, "{sent:?}"); - assert!(sent[6].starts_with("GET /source?")); - } -} +mod tests; diff --git a/crates/ictl-wda/src/client/actions.rs b/crates/ictl-wda/src/client/actions.rs new file mode 100644 index 0000000..e7fe4b8 --- /dev/null +++ b/crates/ictl-wda/src/client/actions.rs @@ -0,0 +1,277 @@ +//! [`WdaClient`]: Gestures, buttons, IOHID events, launching and terminating apps, opening links + +use super::*; + +impl WdaClient { + /// 点击:一个 W3C actions 单指手势(按下 50ms),期间把等待设置临时调小。真机计时(iOS 27): + /// - `/wda/tap` 先等界面空闲:主屏点图标约 1.7 秒(调小等待也没用),App 里约 0.6 秒,锁屏上约 2.9 秒 + /// - actions 手势做完要等动画冷却(`animationCoolOffTimeout`,默认 2 秒):App 里切标签约 1.9 秒 + /// - actions + 临时调小等待:App 里约 0.7 秒,主屏点图标约 0.9 秒 + /// - 冷却不能是 0.2 秒([`IdleSettings::QUICK`]):界面上一直有动画时(键盘弹着、光标在闪)要等约 26 秒才返回, + /// iPhone 18 Pro Max(iOS 27.2.1)在设置里点搜索结果每次都这样;冷却 0 约 0.4 秒。和滑动一样用 + /// [`IdleSettings::NO_COOL_OFF`] + /// + /// 和 `/wda/tap` 一样不等点击引起的动画结束,调用方要看结果就再截图 + pub async fn tap(&mut self, x: f64, y: f64) -> Result<()> { + self.quick_gesture(&tap_steps(x, y, TAP_PRESS_MS), IdleSettings::NO_COOL_OFF).await + } + + /// 依次点几个点,一个手势([`tap_sequence_body`]):同一个键盘、键盘上连按时用。分开点每下都要等界面空闲, + /// 数字键盘上点 7 个键约 3.6 秒,一个手势约 1.9 秒。点的过程中界面变了(跳了页面)后面的点也照样点下去, + /// 所以只给点的时候布局不变的一串点用 + pub async fn tap_sequence(&mut self, points: &[(f64, f64)]) -> Result<()> { + let body = tap_sequence_body(points, TAP_PRESS_MS, SEQUENCE_GAP_MS); + self.quick_actions(body, IdleSettings::NO_COOL_OFF).await + } + + /// 同一点连点 `count` 下(双击、「短时间内连点 N 下」的隐藏入口),一个 actions 手势,每下之间停 + /// [`MULTI_TAP_GAP_MS`]。分开点每下都要等界面空闲(约 0.6 秒),`iphone_batch` 连点 5 下约 2.9 秒,赶不上这类入口的时间窗 + pub async fn multi_tap(&mut self, x: f64, y: f64, count: u32) -> Result<()> { + let steps = multi_tap_steps(x, y, count, TAP_PRESS_MS, MULTI_TAP_GAP_MS); + self.quick_gesture(&steps, IdleSettings::NO_COOL_OFF).await + } + + /// 长按:按下、停 `seconds` 秒、抬起,一个 actions 手势。`/wda/touchAndHold` 前后都等界面空闲, + /// 真机上主屏长按图标 1.2 秒要约 12 秒才返回。等待设置同 [`Self::tap`] + pub async fn touch_and_hold(&mut self, x: f64, y: f64, seconds: f64) -> Result<()> { + self.quick_gesture(&tap_steps(x, y, (seconds * 1000.0) as u64), IdleSettings::NO_COOL_OFF).await + } + + /// 滑动:一个 actions 手势,期间用 [`IdleSettings::NO_COOL_OFF`]。做完时列表可能还在惯性滚动, + /// 要看结果的调用方自己等界面稳定 + pub async fn swipe(&mut self, from: (f64, f64), to: (f64, f64), ms: u64) -> Result<()> { + self.quick_gesture(&swipe_steps(from, to, ms), IdleSettings::NO_COOL_OFF).await + } + + /// The MJPEG stream (the live viewer) at up to [`MJPEG_FPS`] frames a second instead of WDA's 10, at full size + /// ([`MJPEG_SCALE`], why not smaller) and never turned upright, set with each new session: the picture follows a + /// drag closely. In landscape the frames stay portrait with the content sideways (on an iPhone; an iPad's are + /// already landscape) and the viewer page turns them by the interface rotation, as it does the phone's own video: + /// `mjpegFixOrientation` makes WDA decode, rotate and re-encode every frame, 92 % of a core on an iPhone 15 Pro Max + /// in landscape, and iOS killed it within two minutes. WDA only captures while a client is connected + pub fn fast_stream(&mut self) { + self.fast_stream = true; + } + + /// Swipes and stays in polling mode for the caller, who ends it with [`Self::end_polling`]: restoring the settings + /// only to change them again right after would cost two round trips + /// `hold_ms` > 0 holds the finger still at `from` first ([`drag_steps`]) + pub async fn swipe_into_polling(&mut self, from: (f64, f64), to: (f64, f64), hold_ms: u64, ms: u64) -> Result<()> { + self.baseline().await.map_err(WdaError::before_input)?; + self.set_idle_settings(IdleSettings::NO_COOL_OFF).await.map_err(WdaError::before_input)?; + let r = self.actions(&drag_steps(from, to, hold_ms, ms)).await; + if r.is_err() { + self.end_polling().await; + } + r + } + + /// 开始轮询界面:读元素树时不等界面空闲、动画冷却(约 0.2 秒一次),由调用方比较前后两次判断稳定。 + /// 用完调 [`Self::end_polling`] 恢复 + pub async fn begin_polling(&mut self) -> Result<()> { + self.baseline().await?; + self.set_idle_settings(IdleSettings::NO_COOL_OFF).await + } + + pub async fn end_polling(&mut self) { + let b = self.idle_baseline.unwrap_or(IdleSettings::DEFAULT); + if let Err(e) = self.set_idle_settings(b).await { + tracing::warn!( + "{}", + ictl_l10n::log_trf!( + "轮询后恢复 WDA 等待设置失败:{e}", + "Restoring the WDA wait settings after polling failed: {e}" + ) + ); + } + } + + /// 平时的等待设置(第一次用时读一次)。临时调小、改回之前都按它恢复 + pub async fn baseline(&mut self) -> Result { + if let Some(b) = self.idle_baseline { + return Ok(b); + } + // 上次没恢复成功的话读到的就是调小的值:按 WDA 默认值算 + let b = match self.idle_settings().await? { + s if s == IdleSettings::QUICK || s == IdleSettings::NO_COOL_OFF => IdleSettings::DEFAULT, + s => s, + }; + self.idle_baseline = Some(b); + Ok(b) + } + + /// 发一个手势,期间把等待设置临时换成 `during`(见 [`Self::tap`]),做完恢复 + pub(super) async fn quick_gesture(&mut self, steps: &[PointerStep], during: IdleSettings) -> Result<()> { + self.quick_actions(actions_body(steps), during).await + } + + pub(super) async fn quick_actions(&mut self, body: Value, during: IdleSettings) -> Result<()> { + let baseline = self.baseline().await.map_err(WdaError::before_input)?; + self.set_idle_settings(during).await.map_err(WdaError::before_input)?; + let r = self.post("/actions", body).await.map(drop); + if let Err(e) = self.set_idle_settings(baseline).await { + tracing::warn!( + "{}", + ictl_l10n::log_trf!( + "手势后恢复 WDA 等待设置失败:{e}", + "Restoring the WDA wait settings after the gesture failed: {e}" + ) + ); + } + r + } + + /// 一次 W3C actions 请求。注意:多次点击合并成一个请求会漏键,解锁时每位单独发 + pub async fn actions(&mut self, steps: &[PointerStep]) -> Result<()> { + self.post("/actions", actions_body(steps)).await.map(drop) + } + + /// home / volumeUp / volumeDown,走 XCTest 的 `XCUIDevice pressButton`。 + /// iPhone 12 mini(iOS 26.4.1)上 home 不起作用但照样报成功,见 [`Self::press_home_hid`] + pub async fn press_button(&mut self, name: &str) -> Result<()> { + self.post("/wda/pressButton", json!({"name": name})).await.map(drop) + } + + /// 直接发一个 IOHID 按键事件(`/wda/performIoHidEvent`),按住 `seconds` 秒 + pub async fn hid_event(&mut self, page: u32, usage: u32, seconds: f64) -> Result<()> { + self.post("/wda/performIoHidEvent", json!({"page": page, "usage": usage, "duration": seconds})).await.map(drop) + } + + /// 经 IOHID 按 Home(消费者页 AC Home)。iPhone 12 mini(iOS 26.4.1)实测:XCTest 的 home 无效时 + /// 它能从 App 回到主屏、关掉 Spotlight、点亮熄灭的屏幕;同页的 Menu(0x40)没反应 + pub async fn press_home_hid(&mut self) -> Result<()> { + self.hid_event(HID_PAGE_CONSUMER, HID_AC_HOME, 0.05).await + } + + /// 经 IOHID 短按电源键([`POWER_PRESS_SECS`],和手指按一下差不多)。WDA 自己的 `/wda/lock` 在 iOS 27 上按住 0.5 秒, + /// iOS 27 以下用 XCTest 的 `pressLockButton`,iPhone 12 mini(iOS 26.4.1)、iPad mini 5(iPadOS 26.7.3)上锁不了屏。 + /// 屏幕已熄灭时按它会把屏幕点亮,调用方要先确认没锁屏 + pub async fn press_power_hid(&mut self) -> Result<()> { + self.hid_event(HID_PAGE_CONSUMER, HID_POWER, POWER_PRESS_SECS).await + } + + pub async fn lock(&mut self) -> Result<()> { + self.post("/wda/lock", json!({})).await.map(drop) + } + + /// 启动并等到前台、界面稳定(冷启动后立即点击会被吞),最多等 8 秒。 + /// 等待期间查前台出错不算失败(启动命令已经成功了) + pub async fn launch_app(&mut self, bundle_id: &str) -> Result { + let started = tokio::time::Instant::now(); + // 不经 XCTest 启动(LSApplicationWorkspace),发出就返回,到没到前台由下面自己查。`/wda/apps/launch` 要等 XCTest + // 看到 App 在前台:系统 App 第一次打开时隐私说明页盖在上面,它就一直等到 60 秒超时,WDA 也被判卡死重启 + // (iPhone 12 mini,iOS 26.4.1,「备忘录」「提醒事项」都是 65 秒)。这时它回「failed to launch」,说明页已经出来了 + let body = json!({"bundleId": bundle_id}); + match self.call("POST", "/wda/apps/launchUnattached", Some(body.clone()), DEFAULT_TIMEOUT).await { + Ok(_) => {} + Err(WdaError::Remote { message, .. }) if message.contains("failed to launch") => {} + // older WDA without the route: launch as before + Err(WdaError::Remote { kind, message }) if unknown_route(&kind, &message) => { + self.in_session("POST", "/wda/apps/launch", Some(body), Duration::from_secs(60)).await?; + } + Err(e) => return Err(e), + } + let t0 = tokio::time::Instant::now(); + let deadline = t0 + Duration::from_secs(8); + let mut foreground = false; + while tokio::time::Instant::now() < deadline { + match self.active_app().await { + Ok(a) if a == bundle_id => { + foreground = true; + break; + } + Ok(a) if a == PRIVACY_SHEET => { + return Ok(Launch::Blocked( + ictl_l10n::tr!( + "第一次打开时的隐私说明页(点「继续」或「接受并继续」后才进入 App)", + "the privacy notice shown on first launch (tap Continue or Accept & Continue to get into the app)" + ) + .into(), + )); + } + // 系统弹窗(权限请求)挡着时前台一直是 SpringBoard,原来要白等满 8 秒。 + // 刚启动的一瞬间前台也还是 SpringBoard,过 1 秒还是才去查弹窗(查一次约 0.4 秒) + Ok(a) if a == SPRINGBOARD && bundle_id != SPRINGBOARD && t0.elapsed() >= Duration::from_secs(1) => { + if let Ok(Some(text)) = self.alert_text().await { + return Ok(Launch::Blocked(text)); + } + } + _ => {} + } + tokio::time::sleep(Duration::from_millis(500)).await; + } + if !foreground { + return Ok(match self.alert_text().await { + Ok(Some(text)) => Launch::Blocked(text), + _ => Launch::Slow, + }); + } + self.settle_launched(started).await; + Ok(Launch::Foreground) + } + + /// App 到了前台之后再等它画出来。`started`:发出启动请求的时刻 + pub(super) async fn settle_launched(&mut self, started: tokio::time::Instant) { + // 冷启动后立即点击会被吞(回归用例 #13)。原来固定再等 1 秒;改为等界面稳定:连续两次元素树一样 + // (读元素树时 WDA 本身也等界面空闲),最多仍是 1 秒 + let deadline = tokio::time::Instant::now() + Duration::from_secs(1); + let mut prev = None; + while tokio::time::Instant::now() < deadline { + let cur = self.source_xml().await.ok(); + if cur.is_some() && cur == prev { + break; + } + prev = cur; + } + // 切回已在后台的 App 时元素树马上就稳定了(约 0.4 秒),放大进场的动画还没完,这时点击会被吞(真机:小红书、高德各一次) + if let Some(left) = LAUNCH_MIN.checked_sub(started.elapsed()) { + tokio::time::sleep(left).await; + } + } + + pub async fn terminate_app(&mut self, bundle_id: &str) -> Result<()> { + self.post("/wda/apps/terminate", json!({"bundleId": bundle_id})).await.map(drop) + } + + /// 打开网址或 URL Scheme,等打开它的 App 到前台、画出来再返回(最多约 8 秒),同 [`Self::launch_app`]。 + /// 不等的话 App 冷启动时还是黑屏,紧接着截图会把两帧黑屏当成「画面已静止」(iPad Safari 真机)。 + /// 返回结果和前台 App;在原来的前台 App 里打开(Safari 里开网址)时等 1 秒没换就算打开了 + pub async fn open_url(&mut self, url: &str) -> Result<(Launch, String)> { + let started = tokio::time::Instant::now(); + let before = self.active_app().await.unwrap_or_default(); + self.in_session("POST", "/url", Some(json!({"url": url})), Duration::from_secs(60)).await?; + let deadline = started + Duration::from_secs(8); + // 前台要连续两次是同一个才算:Safari 冷启动的一瞬间前台是 `com.apple.DocumentManager.DockFolderViewService`(iPad 真机) + let mut last = String::new(); + loop { + tokio::time::sleep(Duration::from_millis(300)).await; + let waited = started.elapsed() >= Duration::from_secs(1); + let now = self.active_app().await; + let steady = now.as_ref().is_ok_and(|a| *a == last); + if let Ok(a) = &now { + last.clone_from(a); + } + match now { + Ok(a) if a != before && a != SPRINGBOARD && steady => { + self.settle_launched(started).await; + return Ok((Launch::Foreground, a)); + } + Ok(a) if a == before && a != SPRINGBOARD && waited => { + self.settle_launched(started).await; + return Ok((Launch::Foreground, a)); + } + // 「要在某 App 中打开吗」之类的系统弹窗挡着时前台一直是 SpringBoard + Ok(a) if a == SPRINGBOARD && waited => { + if let Ok(Some(text)) = self.alert_text().await { + return Ok((Launch::Blocked(text), a)); + } + } + _ => {} + } + if tokio::time::Instant::now() >= deadline { + let now = self.active_app().await.unwrap_or_default(); + return Ok((Launch::Slow, now)); + } + } + } +} diff --git a/crates/ictl-wda/src/client/screen.rs b/crates/ictl-wda/src/client/screen.rs new file mode 100644 index 0000000..b460dde --- /dev/null +++ b/crates/ictl-wda/src/client/screen.rs @@ -0,0 +1,340 @@ +//! [`WdaClient`]: What is on the screen: size, rotation, lock state, the element tree, screenshots, alerts, the keyboard + +use super::*; + +impl WdaClient { + /// Read the WDA screen size again, including changes to Display Zoom. + pub async fn measure_screen(&mut self) -> Result { + let v = self.get("/wda/screen").await?; + let s = &v["screenSize"]; + let positive = |key: &str| s[key].as_f64().filter(|n| n.is_finite() && *n > 0.0); + let size = positive("width") + .zip(positive("height")) + .map(|(width, height)| ScreenSize { width, height }) + .ok_or_else(|| { + WdaError::Unavailable(ictl_l10n::tr!("/wda/screen 尺寸无效", "Invalid /wda/screen dimensions").into()) + })?; + self.screen = Some(size); + self.screen_at = Some(Instant::now()); + Ok(size) + } + + pub async fn base_screen_size(&mut self) -> Result { + match self.screen { + Some(s) => Ok(s), + None => self.measure_screen().await, + } + } + + /// 当前方向下的屏幕点尺寸(转屏后宽高跟着变) + pub async fn screen_size(&mut self) -> Result { + Ok(self.view().await?.screen) + } + + /// 当前方向下的屏幕尺寸和方向。尺寸只问一次 `/wda/screen`(约 0.3 秒),方向每次问(约 20 毫秒): + /// 尺寸缓存的是问的那一刻的方向,转屏后不换算的话截图会被压扁、屏幕下半截的元素被当成屏幕外。 + /// 问不到方向(旧版 WDA 等)就按缓存的尺寸、方向未知(不换算元素坐标) + pub async fn view(&mut self) -> Result { + let base = self.base_screen_size().await?; + Ok(match self.orientation().await { + Ok(o) => elements::View { screen: o.orient(base), orientation: Some(o) }, + Err(e) => { + tracing::debug!( + "{}", + ictl_l10n::log_trf!( + "读屏幕方向失败,按缓存的屏幕尺寸算:{e}", + "Reading the screen orientation failed, using the cached screen size: {e}" + ) + ); + elements::View { screen: base, orientation: None } + } + }) + } + + /// 界面相对设备竖放转了多少(`GET /rotation` 的 z)。能分出两个横屏方向,`/orientation` 分不出 + pub async fn rotation(&mut self) -> Result { + let v = self.in_session("GET", "/rotation", None, Duration::from_secs(10)).await?; + v["z"].as_f64().and_then(ictl_device::Rotation::from_degrees).ok_or_else(|| { + WdaError::Unavailable(ictl_l10n::trf!( + "看不懂 WDA 给的旋转角:{v}", + "Can't make sense of the rotation WDA reported: {v}" + )) + }) + } + + /// Older WDA versions lack /rotation. Remember an unsupported route for this runner; + /// the regular /orientation endpoint folds opposite directions into the same string. + pub(super) async fn interface_rotation( + &mut self, + fallback: impl Future>, + ) -> Option { + if !self.rotation_unsupported { + match self.rotation().await { + Ok(r) => return Some(r), + Err(WdaError::Remote { kind, message }) + if matches!(kind.as_str(), "unknown command" | "unknown method" | "unsupported operation") + || (kind == "http" && matches!(message.as_str(), "404" | "405")) => + { + self.rotation_unsupported = true; + } + Err(_) => return None, + } + } + fallback.await + } + + /// Poll rotation to detect a changed view. The screen size (a slower request) is measured on acquisition and on + /// rotation, and again once the last measurement is older than [`SCREEN_RECHECK`] (Display Zoom) when + /// `refresh_stale`: a poll while nobody acts, never a gesture's start, which costs only the rotation request. + pub async fn display_sample( + &mut self, + previous: Option, + refresh_stale: bool, + fallback: impl Future>, + ) -> (Option, Option) { + let rotation = self.interface_rotation(fallback).await; + let stale = self.screen_at.is_none_or(|t| t.elapsed() >= SCREEN_RECHECK); + let rotated = rotation.is_some_and(|r| Some(r.degrees()) != previous); + let size = if rotated || (refresh_stale && stale) { + self.measure_screen().await + } else { + self.base_screen_size().await + }; + (size.ok().map(ScreenSize::portrait), rotation) + } + + /// 前台界面的方向 + pub async fn orientation(&mut self) -> Result { + let v = self.in_session("GET", "/orientation", None, Duration::from_secs(10)).await?; + v.as_str().and_then(elements::Orientation::from_wda).ok_or_else(|| { + WdaError::Unavailable(ictl_l10n::trf!( + "看不懂 WDA 给的方向:{v}", + "Can't make sense of the orientation WDA reported: {v}" + )) + }) + } + + /// 是否锁屏。WDA 的 `/wda/locked` 只靠 `com.apple.springboard.lockstate` 的变化通知维护 + /// (WebDriverAgent `XCUIDevice+FBHelpers.m`),有两处误报,用元素树纠正([`elements::cover_sheet`]): + /// - 初值为 false:WDA 在手机锁着时启动就一直报未锁屏,直到下一次锁屏/解锁。确认过一次「确实没锁屏」之后 + /// WDA 就跟上了,此后它说没锁就直接信,不多发请求 + /// - 下拉通知中心时报 true(和锁屏同一个界面):WDA 说锁了时核对一次,是通知中心就算没锁 + /// + /// 核对失败时按 WDA 的结果;需要「拿不准就算锁着」时用 [`Self::check_lock`] 的 strict 模式 + pub async fn locked(&mut self) -> Result { + Ok(self.check_lock(None, false).await?.locked) + } + + /// 锁屏判断,并带回核对时取到的元素树(解锁流程接着用,省一次 `/source`)。 + /// - `reported`:调用方刚问过的 `/wda/locked`,省一次请求 + /// - `strict`:拿不准就算锁着。确认整串密码是否解开时用:把仍锁着误判成已解锁,下一次会把同一个错误密码再输一遍 + pub async fn check_lock(&mut self, reported: Option, strict: bool) -> Result { + let wda_locked = match reported { + Some(v) => v, + None => self.wda_reports_locked().await?, + }; + if self.lock_state_trusted && (!wda_locked || strict) { + // 已同步过:WDA 说没锁就是没锁;strict 场景在密码键盘上,WDA 说锁了也不会是通知中心 + return Ok(LockCheck { locked: wda_locked, uncertain: false, tree: None }); + } + let (sheet, tree) = match self.cover_tree().await { + Ok(x) => x, + Err(e) => { + tracing::debug!( + "{}", + ictl_l10n::log_trf!( + "核对锁屏界面失败,按{}处理:{e}", + "Checking the lock screen failed, going by {}: {e}", + if strict { + ictl_l10n::tr!("锁着", "locked") + } else { + ictl_l10n::tr!(" WDA 的结果", "what WDA reported") + } + ) + ); + return Ok(LockCheck { locked: strict || wda_locked, uncertain: false, tree: None }); + } + }; + let (locked, uncertain) = match (wda_locked, sheet) { + (true, elements::CoverSheet::NotificationCenter) => (false, false), + (true, _) => (true, false), + (false, elements::CoverSheet::Locked) => { + tracing::info!( + "{}", + ictl_l10n::log_tr!( + "WDA 报未锁屏,但屏幕上是锁屏界面(WDA 在锁屏时启动,状态未同步)", + "WDA says unlocked, but the screen shows the lock screen (WDA started while locked and its state is stale)" + ) + ); + (true, false) + } + // 锁屏样式、却没有锁的标记:可能是通知中心,也可能是 Touch ID 机型熄屏、有通知时的锁屏 + // (iPad mini 5 / iPadOS 26.6.1 真机:没有「按下主屏幕按钮以解锁」那行)。WDA 在锁屏时启动的话一直报 false, + // 不能在这里认定它可信,否则之后再也不核对、永远不会自动解锁 + // 严格核对时拿不准就算锁着(同 `strict` 的说明) + (false, elements::CoverSheet::NotificationCenter) => (strict, !strict), + // 普通界面上确认过一次:WDA 的状态是同步的 + (false, elements::CoverSheet::None) => { + self.lock_state_trusted = true; + (false, false) + } + }; + Ok(LockCheck { locked, uncertain, tree }) + } + + /// WDA 自己报的锁屏状态,不核对。可能误报,见 [`Self::locked`];配合 [`Self::lock_state_trusted`] 做快速判断 + pub async fn wda_reports_locked(&self) -> Result { + Ok(self.call("GET", "/wda/locked", None, Duration::from_secs(10)).await?["value"] == true) + } + + /// 本次 WDA 启动后是否确认过一次没锁屏。确认过且 WDA 说没锁,就确定没锁 + pub fn lock_state_trusted(&self) -> bool { + self.lock_state_trusted + } + + /// 前台是 SpringBoard 时看元素树是锁屏、通知中心还是普通界面,并带回元素树;前台是别的 App 就是普通界面 + pub(super) async fn cover_tree(&mut self) -> Result<(elements::CoverSheet, Option)> { + if self.active_app().await? != SPRINGBOARD { + return Ok((elements::CoverSheet::None, None)); + } + let xml = self.source_xml().await?; + Ok((elements::cover_sheet(&xml), Some(xml))) + } + + pub async fn active_app(&self) -> Result { + Ok(self.get("/wda/activeAppInfo").await?["bundleId"].as_str().unwrap_or_default().to_owned()) + } + + pub async fn screenshot_png(&self) -> Result> { + // base64 约 11MB:从 JSON 里直接拿走字符串,原地去掉换行,不再另外复制 + let Value::String(mut b64) = self.get("/screenshot").await? else { + return Err(WdaError::Unavailable( + ictl_l10n::tr!("截图响应不是字符串", "screenshot response is not a string").into(), + )); + }; + b64.retain(|c| !c.is_whitespace()); + base64::engine::general_purpose::STANDARD.decode(b64).map_err(|e| { + WdaError::Unavailable(ictl_l10n::trf!("截图不是有效的 base64:{e}", "screenshot is not valid base64: {e}")) + }) + } + + /// 元素树 XML,排除可见性等慢属性(完整树 7~8 秒,排除后约 0.3 秒)。读得慢就收紧快照上限([`SnapshotLimits`]) + pub async fn source_xml(&mut self) -> Result { + let level = self.snapshot_level; + if self.snapshot_applied.unwrap_or(0) != level { + let l = SNAPSHOT_LEVELS[level]; + let body = json!({"settings": { + "snapshotMaxDepth": l.depth, + "snapshotMaxChildren": l.children.unwrap_or(i32::MAX as u32), + }}); + // 设不上照样读,下次再设 + match self.post("/appium/settings", body).await { + Ok(_) => self.snapshot_applied = Some(level), + Err(e) => tracing::debug!("snapshot limits: {e}"), + } + } + let applied = self.snapshot_applied.unwrap_or(0); + let path = format!("/source?format=xml&excluded_attributes={}", elements::SOURCE_EXCLUDED); + let t0 = Instant::now(); + let r = self.call("GET", &path, None, SOURCE_TIMEOUT).await; + let took = match r { + Ok(_) => Some(t0.elapsed()), + Err(WdaError::Timeout(_)) => None, + Err(e) => return Err(e), + }; + let next = next_snapshot_level(applied, took); + if next != applied { + tracing::info!( + "{}", + ictl_l10n::log_trf!( + "读元素树{},快照上限改为 {:?}", + "Reading the element tree {}; snapshot limits now {:?}", + took.map_or_else( + || ictl_l10n::log_tr!("超时", "timed out").to_owned(), + |t| ictl_l10n::log_trf!("用了 {:.1} 秒", "took {:.1} s", t.as_secs_f64()) + ), + SNAPSHOT_LEVELS[next] + ) + ); + } + self.snapshot_level = next; + let v = r?; + self.snapshot_read = applied; + Ok(v["value"].as_str().unwrap_or_default().to_owned()) + } + + /// 上一次读到的元素树受了快照上限([`SnapshotLimits`])的限制时,给人和 agent 看的说明 + pub fn snapshot_note(&self) -> Option { + let l = SNAPSHOT_LEVELS[self.snapshot_read]; + let children = l.children?; + Some(ictl_l10n::trf!( + "(界面元素太多、读得慢,这次只读了 {} 层、每个元素最多 {children} 个子元素:长列表靠后的行、很深的元素可能没列出;读得快了会自动放宽)", + "(This screen has so many elements that reading them was slow, so this read went {} levels deep with at most {children} children per element: rows far down a long list or deeply nested elements may be missing; the limits loosen again once reads are fast)", + l.depth + )) + } + + pub async fn elements(&mut self) -> Result> { + Ok(self.tree().await?.elements) + } + + /// 元素树,带上「谁盖住谁」「有没有加载圈」等信息 + pub async fn tree(&mut self) -> Result { + let view = self.view().await?; + self.move_detection_point(view.screen).await; + let mut tree = elements::parse_tree(&self.source_xml().await?, view); + tree.incomplete |= SNAPSHOT_LEVELS[self.snapshot_read].children.is_some(); + Ok(tree) + } + + /// 把 WDA 判断前台 App 的点(appium setting `activeAppDetectionPoint`)挪到 [`detection_point`],每个客户端做一次。 + /// + /// WDA 读元素树、问前台 App 时,看屏幕上这个点下面的元素属于哪个进程。默认点在离左上角短边 20% 的地方 + /// (WDA 16.15.3 `FBActiveAppDetectionPoint`,430 点宽的 iPhone 上是 (86, 86)),正好在通知横幅底下:横幅弹着时 + /// 读到的是 SpringBoard 的树,按名字点 App 里的按钮就找不到(iPhone16,2 / iOS 27.2.1 的备忘录,「Device Hub」横幅)。 + /// 设不上不影响读树,只是还用默认的点;连不上 WDA 时下次再试 + pub(super) async fn move_detection_point(&mut self, screen: ScreenSize) { + if self.detection_point_set { + return; + } + let (x, y) = detection_point(screen); + let body = json!({"settings": {"activeAppDetectionPoint": format!("{x},{y}")}}); + match self.post("/appium/settings", body).await { + Ok(_) => self.detection_point_set = true, + Err(e) => { + tracing::debug!("activeAppDetectionPoint: {e}"); + self.detection_point_set = !matches!(e, WdaError::Unavailable(_)); + } + } + } + + /// 屏幕上的系统弹窗(定位权限、通知权限等)的文字;没有弹窗返回 None。 + /// 弹窗挡着时 Home 不生效、App 也到不了前台,WDA 却照样报成功 + pub async fn alert_text(&mut self) -> Result> { + match self.in_session("GET", "/alert/text", None, DEFAULT_TIMEOUT).await { + Ok(v) => Ok(v.as_str().map(str::to_owned).filter(|t| !t.is_empty())), + Err(WdaError::Remote { kind, .. }) if kind.contains("alert") => Ok(None), + Err(e) => Err(e), + } + } + + /// 屏幕上有没有软键盘(有输入框获得了焦点)。`/wda/keys` 在没有焦点时也返回成功,什么都没输进去 + pub async fn keyboard_shown(&mut self) -> Result { + let v = self.post("/elements", json!({"using": "class name", "value": "XCUIElementTypeKeyboard"})).await?; + Ok(v.as_array().is_some_and(|a| !a.is_empty())) + } + + /// 锁屏密码栏的 (总位数, 已输入位数);找不到密码栏返回 None + pub async fn passcode_field(&mut self) -> Result> { + let els = + self.post("/elements", json!({"using": "class name", "value": "XCUIElementTypeSecureTextField"})).await?; + for e in els.as_array().into_iter().flatten() { + let Some(eid) = e.as_object().and_then(|o| o.values().next()).and_then(|v| v.as_str()) else { continue }; + let v = self.in_session("GET", &format!("/element/{eid}/attribute/value"), None, DEFAULT_TIMEOUT).await?; + if let Some(p) = v.as_str().and_then(elements::parse_passcode_value) { + return Ok(Some(p)); + } + } + Ok(None) + } +} diff --git a/crates/ictl-wda/src/client/session.rs b/crates/ictl-wda/src/client/session.rs new file mode 100644 index 0000000..8e16800 --- /dev/null +++ b/crates/ictl-wda/src/client/session.rs @@ -0,0 +1,248 @@ +//! [`WdaClient`]: The transport, the XCTest session, stall detection and the idle-wait settings + +use super::*; + +impl WdaClient { + pub fn new(transport: T) -> Self { + Self { + transport, + session: None, + screen: None, + screen_at: None, + rotation_unsupported: false, + lock_state_trusted: false, + idle_baseline: None, + idle_current: None, + fast_stream: false, + unanswered: AtomicU32::new(0), + snapshot_level: 0, + snapshot_applied: None, + snapshot_read: 0, + detection_point_set: false, + } + } + + pub(super) async fn call(&self, method: &str, path: &str, body: Option, timeout: Duration) -> Result { + self.call_or_abandon(method, path, body, timeout, None).await + } + + /// [`Self::call`];`abandon` 是会话号时,请求没有应答就先结束这个会话,再判断 WDA 是不是卡死了(见 [`Self::in_session`]) + pub(super) async fn call_or_abandon( + &self, + method: &str, + path: &str, + body: Option, + timeout: Duration, + abandon: Option<&str>, + ) -> Result { + // `/status` 不经 XCTest:WDA 半死时它照样应答,不能拿它算 WDA 还活着 + if path == "/status" { + return self.send(method, path, body, timeout).await; + } + // 已判定卡死:不再发、不再一次次等超时(一个工具调用里接连几个请求,每个都等满时限的话, + // 设备会被占好几分钟,守护进程没机会重启 WDA) + if let Some(reason) = self.stall_reason() { + let why = reason.describe(); + return Err(WdaError::Unavailable(ictl_l10n::trf!( + "WDA 卡死判定:{why},等守护进程重启它", + "WDA is considered stuck: {why}; waiting for the daemon to restart it" + ))); + } + let r = self.send(method, path, body, timeout).await; + match &r { + Err(e) if e.no_answer() => { + if let Some(sid) = abandon { + self.delete_session(sid).await; + } + let n = self.unanswered.fetch_add(1, Ordering::Relaxed) + 1; + // 长请求未应答,补一次短探测;保留实际计数,不把两个请求写成三次无应答。 + if n < STALL_LIMIT && timeout > XCTEST_PROBE_TIMEOUT { + match self.send("GET", "/wda/activeAppInfo", None, XCTEST_PROBE_TIMEOUT).await { + Err(p) if p.no_answer() => { + self.unanswered.store((n + 1) | UNANSWERED_PROBE, Ordering::Relaxed); + } + reply if answered(&reply) => self.unanswered.store(0, Ordering::Relaxed), + _ => {} + } + } + } + _ if answered(&r) => self.unanswered.store(0, Ordering::Relaxed), + _ => {} + } + r + } + + /// 连续三次无应答,或长请求和其短探测均无应答时,后续请求不再发送,等待守护进程恢复。 + pub fn stalled(&self) -> bool { + self.stall_reason().is_some() + } + + /// 读取一致的计数与判定原因;`/status` 的响应不参与此状态。 + pub fn stall_reason(&self) -> Option { + let state = self.unanswered.load(Ordering::Relaxed); + if state & UNANSWERED_PROBE != 0 { + Some(StallReason::LongRequestAndProbe) + } else if state >= STALL_LIMIT { + Some(StallReason::ConsecutiveRequests(state)) + } else { + None + } + } + + /// 实际连续无应答次数,不含判定标记。 + pub fn unanswered(&self) -> u32 { + self.unanswered.load(Ordering::Relaxed) & !UNANSWERED_PROBE + } + + pub(super) async fn send(&self, method: &str, path: &str, body: Option, timeout: Duration) -> Result { + let body = body.map(|b| b.to_string().into_bytes()); + let (status, raw) = self.transport.send(method, path, body, timeout).await.map_err(|e| match e.kind() { + std::io::ErrorKind::TimedOut => WdaError::Timeout(e.to_string()), + crate::http::WRITE_FAILED if acts(method, path) => WdaError::Write(e.to_string()), + crate::http::AFTER_SENT => WdaError::Interrupted(e.to_string()), + _ => WdaError::Unavailable(e.to_string()), + })?; + let v: Value = match serde_json::from_slice(&raw) { + Ok(v) => v, + Err(_) if status >= 400 => { + return Err(WdaError::Remote { kind: "http".into(), message: status.to_string() }); + } + Err(e) => { + return Err(WdaError::Interrupted(ictl_l10n::trf!("响应不是 JSON:{e}", "response is not JSON: {e}"))); + } + }; + if let Some(err) = v.get("value").and_then(|x| x.get("error")).and_then(|e| e.as_str()) { + let msg = v["value"].get("message").and_then(|m| m.as_str()).unwrap_or_default(); + return Err(WdaError::Remote { + kind: err.to_owned(), + message: msg.lines().next().unwrap_or_default().to_owned(), + }); + } + // Older runners may return a JSON 404 without a W3C value.error. + if status >= 400 { + return Err(WdaError::Remote { kind: "http".into(), message: status.to_string() }); + } + Ok(v) + } + + pub(super) async fn get(&self, path: &str) -> Result { + Ok(self.call("GET", path, None, DEFAULT_TIMEOUT).await?["value"].take()) + } + + pub(super) async fn session_id(&mut self) -> Result { + if let Some(s) = &self.session { + return Ok(s.clone()); + } + let r = + self.call("POST", "/session", Some(json!({"capabilities": {"alwaysMatch": {}}})), DEFAULT_TIMEOUT).await?; + let id = r + .get("sessionId") + .and_then(|s| s.as_str()) + .or_else(|| r["value"].get("sessionId").and_then(|s| s.as_str())) + .ok_or_else(|| { + WdaError::Unavailable( + ictl_l10n::tr!("创建会话没有返回 sessionId", "creating a session returned no sessionId").into(), + ) + })? + .to_owned(); + self.session = Some(id.clone()); + self.idle_current = None; + self.snapshot_applied = Some(0); + if self.fast_stream { + // fixOrientation explicitly off: a WDA left running in the background keeps what an + // older version set + let settings = json!({ + "mjpegServerFramerate": MJPEG_FPS, + "mjpegScalingFactor": MJPEG_SCALE, + "mjpegFixOrientation": false, + }); + let path = format!("/session/{id}/appium/settings"); + if let Err(e) = self.call("POST", &path, Some(json!({"settings": settings})), DEFAULT_TIMEOUT).await { + tracing::debug!("MJPEG settings: {e}"); + } + } + Ok(id) + } + + /// 带会话的请求;会话失效时重建一次再试。 + /// + /// 改变手机状态的请求([`acts`])没有应答时,马上结束这个会话(`DELETE /session/:id`,WDA 16.15.3 不排队处理它): + /// WDA 在主线程上一个一个处理请求,我们不等了它还会接着做。排在慢请求后面的点击、滑动会在报了失败之后很久才落到屏幕上 + /// (Poki 在真机上见过)。结束会话后,这个会话里还在排队的请求 WDA 直接回「会话不存在」,不再执行;正在执行的那个照样做完。 + /// 下一个请求开新会话 + pub async fn in_session( + &mut self, + method: &str, + path: &str, + body: Option, + timeout: Duration, + ) -> Result { + for attempt in 0..2 { + let input = acts(method, path); + let sid = self.session_id().await.map_err(|e| if input { e.before_input() } else { e })?; + let abandon = input.then_some(sid.as_str()); + let r = + self.call_or_abandon(method, &format!("/session/{sid}{path}"), body.clone(), timeout, abandon).await; + match r { + Err(WdaError::Remote { kind, .. }) if attempt == 0 && kind == "invalid session id" => { + self.session = None + } + Err(e) if abandon.is_some() && e.no_answer() => { + self.forget_session(); + return Err(e); + } + other => return other.map(|mut v| v["value"].take()), + } + } + unreachable!() + } + + /// 结束会话,不管结果:结束不了的会话 WDA 下次开会话时也会结束它 + pub(super) async fn delete_session(&self, sid: &str) { + // send 而不是 call:WDA 卡死时也要发,也不算进卡死计数 + if let Err(e) = self.send("DELETE", &format!("/session/{sid}"), None, SESSION_DELETE_TIMEOUT).await { + tracing::debug!("DELETE /session/{sid}: {e}"); + } + } + + /// 会话已经结束(或要当作结束):下一个请求开新会话,WDA 那时把设置重置成默认 + pub(super) fn forget_session(&mut self) { + self.session = None; + self.idle_current = None; + } + + pub(super) async fn post(&mut self, path: &str, body: Value) -> Result { + self.in_session("POST", path, Some(body), DEFAULT_TIMEOUT).await + } + + pub async fn ready(&self) -> Result { + Ok(self.call("GET", "/status", None, Duration::from_secs(5)).await?["value"]["ready"] == true) + } + + /// WDA 还能不能经 XCTest 办事:问一次前台 App,限时 [`XCTEST_PROBE_TIMEOUT`]。 + /// `/status` 不经 XCTest,WDA 半死(iPad 真机:`/status` 照常 200,前台 App、截图、读元素、`/wda/locked` 全部超时)时 + /// 它照样报 ready;这一问才看得出来 + pub async fn xctest_responsive(&self) -> Result<()> { + self.call("GET", "/wda/activeAppInfo", None, XCTEST_PROBE_TIMEOUT).await.map(drop) + } + + pub async fn idle_settings(&mut self) -> Result { + let v = self.in_session("GET", "/appium/settings", None, DEFAULT_TIMEOUT).await?; + Ok(IdleSettings { + wait_for_idle_timeout: v["waitForIdleTimeout"].as_f64().unwrap_or(10.0), + animation_cool_off_timeout: v["animationCoolOffTimeout"].as_f64().unwrap_or(2.0), + }) + } + + pub async fn set_idle_settings(&mut self, s: IdleSettings) -> Result<()> { + if self.idle_current == Some(s) { + return Ok(()); + } + // not known if this fails + self.idle_current = None; + let body = json!({"settings": {"waitForIdleTimeout": s.wait_for_idle_timeout, "animationCoolOffTimeout": s.animation_cool_off_timeout}}); + self.post("/appium/settings", body).await?; + self.idle_current = Some(s); + Ok(()) + } +} diff --git a/crates/ictl-wda/src/client/tests.rs b/crates/ictl-wda/src/client/tests.rs new file mode 100644 index 0000000..6a32df9 --- /dev/null +++ b/crates/ictl-wda/src/client/tests.rs @@ -0,0 +1,879 @@ +use super::*; +use std::collections::VecDeque; +use std::sync::Mutex; + +/// 按顺序返回预设响应,并记录收到的请求 +#[derive(Default)] +struct Mock { + replies: Mutex>, + seen: Mutex)>>, +} + +impl Mock { + fn with(replies: &[(u16, &str)]) -> Self { + Self { replies: Mutex::new(replies.iter().map(|(s, b)| (*s, b.to_string())).collect()), ..Default::default() } + } +} + +impl Transport for &Mock { + async fn send( + &self, + method: &str, + path: &str, + body: Option>, + _: Duration, + ) -> std::io::Result<(u16, Vec)> { + self.seen.lock().unwrap().push((method.into(), path.into(), body.map(|b| String::from_utf8(b).unwrap()))); + let (s, b) = self.replies.lock().unwrap().pop_front().ok_or_else(|| std::io::Error::other("连接被拒绝"))?; + Ok((s, b.into_bytes())) + } +} + +#[tokio::test] +async fn display_poll_remeasures_size_only_when_needed() { + let session = (200, r#"{"sessionId":"A"}"#); + let size = (200, r#"{"value":{"screenSize":{"width":393,"height":852}}}"#); + let portrait = (200, r#"{"value":{"z":0}}"#); + let landscape = (200, r#"{"value":{"z":90}}"#); + let m = Mock::with(&[session, portrait, size, portrait, landscape, size, landscape, landscape, landscape, size]); + let mut w = WdaClient::new(&m); + // (previous rotation, a poll that may refresh the size, size older than SCREEN_RECHECK, expected rotation) + for (previous, refresh, stale, expected) in [ + (None, true, false, Rotation::Portrait), + (Some(0), true, false, Rotation::Portrait), + // rotated: measured whatever the caller + (Some(0), false, false, Rotation::TopToRight), + // a touch-down with a recent size: rotation only + (Some(90), false, false, Rotation::TopToRight), + // a touch-down with an old size: still rotation only (0.95 s on an iPad mini 5) + (Some(90), false, true, Rotation::TopToRight), + // a quiet poll with an old size: measured again (Display Zoom) + (Some(90), true, true, Rotation::TopToRight), + ] { + if stale { + w.screen_at = Some(Instant::now() - SCREEN_RECHECK); + } + let (size, rotation) = w.display_sample(previous, refresh, async { panic!("unexpected fallback") }).await; + assert_eq!(rotation, Some(expected)); + assert_eq!(size.unwrap().width, 393.); + } + let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect(); + assert_eq!( + paths, + [ + "/session", + "/session/A/rotation", + "/wda/screen", + "/session/A/rotation", + "/session/A/rotation", + "/wda/screen", + "/session/A/rotation", + "/session/A/rotation", + "/session/A/rotation", + "/wda/screen" + ] + ); +} + +#[tokio::test] +async fn legacy_http_404_is_distinct_from_a_transient_rotation_failure() { + let m = Mock::with(&[ + (200, r#"{"sessionId":"A"}"#), + (500, r#"{"value":"runner busy"}"#), + (200, r#"{"value":{"z":90}}"#), + (404, r#"{"value":{"message":"Unhandled endpoint"}}"#), + ]); + let mut w = WdaClient::new(&m); + assert_eq!(w.interface_rotation(async { panic!("500 is not a missing route") }).await, None); + assert_eq!(w.interface_rotation(async { panic!("supported route") }).await, Some(Rotation::TopToRight)); + assert_eq!(w.interface_rotation(async { Some(Rotation::UpsideDown) }).await, Some(Rotation::UpsideDown)); +} + +#[tokio::test] +async fn legacy_wda_uses_a_fresh_interface_rotation_without_retrying_the_missing_route() { + let m = Mock::with(&[ + (200, r#"{"sessionId":"A"}"#), + (404, r#"{"value":{"error":"unknown command"}}"#), + (200, r#"{"value":{"screenSize":{"width":393,"height":852}}}"#), + ]); + let mut w = WdaClient::new(&m); + let (size, rotation) = w.display_sample(None, false, async { Some(Rotation::UpsideDown) }).await; + assert_eq!(size.unwrap().width, 393.); + assert_eq!(rotation, Some(Rotation::UpsideDown)); + assert_eq!(w.interface_rotation(async { Some(Rotation::TopToLeft) }).await, Some(Rotation::TopToLeft)); + assert_eq!(w.interface_rotation(async { None }).await, None); + assert_eq!(m.seen.lock().unwrap().len(), 3); +} + +#[tokio::test] +async fn session_is_recreated_once_after_invalid_session() { + let m = Mock::with(&[ + (200, r#"{"sessionId":"A","value":{}}"#), + (404, r#"{"value":{"error":"invalid session id","message":"gone\nmore"}}"#), + (200, r#"{"value":{"sessionId":"B"}}"#), + (200, r#"{"value":null}"#), + ]); + let mut c = WdaClient::new(&m); + c.press_button("home").await.unwrap(); + let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect(); + assert_eq!(paths, ["/session", "/session/A/wda/pressButton", "/session", "/session/B/wda/pressButton"]); +} + +#[tokio::test] +async fn hid_buttons_send_consumer_page_events() { + let ok = r#"{"value":null}"#; + let m = Mock::with(&[(200, r#"{"sessionId":"A"}"#), (200, ok), (200, ok)]); + let mut c = WdaClient::new(&m); + c.press_home_hid().await.unwrap(); + c.press_power_hid().await.unwrap(); + let seen = m.seen.lock().unwrap().clone(); + assert_eq!(seen[1].1, "/session/A/wda/performIoHidEvent"); + let body = |i: usize| serde_json::from_str::(seen[i].2.as_deref().unwrap()).unwrap(); + assert_eq!((body(1)["page"].as_u64(), body(1)["usage"].as_u64()), (Some(0x0C), Some(0x223))); + assert_eq!((body(2)["page"].as_u64(), body(2)["usage"].as_u64()), (Some(0x0C), Some(0x30))); + // 0.1 秒在 iPhone 15 Pro Max、iPad mini 5 上锁不了屏,0.5 秒在 iPhone 18 Pro Max 上锁不了(见 POWER_PRESS_SECS) + assert_eq!(body(2)["duration"], 0.15); +} + +#[tokio::test] +async fn tap_is_one_gesture_with_quick_waits_then_restores_baseline() { + let ok = r#"{"value":null}"#; + let m = Mock::with(&[ + (200, r#"{"sessionId":"A"}"#), + (200, r#"{"value":{"waitForIdleTimeout":10,"animationCoolOffTimeout":2}}"#), + (200, ok), + (200, ok), + (200, ok), + // 第二次点击不再读设置 + (200, ok), + (200, ok), + (200, ok), + ]); + let mut c = WdaClient::new(&m); + c.tap(10.0, 20.0).await.unwrap(); + c.tap(30.0, 40.0).await.unwrap(); + let seen = m.seen.lock().unwrap().clone(); + let paths: Vec<_> = seen.iter().map(|s| s.1.as_str()).collect(); + assert_eq!( + paths, + [ + "/session", + "/session/A/appium/settings", + "/session/A/appium/settings", + "/session/A/actions", + "/session/A/appium/settings", + "/session/A/appium/settings", + "/session/A/actions", + "/session/A/appium/settings", + ] + ); + let body = |i: usize| serde_json::from_str::(seen[i].2.as_deref().unwrap()).unwrap(); + assert_eq!(body(2)["settings"]["animationCoolOffTimeout"], 0.0); + assert_eq!(body(4)["settings"]["animationCoolOffTimeout"], 2.0); + let a = body(3); + let steps = a["actions"][0]["actions"].as_array().unwrap(); + assert_eq!(steps.iter().filter(|s| s["type"] == "pointerDown").count(), 1); +} + +/// 启动不经 XCTest(`launchUnattached`),发出就返回;系统 App 第一次打开时它回 failed to launch,前台是隐私说明页, +/// 马上报被挡住,不再等 60 秒 +#[tokio::test] +async fn a_first_launch_privacy_notice_is_reported_at_once() { + let fail = r#"{"value":{"error":"unknown error","message":"LSApplicationWorkspace failed to launch app"}}"#; + let m = Mock::with(&[(500, fail), (200, r#"{"value":{"bundleId":"com.apple.PDUIApp"}}"#)]); + let mut w = WdaClient::new(&m); + let t0 = std::time::Instant::now(); + let r = w.launch_app("com.apple.mobilenotes").await.unwrap(); + assert!(matches!(r, Launch::Blocked(ref t) if !t.is_empty()), "{r:?}"); + assert!(t0.elapsed() < Duration::from_secs(1)); + let seen = m.seen.lock().unwrap(); + assert_eq!(seen[0].1, "/wda/apps/launchUnattached"); + assert!(seen.iter().all(|(_, p, _)| !p.ends_with("/wda/apps/launch"))); +} + +/// 旧版 WDA 没有 launchUnattached:照旧经会话启动 +#[tokio::test] +async fn an_older_wda_without_unattached_launch_launches_as_before() { + let m = Mock::with(&[ + (404, r#"{"value":{"error":"unknown command","message":"Unhandled endpoint"}}"#), + (200, r#"{"sessionId":"A"}"#), + (200, r#"{"value":null}"#), + (200, r#"{"value":{"bundleId":"com.apple.PDUIApp"}}"#), + ]); + let mut w = WdaClient::new(&m); + assert!(matches!(w.launch_app("com.apple.mobilenotes").await.unwrap(), Launch::Blocked(_))); + let seen = m.seen.lock().unwrap(); + assert_eq!(seen[2].1, "/session/A/wda/apps/launch"); +} + +/// 别的错误照样报出来,不当成启动了 +#[tokio::test] +async fn other_launch_errors_are_errors() { + let m = Mock::with(&[(500, r#"{"value":{"error":"invalid argument","message":"bad bundle"}}"#)]); + let mut w = WdaClient::new(&m); + assert!(matches!(w.launch_app("x").await, Err(WdaError::Remote { .. }))); +} + +/// 依次点几个点:每个点一根手指,第 k 根先空等前面的点按完;各手指的节拍数对得上,按下抬起一个接一个、不重叠 +#[test] +fn a_sequence_is_one_finger_per_point_in_turn() { + let body = tap_sequence_body(&[(10.0, 20.0), (30.0, 40.0), (50.0, 60.0)], 50, 40); + let fingers = body["actions"].as_array().unwrap(); + assert_eq!(fingers.len(), 3); + for (k, f) in fingers.iter().enumerate() { + let a = f["actions"].as_array().unwrap(); + assert_eq!(a.len(), 5 * k + 4, "finger {k}"); + // pauses only until its own turn, then move, down, hold, up at its point + assert!(a[..5 * k].iter().all(|s| s["type"] == "pause")); + assert_eq!(a[5 * k]["type"], "pointerMove"); + assert_eq!(a[5 * k]["x"].as_f64(), Some(10.0 + 20.0 * k as f64)); + assert_eq!(a[5 * k + 1]["type"], "pointerDown"); + assert_eq!(a[5 * k + 3]["type"], "pointerUp"); + assert_ne!(fingers[0]["id"], fingers[k.max(1)]["id"]); + } + // finger k waits 5 ticks per earlier point: move, down, hold, up, gap + assert_eq!(fingers[1]["actions"][2]["duration"], 50); + assert_eq!(fingers[1]["actions"][4]["duration"], 40); +} + +/// 连点是一个 actions 请求:一根手指只移动一次,在同一点按下抬起 N 次,两下之间停 MULTI_TAP_GAP_MS; +/// 5 下在 0.8 秒内点完 +#[tokio::test] +async fn multi_tap_is_one_request_at_one_point() { + let ok = r#"{"value":null}"#; + let m = Mock::with(&[ + (200, r#"{"sessionId":"A"}"#), + (200, r#"{"value":{"waitForIdleTimeout":10,"animationCoolOffTimeout":2}}"#), + (200, ok), + (200, ok), + (200, ok), + ]); + let mut c = WdaClient::new(&m); + c.multi_tap(10.0, 20.0, 5).await.unwrap(); + let seen = m.seen.lock().unwrap().clone(); + let actions: Vec<_> = seen.iter().filter(|s| s.1.ends_with("/actions")).collect(); + assert_eq!(actions.len(), 1); + let body = serde_json::from_str::(actions[0].2.as_deref().unwrap()).unwrap(); + let steps = body["actions"][0]["actions"].as_array().unwrap(); + let count = |t: &str| steps.iter().filter(|s| s["type"] == t).count(); + assert_eq!((count("pointerMove"), count("pointerDown"), count("pointerUp")), (1, 5, 5)); + assert_eq!((steps[0]["x"].as_f64(), steps[0]["y"].as_f64()), (Some(10.0), Some(20.0))); + let ms: u64 = steps.iter().filter_map(|s| s["duration"].as_u64()).sum(); + assert_eq!(ms, 5 * TAP_PRESS_MS + 4 * MULTI_TAP_GAP_MS); + assert!(ms < 800); +} + +#[tokio::test] +async fn remote_error_keeps_first_line_and_unreachable_maps_to_unavailable() { + let m = Mock::with(&[ + (200, r#"{"sessionId":"A"}"#), + (500, r#"{"value":{"error":"unknown error","message":"boom\nstack"}}"#), + ]); + let mut c = WdaClient::new(&m); + match c.press_button("home").await { + Err(WdaError::Remote { kind, message }) => { + assert_eq!((kind.as_str(), message.as_str()), ("unknown error", "boom")) + } + other => panic!("{other:?}"), + } + assert!(matches!(c.active_app().await, Err(WdaError::Unavailable(_)))); +} + +/// 传输层报的错误按「请求送没送到」分类:只有没送到的才是 Unavailable(调用方会退到 HID 重做) +#[tokio::test] +async fn errors_after_sending_are_not_unavailable() { + struct Fails(std::io::ErrorKind); + impl Transport for Fails { + async fn send(&self, _: &str, _: &str, _: Option>, _: Duration) -> std::io::Result<(u16, Vec)> { + Err(std::io::Error::new(self.0, "x")) + } + } + let kind = |k| async move { WdaClient::new(Fails(k)).active_app().await }; + assert!(matches!(kind(crate::http::AFTER_SENT).await, Err(WdaError::Interrupted(_)))); + assert!(matches!(kind(crate::http::WRITE_FAILED).await, Err(WdaError::Unavailable(_)))); + let client = WdaClient::new(Fails(crate::http::WRITE_FAILED)); + for (path, acts) in [("/session/1/element", false), ("/session/1/wda/keys", true)] { + let error = client.send("POST", path, None, Duration::from_secs(1)).await.unwrap_err(); + assert!(if acts { matches!(error, WdaError::Write(_)) } else { matches!(error, WdaError::Unavailable(_)) }); + } + assert!(matches!(kind(std::io::ErrorKind::TimedOut).await, Err(WdaError::Timeout(_)))); + assert!(matches!(kind(std::io::ErrorKind::NotConnected).await, Err(WdaError::Unavailable(_)))); + // 应答了但不是 JSON:WDA 收到了请求 + let m = Mock::with(&[(200, "")]); + assert!(matches!(WdaClient::new(&m).active_app().await, Err(WdaError::Interrupted(_)))); +} + +/// 经 XCTest 的请求(工具调用和探测一样算)连续 3 次没有应答就判定卡死:之后不再发,直接报不可用; +/// `/status` 不经 XCTest,既不算数也不受影响;中间有一次应答(哪怕是错误)就从头数。 +/// 长请求没应答时马上问一次前台 App(5 秒):它也没应答就立刻判定卡死,它应答了只是慢 +#[tokio::test] +async fn three_unanswered_requests_mean_stalled() { + type Reply = std::io::Result<(u16, Vec)>; + struct Scripted { + replies: Mutex>, + sent: Mutex>, + } + impl Transport for &Scripted { + async fn send(&self, _: &str, path: &str, _: Option>, _: Duration) -> std::io::Result<(u16, Vec)> { + self.sent.lock().unwrap().push(path.to_owned()); + self.replies.lock().unwrap().pop_front().expect("unexpected request") + } + } + let timeout = || Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "t")); + let ok = |b: &str| Ok((200, b.as_bytes().to_vec())); + let t = Scripted { + replies: Mutex::new(VecDeque::from([ + // a long request unanswered, the quick question after it answered: slow, not stuck + timeout(), + ok(r#"{"value":{}}"#), + timeout(), + ok(r#"{"value":{}}"#), + ok(r#"{"value":{"error":"unknown error","message":"busy"}}"#), + // the probe itself is short: no question after it + timeout(), + ok(r#"{"value":{"ready":true}}"#), + // a long request and the quick question both unanswered: stuck at once + timeout(), + timeout(), + ok(r#"{"value":{"ready":true}}"#), + ])), + sent: Mutex::default(), + }; + let c = WdaClient::new(&t); + assert!(c.wda_reports_locked().await.unwrap_err().no_answer()); + assert!(c.active_app().await.unwrap_err().no_answer()); + assert_eq!(c.unanswered(), 0, "两次短探测均获得回答,应清零"); + // 回了错误:还活着,从头数 + assert!(matches!(c.active_app().await, Err(WdaError::Remote { .. }))); + assert_eq!(c.unanswered(), 0); + assert!(c.xctest_responsive().await.unwrap_err().no_answer()); + // /status 应答了也不清零 + assert!(c.ready().await.unwrap()); + assert_eq!(c.unanswered(), 1); + assert!(!c.stalled()); + assert!(c.wda_reports_locked().await.is_err()); + assert!(c.stalled(), "the quick question went unanswered too"); + assert!(t.replies.lock().unwrap().len() == 1, "every scripted reply but /status was used"); + // 卡死后经 XCTest 的请求不再发出,直接报不可用(调用方可以退到 HID);/status 照常 + let sent = t.sent.lock().unwrap().len(); + assert!(matches!(c.screenshot_png().await, Err(WdaError::Unavailable(_)))); + assert!(matches!(c.xctest_responsive().await, Err(WdaError::Unavailable(_)))); + assert_eq!(t.sent.lock().unwrap().len(), sent); + assert!(c.ready().await.unwrap()); + assert!(c.stalled()); +} + +/// 较长请求超时后,短探测的正常回答或远端错误都证明 WDA 仍有响应,应重新计数。 +#[tokio::test] +async fn answered_probe_resets_stall_count_after_each_slow_request() { + for (status, body) in [ + (200, r#"{"value":{}}"#), + (500, r#"{"value":{"error":"unknown error","message":"busy"}}"#), + (404, r#"{"message":"unknown route"}"#), + (502, "temporarily unavailable"), + ] { + let replies = (0..4).flat_map(|_| [timed_out(), Ok((status, body.as_bytes().to_vec()))]).collect(); + let t = Script::new(replies); + let c = WdaClient::new(&t); + for _ in 0..4 { + assert!(c.wda_reports_locked().await.unwrap_err().no_answer()); + assert_eq!(c.unanswered(), 0, "探测返回 {status} {body}"); + assert!(!c.stalled()); + } + assert_eq!(t.sent().len(), 8, "每个慢请求后都应继续做短探测"); + } +} + +/// 连不上不是收到回答,不能抹掉之前已经发生的无应答。 +#[tokio::test] +async fn connection_error_does_not_reset_unanswered_count() { + let t = Script::new(vec![ + timed_out(), + Err(std::io::Error::new(std::io::ErrorKind::NotConnected, "offline")), + Ok((500, br#"{"value":{"error":"unknown error","message":"busy"}}"#.to_vec())), + ]); + let c = WdaClient::new(&t); + assert!(c.xctest_responsive().await.unwrap_err().no_answer()); + assert_eq!(c.unanswered(), 1); + assert!(matches!(c.xctest_responsive().await, Err(WdaError::Unavailable(_)))); + assert_eq!(c.unanswered(), 1); + assert!(matches!(c.xctest_responsive().await, Err(WdaError::Remote { .. }))); + assert_eq!(c.unanswered(), 0); + assert!(!c.stalled()); +} + +/// 两个请求未应答即可触发快速恢复,但实际计数和原因不能伪装成三次无应答。 +#[tokio::test] +async fn long_request_and_failed_probe_keep_the_actual_count_and_reason() { + let t = Script::new(vec![timed_out(), timed_out(), ok(r#"{"value":{"ready":true}}"#)]); + let c = WdaClient::new(&t); + assert!(c.wda_reports_locked().await.unwrap_err().no_answer()); + assert_eq!(c.unanswered(), 2); + assert_eq!(c.stall_reason(), Some(StallReason::LongRequestAndProbe)); + assert!(c.stalled()); + let why = c.stall_reason().unwrap().describe(); + assert!(why.contains("/wda/activeAppInfo")); + assert!(!why.contains("3 次")); + // 本地 /status 的回答不应把已记录的判定抹掉。 + assert!(c.ready().await.unwrap()); + assert_eq!(c.stall_reason(), Some(StallReason::LongRequestAndProbe)); + assert_eq!(t.sent(), ["GET /wda/locked", "GET /wda/activeAppInfo", "GET /status"]); +} + +#[tokio::test] +async fn three_short_unanswered_requests_report_a_consecutive_stall() { + let t = Script::new(vec![timed_out(), timed_out(), timed_out()]); + let c = WdaClient::new(&t); + for n in 1..=STALL_LIMIT { + assert!(c.xctest_responsive().await.unwrap_err().no_answer()); + assert_eq!(c.unanswered(), n); + assert_eq!(c.stalled(), n == STALL_LIMIT); + } + assert_eq!(c.stall_reason(), Some(StallReason::ConsecutiveRequests(STALL_LIMIT))); + // 后续调用仍立即拒绝,不再发送请求。 + assert!(matches!(c.xctest_responsive().await, Err(WdaError::Unavailable(_)))); + assert_eq!(t.sent().len(), STALL_LIMIT as usize); +} + +/// 结束会话的回答只用于清理,不应代替真正的前台响应探测。 +#[tokio::test] +async fn answered_session_delete_does_not_mask_a_failed_probe() { + let t = Script::new(vec![ok(r#"{"sessionId":"A"}"#), timed_out(), ok(r#"{"value":null}"#), timed_out()]); + let mut c = WdaClient::new(&t); + assert!(matches!(c.press_button("home").await, Err(WdaError::Timeout(_)))); + assert_eq!(c.unanswered(), 2); + assert_eq!(c.stall_reason(), Some(StallReason::LongRequestAndProbe)); + assert_eq!(t.sent()[2], "DELETE /session/A"); +} + +/// 经 XCTest 的探测:只有「送到了却没有应答」算卡死的迹象;WDA 回了错误说明它还在办事,连不上归 `/status` 管 +#[tokio::test] +async fn xctest_probe_counts_only_missing_answers() { + struct Fails(std::io::ErrorKind); + impl Transport for Fails { + async fn send(&self, _: &str, _: &str, _: Option>, t: Duration) -> std::io::Result<(u16, Vec)> { + assert_eq!(t, XCTEST_PROBE_TIMEOUT); + Err(std::io::Error::new(self.0, "x")) + } + } + let probe = |k| async move { WdaClient::new(Fails(k)).xctest_responsive().await }; + assert!(probe(std::io::ErrorKind::TimedOut).await.unwrap_err().no_answer()); + assert!(probe(crate::http::AFTER_SENT).await.unwrap_err().no_answer()); + assert!(!probe(std::io::ErrorKind::NotConnected).await.unwrap_err().no_answer()); + let m = Mock::with(&[ + (200, r#"{"value":{"bundleId":"com.apple.springboard","pid":60}}"#), + (500, r#"{"value":{"error":"unknown error","message":"busy"}}"#), + ]); + let c = WdaClient::new(&m); + assert!(c.xctest_responsive().await.is_ok()); + assert!(!c.xctest_responsive().await.unwrap_err().no_answer()); + assert_eq!(m.seen.lock().unwrap()[0].1, "/wda/activeAppInfo"); +} + +#[tokio::test] +async fn screen_size_is_cached_and_status_ready() { + let unknown = r#"{"value":{"error":"unknown command","message":"no"}}"#; + let m = Mock::with(&[ + (200, r#"{"value":{"screenSize":{"width":430,"height":932},"scale":3}}"#), + (200, r#"{"sessionId":"S"}"#), + (404, unknown), + (404, unknown), + (200, r#"{"value":{"ready":true}}"#), + ]); + let mut c = WdaClient::new(&m); + // 问不到方向:按缓存的尺寸 + assert_eq!(c.screen_size().await.unwrap(), ScreenSize { width: 430.0, height: 932.0 }); + assert_eq!(c.screen_size().await.unwrap().width, 430.0); + assert!(c.ready().await.unwrap()); + let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect(); + assert_eq!(paths.iter().filter(|p| *p == "/wda/screen").count(), 1); +} + +#[tokio::test] +async fn rotation_reads_z_angle() { + let m = Mock::with(&[ + (200, r#"{"sessionId":"S"}"#), + (200, r#"{"value":{"x":0,"y":0,"z":270}}"#), + (200, r#"{"value":{"x":0,"y":0,"z":12}}"#), + ]); + let mut c = WdaClient::new(&m); + assert_eq!(c.rotation().await.unwrap(), ictl_device::Rotation::TopToLeft); + assert!(c.rotation().await.is_err()); + assert_eq!(m.seen.lock().unwrap()[1].1, "/session/S/rotation"); +} + +/// WDA 在横屏时启动,缓存的是 1024x768;转成竖屏后要给 768x1024 +#[tokio::test] +async fn screen_size_follows_orientation_after_rotation() { + let m = Mock::with(&[ + (200, r#"{"value":{"screenSize":{"width":1024,"height":768},"scale":2}}"#), + (200, r#"{"sessionId":"S"}"#), + (200, r#"{"value":"LANDSCAPE"}"#), + (200, r#"{"value":"PORTRAIT"}"#), + ]); + let mut c = WdaClient::new(&m); + let v = c.view().await.unwrap(); + assert_eq!( + (v.screen, v.orientation), + (ScreenSize { width: 1024.0, height: 768.0 }, Some(elements::Orientation::LandscapeLeft)) + ); + assert_eq!(c.screen_size().await.unwrap(), ScreenSize { width: 768.0, height: 1024.0 }); + assert_eq!(m.seen.lock().unwrap()[2].1, "/session/S/orientation"); +} + +/// 从主屏打开网址:等 Safari 到前台、元素树稳定才返回,不是发完请求就走;一闪而过的系统服务不算 +#[tokio::test] +async fn open_url_waits_for_the_opening_app() { + let m = Mock::with(&[ + (200, r#"{"value":{"bundleId":"com.apple.springboard"}}"#), + (200, r#"{"sessionId":"S"}"#), + (200, r#"{"value":null}"#), + (200, r#"{"value":{"bundleId":"com.apple.DocumentManager.DockFolderViewService"}}"#), + (200, r#"{"value":{"bundleId":"com.apple.mobilesafari"}}"#), + (200, r#"{"value":{"bundleId":"com.apple.mobilesafari"}}"#), + (200, r#"{"value":""}"#), + (200, r#"{"value":""}"#), + ]); + let mut c = WdaClient::new(&m); + let t0 = std::time::Instant::now(); + let (r, app) = c.open_url("https://example.com").await.unwrap(); + assert_eq!((r, app.as_str()), (Launch::Foreground, "com.apple.mobilesafari")); + assert!(t0.elapsed() >= LAUNCH_MIN); + let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect(); + assert_eq!(paths[2], "/session/S/url"); + assert!(paths[6].starts_with("/source"), "{paths:?}"); +} + +#[tokio::test] +async fn source_request_excludes_slow_attributes() { + let m = Mock::with(&[(200, r#"{"value":""}"#)]); + let mut c = WdaClient::new(&m); + c.source_xml().await.unwrap(); + let path = m.seen.lock().unwrap()[0].1.clone(); + assert!(path.starts_with("/source?format=xml&excluded_attributes=visible,"), "{path}"); +} + +#[tokio::test] +async fn passcode_field_reads_secure_text_field_value() { + let m = Mock::with(&[ + (200, r#"{"sessionId":"S"}"#), + (200, r#"{"value":[{"ELEMENT":"E1","element-6066-11e4-a52e-4f735466cecf":"E1"}]}"#), + (200, r#"{"value":"共6位数,已输入2位"}"#), + ]); + let mut c = WdaClient::new(&m); + assert_eq!(c.passcode_field().await.unwrap(), Some((6, 2))); + assert_eq!(m.seen.lock().unwrap()[2].1, "/session/S/element/E1/attribute/value"); +} + +#[tokio::test] +async fn focused_field_reads_its_type_and_placeholder() { + let m = Mock::with(&[ + (200, r#"{"sessionId":"S"}"#), + (200, r#"{"value":{"ELEMENT":"F1","element-6066-11e4-a52e-4f735466cecf":"F1"}}"#), + (200, r#"{"value":"XCUIElementTypeSearchField"}"#), + (200, r#"{"value":"搜索"}"#), + // empty: reads its placeholder + (200, r#"{"value":"搜索"}"#), + (200, r#"{"value":"wifi"}"#), + ]); + let mut c = WdaClient::new(&m); + let f = c.focused_field().await.unwrap().unwrap(); + assert_eq!(f, FocusedField { id: "F1".into(), kind: "SearchField".into(), placeholder: "搜索".into() }); + assert_eq!(c.field_text(&f).await.unwrap(), ""); + assert_eq!(c.field_text(&f).await.unwrap(), "wifi"); + let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect(); + assert_eq!( + paths[1..4], + [ + "/session/S/element/active", + "/session/S/element/F1/attribute/type", + "/session/S/element/F1/attribute/placeholderValue" + ] + ); +} + +#[tokio::test] +async fn no_focused_element_is_none() { + let m = Mock::with(&[ + (200, r#"{"sessionId":"S"}"#), + (404, r#"{"value":{"error":"no such element","message":"No element is in focus"}}"#), + ]); + assert_eq!(WdaClient::new(&m).focused_field().await.unwrap(), None); +} + +/// Finding elements reads; clearing one changes the phone (its session is ended when it doesn't answer) +#[test] +fn element_finds_read_and_element_edits_act() { + assert!(!acts("POST", "/elements")); + assert!(!acts("POST", "/element")); + assert!(!acts("POST", "/element/E1/elements")); + assert!(!acts("GET", "/element/active")); + assert!(acts("POST", "/element/E1/clear")); + assert!(acts("POST", "/wda/keys")); +} + +#[test] +fn actions_body_is_one_pointer_with_steps() { + let b = actions_body(&tap_steps(10.0, 20.0, 80)); + let a = &b["actions"][0]; + assert_eq!(a["parameters"]["pointerType"], "touch"); + let types: Vec<_> = a["actions"].as_array().unwrap().iter().map(|s| s["type"].as_str().unwrap()).collect(); + assert_eq!(types, ["pointerMove", "pointerDown", "pause", "pointerUp"]); + assert_eq!(a["actions"][2]["duration"], 80); + let s = swipe_steps((1.0, 2.0), (3.0, 4.0), 300); + assert_eq!(s[3], PointerStep::Move { x: 3.0, y: 4.0, ms: 300 }); +} + +/// 按住再拖:按下后原地 move 按住(不是 pause,pause 拖不动图标),再移到终点;不按住就是普通滑动 +#[test] +fn a_held_drag_holds_with_a_move_in_place() { + let s = drag_steps((1.0, 2.0), (3.0, 4.0), 600, 700); + assert_eq!( + s, + [ + PointerStep::Move { x: 1.0, y: 2.0, ms: 0 }, + PointerStep::Down, + PointerStep::Move { x: 1.0, y: 2.0, ms: 600 }, + PointerStep::Move { x: 3.0, y: 4.0, ms: 700 }, + PointerStep::Up, + ] + ); + assert_eq!(drag_steps((1.0, 2.0), (3.0, 4.0), 0, 300), swipe_steps((1.0, 2.0), (3.0, 4.0), 300)); +} + +#[tokio::test] +async fn locked_checks_tree_until_unlocked_once_then_trusts_wda() { + let lock_xml = serde_json::to_string(include_str!("../../tests/fixtures/lockscreen-ios27.xml")).unwrap(); + let home_xml = serde_json::to_string(include_str!("../../tests/fixtures/home.xml")).unwrap(); + let sb = r#"{"value":{"bundleId":"com.apple.springboard"}}"#; + let no = r#"{"value":false}"#; + let (lock_src, home_src) = (format!(r#"{{"value":{lock_xml}}}"#), format!(r#"{{"value":{home_xml}}}"#)); + let m = Mock::with(&[ + // 1. WDA 在锁屏时启动:/wda/locked 误报 false,元素树是锁屏 + (200, no), + (200, sb), + (200, &lock_src), + // 2. 人工解锁后:主屏幕,确认一次 + (200, no), + (200, sb), + (200, &home_src), + // 3. 之后 WDA 说没锁就直接信 + (200, no), + // 4. WDA 说锁了:核对一次,确实是锁屏 + (200, r#"{"value":true}"#), + (200, sb), + (200, &lock_src), + ]); + let mut c = WdaClient::new(&m); + assert!(c.locked().await.unwrap()); + assert!(!c.locked().await.unwrap()); + assert!(!c.locked().await.unwrap()); + assert!(c.locked().await.unwrap()); + let paths: Vec = m.seen.lock().unwrap().iter().map(|(_, p, _)| p.clone()).collect(); + assert_eq!(paths.iter().filter(|p| p.starts_with("/source")).count(), 3, "{paths:?}"); +} + +#[tokio::test] +async fn notification_center_is_not_locked_even_if_wda_says_so() { + let nc = serde_json::to_string(include_str!("../../tests/fixtures/notification-center-ios27.xml")).unwrap(); + let pin = serde_json::to_string(include_str!("../../tests/fixtures/passcode-view-ios27.xml")).unwrap(); + let sb = r#"{"value":{"bundleId":"com.apple.springboard"}}"#; + let yes = r#"{"value":true}"#; + let (nc, pin) = (format!(r#"{{"value":{nc}}}"#), format!(r#"{{"value":{pin}}}"#)); + let m = Mock::with(&[(200, yes), (200, sb), (200, &nc), (200, yes), (200, sb), (200, &pin), (200, yes)]); + let mut c = WdaClient::new(&m); + assert!(!c.locked().await.unwrap(), "通知中心"); + assert!(c.locked().await.unwrap(), "密码键盘界面"); + // 核对失败时按 WDA 的结果 + assert!(c.locked().await.unwrap()); +} + +#[tokio::test] +async fn locked_falls_back_to_wda_when_tree_check_fails() { + // 核对失败(例如取元素树超时)不能把可用的手机误判成锁屏,也不能就此信任 WDA + let m = Mock::with(&[(200, r#"{"value":false}"#)]); + let mut c = WdaClient::new(&m); + assert!(!c.locked().await.unwrap()); + assert!(!c.lock_state_trusted); +} + +/// 传输层给出的一个结果:状态码和响应体,或者超时之类的错误 +type Reply = std::io::Result<(u16, Vec)>; + +/// 按顺序给出预设结果(可以是超时),记下每个请求的方法、路径和请求体 +#[derive(Default)] +struct Script { + replies: Mutex>, + sent: Mutex)>>, +} + +impl Script { + fn new(replies: Vec) -> Self { + Self { replies: Mutex::new(replies.into()), ..Default::default() } + } + + fn sent(&self) -> Vec { + self.sent.lock().unwrap().iter().map(|(m, p, _)| format!("{m} {p}")).collect() + } + + fn body(&self, i: usize) -> Value { + self.sent.lock().unwrap()[i].2.clone().expect("a body") + } +} + +impl Transport for &Script { + async fn send( + &self, + method: &str, + path: &str, + body: Option>, + _: Duration, + ) -> std::io::Result<(u16, Vec)> { + let body = body.map(|b| serde_json::from_slice(&b).unwrap()); + self.sent.lock().unwrap().push((method.into(), path.into(), body)); + self.replies.lock().unwrap().pop_front().expect("unexpected request") + } +} + +fn timed_out() -> Reply { + Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "t")) +} + +fn ok(body: &str) -> Reply { + Ok((200, body.as_bytes().to_vec())) +} + +/// 动作没有应答:先结束会话(WDA 不再执行这个会话里还在排队的请求),再问一次前台 App 判断是不是卡死; +/// 下一个动作开新会话 +#[tokio::test] +async fn an_unanswered_action_ends_its_session() { + let t = Script::new(vec![ + ok(r#"{"sessionId":"A"}"#), + timed_out(), + ok(r#"{"value":null}"#), + ok(r#"{"value":{}}"#), + ok(r#"{"sessionId":"B"}"#), + ok(r#"{"value":null}"#), + ]); + let mut c = WdaClient::new(&t); + assert!(matches!(c.press_button("home").await, Err(WdaError::Timeout(_)))); + c.press_button("home").await.unwrap(); + assert_eq!( + t.sent(), + [ + "POST /session", + "POST /session/A/wda/pressButton", + "DELETE /session/A", + "GET /wda/activeAppInfo", + "POST /session", + "POST /session/B/wda/pressButton", + ] + ); +} + +/// 读没有应答不结束会话:排在读后面的不会动手机,结束了只会让下一次开会话也排到它后面 +#[tokio::test] +async fn an_unanswered_read_keeps_its_session() { + let t = Script::new(vec![ + ok(r#"{"sessionId":"A"}"#), + timed_out(), + ok(r#"{"value":{}}"#), + timed_out(), + ok(r#"{"value":{}}"#), + ok(r#"{"value":null}"#), + ]); + let mut c = WdaClient::new(&t); + assert!(c.alert_text().await.unwrap_err().no_answer()); + assert!(c.keyboard_shown().await.unwrap_err().no_answer()); + c.press_button("home").await.unwrap(); + assert_eq!( + t.sent(), + [ + "POST /session", + "GET /session/A/alert/text", + "GET /wda/activeAppInfo", + "POST /session/A/elements", + "GET /wda/activeAppInfo", + "POST /session/A/wda/pressButton", + ] + ); +} + +#[test] +fn snapshot_limits_tighten_when_slow_and_loosen_when_fast() { + let slow = Some(SLOW_SOURCE); + let fast = Some(Duration::from_millis(300)); + let fair = Some(Duration::from_secs(3)); + assert_eq!(next_snapshot_level(0, slow), 1); + assert_eq!(next_snapshot_level(1, None), 2); + assert_eq!(next_snapshot_level(3, None), 3, "never tighter than the last level"); + assert_eq!(next_snapshot_level(2, fair), 2); + assert_eq!(next_snapshot_level(2, fast), 1); + assert_eq!(next_snapshot_level(0, fast), 0); + assert_eq!(next_snapshot_level(0, fair), 0); + // 先限子元素再减层数,都有下限 + assert_eq!(SNAPSHOT_LEVELS[1], SnapshotLimits { depth: 50, children: Some(150) }); + assert!(SNAPSHOT_LEVELS.windows(2).all(|w| w[1].depth <= w[0].depth)); + assert_eq!(SNAPSHOT_LEVELS[3], SnapshotLimits { depth: 12, children: Some(60) }); +} + +/// 读树超时后下一次先设上限再读,读得快了再放宽;新会话里 WDA 是不限的,不为读树专门设 +#[tokio::test] +async fn a_timed_out_tree_is_read_again_with_limits() { + let xml = r#"{"value":""}"#; + let t = Script::new(vec![ + timed_out(), + ok(r#"{"value":{}}"#), + ok(r#"{"sessionId":"A"}"#), + ok(r#"{"value":null}"#), + ok(xml), + ok(r#"{"value":null}"#), + ok(xml), + ok(xml), + ]); + let mut c = WdaClient::new(&t); + assert!(matches!(c.source_xml().await, Err(WdaError::Timeout(_)))); + assert_eq!(c.snapshot_note(), None, "nothing was read with limits yet"); + assert_eq!(c.source_xml().await.unwrap(), ""); + assert!(c.snapshot_note().unwrap().contains("150")); + c.source_xml().await.unwrap(); + assert_eq!(c.snapshot_note(), None); + c.source_xml().await.unwrap(); + let sent = t.sent(); + assert!(sent[0].starts_with("GET /source?")); + assert_eq!(sent[1..4], ["GET /wda/activeAppInfo", "POST /session", "POST /session/A/appium/settings"]); + assert_eq!(t.body(3)["settings"], json!({"snapshotMaxDepth": 50, "snapshotMaxChildren": 150})); + assert_eq!(sent[5], "POST /session/A/appium/settings"); + assert_eq!(t.body(5)["settings"]["snapshotMaxChildren"], i32::MAX); + assert_eq!(sent.len(), 8, "the last read needs no settings: {sent:?}"); +} + +#[test] +fn the_detection_point_is_below_banners_in_either_orientation() { + assert_eq!(detection_point(ScreenSize { width: 430.0, height: 932.0 }), (215, 215)); + assert_eq!(detection_point(ScreenSize { width: 932.0, height: 430.0 }), (215, 215)); + assert_eq!(detection_point(ScreenSize { width: 744.0, height: 1133.0 }), (372, 372)); +} + +/// 第一次读元素树时挪一次判断前台 App 的点,之后不再设 +#[tokio::test] +async fn the_first_tree_read_moves_the_detection_point_once() { + let xml = r#"{"value":""}"#; + let t = Script::new(vec![ + ok(r#"{"value":{"screenSize":{"width":430,"height":932}}}"#), + ok(r#"{"sessionId":"A"}"#), + ok(r#"{"value":"PORTRAIT"}"#), + ok(r#"{"value":null}"#), + ok(xml), + ok(r#"{"value":"PORTRAIT"}"#), + ok(xml), + ]); + let mut c = WdaClient::new(&t); + c.tree().await.unwrap(); + c.tree().await.unwrap(); + let sent = t.sent(); + assert_eq!(sent[3], "POST /session/A/appium/settings", "{sent:?}"); + assert_eq!(t.body(3)["settings"], json!({"activeAppDetectionPoint": "215,215"})); + assert_eq!(sent.len(), 7, "{sent:?}"); + assert!(sent[6].starts_with("GET /source?")); +} diff --git a/crates/ictl-wda/src/client/typing.rs b/crates/ictl-wda/src/client/typing.rs new file mode 100644 index 0000000..1c2d924 --- /dev/null +++ b/crates/ictl-wda/src/client/typing.rs @@ -0,0 +1,54 @@ +//! [`WdaClient`]: The focused field: reading it back, clearing it, typing keys + +use super::*; + +impl WdaClient { + /// The element with keyboard focus (`GET /element/active`); None when no element has it + pub async fn focused_field(&mut self) -> Result> { + let Some(id) = self.active_element().await? else { return Ok(None) }; + let kind = self.attribute(&id, "type").await?; + let kind = kind.strip_prefix("XCUIElementType").unwrap_or(&kind).to_owned(); + let placeholder = self.attribute(&id, "placeholderValue").await?; + Ok(Some(FocusedField { id, kind, placeholder })) + } + + /// The id of the element with keyboard focus (`GET /element/active`), one request; nothing has focus: `None`. + /// Rereading a field already known ([`Self::focused_field`] takes three) only needs this and its value + pub async fn active_element(&mut self) -> Result> { + match self.in_session("GET", "/element/active", None, DEFAULT_TIMEOUT).await { + Ok(v) => Ok(element_id(&v)), + Err(WdaError::Remote { kind, .. }) if kind.contains("no such element") => Ok(None), + Err(e) => Err(e), + } + } + + /// An attribute of an element as text; a missing one (`null`) reads as empty + pub async fn attribute(&mut self, id: &str, name: &str) -> Result { + let v = self.in_session("GET", &format!("/element/{id}/attribute/{name}"), None, DEFAULT_TIMEOUT).await?; + Ok(match v { + Value::String(s) => s, + Value::Null => String::new(), + other => other.to_string(), + }) + } + + /// What the field holds: an empty field reads its placeholder as its value (Spotlight's reads «搜索»), so that + /// counts as empty, as with native control + pub async fn field_text(&mut self, f: &FocusedField) -> Result { + let v = self.attribute(&f.id, "value").await?; + Ok(if !f.placeholder.is_empty() && v == f.placeholder { String::new() } else { v }) + } + + /// Empties a field (`POST /element/:id/clear`): WDA deletes the text with the keyboard until the field reads + /// empty, and answers an error when it doesn't (some custom fields) + pub async fn clear(&mut self, id: &str) -> Result<()> { + self.in_session("POST", &format!("/element/{id}/clear"), Some(json!({})), Duration::from_secs(60)) + .await + .map(drop) + } + + pub async fn keys(&mut self, text: &str) -> Result<()> { + let chars: Vec = text.chars().map(String::from).collect(); + self.in_session("POST", "/wda/keys", Some(json!({"value": chars})), Duration::from_secs(120)).await.map(drop) + } +} From 0bc31120cc6aaf6a7a2dd9c2b1c6eacdec6150ca Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:44:58 +0800 Subject: [PATCH 3/5] refactor(viewer): page sources in web/, assembled by build.rs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit viewer.html was one 3,700-line file: 860 lines of CSS, the markup and a 2,560-line script. Its sources are now apps/iphone-control/web/: index.html with `@include` lines for viewer.css and the scripts in the order they run (js/i18n, ui, state, demo, screen, info, video, device, tasks, alert, scope, layout). build.rs replaces each include with its file and writes the page to OUT_DIR, which viewer.rs embeds as before; no Node or other tool is needed to build. The scripts are plain scripts in one scope, as the single file was, so nothing about how the page runs changes: the page build.rs puts together is byte for byte the old viewer.html. Turning them into ES modules would mean giving every shared global (S, T, W, D…) an import, a rewrite of its own; inline modules couldn't import each other anyway. The page tests read the assembled page through tests/viewer/page.mjs, which expands the includes the same way. A unit test checks that the embedded page has every include expanded and stays strict. Co-authored-by: Claude Opus 5.5 --- CONTRIBUTING.md | 2 + DESIGN.md | 2 +- apps/iphone-control/build.rs | 28 + apps/iphone-control/src/video/mod.rs | 2 +- apps/iphone-control/src/viewer.html | 3689 -------------------------- apps/iphone-control/src/viewer.rs | 13 +- apps/iphone-control/web/index.html | 282 ++ apps/iphone-control/web/js/alert.js | 50 + apps/iphone-control/web/js/demo.js | 183 ++ apps/iphone-control/web/js/device.js | 295 ++ apps/iphone-control/web/js/i18n.js | 99 + apps/iphone-control/web/js/info.js | 240 ++ apps/iphone-control/web/js/layout.js | 385 +++ apps/iphone-control/web/js/scope.js | 64 + apps/iphone-control/web/js/screen.js | 344 +++ apps/iphone-control/web/js/state.js | 75 + apps/iphone-control/web/js/tasks.js | 431 +++ apps/iphone-control/web/js/ui.js | 191 ++ apps/iphone-control/web/js/video.js | 206 ++ apps/iphone-control/web/viewer.css | 857 ++++++ docs/architecture.md | 2 +- tests/viewer/actions.test.mjs | 4 +- tests/viewer/alert.test.mjs | 4 +- tests/viewer/lan.test.mjs | 4 +- tests/viewer/lowbandwidth.test.mjs | 4 +- tests/viewer/page.mjs | 10 + tests/viewer/scope.test.mjs | 4 +- tests/viewer/summary.test.mjs | 4 +- tests/viewer/syntax.test.mjs | 4 +- tests/viewer/tasks.test.mjs | 4 +- tests/viewer/video-retry.test.mjs | 4 +- tests/viewer/zoom.test.mjs | 4 +- 32 files changed, 3777 insertions(+), 3713 deletions(-) create mode 100644 apps/iphone-control/build.rs delete mode 100644 apps/iphone-control/src/viewer.html create mode 100644 apps/iphone-control/web/index.html create mode 100644 apps/iphone-control/web/js/alert.js create mode 100644 apps/iphone-control/web/js/demo.js create mode 100644 apps/iphone-control/web/js/device.js create mode 100644 apps/iphone-control/web/js/i18n.js create mode 100644 apps/iphone-control/web/js/info.js create mode 100644 apps/iphone-control/web/js/layout.js create mode 100644 apps/iphone-control/web/js/scope.js create mode 100644 apps/iphone-control/web/js/screen.js create mode 100644 apps/iphone-control/web/js/state.js create mode 100644 apps/iphone-control/web/js/tasks.js create mode 100644 apps/iphone-control/web/js/ui.js create mode 100644 apps/iphone-control/web/js/video.js create mode 100644 apps/iphone-control/web/viewer.css create mode 100644 tests/viewer/page.mjs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aa33525..8848505 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,6 +21,8 @@ cargo test --workspace --all-features --locked # Linux/macOS PTY regression; temporary settings only, no daemon or device actions python3 tests/terminal.py --binary target/debug/iphone-control --test-dir target/debug/deps cargo clippy --workspace --all-targets --all-features --locked -- -D warnings +# the control page's tests (Node 22, no packages): the page is apps/iphone-control/web/, put together by build.rs +node --test tests/viewer/*.test.mjs # vendor/ is upstream code and isn't formatted; check only this repository's packages: for p in ictl-l10n ictl-webinspector ictl-device ictl-wda ictl-sign ictl-unlock ictl-daemon ictl-mcp ictl-protocol iphone-control; do cargo fmt -p $p -- --check; done ``` diff --git a/DESIGN.md b/DESIGN.md index 0cd705d..3c52785 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1,6 +1,6 @@ # Web 控制台设计规范 -桌面从左到右排列 AI 助手、设备画面、设备面板。窄窗口用抽屉或标签切换。接入新控件时沿用这套结构,优先把可用空间留给设备画面。[页面实现](apps/iphone-control/src/viewer.html) +桌面从左到右排列 AI 助手、设备画面、设备面板。窄窗口用抽屉或标签切换。接入新控件时沿用这套结构,优先把可用空间留给设备画面。[页面实现](apps/iphone-control/web/) ## 输入与排版 diff --git a/apps/iphone-control/build.rs b/apps/iphone-control/build.rs new file mode 100644 index 0000000..3680127 --- /dev/null +++ b/apps/iphone-control/build.rs @@ -0,0 +1,28 @@ +//! Puts the control page together: `web/index.html` with each `@include ` line replaced by that file (the +//! stylesheet, then the scripts in order), written to `$OUT_DIR/viewer.html`, which `viewer.rs` embeds. The scripts +//! share one scope, as they did in the single file, so the order in `index.html` is the order they run in. No other +//! tool is needed (tests/viewer/page.mjs does the same for the page tests). + +use std::path::Path; + +fn main() { + let web = Path::new("web"); + let index = web.join("index.html"); + println!("cargo:rerun-if-changed={}", index.display()); + let text = std::fs::read_to_string(&index).unwrap_or_else(|e| panic!("{}: {e}", index.display())); + let mut page = String::with_capacity(256 * 1024); + for line in text.split_inclusive('\n') { + let Some(rel) = line.strip_prefix("@include ") else { + page.push_str(line); + continue; + }; + let part = web.join(rel.trim()); + println!("cargo:rerun-if-changed={}", part.display()); + let body = std::fs::read_to_string(&part).unwrap_or_else(|e| panic!("{}: {e}", part.display())); + assert!(body.ends_with('\n'), "{} must end with a line break", part.display()); + assert!(!body.lines().any(|l| l.starts_with("@include ")), "{}: includes don't nest", part.display()); + page.push_str(&body); + } + let out = Path::new(&std::env::var_os("OUT_DIR").expect("OUT_DIR")).join("viewer.html"); + std::fs::write(&out, page).unwrap_or_else(|e| panic!("{}: {e}", out.display())); +} diff --git a/apps/iphone-control/src/video/mod.rs b/apps/iphone-control/src/video/mod.rs index 05d97c4..d687c4e 100644 --- a/apps/iphone-control/src/video/mod.rs +++ b/apps/iphone-control/src/video/mod.rs @@ -631,7 +631,7 @@ mod tests { (Instant::now(), phone) }); - // the page, over a real TCP connection, reporting what it read every 100 ms like viewer.html + // the page, over a real TCP connection, reporting what it read every 100 ms like the control page let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let mut page = tokio::net::TcpStream::connect(l.local_addr().unwrap()).await.unwrap(); let (server_side, _) = l.accept().await.unwrap(); diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.html deleted file mode 100644 index 855364a..0000000 --- a/apps/iphone-control/src/viewer.html +++ /dev/null @@ -1,3689 +0,0 @@ - - - - - -iphone-control 控制台 - - - - -
- - -
-
- -
iphone-control控制台
-
-
- - - -
-
- - -
- - -
-
-
-
- -
- -
-
-
-
-
-
- - - - -
- - -
-
-
-
-
-
- - - - - -
正在连接 iphone-control 服务…
-
-
-
-

-
-
-
- -
-
- - - - -
-
- - - - -
- -
-
-
-
正在连接…
-
-
-
- - - -
- - -

设置

-
-
-
-
-
-

画面流量减少约一半,帧率不变,适合外网或信号差时用;画面动起来时会略糊。手机自己的画面(HEVC)只有一路,开着时所有在看这台手机的页面都会一起降,切换时画面会断开半秒左右。

-
-
-
- -

清空全部操作记录?

-

只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。

-
- - -
-
- - -

停止这个任务?

-

AI 会立刻停下。已经在设备上做完的操作不会撤销。

-
- - -
-
- - - - diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs index cd84a88..8914896 100644 --- a/apps/iphone-control/src/viewer.rs +++ b/apps/iphone-control/src/viewer.rs @@ -47,7 +47,8 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt}; use crate::agent::{self, Agents}; -const PAGE: &str = include_str!("viewer.html"); +/// The control page, put together from `web/` by build.rs +const PAGE: &str = include_str!(concat!(env!("OUT_DIR"), "/viewer.html")); /// WDA's MJPEG server on the phone const MJPEG_PORT: u16 = 9100; const MAX_BODY: usize = 16 * 1024; @@ -2075,6 +2076,16 @@ mod tests { } } + /// build.rs put the page together whole: every include expanded, one stylesheet and one script, in order + #[test] + fn the_embedded_page_is_assembled() { + assert!(!PAGE.lines().any(|l| l.starts_with("@include "))); + assert!(PAGE.starts_with("") && PAGE.trim_end().ends_with("")); + assert_eq!((PAGE.matches(" + + +
+ + +
+
+ +
iphone-control控制台
+
+
+ + + +
+
+ + + + + +
+
+
+
+ +
+ +
+
+
+
+
+
+ + + + +
+ + +
+
+
+
+
+
+ + + + + +
正在连接 iphone-control 服务…
+
+
+
+

+
+
+
+ +
+
+ + + + +
+
+ + + + +
+ +
+
+
+
正在连接…
+
+
+
+ + + +
+ + +

设置

+
+
+
+
+
+

画面流量减少约一半,帧率不变,适合外网或信号差时用;画面动起来时会略糊。手机自己的画面(HEVC)只有一路,开着时所有在看这台手机的页面都会一起降,切换时画面会断开半秒左右。

+
+
+
+ +

清空全部操作记录?

+

只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。

+
+ + +
+
+ + +

停止这个任务?

+

AI 会立刻停下。已经在设备上做完的操作不会撤销。

+
+ + +
+
+ + + + diff --git a/apps/iphone-control/web/js/alert.js b/apps/iphone-control/web/js/alert.js new file mode 100644 index 0000000..5acb5df --- /dev/null +++ b/apps/iphone-control/web/js/alert.js @@ -0,0 +1,50 @@ +const SA = { busy: false, key: '', quietUntil: 0 }; +function alertQuiet() { SA.quietUntil = Date.now() + 3000; } +async function alertLoop() { + const t0 = performance.now(); + await pollAlert(); + const slow = performance.now() - t0 > 300; + setTimeout(alertLoop, S.sysAlert ? 1500 : slow ? 6000 : 2000); +} +async function pollAlert() { + if (SA.busy || Date.now() < SA.quietUntil) return; + if (S.mode !== 'live' || document.hidden || !V.device) { + if (S.sysAlert) { S.sysAlert = null; renderSysAlert(); } + return; + } + SA.busy = true; + // busy:手机正在执行操作,这次没查(让操作先走),保留上次的结果 + try { const v = await api('/api/alert'); if (!v.busy) S.sysAlert = v.alert || null; } catch { /* 下一轮再问 */ } finally { SA.busy = false; } + renderSysAlert(); +} +function renderSysAlert() { + const el = $('#sys-alert'), a = S.sysAlert, locked = guarded(); + const f = a && a.frame, d = f ? dims() : null; + const key = a ? JSON.stringify([a, locked, d]) : ''; + if (key === SA.key) return; + SA.key = key; + el.hidden = !a; + if (!a) { el.innerHTML = ''; return; } + // 真实弹窗的位置(点 → 画面的百分比),竖直方向对齐它的中心;画面尺寸还不知道时放在中间 + const pct = v => `${(v * 100).toFixed(2)}%`; + const pos = d ? `left:${pct(f.x / d.W)};width:${pct(f.width / d.W)};top:${pct((f.y + f.height / 2) / d.H)}` : 'left:18%;width:64%;top:50%'; + // 整行宽的是弹窗的操作按钮;窄的(「精确位置:打开」这类开关)做成小标签 + const wide = b => !f || !b.width || b.width >= f.width * 0.6; + const btn = (b, i, cls) => ``; + const chips = a.buttons.map((b, i) => wide(b) ? '' : btn(b, i, 'sa-chip')).join(''); + const acts = a.buttons.map((b, i) => wide(b) ? btn(b, i, 'sa-btn') : '').join(''); + const [title, ...rest] = String(a.text).split('\n'); + el.innerHTML = `
+

${esc(title)}

${rest.length ? `

${esc(rest.join('\n'))}

` : ''} + ${chips ? `
${chips}
` : ''}${acts ? `
${acts}
` : ''} +

${icon('alert')}${locked ? tr('AI 任务进行中:要自己点,先接管。') : tr('实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮')}

`; +} +async function tapSysAlert(i) { + const b = S.sysAlert && S.sysAlert.buttons[i]; + if (!b || !S.display || guarded()) return; + await act('/api/tap', { x: b.x, y: b.y, view: S.display.id }); + S.sysAlert = null; renderSysAlert(); + setTimeout(pollAlert, 800); +} +/* ---------- 任务的 App 范围:开任务时可以限定只在哪些 App 里操作(守护进程强制,见 docs/task-control.md 5.5)。 + * 选择在本次页面里一直保留,按钮上始终显示;刷新后不保留,免得忘了而让任务被悄悄限制。演示模式里没有 ---------- */ diff --git a/apps/iphone-control/web/js/demo.js b/apps/iphone-control/web/js/demo.js new file mode 100644 index 0000000..6015219 --- /dev/null +++ b/apps/iphone-control/web/js/demo.js @@ -0,0 +1,183 @@ +const APPS = [ + { id: 'clock', name: tr('时钟'), bundle: 'com.apple.mobiletimer', glyph: tr('时'), bg: '#1c1c1e', fg: '#fff' }, + { id: 'calendar', name: tr('日历'), bundle: 'com.apple.mobilecal', glyph: String(new Date().getDate()), bg: '#fff', fg: '#ff3b30' }, + { id: 'photos', name: tr('照片'), bundle: 'com.apple.mobileslideshow', glyph: tr('照'), bg: '#fff', fg: '#ff9500' }, + { id: 'camera', name: tr('相机'), bundle: 'com.apple.camera', glyph: tr('摄'), bg: '#8e8e93', fg: '#1c1c1e' }, + { id: 'messages', name: tr('信息'), bundle: 'com.apple.MobileSMS', glyph: tr('信'), bg: '#34c759', fg: '#fff' }, + { id: 'notes', name: tr('备忘录'), bundle: 'com.apple.mobilenotes', glyph: tr('记'), bg: '#ffcc00', fg: '#1c1c1e' }, + { id: 'weather', name: tr('天气'), bundle: 'com.apple.weather', glyph: tr('晴'), bg: '#2f80ed', fg: '#fff' }, + { id: 'maps', name: tr('地图'), bundle: 'com.apple.Maps', glyph: tr('图'), bg: '#7cc576', fg: '#1c1c1e' }, + { id: 'settings', name: tr('设置'), bundle: 'com.apple.Preferences', glyph: tr('设'), bg: '#8e8e93', fg: '#fff' }, + { id: 'appstore', name: 'App Store', bundle: 'com.apple.AppStore', glyph: 'A', bg: '#0a84ff', fg: '#fff' }, + { id: 'health', name: tr('健康'), bundle: 'com.apple.Health', glyph: tr('康'), bg: '#fff', fg: '#ff2d55' }, + { id: 'wallet', name: tr('钱包'), bundle: 'com.apple.Passbook', glyph: tr('钱'), bg: '#1c1c1e', fg: '#fff' } +]; +const DOCK = [ + { id: 'phone', name: tr('电话'), bundle: 'com.apple.mobilephone', glyph: tr('话'), bg: '#34c759', fg: '#fff' }, + { id: 'safari', name: 'Safari', bundle: 'com.apple.mobilesafari', glyph: 'S', bg: '#fff', fg: '#0a84ff' }, + { id: 'mail', name: tr('邮件'), bundle: 'com.apple.mobilemail', glyph: tr('邮'), bg: '#2f80ed', fg: '#fff' }, + { id: 'music', name: tr('音乐'), bundle: 'com.apple.Music', glyph: tr('乐'), bg: '#fa2d48', fg: '#fff' } +]; +const ALL_APPS = [...APPS, ...DOCK]; +const appById = id => ALL_APPS.find(a => a.id === id); +const appByAny = s => ALL_APPS.find(a => a.name === s || a.bundle === s || a.id === s); +const CLOCK_TABS = [['world', tr('世界时钟')], ['alarm', tr('闹钟')], ['stopwatch', tr('秒表')], ['timer', tr('计时器')]]; +const ALARMS = [{ time: '07:00', note: tr('工作日'), on: true }, { time: '08:30', note: tr('周末'), on: false }]; +const SETTINGS = { + root: { title: tr('设置'), back: null, groups: [[[tr('无线局域网'), tr('已连接'), 'set:none'], [tr('蓝牙'), tr('打开'), 'set:none']], [[tr('通用'), '', 'set:general'], [tr('显示与亮度'), '', 'set:none'], [tr('电池'), '', 'set:none'], [tr('隐私与安全性'), '', 'set:none']]] }, + general: { title: tr('通用'), back: [tr('设置'), 'set:root'], groups: [[[tr('关于本机'), '', 'set:about'], [tr('软件更新'), '', 'set:none']], [[tr('日期与时间'), '', 'set:none'], [tr('键盘'), '', 'set:none']]] }, + about: { title: tr('关于本机'), back: [tr('通用'), 'set:general'], groups: [[[tr('名称'), 'iPhone', null], [tr('iOS 版本'), '18.1', null], [tr('型号名称'), 'iPhone 15 Pro', null], [tr('容量'), '256 GB', null]]] } +}; +const DEMO_DEVICES = [ + { udid: '00008130-001A2B3C4D5E001E', name: 'iPhone 15 Pro', model: 'iPhone16,1', model_name: 'iPhone 15 Pro', family: 'iphone', ios: '18.1', kind: 'iphone', w: 393, h: 852 }, + { udid: '00008112-000C1D2E3F4A5B6C', name: tr('iPad mini(第 6 代)'), model: 'iPad14,1', model_name: tr('iPad mini(第 6 代)'), family: 'ipad', ios: '18.1', kind: 'ipad', w: 1133, h: 744 } // iPad 默认横屏 +]; +let demoDev = DEMO_DEVICES[0]; +const DW = () => demoDev.w, DH = () => demoDev.h; +function osVersion(device) { + const family = device.family ?? (/^iPad[0-9]+,[0-9]+$/.test(device.model) ? 'ipad' : /^iPhone[0-9]+,[0-9]+$/.test(device.model) ? 'iphone' : 'unknown'); + const system = family === 'ipad' ? 'iPadOS' : family === 'iphone' ? 'iOS' : ''; + return device.ios ? [system, device.ios].filter(Boolean).join(' ') : ''; +} +function deviceOptionLabel(device) { + const model = device.model_name || device.model; + if (device.name && model && device.name !== model) return device.name + ' · ' + model; + return device.name || model || device.udid; +} + +const D = { + screen: 'home', clockTab: 'world', setPage: 'root', generic: '', genericSub: '', + sw: { running: false, start: 0, acc: 0, laps: [] }, + chats: { + [tr('妈妈')]: [{ me: false, text: tr('晚上回来吃饭吗?'), t: '18:12' }], + [tr('王磊')]: [{ me: false, text: tr('明天的评审改到上午十点了'), t: '17:40' }], + [tr('快递通知')]: [{ me: false, text: tr('您的包裹已到驿站,凭取件码取件'), t: tr('昨天') }] + }, + chatWho: tr('妈妈'), draft: '', focused: false +}; +const swElapsed = () => D.sw.acc + (D.sw.running ? performance.now() - D.sw.start : 0); +function screenName() { + switch (D.screen) { + case 'home': return tr('主屏幕'); + case 'lock': return tr('锁定屏幕'); + case 'clock': return `${tr('时钟')} · ${CLOCK_TABS.find(t => t[0] === D.clockTab)[1]}`; + case 'settings': return D.setPage === 'root' ? tr('设置') : `${tr('设置')} · ${SETTINGS[D.setPage].title}`; + case 'messages': return tr('信息'); + case 'chat': return `${tr('与「')}${D.chatWho}${tr('」的对话')}`; + default: return D.generic; + } +} +function foreground() { return { home: tr('主屏幕'), lock: tr('主屏幕'), clock: tr('时钟'), settings: tr('设置'), messages: tr('信息'), chat: tr('信息') }[D.screen] || D.generic; } + +function appTile(a, dock) { + return `
${esc(a.glyph)}
${dock ? '' : `
${esc(a.name)}
`}
`; +} +const tz = zone => new Date().toLocaleTimeString('zh-CN', { timeZone: zone, hour: '2-digit', minute: '2-digit', hour12: false }); +function clockBody() { + if (D.clockTab === 'stopwatch') { + const run = D.sw.running; + const laps = D.sw.laps.map((ms, i) => `
${tr('计次')} ${i + 1}${fmtSw(ms)}
`).reverse().join(''); + return `
${fmtSw(swElapsed())}
+
${run ? tr('计次') : tr('复位')}
${run ? tr('停止') : tr('启动')}
+
${laps}
`; + } + if (D.clockTab === 'world') { + const rows = [[tr('北京'), 'Asia/Shanghai', tr('今天')], [tr('伦敦'), 'Europe/London', tr('今天,−8 小时')], [tr('纽约'), 'America/New_York', tr('今天,−13 小时')]]; + return `
${tr('世界时钟')}
${rows.map(([c, z, sub]) => `
${sub}${c}
${tz(z)}
`).join('')}`; + } + if (D.clockTab === 'alarm') { + return `
${tr('闹钟')}
${ALARMS.map(a => `
${a.time}${tr('闹钟,')}${a.note}
`).join('')}`; + } + return `
${tr('计时器')}
05:00
+
${tr('取消')}
${tr('启动')}
`; +} +function screenHtml() { + switch (D.screen) { + case 'home': return `
${APPS.map(a => appTile(a)).join('')}
${DOCK.map(a => appTile(a, true)).join('')}
`; + case 'lock': { const d = new Date(); return `
${d.toLocaleDateString(LANG === 'en' ? 'en-US' : 'zh-CN', { month: 'long', day: 'numeric', weekday: 'long' })}
${hhmm(d)}
${tr('向上轻扫以打开')}
`; } + case 'clock': return `
${clockBody()}
${CLOCK_TABS.map(([k, l]) => `
${l}
`).join('')}
`; + case 'settings': { + const pg = SETTINGS[D.setPage]; + return `
${pg.back ? `
‹ ${pg.back[0]}
` : ''}
${pg.title}
${pg.groups.map(g => `
${g.map(([l, v, act]) => `
${l}${v}${act ? ' ›' : ''}
`).join('')}
`).join('')}
`; + } + case 'messages': return `
${tr('信息')}
${Object.entries(D.chats).map(([who, msgs]) => { const last = msgs[msgs.length - 1]; return `
${esc(who[0])}
${esc(who)}${esc(last.text)}
${esc(last.t)}
`; }).join('')}
`; + case 'chat': { + const msgs = D.chats[D.chatWho] || [], has = D.draft.length > 0; + return `
‹ ${tr('信息')}
${esc(D.chatWho[0])}
${esc(D.chatWho)}
+
${msgs.map(m => `
${esc(m.text)}
`).join('')}
+
${has ? esc(D.draft) : tr('iMessage 信息')}
${tr('发送')}
+ ${D.focused ? tr('
键盘
') : ''}
`; + } + default: return `
${esc(D.generic)}

${esc(D.genericSub || tr('演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。'))}

`; + } +} +function renderDemo() { + const tone = ['messages', 'chat', 'generic'].includes(D.screen) ? ' ph--light' : D.screen === 'settings' ? ' ph--gray' : D.screen === 'clock' ? ' ph--black' : ''; + demoEl.className = 'ph' + tone + (demoDev.kind === 'ipad' ? ' ph--ipad' : ''); + demoEl.innerHTML = `
${hhmm()}5G
${screenHtml()}
`; + if (S.mode === 'demo') { + if (S.dstatus) { S.dstatus.foreground = foreground(); S.dstatus.locked = D.screen === 'lock'; } + S.elements = []; S.elState = 'stale'; renderChips(); if (S.devTab === 'status') renderStatusPanel(); if (S.devTab === 'elements') renderElements(); } +} +function demoOpen(screen) { D.screen = screen; if (screen !== 'chat') D.focused = false; renderDemo(); } +function demoLaunch(a) { + if (a.id === 'clock') { demoOpen('clock'); } + else if (a.id === 'settings') { D.setPage = 'root'; demoOpen('settings'); } + else if (a.id === 'messages') { demoOpen('messages'); } + else { D.generic = a.name; D.genericSub = ''; demoOpen('generic'); } + return `${tr('打开了「')}${a.name}${tr('」')}`; +} +function demoAct(act) { + const i = act.indexOf(':'), k = act.slice(0, i), v = act.slice(i + 1); + switch (k) { + case 'app': return demoLaunch(appById(v)); + case 'tab': D.clockTab = v; renderDemo(); return `${tr('切到「')}${CLOCK_TABS.find(t => t[0] === v)[1]}${tr('」')}`; + case 'set': if (v === 'none') return tr('演示模式没有模拟这一页'); D.setPage = v; renderDemo(); return `${tr('进入「')}${SETTINGS[v].title}${tr('」')}`; + case 'sw': + if (v === 'toggle') { + if (D.sw.running) { D.sw.acc = swElapsed(); D.sw.running = false; renderDemo(); return tr('秒表已停止'); } + D.sw.start = performance.now(); D.sw.running = true; renderDemo(); return tr('秒表开始计时'); + } + if (v === 'lap') { D.sw.laps.push(swElapsed()); renderDemo(); return `${tr('记了第')} ${D.sw.laps.length} ${tr('次计次')}`; } + D.sw = { running: false, start: 0, acc: 0, laps: [] }; renderDemo(); return tr('秒表已复位'); + case 'open-chat': D.chatWho = v; D.draft = ''; D.focused = false; demoOpen('chat'); return `${tr('打开了与「')}${v}${tr('」的对话')}`; + case 'chat': + if (v === 'back') { demoOpen('messages'); return tr('回到「信息」列表'); } + if (v === 'focus') { D.focused = true; renderDemo(); return tr('输入框获得焦点,弹出了键盘'); } + return demoSend(); + case 'timer': return tr('演示模式没有模拟计时器'); + } + return tr('这里没有可点的东西'); +} +function demoSend() { + if (!D.draft) return tr('输入框是空的,没有发出任何内容'); + (D.chats[D.chatWho] ||= []).push({ me: true, text: D.draft, t: hhmm() }); + const sent = D.draft; D.draft = ''; renderDemo(); + return `${tr('已发送给「')}${D.chatWho}${tr('」:')}${sent}`; +} +function demoType(text, submit) { + if (!(D.screen === 'chat' && D.focused)) return { ok: false, message: tr('没有弹出键盘:先在画面里点一下输入框。') }; + D.draft += text; renderDemo(); + return submit ? { ok: true, message: demoSend() } : { ok: true, message: `${tr('已输入「')}${text}${tr('」')}` }; +} +function demoKey(key) { + if (key === 'home') { const wasLocked = D.screen === 'lock'; demoOpen('home'); return wasLocked ? tr('已自动解锁,回到主屏幕') : tr('回到主屏幕'); } + if (key === 'lock') { demoOpen('lock'); return tr('已锁屏'); } + return key === 'volume_up' ? tr('音量加(演示画面没有变化)') : tr('音量减(演示画面没有变化)'); +} +setInterval(() => { + if (S.mode === 'demo' && D.screen === 'clock' && D.clockTab === 'stopwatch' && D.sw.running) { + const el = $('.sw-time', demoEl); if (el) el.textContent = fmtSw(swElapsed()); + } +}, 50); +function demoElements() { + const R = demoEl.getBoundingClientRect(), k = R.width / DW() || 0; + return $$('[data-label]', demoEl).map(e => { + const r = e.getBoundingClientRect(); + return { type: e.dataset.type || 'StaticText', label: e.dataset.label, x: k ? round1((r.left - R.left) / k) : 0, y: k ? round1((r.top - R.top) / k) : 0, width: k ? round1(r.width / k) : 0, height: k ? round1(r.height / k) : 0 }; + }); +} + +/* ================================================================ + * 画面几何 + * ================================================================ */ diff --git a/apps/iphone-control/web/js/device.js b/apps/iphone-control/web/js/device.js new file mode 100644 index 0000000..eda4152 --- /dev/null +++ b/apps/iphone-control/web/js/device.js @@ -0,0 +1,295 @@ +const CHECKS = [ + { name: tr('USB 连接'), fail: ['Absent'], hint: tr('用 USB 连上设备,确认数据线能传数据。') }, + { name: tr('信任这台电脑'), fail: ['NeedsTrust'], hint: tr('运行 iphone-control setup --reconfigure 选「手机」,在设备上点「信任」。') }, + { name: tr('开发者模式'), fail: ['DeveloperModeOff'], hint: tr('在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。') }, + { name: tr('WDA 已签名安装'), fail: ['NeedsSigning'], hint: tr('运行 iphone-control sign,用免费 Apple ID 签名并安装。'), action: 'sign' }, + { name: tr('WDA 运行中'), fail: ['WdaStarting', 'NeedsUnlock', 'NeedsAutomationPin'], hint: '' } +]; +/* 原生控制(iOS 27 起不用 WDA):不签名、不启动 WDA,只挂开发者镜像、连无障碍服务 */ +const NATIVE_CHECKS = [...CHECKS.slice(0, 3), + { name: tr('开发者镜像、无障碍服务'), fail: ['Preparing', 'NeedsUnlock'], hint: '' } +]; +const STARTING_NO_HID = tr('正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。'); +const STARTING_HINT = { + WdaStarting: tr('正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。'), + NeedsUnlock: tr('设备重启后还没解锁过,需要在设备上手动解锁一次。'), + NeedsAutomationPin: tr('设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。'), + Preparing: tr('正在挂开发者镜像、连接无障碍服务,通常几秒到半分钟。') +}; +let statusTimerId = 0, statusSequence = 0; +function refreshStatusSoon() { clearTimeout(statusTimerId); statusTimerId = setTimeout(loadDeviceState, 600); } +async function loadDeviceState() { + if (S.mode === 'demo') { + S.daemon = { state: 'Ready', device: demoDev, auto_unlock: true }; + S.dstatus = { wda_ready: true, locked: D.screen === 'lock', foreground: foreground(), width: DW(), height: DH(), route: 'wda' }; + S.devices = DEMO_DEVICES.map(d => ({ ...d, controlled: d === demoDev })); S.statusErr = ''; S.devicesErr = ''; + } else if (S.mode === 'live') { + const udid = S.udid, sequence = ++statusSequence; + const [d, s, l] = await Promise.allSettled([api('/api/daemon'), api('/api/status'), api('/api/devices')]); + // Video can reconnect while the same device is still waiting for trust or signing. + if (udid !== S.udid || sequence !== statusSequence) return; + S.daemon = d.status === 'fulfilled' ? d.value : null; + // busy: the phone was busy with one of the user's actions, so the check gave way; what was shown stays, asked again soon + if (s.status === 'fulfilled' && s.value.busy) refreshStatusSoon(); + else S.dstatus = s.status === 'fulfilled' ? s.value : null; + S.statusErr = d.status === 'rejected' ? String(d.reason.message) : s.status === 'rejected' ? String(s.reason.message) : ''; + if (l.status === 'fulfilled') { S.devices = l.value.devices || []; S.devicesFixed = !!l.value.fixed; S.devicesErr = ''; } else { S.devices = []; S.devicesErr = String(l.reason.message); } + } + $('#pane-dev').dataset.noDevice = String(S.mode === 'live' && !S.udid); + renderDevices(); renderChips(); renderFeed(); if (S.devTab === 'status') renderStatusPanel(); +} +/* 新设备上还没装 WDA:用已登录的 Apple ID 签名并安装,大约 1–2 分钟 */ +async function signWda() { + if (S.signing) return; + S.signing = true; renderFeed(); if (S.devTab === 'status') renderStatusPanel(); + show(tr('正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…')); + try { await act('/api/sign', {}); } finally { S.signing = false; await loadDeviceState(); } +} +function renderDevices() { + if (S.mode === 'detecting') return; + if (!S.devices.length) { + deviceEl.innerHTML = ``; deviceEl.disabled = true; + deviceEl.title = S.devicesErr || ''; pickerSync.device(); return; + } + const cur = S.devices.find(d => d.controlled); + const labels = S.devices.map(deviceOptionLabel); + deviceEl.innerHTML = S.devices.map((d, index) => { + const name = labels[index]; + const duplicate = labels.indexOf(name) !== labels.lastIndexOf(name); + const label = duplicate ? name + ' · ' + d.udid : name; + return ``; + }).join('') + + ``; + deviceEl.disabled = guarded() || S.switching || S.devicesFixed; + deviceEl.title = [deviceEl.selectedOptions[0]?.textContent, S.devicesFixed && tr('已用 IPHONE_UDID 固定设备,不能切换')].filter(Boolean).join(' · '); + pickerSync.device(); +} +deviceEl.addEventListener('change', () => selectDevice(deviceEl.value)); +$('#nav-devices').addEventListener('click', ev => { + const row = ev.target.closest('button[data-device]'); + if (row && !row.disabled && row.getAttribute('aria-current') !== 'true') selectDevice(row.dataset.device); +}); +async function selectDevice(v) { + if (guarded() || S.switching || S.devicesFixed) return; + if (S.mode === 'demo') { + const next = v === 'auto' ? demoDev : DEMO_DEVICES.find(d => d.udid === v); + if (!next || next === demoDev) { show(v === 'auto' ? `${tr('已改为自动选择:继续控制')} ${demoDev.name}` : tr('已经在控制这台设备')); return; } + demoDev = next; D.screen = 'home'; D.focused = false; + applyDemoGeometry(); renderDemo(); await loadDeviceState(); + S.appsState = 'idle'; if (S.devTab === 'apps') loadApps(); + show(`${tr('已切换到')} ${next.name}${tr('(演示)')}`); + return; + } + cancelGestures(); S.switching = true; deviceEl.disabled = true; pickerSync.device(); + try { + const r = await act('/api/select', { device: v }, true); + // /api/info 确认当前设备后才重新启用输入 + if (r.ok) { const u = S.udid; await loadInfo(); if (S.udid === u) show(r.message || tr('已经在控制这台设备')); } + } finally { S.switching = false; renderFeed(); renderElements(); await loadDeviceState(); } +} +function renderChips() { + const c = $('#chips'), d = S.daemon, s = S.dstatus; + if (S.mode === 'detecting') { c.innerHTML = ''; return; } + const chips = []; + if (frame.hasAttribute('data-absent')) { c.replaceChildren(); return; } + const ready = d?.state === 'Ready'; + chips.push(`${ready ? tr('就绪') : d ? tr('未就绪') : S.stream === 'error' ? tr('画面断开') : tr('连接中')}`); + // 不知道锁没锁(WDA 没起来、又没有 HID)时不显示 + if (s && s.locked != null) { + chips.push(`${tr('屏幕')}${s.locked ? tr('已锁定') : tr('未锁定')}`); + } + // first: the most important to see, and the row may be cut off on the right + if (S.readOnly) chips.unshift(`${tr('只读')}`); + c.innerHTML = chips.join(''); +} +// Keep the native disclosures and focused device buttons intact between status polls. +function navigatorHTML(id, html) { + const node = $(id); + if (node.navMarkup !== html) { node.innerHTML = html; node.navMarkup = html; } +} +function renderStatusPanel() { + const d = S.daemon, s = S.dstatus, dev = d?.device; + const list = S.devices.length ? S.devices : dev?.udid ? [dev] : []; + const selected = dev?.udid || S.udid; + const entries = list.map(item => { + const active = !!item.controlled || item.udid === selected; + const title = item.name || item.model_name || item.model || item.udid; + const model = item.model_name || item.model; + const duplicate = list.some(other => other.udid !== item.udid && deviceOptionLabel(other) === deviceOptionLabel(item)); + const sub = [model && model !== title && model, osVersion(item), duplicate && item.udid].filter(Boolean).join(' · '); + return `
  • `; + }); + const empty = S.mode === 'detecting' ? tr('正在查找…') : S.devicesErr ? tr('不可用') : tr('没有设备'); + navigatorHTML('#nav-devices', entries.join('') || ``); + + const screen = dims(); + const fact = ([k, v], mono = false) => `
    ${esc(k)}
    ${esc(v)}
    `; + const facts = [ + [tr('前台 App'), s?.foreground], [tr('屏幕'), s?.locked != null && (s.locked ? tr('已锁定') : tr('未锁定'))], + [tr('操作通道'), s?.route === 'wda' ? 'WDA' : s?.route === 'hid' ? tr('HID 后备') : s?.route === 'native' ? tr('原生') : null], + [tr('屏幕尺寸'), screen && `${screen.W} × ${screen.H} pt`], [tr('自动解锁'), d && (d.auto_unlock ? tr('已设置密码') : tr('未设置'))] + ].filter(([,v]) => v); + $('#nav-facts').hidden = !selected || !facts.length; + navigatorHTML('#nav-facts', facts.map(row => fact(row)).join('')); + const ids = [['ProductType', dev?.model], ['UDID', selected]].filter(([,v]) => v); + $('#device-identifiers').hidden = !ids.length; + navigatorHTML('#nav-ids', ids.map(row => fact(row, true)).join('')); + + const error = S.statusErr || S.devicesErr; + const allChecks = d?.state === 'Preparing' || s?.route === 'native' ? NATIVE_CHECKS : CHECKS; + const failAt = allChecks.findIndex(check => check.fail.includes(d?.state)); + const checks = d?.state === 'Ready' ? allChecks : allChecks.slice(0, failAt + 1); + const rows = checks.map((c,i) => { + const issue = i === failAt; + const busy = issue && (d.state === 'WdaStarting' || d.state === 'Preparing'); + const hint = issue && (c.hint || (busy && s?.route === 'none' ? STARTING_NO_HID : STARTING_HINT[d.state])); + const label = issue ? (busy ? tr('进行中') : tr('需要处理')) : tr('已完成'); + const sign = issue && c.action === 'sign' && d.signed_in; + return `
  • ${icon(issue ? (busy ? 'loader' : 'info') : 'check', issue ? (busy ? 'spin' : '') : 'check-ok')} +
    ${c.name}${tr(':')}${label} + ${hint ? `${hint}` : ''} + ${sign ? `` : ''} + ${issue && d.last_error ? `${esc(d.last_error)}` : ''}
  • `; + }); + navigatorHTML('#nav-checks', (rows.length ? `` : '') + + (error || !d ? `

    ${esc(error || tr('还没有拿到守护进程状态。'))}

    ` : '')); +} + +/* ================================================================ + * 应用 + * ================================================================ */ +async function loadApps() { + S.appsState = 'loading'; renderApps(); + const sys = $('#app-sys').checked, target = S.udid; + try { + if (S.mode === 'demo') { await sleep(350); S.apps = sys ? ALL_APPS.map(a => ({ name: a.name, bundle_id: a.bundle })) : []; } + else { + const result = await api(`/api/apps?system=${sys ? 1 : 0}`); + if (target !== S.udid || sys !== $('#app-sys').checked) return; + S.apps = result.apps || []; + } + S.appsState = 'ok'; + } catch (e) { if (target !== S.udid || sys !== $('#app-sys').checked) return; S.appsState = 'error'; S.appsErr = String(e.message || e); } + renderApps(); +} +function renderApps() { + const ul = $('#apps'), q = $('#app-q').value.trim().toLowerCase(), lock = guarded(); + const list = S.apps.filter(a => !q || a.name.toLowerCase().includes(q) || a.bundle_id.toLowerCase().includes(q)); + $('#apps-count').textContent = S.appsState === 'ok' ? `${list.length} ${tr('个')}${S.mode === 'demo' ? tr(' · 演示数据') : ''}` : ''; + if (S.appsState === 'loading') { ul.innerHTML = tr('
  • 正在读取 App 列表…
  • ') + ''.repeat(6); return; } + if (S.appsState === 'error') { ul.innerHTML = `
  • ${esc(S.appsErr)}
  • `; return; } + if (S.appsState !== 'ok') { ul.innerHTML = tr('
  • 打开这一页时会读取已安装的 App。
  • '); return; } + if (!list.length) { ul.innerHTML = `
  • ${q ? `${tr('没有名称或 bundle id 含「')}${esc(q)}${tr('」的 App。')}` : $('#app-sys').checked ? tr('没有读到 App。') : tr('没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。')}
  • `; return; } + ul.innerHTML = list.map(a => { + const meta = appByAny(a.bundle_id); + const tile = meta ? `style="background:${meta.bg};color:${meta.fg}"` : 'style="background:var(--sunken);color:var(--text-2)"'; + return `
  • + ${esc(a.name)}${esc(a.bundle_id)} + +
  • `; + }).join(''); +} +$('#app-q').addEventListener('input', renderApps); +$('#app-sys').addEventListener('change', loadApps); +async function launchApp(bundle, name) { + if (guarded()) { nudgeGuard(); return; } + if (S.mode === 'live') return act('/api/launch_app', { app: bundle }); + show(demoLaunch(appByAny(bundle) || { id: bundle, name })); +} +async function terminateApp(bundle, name) { + if (guarded()) { nudgeGuard(); return; } + if (S.mode === 'live') return act('/api/terminate_app', { app: bundle }); + if (foreground() === name) demoOpen('home'); + show(`${tr('已结束「')}${name}${tr('」')}`); +} +async function openUrl() { + if (guarded()) { nudgeGuard(); return; } + const inp = $('#url'), url = inp.value.trim(); + if (!url) { show(tr('先填要打开的链接'), 'err'); inp.focus(); return; } + if (S.mode === 'live') { if ((await act('/api/open_url', { url })).ok) inp.value = ''; return; } + if (/^https?:\/\//i.test(url)) { D.generic = 'Safari'; D.genericSub = `${tr('正在打开')} ${url}${tr('(演示画面不加载网页)')}`; demoOpen('generic'); show(`${tr('已用 Safari 打开')} ${url}`); inp.value = ''; } + else show(tr('演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试'), 'err'); +} +$('#url').addEventListener('keydown', ev => { if (ev.key === 'Enter' && !ev.isComposing) { ev.preventDefault(); openUrl(); } }); + +/* ================================================================ + * 元素 + * ================================================================ */ +async function loadElements() { + const epoch = feedEpoch; + S.elState = 'loading'; renderElements(); + try { + if (S.mode === 'demo') { await sleep(300); S.elements = demoElements(); } + else { + const result = await api('/api/elements?filter='); + if (epoch !== feedEpoch) return; + S.elements = result.elements || []; + } + S.elState = 'ok'; + } catch (e) { if (epoch !== feedEpoch) return; S.elState = 'error'; S.elErr = String(e.message || e); } + renderElements(); +} +function renderElements() { + const ul = $('#elements'), q = $('#el-q').value.trim().toLowerCase(), lock = guarded() || (S.mode === 'live' && (!S.udid || S.switching)); + const list = S.elements.map((e, i) => ({ ...e, i })).filter(e => !q || e.label.toLowerCase().includes(q) || e.type.toLowerCase().includes(q)); + $('#el-count').textContent = S.elState === 'ok' ? `${list.length} ${tr('个')}${S.mode === 'demo' ? tr(' · 演示数据') : ''}` : ''; + if (S.elState === 'loading') { ul.innerHTML = tr('
  • 正在读取元素…
  • ') + ''.repeat(6); return; } + if (S.elState === 'error') { ul.innerHTML = `
  • ${esc(S.elErr)}
  • `; return; } + if (S.elState === 'stale' || S.elState === 'idle') { ul.innerHTML = `
  • ${S.elState === 'stale' ? tr('界面变了,') : ''}${tr('点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。')}
  • `; return; } + if (!list.length) { ul.innerHTML = `
  • ${q ? `${tr('没有含「')}${esc(q)}${tr('」的元素。')}` : tr('当前界面没有带文字的元素。')}
  • `; return; } + ul.innerHTML = list.map(e => `
  • + ${esc(e.label)}${esc(e.type)} · ${Math.round(e.x + e.width / 2)}, ${Math.round(e.y + e.height / 2)} +
  • `).join(''); +} +$('#el-q').addEventListener('input', renderElements); +const elList = $('#elements'); +elList.addEventListener('pointerover', ev => { const row = ev.target.closest('[data-el]'); if (row) highlight(S.elements[+row.dataset.el]); }); +elList.addEventListener('pointerleave', () => highlight(null)); +elList.addEventListener('focusin', ev => { const row = ev.target.closest('[data-el]'); if (row) highlight(S.elements[+row.dataset.el]); }); +elList.addEventListener('focusout', () => highlight(null)); +async function tapElement(i) { + if (guarded()) { nudgeGuard(); return; } + const e = S.elements[i]; if (!e) return; + const same = S.elements.slice(0, i).filter(x => x.label === e.label).length; + highlight(null); + if (dims()) drawMark('tap', 'user', { x: round1(e.x + e.width / 2), y: round1(e.y + e.height / 2) }); + if (S.mode === 'live') await act('/api/tap_element', { text: e.label, index: same }); + else { + const el = $$('[data-label]', demoEl).filter(x => x.dataset.label === e.label)[same]; + show(`${tr('按名字点「')}${e.label}${tr('」:')}${el && el.dataset.act ? demoAct(el.dataset.act) : tr('它不是可点的控件,界面没有变化')}`); + } + S.elState = 'stale'; renderElements(); +} +async function waitFor() { + const inp = $('#wait-q'), text = inp.value.trim(), out = $('#wait-result'), btn = $('#wait-btn'); + if (!text) { inp.focus(); out.hidden = false; out.className = 'wait-result t-danger'; out.textContent = tr('先填要等的文字。'); return; } + btn.disabled = true; btn.textContent = tr('等待中…'); out.hidden = false; out.className = 'wait-result t-muted'; out.textContent = `${tr('等「')}${text}${tr('」出现,最多 5 秒')}…`; + let ok = false, msg = ''; + try { + if (S.mode === 'live') { const v = await api('/api/wait_for', { text, timeout: 5 }); ok = !!v.ok; msg = v.message || ''; } + else { + const t0 = Date.now(); + while (Date.now() - t0 < 5000) { if (demoElements().some(e => e.label.includes(text) && e.type !== 'TextField')) { ok = true; break; } await sleep(200); } + msg = ok ? `${tr('「')}${text}${tr('」已经出现(')}${((Date.now() - t0) / 1000).toFixed(1)} ${tr('秒)')}` : `5 ${tr('秒内没有出现「')}${text}${tr('」')}`; + } + } catch (e) { msg = String(e.message || e); } + out.className = `wait-result ${ok ? 't-ok' : 't-danger'}`; out.textContent = msg; + btn.disabled = false; btn.textContent = tr('等待 5 秒'); +} +$('#wait-q').addEventListener('keydown', ev => { if (ev.key === 'Enter' && !ev.isComposing) { ev.preventDefault(); waitFor(); } }); + +function setDevTab(tab) { + S.devTab = tab; + ['status', 'apps', 'elements'].forEach(t => { + $(`#tab-${t}`).setAttribute('aria-selected', String(t === tab)); + $(`#tp-${t}`).hidden = t !== tab; + }); + if (tab === 'status') renderStatusPanel(); + if (tab === 'apps' && S.appsState === 'idle' && (S.mode === 'demo' || S.udid)) loadApps(); else if (tab === 'apps') renderApps(); + if (tab === 'elements') renderElements(); +} + +/* ================================================================ + * AI 任务:演示脚本 + * ================================================================ */ diff --git a/apps/iphone-control/web/js/i18n.js b/apps/iphone-control/web/js/i18n.js new file mode 100644 index 0000000..0f0294d --- /dev/null +++ b/apps/iphone-control/web/js/i18n.js @@ -0,0 +1,99 @@ +'use strict'; + +/* ================================================================ + * 语言:页面的文字中英两套。默认跟着 viewer(IPHONE_CONTROL_LANG,服务端写在 ),页面上切换后记在浏览器里。 + * 每个请求带上 X-Ictl-Lang,守护进程的回复和 AI 任务也用这种语言 + * ================================================================ */ +const LANG = (() => { + let v = null; + try { v = localStorage.getItem('ictl.lang'); } catch { /* 预览环境可能禁用存储 */ } + return v === 'en' || v === 'zh' ? v : document.documentElement.dataset.lang === 'en' ? 'en' : 'zh'; +})(); +document.documentElement.lang = LANG === 'en' ? 'en' : 'zh-CN'; +const EN = {"登录已过期":"Login expired","只读登录":"Read-only login",":能看画面、设备状态和任务,不能操作手机,也不能开始、暂停或确认任务。":": you can watch the picture, the device's state and tasks, but not act on the phone or start, pause or confirm tasks.","只读":"Read-only","只读登录:只能看,不能操作":"Read-only login: you can watch, not act","任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","
    键盘
    ":"
    Keyboard
    ","
  • 打开这一页时会读取已安装的 App。
  • ":"
  • The installed apps are read when this tab opens.
  • ","
  • 正在读取 App 列表…
  • ":"
  • Reading the app list…
  • ","
  • 正在读取元素…
  • ":"
  • Reading elements…
  • ","":"","

    正在连接 iphone-control 服务…

    ":"

    Connecting to the iphone-control service…

    ","演示模式":"Demo","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","原生":"Native","正在准备设备(挂载开发者镜像、连接无障碍服务)…":"Preparing the device (mounting the developer disk image, connecting to the accessibility service)…",":准备设备失败,会自动重试":": preparing the device failed, retrying automatically","开发者镜像、无障碍服务":"Developer disk image, accessibility service","正在挂开发者镜像、连接无障碍服务,通常几秒到半分钟。":"Mounting the developer disk image and connecting to the accessibility service, usually a few seconds to half a minute.","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 iphone-control sign,用免费 Apple ID 签名并安装。":"Run iphone-control sign to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 iphone-control setup --reconfigure 选「手机」,在设备上点「信任」。":"Run iphone-control setup --reconfigure, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress","弱网模式":"Low-bandwidth mode","画面流量减少约一半,帧率不变,适合外网或信号差时用;画面动起来时会略糊。手机自己的画面(HEVC)只有一路,开着时所有在看这台手机的页面都会一起降,切换时画面会断开半秒左右。":"About half the picture's traffic at the same frame rate, for use over the internet or a weak signal; moving content gets a little blurry. The phone's own picture (HEVC) is one stream, so while this is on every page watching this phone gets it too, and switching interrupts the picture for about half a second.","已开启弱网模式,正在重新连接画面…":"Low-bandwidth mode on, reconnecting the picture…","已关闭弱网模式,正在重新连接画面…":"Low-bandwidth mode off, reconnecting the picture…"}; +Object.assign(EN, { + '未连接设备':'No device connected', '用数据线连接 iPhone 或 iPad。':'Connect an iPhone or iPad with a USB cable.', '等待设备连接':'Waiting for a device', + '外观':'Appearance', '界面字号':'Text size', '标准':'Standard', '大':'Large', '特大':'Extra large', + '暂无任务':'No tasks yet', '执行步骤和确认请求会显示在这里。':'Steps and approval requests appear here.', + '可以先写下任务,连接设备后再执行。':'Draft a task while waiting for a device.', + '任务将在模拟设备上运行。':'Tasks run on the simulated device.', '开始任务(Enter)':'Start task (Enter)', + '明暗':'Theme', '跟随系统':'System', '浅色':'Light', '深色':'Dark', '完成':'Done' +}); +Object.assign(EN, { + '设备列表':'Devices', '设备标识':'Device identifiers', '连接检查':'Connection checks', + '连接设备后可查看应用。':'Connect a device to view its apps.', + '连接设备后可查看界面元素。':'Connect a device to inspect its interface.' +}); +Object.assign(EN, { + '设备画面':'Device view', '连接你的设备':'Connect your device', '连接帮助':'Connection help', + '用 USB 数据线连接 iPhone 或 iPad,并在设备上轻点「信任」。':'Connect your iPhone or iPad with a USB cable, then tap Trust on the device.', + '等待设备画面':'Waiting for the screen', '正在连接本地服务':'Connecting to the local service' +}); +Object.assign(EN, {'版本详情':'Details','复制升级命令':'Copy upgrade command','关闭版本信息':'Close version information','关于与更新':'About & updates','完成':'Done','检查更新':'Check for updates','检查中…':'Checking…','发行说明':'Release notes','升级命令':'Upgrade command','复制命令':'Copy command','已复制':'Copied','请选中命令并手动复制。':'Select the command and copy it manually.'}); +/* 中文原文 → 当前语言 */ +Object.assign(EN, { '画面已连接 · 等待屏幕尺寸和方向,仅可观看':'Picture connected · waiting for screen dimensions and orientation (view only)', '没有收到设备画面,3 秒后自动重试。':'No picture received. Retrying in 3 seconds.' }); +Object.assign(EN, { + '设置': 'Settings', '界面语言': 'Language', '没有可用的 AI': 'No AI available' +}); +function tr(zh) { return LANG === 'en' ? (EN[zh] ?? zh) : zh; } +/* 静态标记里的文字和提示(aria-label、title、placeholder、alt)开始时译一次 */ +(function translateStatic() { + if (LANG !== 'en') return; + document.title = tr(document.title); + const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); + for (let n = walk.nextNode(); n; n = walk.nextNode()) { + const s = n.nodeValue.trim(); + if (s && EN[s] !== undefined) n.nodeValue = n.nodeValue.replace(s, EN[s]); + } + document.querySelectorAll('[aria-label],[title],[placeholder],[alt]').forEach(el => { + for (const a of ['aria-label', 'title', 'placeholder', 'alt']) { const v = el.getAttribute(a); if (v && EN[v] !== undefined) el.setAttribute(a, EN[v]); } + }); +})(); +const language = document.getElementById('language-value'); +language.value = LANG; +language.addEventListener('change', () => { + try { + localStorage.setItem('ictl.lang', language.value); + sessionStorage.setItem('ictl.languageDraft', document.getElementById('prompt').value); + } catch { /* Storage can be unavailable in a local preview. */ } + location.reload(); +}); +/* ================================================================ + * 接口(apps/iphone-control/src/viewer.rs、agent.rs) + * + * 画面与手动操作,都经守护进程,和 MCP 工具一样排队、自动解锁、只作用于这个页面跟着的设备: + * GET /stream → WebDriverAgent 的 MJPEG 画面 + * GET /api/info → { width, height, udid, device, warning? } + * POST /api/tap | swipe | long_press | type | button | launch_app | terminate_app | open_url | tap_element | wait_for + * → { ok, message } + * + * 设备面板: + * GET /api/daemon → { state, state_text, last_error?, device: { name, model, ios, udid }, auto_unlock } + * GET /api/status → { wda_ready, locked, foreground, foreground_id, width, height, route: "wda"|"hid"|"none" } + * GET /api/devices → { devices: [{ udid, name, model, ios, controlled }], fixed, auto } + * POST /api/select { device } // UDID、设备名或 "auto" + * GET /api/apps?system=1 → { apps: [{ name, bundle_id }] } + * GET /api/elements?filter= → { elements: [{ type, label, x, y, width, height }] } // x、y 是左上角,单位点 + * GET /api/alert → { alert: null | { text, frame?: { x, y, width, height }, buttons: [{ label, x, y, width }] } } // 系统弹窗,单位点:弹窗的框(左上角)、按钮中心和宽;画面是手机自己的视频时页面定时问(2~6 秒,见 alertLoop) + * state 取值:Absent | NeedsTrust | DeveloperModeOff | NeedsSigning | WdaStarting | NeedsUnlock | NeedsAutomationPin | Preparing | Ready + * + * AI 任务:交给本机的 Claude Code 或 Codex,它只能用 iphone-control 的 MCP 工具;每一步都经守护进程过一道闸, + * 所以暂停、接管、确认在那里生效,和用哪个 agent 无关: + * GET /api/agent/backends → { backends: [{ id, name, available }] } + * GET /api/agent/tasks → { tasks: [{ id, title, owner, udid, state, started, ended?, steps }] } + * 守护进程里的全部任务,含在别处开的(iphone-control task run);有正在进行的就接上它的事件 + * POST /api/agent/tasks { prompt, agent } → { id } + * GET /api/agent/tasks/{id}/events SSE:step | confirm | state | done(连上时先重放已有的事件) + * step { id, thought?, tool?, args?, status: running|ok|error|waiting|rejected|stopped, ms?, result?, screenshot?, gesture? } + * confirm { step, action, detail } + * state { state: running|paused|takeover|waiting } + * done { ok, stopped?, outcome, summary } outcome:completed|failed|cancelled|rejected|abandoned|interrupted + * POST /api/agent/tasks/{id}/pause | resume | takeover | handback | stop + * POST /api/agent/tasks/{id}/confirm { step, approve } + * 任务在守护进程里(docs/task-control.md):任务进行中(没有接管时)守护进程拒绝别人的操作,结果里说明原因。 + * + * 所有 POST 要求同源 Origin + JSON。打不开 /api/info 时(例如直接打开这个文件)进入演示模式,所有数据都在本地模拟。 + * ================================================================ */ + +const $ = (s, r = document) => r.querySelector(s); +const $$ = (s, r = document) => Array.from(r.querySelectorAll(s)); diff --git a/apps/iphone-control/web/js/info.js b/apps/iphone-control/web/js/info.js new file mode 100644 index 0000000..733a55a --- /dev/null +++ b/apps/iphone-control/web/js/info.js @@ -0,0 +1,240 @@ +function applyInfo(v) { + const udid = v.udid || null; + S.login = v.login || null; S.readOnly = S.login?.role === 'view'; + document.documentElement.toggleAttribute('data-readonly', S.readOnly); + if (S.readOnly) $('#readonly-note').textContent = `${tr('只读登录')}(${S.login.name})${tr(':能看画面、设备状态和任务,不能操作手机,也不能开始、暂停或确认任务。')}`; + S.video = v.video || null; S.deviceVideo = !!v.device_video; + S.size = v.width > 0 && v.height > 0 ? { w: v.width, h: v.height } : null; + frame.toggleAttribute('data-absent', v.state === 'Absent' && !udid); + const changed = S.udid !== udid, display = v.display || null; + if (changed || S.display?.id !== display?.id) { + cancelGestures(); // queue a release for the original device and view + T.fails = 0; + S.rtt = null; S.elements = []; S.elState = 'idle'; + highlight(null); marks.replaceChildren(); hoverDot = null; + if (changed) { + S.daemon = null; S.dstatus = null; S.apps = []; S.appsState = 'idle'; appNames.map = null; appNames.loading = false; + T.warm = 0; V.noDevice = false; V.devRetries = 0; + } + } + const reconnect = feedId && (changed || S.display?.id !== display?.id); + S.udid = udid; S.display = display; + if (changed) { renderManual(); syncSend(); } + S.family = v.family || 'unknown'; frame.dataset.kind = S.family; S.deviceName = v.device || ''; + S.liveTouch = T.fails < 2 && !!v.live_touch; + if (reconnect) { + connect(); + loadDeviceState(); + if (changed && S.devTab === 'apps') loadApps(); + } else if (v.feed_open === false && S.stream === 'ok') { + feedError(); + } + if (v.warning && !S.infoWarning) show(v.warning, 'err'); + S.infoWarning = v.warning || ''; +} +function signButton(label) { + return ``; +} +/* 没有画面时,按守护进程的状态说清楚卡在哪、怎么办 */ +function stageNote() { + const d = S.daemon, name = d?.device?.name || S.deviceName || tr('设备'); + switch (d?.state || (frame.hasAttribute('data-absent') ? 'Absent' : null)) { + case 'Absent': return '' + tr('未连接设备') + '' + tr('用数据线连接 iPhone 或 iPad。'); + case 'NeedsTrust': case 'DeveloperModeOff': + return `${esc(name)} ${esc(tr('还没设置好(配对、开发者模式)。在终端运行'))} iphone-control setup --reconfigure${esc(tr(',选「手机」。'))}`; + case 'NeedsSigning': + return d.signed_in + ? `${esc(name)} ${esc(tr('上还没装 WebDriverAgent。'))}
    ${signButton(tr('签名并安装 WDA'))}` + : `${esc(name)} ${esc(tr('上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行'))} iphone-control setup --reconfigure${esc(tr(',选「Apple ID」。'))}`; + case 'WdaStarting': + // 启动失败过就把原因摆出来(守护进程会自动重试),不要一直说「通常 10–60 秒」 + // 启动失败常见的一种是签名证书变了(给另一台设备重签时换了证书),重签这台就好;登录了 Apple ID 就给个按钮 + if (d.last_error) return `${esc(name)}${esc(tr(':WebDriverAgent 启动失败,会自动重试'))}
    ${esc(d.last_error)}${d.signed_in ? `
    ${signButton(tr('重新签名并安装 WDA'))}` : ''}`; + return `${esc(tr('正在'))} ${esc(name)} ${esc(tr('上启动 WebDriverAgent,通常 10–60 秒…'))}`; + case 'Preparing': + // 原生控制(iOS 27 起不用 WDA):只要挂开发者镜像、连无障碍服务 + if (d.last_error) return `${esc(name)}${esc(tr(':准备设备失败,会自动重试'))}
    ${esc(d.last_error)}`; + return esc(tr('正在准备设备(挂载开发者镜像、连接无障碍服务)…')); + case 'NeedsUnlock': return esc(tr('设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。')); + case 'NeedsAutomationPin': return esc(tr('设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。')); + default: return esc(tr('没有收到设备画面,3 秒后自动重试。')); + } +} +function showStageNote() { + if (S.mode !== 'live' || S.stream !== 'error') return; + const html = stageNote(); if (stageMsg.dataset.note !== html) { stageMsg.innerHTML = html; stageMsg.dataset.note = html; } // 不变就不重画,免得按钮丢了焦点 + stageMsg.hidden = false; +} +// Opening the popover reads the host's cached report, even when no device is connected. +const updateDialog = $('#updates-dialog'), updateCheck = $('#update-check'); +const aboutUpdates = $('#about-updates'), updateCommand = $('#update-command'), copyStatus = $('#update-copy-status'); +let updatePoll, readingUpdates = false; +const updateText = (zh, en) => LANG === 'en' ? en : zh; +function newerRelease(r) { + return r.available_version && ['available', 'brew_check', 'platform_pending', 'manual_only', 'unsupported'].includes(r.availability); +} +function drawUpdateBadge(r) { + const newer = newerRelease(r); + $('#update-dot').hidden = !newer; + const label = tr('关于与更新') + (newer ? updateText(' · 新版本 ', ' · New release ') + r.available_version : ''); + aboutUpdates.title = label; + aboutUpdates.setAttribute('aria-label', label); +} +function setUpdateCommand(command) { + if (updateCommand.textContent !== command) { + copyStatus.textContent = ''; + updateCommand.textContent = command; + } + $('#update-command-block').hidden = $('#update-copy').hidden = !command; +} +// The first changelog item is an excerpt. The release page has the full notes. +function updateExcerpt(markdown) { + const line = markdown.split(/\r?\n/).map(s => s.trim()).find(s => s && !/^#|^---|^