Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

refactor(daemon): one error type for carrying out requests (#94)

Qinghe Li9a6e8b2ea318
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c4280fe..3b91faa 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -83,6 +83,7 @@ Notes:
- **Vendored code** (`vendor/`) keeps its license. Record any change in [THIRD_PARTY.md](THIRD_PARTY.md); changed MPL-2.0 files stay MPL-2.0.
- **Never commit** `data/`, `~/.config/iphone-control/env` or other settings files with secrets, certificates, provisioning profiles, pairing records or anything Apple ships (Developer Disk Images, frameworks).
- Comments explain *why*, especially device quirks; put measured numbers next to timeouts and thresholds.
+- **Errors:** the daemon returns `crate::error::Result` (`ictl_daemon::error::Error`): WDA's, the device's and unlocking's errors pass through `?` as they are, the daemon's own messages are `Error::Msg`; small pure helpers may keep `Result<_, String>`. The caller gets the text in its language, so word messages for it. The CLI uses `anyhow` (with context for people reading it), the control page's JSON carries a `message` string. New facts a client acts on go into a structured field (`Outcome`, `Data`, `retry_as_gesture`), never into wording it has to match.
## Required tests
diff --git a/Cargo.lock b/Cargo.lock
index ab08ea2..1f7a249 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1973,6 +1973,7 @@ dependencies = [
"serde",
"serde_json",
"sha2 0.10.9",
+ "thiserror 2.0.21",
"tokio",
"tracing",
"uuid",
diff --git a/crates/ictl-daemon/Cargo.toml b/crates/ictl-daemon/Cargo.toml
index feb9bc1..d9df417 100644
--- a/crates/ictl-daemon/Cargo.toml
+++ b/crates/ictl-daemon/Cargo.toml
@@ -24,6 +24,7 @@ serde.workspace = true
serde_json.workspace = true
tracing.workspace = true
anyhow.workspace = true
+thiserror.workspace = true
image.workspace = true
base64.workspace = true
sha2.workspace = true
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index 35a5f92..62b7039 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -657,9 +657,9 @@ impl Daemon {
if g.runner.as_ref().is_some_and(|r| r.alive()) { g.wda.as_mut() } else { None }
}
- pub(crate) fn require_wda<'a>(&self, g: &'a mut Inner) -> Result<&'a mut WdaClient<DeviceTransport>, String> {
+ pub(crate) fn require_wda<'a>(&self, g: &'a mut Inner) -> crate::error::Result<&'a mut WdaClient<DeviceTransport>> {
let msg = wda_down(&g.state, g.info.as_ref());
- self.wda(g).ok_or(msg)
+ self.wda(g).ok_or(msg.into())
}
pub(crate) fn account(&self) -> ictl_sign::AccountDir {
@@ -836,7 +836,7 @@ impl Daemon {
}
/// A task's scope from names or bundle IDs: the bundle IDs, each once. `Err` names the app that isn't there
- pub(crate) async fn resolve_scope(&self, apps: &[String]) -> Result<Vec<String>, String> {
+ pub(crate) async fn resolve_scope(&self, apps: &[String]) -> crate::error::Result<Vec<String>> {
let apps: Vec<&str> = apps.iter().map(|a| a.trim()).filter(|a| !a.is_empty()).collect();
if apps.is_empty() {
return Ok(Vec::new());
@@ -860,7 +860,7 @@ impl Daemon {
mut ctx: CallCtx,
admission: &crate::tasks::Admission,
) -> Response {
- let text = |r: Result<String, String>| {
+ let text = |r: crate::error::Result<String>| {
r.map(|t| Response::text_with(t, crate::protocol::Outcome::default())).unwrap_or_else(Response::error)
};
match lane(&req) {
diff --git a/crates/ictl-daemon/src/devices.rs b/crates/ictl-daemon/src/devices.rs
index 05b9815..e2b72b6 100644
--- a/crates/ictl-daemon/src/devices.rs
+++ b/crates/ictl-daemon/src/devices.rs
@@ -140,7 +140,7 @@ impl Daemon {
}
/// 改为控制 `query` 指的那台(UDID、设备名或 `auto`),选定的写进 state.json,重启后还记得
- pub(crate) async fn select_device(&self, g: &mut Inner, query: &str) -> Result<String, String> {
+ pub(crate) async fn select_device(&self, g: &mut Inner, query: &str) -> crate::error::Result<String> {
if let Ok(d) = ictl_device::list_devices().await {
self.note_connected(g, d).await;
}
@@ -150,7 +150,7 @@ impl Daemon {
return Err(ictl_l10n::trf!(
"IPHONE_UDID 固定为 {u};要改回自动选,先从 ~/.config/iphone-control/env 里删掉它,再重启守护进程",
"IPHONE_UDID pins {u}; to go back to automatic, remove it from ~/.config/iphone-control/env and restart the daemon"
- ));
+ ).into());
}
g.persisted.selected_udid = None;
g.persisted.save(&self.cfg.state_file());
@@ -168,7 +168,7 @@ impl Daemon {
return Err(ictl_l10n::trf!(
"IPHONE_UDID 固定为 {u};要换设备,先改 ~/.config/iphone-control/env 里的 IPHONE_UDID,再重启守护进程",
"IPHONE_UDID pins {u}; to switch devices, change IPHONE_UDID in ~/.config/iphone-control/env and restart the daemon"
- ));
+ ).into());
}
if self.cfg.udid.is_none() {
g.persisted.selected_udid = Some(target.udid.clone());
diff --git a/crates/ictl-daemon/src/devtools.rs b/crates/ictl-daemon/src/devtools.rs
index 1d95416..1f0f672 100644
--- a/crates/ictl-daemon/src/devtools.rs
+++ b/crates/ictl-daemon/src/devtools.rs
@@ -59,11 +59,11 @@ impl Daemon {
since: Duration,
limit: usize,
errors_only: bool,
- ) -> Result<String, String> {
+ ) -> crate::error::Result<String> {
let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
let running = g.dev.log_capture.as_ref().is_some_and(|c| c.udid == device.udid && !c.task.is_finished());
if !running {
- let mut stream = device.log_stream().await.map_err(|e| e.to_string())?;
+ let mut stream = device.log_stream().await?;
let buf = Arc::new(Mutex::new(Buffer::default()));
let b = buf.clone();
let task = tokio::spawn(async move {
@@ -155,7 +155,7 @@ impl Daemon {
process.to_owned()
}
- pub(crate) async fn crash_reports(&self, g: &mut Inner, filter: &str, name: &str) -> Result<String, String> {
+ pub(crate) async fn crash_reports(&self, g: &mut Inner, filter: &str, name: &str) -> crate::error::Result<String> {
let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
if !name.is_empty() {
if name.contains('/') || name.contains("..") {
@@ -165,7 +165,7 @@ impl Daemon {
)
.into());
}
- let data = device.crash_report(name).await.map_err(|e| e.to_string())?;
+ let data = device.crash_report(name).await?;
let text = String::from_utf8_lossy(&data);
let n = text.chars().count();
if n <= MAX_REPORT_CHARS {
@@ -178,7 +178,7 @@ impl Daemon {
"\n… ({n} characters in total, only the first {MAX_REPORT_CHARS} returned)"
));
}
- let names = device.crash_reports().await.map_err(|e| e.to_string())?;
+ let names = device.crash_reports().await?;
let list = crash_list(names, filter);
if list.is_empty() {
return Ok(if filter.is_empty() {
@@ -197,22 +197,23 @@ impl Daemon {
/// Runs without holding the daemon lock (an install can take minutes), like re-signing
/// Installs are queued one at a time inside `Device::install` (they share one upload path on the phone)
- pub(crate) async fn install_app(&self, device: &ictl_device::Device, path: &str) -> Result<String, String> {
+ pub(crate) async fn install_app(&self, device: &ictl_device::Device, path: &str) -> crate::error::Result<String> {
let p = std::path::Path::new(path);
if !p.exists() {
return Err(ictl_l10n::trf!(
"找不到 {path}(路径要在运行守护进程的机器上)",
"{path} not found (the path is on the machine that runs the daemon)"
- ));
+ )
+ .into());
}
- device.install(p).await.map_err(|e| e.to_string())?;
+ device.install(p).await?;
self.inner.lock().await.dev.apps.clear();
Ok(ictl_l10n::trf!("已安装 {path}", "Installed {path}"))
}
/// Uninstalling deletes the app's data, so unlike launching, the name must match exactly: a bundle ID or the
/// whole display name. The app lists are read again first, so an app installed a moment ago is found
- pub(crate) async fn uninstall_app(&self, g: &mut Inner, app: &str) -> Result<String, String> {
+ pub(crate) async fn uninstall_app(&self, g: &mut Inner, app: &str) -> crate::error::Result<String> {
g.dev.apps.clear();
let mut all = self.list_apps(g, false).await?;
all.extend(self.list_apps(g, true).await?);
@@ -221,10 +222,11 @@ impl Daemon {
return Err(ictl_l10n::trf!(
"{bid} 是 WebDriverAgent,iphone-control 靠它控制手机,不能卸载",
"{bid} is WebDriverAgent, which iphone-control needs to control the phone; it can't be uninstalled"
- ));
+ )
+ .into());
}
let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
- device.uninstall(&bid).await.map_err(|e| e.to_string())?;
+ device.uninstall(&bid).await?;
g.dev.apps.clear();
Ok(ictl_l10n::trf!("已卸载 {bid}", "Uninstalled {bid}"))
}
diff --git a/crates/ictl-daemon/src/error.rs b/crates/ictl-daemon/src/error.rs
new file mode 100644
index 0000000..88f4270
--- /dev/null
+++ b/crates/ictl-daemon/src/error.rs
@@ -0,0 +1,58 @@
+//! What went wrong carrying out a request. The caller (an agent, the CLI, the control page) gets its text, worded
+//! for it and in its language; inside the daemon the cause stays what it was (WDA's, the device's, unlocking's),
+//! so `?` passes it on without turning it into a string first, and code can still look at which one it was.
+
+use ictl_device::DeviceError;
+use ictl_unlock::UnlockError;
+use ictl_wda::WdaError;
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error(transparent)]
+ Wda(#[from] WdaError),
+ #[error(transparent)]
+ Device(#[from] DeviceError),
+ #[error(transparent)]
+ Unlock(#[from] UnlockError),
+ #[error(transparent)]
+ Io(#[from] std::io::Error),
+ /// The daemon's own message, already worded for the caller
+ #[error("{0}")]
+ Msg(String),
+}
+
+/// The daemon's result: its [`Error`] unless another is named (`Result<(), Response>`)
+pub type Result<T, E = Error> = std::result::Result<T, E>;
+
+impl From<String> for Error {
+ fn from(m: String) -> Self {
+ Self::Msg(m)
+ }
+}
+
+impl From<&str> for Error {
+ fn from(m: &str) -> Self {
+ Self::Msg(m.to_owned())
+ }
+}
+
+/// The text the caller gets ([`crate::protocol::Response::error`] takes it)
+impl From<Error> for String {
+ fn from(e: Error) -> Self {
+ e.to_string()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The caller reads the same text as before: a cause's own, or the daemon's message
+ #[test]
+ fn the_text_is_the_cause_s_own() {
+ let e: Error = WdaError::StartFailed("x".into()).into();
+ assert_eq!(e.to_string(), WdaError::StartFailed("x".into()).to_string());
+ assert!(matches!(e, Error::Wda(WdaError::StartFailed(_))), "and the cause is still there");
+ assert_eq!(String::from(Error::from("手机未连接")), "手机未连接");
+ }
+}
diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs
index 65175c9..fb23217 100644
--- a/crates/ictl-daemon/src/lib.rs
+++ b/crates/ictl-daemon/src/lib.rs
@@ -11,6 +11,7 @@ pub mod core;
pub mod devices;
mod devtools;
mod doctor;
+pub mod error;
pub mod eventlog;
pub mod imaging;
pub mod machine;
diff --git a/crates/ictl-daemon/src/screen.rs b/crates/ictl-daemon/src/screen.rs
index 152548a..d14036c 100644
--- a/crates/ictl-daemon/src/screen.rs
+++ b/crates/ictl-daemon/src/screen.rs
@@ -162,7 +162,7 @@ impl Daemon {
async fn screen_feed(
self: &Arc<Self>,
expect_udid: Option<&str>,
- ) -> Result<(ictl_device::ScreenFeed, Viewer), String> {
+ ) -> crate::error::Result<(ictl_device::ScreenFeed, Viewer)> {
let mut g = self.inner.lock().await;
let g = &mut *g;
let udid =
diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rs
index 1b4be25..1907e04 100644
--- a/crates/ictl-daemon/src/supervise.rs
+++ b/crates/ictl-daemon/src/supervise.rs
@@ -159,7 +159,7 @@ impl Daemon {
tokio::task::spawn_local(async move {
if let Err(e) = d.resign_now(false).await {
let mut g = d.inner.lock().await;
- d.notify(&mut g, Event::ResignFailed(e));
+ d.notify(&mut g, Event::ResignFailed(e.to_string()));
}
});
}
@@ -647,7 +647,7 @@ impl Daemon {
}
if let Err(e) = self.resign_now(true).await {
let mut g = self.inner.lock().await;
- self.notify(&mut g, Event::ResignFailed(e));
+ self.notify(&mut g, Event::ResignFailed(e.to_string()));
}
}
@@ -747,8 +747,8 @@ impl Daemon {
}
/// 检查描述文件并按需重签(`force` 立即重签)。分三段:持锁取参数 → 不持锁签名、安装(几十秒)→ 持锁写结果
- pub(crate) async fn resign_now(self: &Arc<Self>, force: bool) -> Result<String, String> {
- let _lease = crate::maintenance::shared().map_err(|e| e.to_string())?;
+ pub(crate) async fn resign_now(self: &Arc<Self>, force: bool) -> crate::error::Result<String> {
+ let _lease = crate::maintenance::shared()?;
let (device, name) = {
let mut g = self.inner.lock().await;
let g = &mut *g;
@@ -882,7 +882,7 @@ impl Daemon {
g.persisted.record_resign(now_secs(), Some(e.clone()));
g.persisted.save(&self.cfg.state_file());
self.log.log(&ictl_l10n::log_trf!("重签失败:{e}", "Re-signing failed: {e}"));
- Err(e)
+ Err(e.into())
}
};
self.publish(g);
diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rs
index 4ae8ea8..25df659 100644
--- a/crates/ictl-daemon/src/tasks.rs
+++ b/crates/ictl-daemon/src/tasks.rs
@@ -784,7 +784,7 @@ impl Tasks {
udid: Option<&str>,
apps: Vec<String>,
opener: Option<u32>,
- ) -> Result<Arc<Task>, String> {
+ ) -> crate::error::Result<Arc<Task>> {
let title = title.trim();
if title.is_empty() {
return Err(ictl_l10n::tr!("任务要有标题", "A task needs a title").into());
@@ -803,7 +803,8 @@ impl Tasks {
"A task is already running ({}, {}): wait for it to end or stop it first",
t.id,
t.title
- ));
+ )
+ .into());
}
let id = uuid::Uuid::new_v4().simple().to_string()[..12].to_owned();
let task = Arc::new(Task {
@@ -1247,7 +1248,7 @@ mod tests {
assert!(ts.open("x", "", None, Vec::new(), None).is_err());
assert!(ts.open(" ", "", Some(PHONE), Vec::new(), None).is_err());
let t = open(&ts);
- assert!(ts.open("another", "", Some(PHONE), Vec::new(), None).err().unwrap().contains(&t.id));
+ assert!(ts.open("another", "", Some(PHONE), Vec::new(), None).err().unwrap().to_string().contains(&t.id));
t.end(End::Completed, "");
assert!(ts.open("another", "", Some(PHONE), Vec::new(), None).is_ok());
}
diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rs
index 710ad02..e4f69e0 100644
--- a/crates/ictl-daemon/src/tools/input.rs
+++ b/crates/ictl-daemon/src/tools/input.rs
@@ -10,7 +10,7 @@ impl Daemon {
g: &mut Inner,
view: Option<&str>,
start: bool,
- ) -> Result<Option<Rotation>, String> {
+ ) -> crate::error::Result<Option<Rotation>> {
let changed = || {
ictl_l10n::tr!(
"画面已变化或尺寸尚未确认,请在新画面上重试",
@@ -21,7 +21,7 @@ impl Daemon {
if let Some(id) = view
&& g.dev.display.as_ref().is_none_or(|v| v.id != id)
{
- return Err(changed());
+ return Err(changed().into());
}
// Move and Up use the finger's orientation from Down. A known display change
// has already invalidated the token and released that finger in update_display.
@@ -32,12 +32,12 @@ impl Daemon {
let Some(id) = view else { return Ok(None) };
let (rotation, _) = self.sample_display(g, true).await;
if g.dev.display.as_ref().is_none_or(|v| v.id != id) {
- return Err(changed());
+ return Err(changed().into());
}
Ok(rotation)
}
- pub(crate) async fn tap(&self, g: &mut Inner, x: f64, y: f64, view: Option<&str>) -> Result<String, String> {
+ pub(crate) async fn tap(&self, g: &mut Inner, x: f64, y: f64, view: Option<&str>) -> crate::error::Result<String> {
self.prepare_coordinates(g, view, true).await?;
let pos = format!("({},{})", fmt_g(x), fmt_g(y));
if let Some(w) = self.wda(g) {
@@ -45,11 +45,11 @@ impl Daemon {
match w.tap(x, y).await {
Ok(()) => return Ok(ictl_l10n::trf!("已点击 {pos}", "Tapped {pos}")),
Err(WdaError::Unavailable(_)) if view.is_none() => {}
- Err(e) => return Err(e.to_string()),
+ Err(e) => return Err(e.into()),
}
}
if view.is_some() {
- return Err(wda_down(&g.state, g.info.as_ref()));
+ return Err(wda_down(&g.state, g.info.as_ref()).into());
}
let rot = self.hid_touch_rotation(g).await?;
self.hid_do(g, move |h| {
@@ -118,7 +118,10 @@ impl Daemon {
Ok(h) => h,
Err(message) => {
g.dev.touch_rotation = None;
- return Err(Response::Error { message, retry_as_gesture: phase == TouchPhase::Down });
+ return Err(Response::Error {
+ message: message.into(),
+ retry_as_gesture: phase == TouchPhase::Down,
+ });
}
},
};
@@ -140,7 +143,7 @@ impl Daemon {
text: &str,
index: usize,
max_age: Duration,
- ) -> Result<(String, bool), String> {
+ ) -> crate::error::Result<(String, bool)> {
self.ensure_unlocked(g).await?;
let tree = self.tree(g, max_age).await?;
let matches = elements::find(&tree.elements, text);
@@ -192,7 +195,7 @@ impl Daemon {
));
}
};
- self.require_wda(g)?.tap(x, y).await.map_err(|e| e.to_string())?;
+ self.require_wda(g)?.tap(x, y).await?;
let note = if matches.len() > 1 {
ictl_l10n::trf!("(共匹配 {} 个,点的是第 {index} 个)", " ({} matches, tapped number {index})", matches.len())
} else {
@@ -208,9 +211,9 @@ impl Daemon {
y: f64,
seconds: f64,
view: Option<&str>,
- ) -> Result<String, String> {
+ ) -> crate::error::Result<String> {
self.prepare_coordinates(g, view, true).await?;
- self.require_wda(g)?.touch_and_hold(x, y, seconds).await.map_err(|e| e.to_string())?;
+ self.require_wda(g)?.touch_and_hold(x, y, seconds).await?;
Ok(ictl_l10n::trf!("已长按 ({},{}) {} 秒", "Long-pressed ({},{}) for {} s", fmt_g(x), fmt_g(y), fmt_g(seconds)))
}
@@ -221,7 +224,7 @@ impl Daemon {
to: (f64, f64),
seconds: f64,
view: Option<&str>,
- ) -> Result<String, String> {
+ ) -> crate::error::Result<String> {
self.prepare_coordinates(g, view, true).await?;
let desc = format!("({},{}) → ({},{})", fmt_g(from.0), fmt_g(from.1), fmt_g(to.0), fmt_g(to.1));
if let Some(w) = self.wda(g) {
@@ -235,11 +238,11 @@ impl Daemon {
return Ok(ictl_l10n::trf!("已滑动 {desc}{note}", "Swiped {desc}{note}"));
}
Err(WdaError::Unavailable(_)) if view.is_none() => {}
- Err(e) => return Err(e.to_string()),
+ Err(e) => return Err(e.into()),
}
}
if view.is_some() {
- return Err(wda_down(&g.state, g.info.as_ref()));
+ return Err(wda_down(&g.state, g.info.as_ref()).into());
}
let rot = self.hid_touch_rotation(g).await?;
self.hid_do(g, move |h| {
@@ -252,7 +255,7 @@ impl Daemon {
Ok(ictl_l10n::trf!("已滑动 {desc}(经 HID)", "Swiped {desc} (via HID)"))
}
- pub(crate) async fn type_text(&self, g: &mut Inner, text: &str, submit: bool) -> Result<String, String> {
+ pub(crate) async fn type_text(&self, g: &mut Inner, text: &str, submit: bool) -> crate::error::Result<String> {
self.ensure_unlocked(g).await?;
let n = text.chars().count();
if let Some(w) = self.wda(g) {
@@ -282,7 +285,7 @@ impl Daemon {
"输入了 {n} 个字符,但输入框里现在是「{now}」,和要输入的「{text}」对不上(App 可能吞掉了部分字符){};截图确认后再处理",
"Typed {n} characters, but the field now contains “{now}”, which doesn't match “{text}” (the app may have swallowed some characters){}; check with a screenshot before going on",
if submit { ictl_l10n::tr!(",没有按回车", ", Return not pressed") } else { "" }
- ));
+ ).into());
}
};
if submit {
@@ -300,7 +303,7 @@ impl Daemon {
));
}
Err(WdaError::Unavailable(_)) => {}
- Err(e) => return Err(e.to_string()),
+ Err(e) => return Err(e.into()),
}
}
let payload = if submit { format!("{text}\n") } else { text.to_owned() };
@@ -309,7 +312,8 @@ impl Daemon {
return Err(ictl_l10n::trf!(
"WDA 不可用,HID 只能输入美式键盘上的英文和符号,不能输入 {c:?}",
"WDA unavailable; HID can only type English letters and symbols of a US keyboard, not {c:?}"
- ));
+ )
+ .into());
}
self.hid_do(g, move |h| Box::pin(async move { h.type_ascii(&payload).await })).await?;
Ok(ictl_l10n::trf!("已输入 {n} 个字符(经 HID)", "Typed {n} characters (via HID)"))
@@ -353,8 +357,9 @@ pub(super) async fn wait_scrolled(w: &mut WdaClient<DeviceTransport>, vertical:
}
}
-/// How a missed `iphone_tap_element` result starts: the Chinese prefixes are fixed because older MCP servers
-/// recognise them; new ones read [`crate::protocol::Outcome`] instead
+/// How a missed `iphone_tap_element` result starts: the Chinese prefixes are fixed because MCP servers before 0.1.5
+/// recognise them; new ones read [`crate::protocol::Outcome`] instead. Goes in 0.3.0
+/// ([`crate::protocol::TEXT_FALLBACK_UNTIL`])
pub(super) fn tap_missed_prefixes() -> [&'static str; 3] {
if ictl_l10n::is_en() { ["Not found", "Only matched", "Covered"] } else { TAP_MISSED }
}
diff --git a/crates/ictl-daemon/src/tools/keys.rs b/crates/ictl-daemon/src/tools/keys.rs
index 9b83507..ecdec33 100644
--- a/crates/ictl-daemon/src/tools/keys.rs
+++ b/crates/ictl-daemon/src/tools/keys.rs
@@ -3,7 +3,7 @@
use super::*;
impl Daemon {
- pub(crate) async fn press_button(&self, g: &mut Inner, button: &str) -> Result<String, String> {
+ pub(crate) async fn press_button(&self, g: &mut Inner, button: &str) -> crate::error::Result<String> {
let hid_button = Button::parse(button).ok_or(ictl_l10n::tr!(
"button 只能是 home / volume_up / volume_down / lock",
"button must be home / volume_up / volume_down / lock"
@@ -43,14 +43,14 @@ impl Daemon {
match r {
Ok(text) => return Ok(text),
Err(WdaError::Unavailable(_)) => {}
- Err(e) => return Err(e.to_string()),
+ Err(e) => return Err(e.into()),
}
}
self.hid_do(g, |h| Box::pin(h.press(hid_button))).await?;
Ok(ictl_l10n::trf!("已按 {button}", "Pressed {button}"))
}
- pub(super) async fn lock_screen(&self, g: &mut Inner) -> Result<String, String> {
+ pub(super) async fn lock_screen(&self, g: &mut Inner) -> crate::error::Result<String> {
let via_wda = g.dev.lock_via_wda;
// Ok(way):用 way 锁上了;Err:WDA 两种办法没锁上的原因(WDA 不可用时为空),退到 HID
let outcome = match self.wda(g) {
@@ -71,7 +71,7 @@ impl Daemon {
worked = Some(way);
break;
}
- Err(why) => failed.push(why),
+ Err(why) => failed.push(why.to_string()),
}
}
worked.ok_or(failed)
@@ -82,7 +82,7 @@ impl Daemon {
Ok(way) => Some(way),
// WDA 在、只是没锁上:没有 HID 后备时如实说两种办法各自怎么了,不能说成「WDA 不可用」
Err(failed) if !failed.is_empty() && !hid_supported(g.info.as_ref()) => {
- return Err(lock_failed(&failed));
+ return Err(lock_failed(&failed).into());
}
Err(_) => None,
};
@@ -108,7 +108,7 @@ impl Daemon {
self.locked_now(g)
}
- pub(super) fn locked_now(&self, g: &mut Inner) -> Result<String, String> {
+ pub(super) fn locked_now(&self, g: &mut Inner) -> crate::error::Result<String> {
g.dev.last_lock = Some(Instant::now());
Ok(ictl_l10n::tr!("已锁屏", "Locked").into())
}
@@ -192,7 +192,7 @@ pub(super) fn lock_order(via_wda: bool) -> [LockWay; 2] {
/// WDA 的 `/wda/lock`。偶尔等 5 秒报 500(手机其实已锁):报错时看 WDA 报的锁屏状态,确认锁了就不退到 HID
/// (HID 会开屏幕媒体流)。没锁上时返回原因
-pub(super) async fn lock_by_wda(w: &mut WdaClient<DeviceTransport>) -> Result<(), String> {
+pub(super) async fn lock_by_wda(w: &mut WdaClient<DeviceTransport>) -> crate::error::Result<()> {
match w.lock().await {
Ok(()) => Ok(()),
Err(e) => {
@@ -200,20 +200,22 @@ pub(super) async fn lock_by_wda(w: &mut WdaClient<DeviceTransport>) -> Result<()
if w.wda_reports_locked().await.unwrap_or(false) {
return Ok(());
}
- Err(ictl_l10n::trf!("WDA 的锁屏报错:{e}", "WDA's lock returned an error: {e}"))
+ Err(ictl_l10n::trf!("WDA 的锁屏报错:{e}", "WDA's lock returned an error: {e}").into())
}
}
}
/// 经 IOHID 按电源键锁屏,等 WDA 报锁屏,最多 [`LOCK_WAIT`]。没锁上时返回原因。
/// WDA 的 `/wda/lock` 在 iOS 27 以下用 XCTest 的 `pressLockButton`,iPhone 12 mini(iOS 26.4.1)上锁不了屏
-pub(super) async fn lock_by_power_hid(w: &mut WdaClient<DeviceTransport>) -> Result<(), String> {
+pub(super) async fn lock_by_power_hid(w: &mut WdaClient<DeviceTransport>) -> crate::error::Result<()> {
if let Err(e) = w.press_power_hid().await {
tracing::info!(
"{}",
ictl_l10n::log_trf!("经 IOHID 按电源键报错:{e}", "Pressing the power key via IOHID failed: {e}")
);
- return Err(ictl_l10n::trf!("经 IOHID 按电源键报错:{e}", "pressing the power key via IOHID failed: {e}"));
+ return Err(
+ ictl_l10n::trf!("经 IOHID 按电源键报错:{e}", "pressing the power key via IOHID failed: {e}").into()
+ );
}
let deadline = Instant::now() + LOCK_WAIT;
loop {
@@ -232,7 +234,8 @@ pub(super) async fn lock_by_power_hid(w: &mut WdaClient<DeviceTransport>) -> Res
return Err(ictl_l10n::trf!(
"经 IOHID 按电源键后 {secs} 秒还没锁屏",
"still not locked {secs} s after pressing the power key via IOHID"
- ));
+ )
+ .into());
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
diff --git a/crates/ictl-daemon/src/tools/launch.rs b/crates/ictl-daemon/src/tools/launch.rs
index dcd0415..84180ba 100644
--- a/crates/ictl-daemon/src/tools/launch.rs
+++ b/crates/ictl-daemon/src/tools/launch.rs
@@ -3,17 +3,17 @@
use super::*;
impl Daemon {
- pub(crate) async fn list_apps(&self, g: &mut Inner, include_system: bool) -> Result<Vec<AppInfo>, String> {
+ pub(crate) async fn list_apps(&self, g: &mut Inner, include_system: bool) -> crate::error::Result<Vec<AppInfo>> {
if let Some(a) = g.dev.apps.get(&include_system) {
return Ok(a.clone());
}
let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
- let a = device.list_apps(include_system).await.map_err(|e| e.to_string())?;
+ let a = device.list_apps(include_system).await?;
g.dev.apps.insert(include_system, a.clone());
Ok(a)
}
- pub(crate) async fn resolve_app(&self, g: &mut Inner, app: &str) -> Result<String, String> {
+ pub(crate) async fn resolve_app(&self, g: &mut Inner, app: &str) -> crate::error::Result<String> {
if apps::looks_like_bundle_id(app) {
return Ok(app.to_owned());
}
@@ -27,10 +27,11 @@ impl Daemon {
"找不到名为 \"{app}\" 的 App,用 iphone_list_apps 查看",
"No app named \"{app}\"; see iphone_list_apps"
)
+ .into()
})
}
- pub(super) async fn resolve_cached(&self, g: &mut Inner, app: &str) -> Result<Option<String>, String> {
+ pub(super) async fn resolve_cached(&self, g: &mut Inner, app: &str) -> crate::error::Result<Option<String>> {
// 先只查用户 App;列系统 App 要好几秒,只在找不到时才去取
let user = self.list_apps(g, false).await?;
if let Some(b) = user.iter().find(|a| a.name == app) {
@@ -40,11 +41,11 @@ impl Daemon {
Ok(apps::resolve(app, [&user[..], &system[..]]))
}
- pub(crate) async fn launch_app(&self, g: &mut Inner, app: &str) -> Result<(String, bool), String> {
+ pub(crate) async fn launch_app(&self, g: &mut Inner, app: &str) -> crate::error::Result<(String, bool)> {
let bid = self.resolve_app(g, app).await?;
self.ensure_unlocked(g).await?;
let w = self.require_wda(g)?;
- let r = w.launch_app(&bid).await.map_err(|e| e.to_string())?;
+ let r = w.launch_app(&bid).await?;
let blocked = matches!(r, Launch::Blocked(_));
let text = match r {
Launch::Foreground => ictl_l10n::trf!("已启动 {bid}", "Launched {bid}"),
@@ -63,16 +64,16 @@ impl Daemon {
Ok((text, blocked))
}
- pub(crate) async fn terminate_app(&self, g: &mut Inner, app: &str) -> Result<String, String> {
+ pub(crate) async fn terminate_app(&self, g: &mut Inner, app: &str) -> crate::error::Result<String> {
let bid = self.resolve_app(g, app).await?;
self.ensure_unlocked(g).await?;
- self.require_wda(g)?.terminate_app(&bid).await.map_err(|e| e.to_string())?;
+ self.require_wda(g)?.terminate_app(&bid).await?;
Ok(ictl_l10n::trf!("已结束 {bid}", "Terminated {bid}"))
}
- pub(crate) async fn open_url(&self, g: &mut Inner, url: &str) -> Result<(String, bool), String> {
+ pub(crate) async fn open_url(&self, g: &mut Inner, url: &str) -> crate::error::Result<(String, bool)> {
self.ensure_unlocked(g).await?;
- let (r, app) = self.require_wda(g)?.open_url(url).await.map_err(|e| e.to_string())?;
+ let (r, app) = self.require_wda(g)?.open_url(url).await?;
let blocked = matches!(r, Launch::Blocked(_));
let text = match r {
Launch::Foreground => ictl_l10n::trf!("已打开 {url}(前台 {app})", "Opened {url} (foreground {app})"),
diff --git a/crates/ictl-daemon/src/tools/mod.rs b/crates/ictl-daemon/src/tools/mod.rs
index c3b5892..2c86a03 100644
--- a/crates/ictl-daemon/src/tools/mod.rs
+++ b/crates/ictl-daemon/src/tools/mod.rs
@@ -48,7 +48,7 @@ const LOCK_WAIT: Duration = Duration::from_secs(3);
impl Daemon {
/// 配置了密码就在锁屏时自动解锁;没配置而手机锁着则报错(与 toolkit 一致)
- pub(crate) async fn ensure_unlocked(&self, g: &mut Inner) -> Result<(), String> {
+ pub(crate) async fn ensure_unlocked(&self, g: &mut Inner) -> crate::error::Result<()> {
let cfg = self.unlock_cfg(g.device.as_ref().map(|d| d.udid.as_str()));
if let Some(left) = g.dev.last_lock.and_then(|t| LOCK_SETTLE.checked_sub(t.elapsed())) {
tokio::time::sleep(left).await;
@@ -58,18 +58,18 @@ impl Daemon {
Ok(_) => Ok(()),
Err(e @ (UnlockError::WrongPasscode | UnlockError::Uncertain(_))) => {
self.notify(g, Event::UnlockDisabled);
- Err(ictl_l10n::trf!("{e},已推送通知", "{e}, notification sent"))
+ Err(ictl_l10n::trf!("{e},已推送通知", "{e}, notification sent").into())
}
Err(UnlockError::NoPasscode) if self.cfg.legacy_passcode_file().is_file() => {
Err(ictl_l10n::tr!("手机已锁屏,需要人工解锁:旧版本保存的锁屏密码没记是哪台设备的,同时接着几台时不会用它;\
在这台设备连着时运行 iphone-control passcode set 重新设置", "The phone is locked and has to be unlocked by hand: the passcode saved by an older version has no device, and it isn't used while several devices are connected; run iphone-control passcode set while this device is connected to set it again")
.into())
}
- Err(e) => Err(e.to_string()),
+ Err(e) => Err(e.into()),
}
}
- async fn screen(&self, g: &mut Inner) -> Result<ScreenSize, String> {
+ async fn screen(&self, g: &mut Inner) -> crate::error::Result<ScreenSize> {
if let Some(w) = self.wda(g)
&& let Ok(s) = w.screen_size().await
{
@@ -84,7 +84,7 @@ impl Daemon {
/// 每次 HID 触摸前重新截图核对横竖,不依赖上次截图(转屏、回主屏、解锁都可能改变方向)。
/// 截图只给宽高,不能分辨横屏左右;短暂掉线时借用近期实测方向,过期或不匹配就不触摸。
- async fn hid_touch_rotation(&self, g: &mut Inner) -> Result<Rotation, String> {
+ async fn hid_touch_rotation(&self, g: &mut Inner) -> crate::error::Result<Rotation> {
self.sample_display(g, false).await;
let png = self.hid_screenshot(g).await.map_err(|e| {
ictl_l10n::trf!(
@@ -95,27 +95,27 @@ impl Daemon {
let (w, h) = imaging::png_size(&png)
.ok_or(ictl_l10n::tr!("无法读取截图尺寸,没有发送触摸", "Can't read the screenshot size, no touch sent"))?;
let known = g.dev.last_rotation.map(|(at, r)| (at.elapsed(), r));
- hid_rotation(w, h, known)
+ Ok(hid_rotation(w, h, known)?)
}
/// 经隧道截图(WDA 不可用时)。失败就丢掉隧道,下次重建
- async fn hid_screenshot(&self, g: &mut Inner) -> Result<Vec<u8>, String> {
+ async fn hid_screenshot(&self, g: &mut Inner) -> crate::error::Result<Vec<u8>> {
let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
- let t = self.ensure_tunnel(g, &device).await.map_err(|e| e.to_string())?;
+ let t = self.ensure_tunnel(g, &device).await?;
match t.screenshot_png().await {
Ok(p) => Ok(p),
Err(e) => {
drop_tunnel(g).await;
- Err(e.to_string())
+ Err(e.into())
}
}
}
/// HID 会话(WDA 不可用时的后备路线)。开不起来就丢掉隧道,下次重建
- pub(crate) async fn hid<'a>(&self, g: &'a mut Inner) -> Result<&'a mut HidSession, String> {
+ pub(crate) async fn hid<'a>(&self, g: &'a mut Inner) -> crate::error::Result<&'a mut HidSession> {
// 低版本建隧道只会报 service not found:直接说清楚
if !hid_supported(g.info.as_ref()) {
- return Err(wda_down(&g.state, g.info.as_ref()));
+ return Err(wda_down(&g.state, g.info.as_ref()).into());
}
let screen = self.screen(g).await?;
let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
@@ -127,13 +127,13 @@ impl Daemon {
.map_err(|e| ictl_l10n::trf!("HID 后备路线不可用:{e}", "HID fallback unavailable: {e}"))?;
if let Err(e) = t.hid(screen).await {
drop_tunnel(g).await;
- return Err(ictl_l10n::trf!("HID 后备路线不可用:{e}", "HID fallback unavailable: {e}"));
+ return Err(ictl_l10n::trf!("HID 后备路线不可用:{e}", "HID fallback unavailable: {e}").into());
}
// 第二次调用直接返回已开好的会话(这样写是为了绕开借用检查对条件返回的限制)
- g.tunnel.as_mut().expect("刚建好").hid(screen).await.map_err(|e| e.to_string())
+ Ok(g.tunnel.as_mut().expect("刚建好").hid(screen).await?)
}
- async fn hid_do<F>(&self, g: &mut Inner, f: F) -> Result<(), String>
+ async fn hid_do<F>(&self, g: &mut Inner, f: F) -> crate::error::Result<()>
where
F: for<'h> FnOnce(
&'h mut HidSession,
@@ -145,10 +145,10 @@ impl Daemon {
match r {
Ok(()) => Ok(()),
// 参数问题(例如不能输入的字符),连接没坏,不用重建
- Err(e @ DeviceError::InvalidInput(_)) => Err(e.to_string()),
+ Err(e @ DeviceError::InvalidInput(_)) => Err(e.into()),
Err(e) => {
drop_tunnel(g).await;
- Err(ictl_l10n::trf!("HID 命令失败: {e}", "HID command failed: {e}"))
+ Err(ictl_l10n::trf!("HID 命令失败: {e}", "HID command failed: {e}").into())
}
}
}
@@ -258,7 +258,7 @@ impl Daemon {
&self,
g: &mut Inner,
region: Option<(f64, f64, f64, f64)>,
- ) -> Result<Response, String> {
+ ) -> crate::error::Result<Response> {
self.ensure_unlocked(g).await?;
let wda_png = match self.wda(g) {
Some(w) => w.screenshot_png().await.ok(),
@@ -272,7 +272,7 @@ impl Daemon {
Some(p) => (p, "WDA"),
None => {
if !hid_supported(g.info.as_ref()) {
- return Err(wda_down(&g.state, g.info.as_ref()));
+ return Err(wda_down(&g.state, g.info.as_ref()).into());
}
(
self.hid_screenshot(g)
@@ -321,12 +321,13 @@ pub(crate) fn hid_rotation(w: u32, h: u32, known: Option<(Duration, Rotation)>)
}
/// 判断画面动没动用的缩略图。解码是 CPU 活,放到阻塞线程
-async fn thumbnail(png: Vec<u8>) -> Result<Vec<u8>, String> {
+async fn thumbnail(png: Vec<u8>) -> crate::error::Result<Vec<u8>> {
// 阻塞线程上没有请求的语言,带过去(解码失败的报错会返回给调用方)
let lang = ictl_l10n::lang();
tokio::task::spawn_blocking(move || ictl_l10n::with_lang(lang, || imaging::thumbnail(&png)))
.await
.map_err(|e| ictl_l10n::trf!("图像处理任务异常:{e}", "Image processing task failed: {e}"))?
+ .map_err(Into::into)
}
fn needs_wda() -> &'static str {
diff --git a/crates/ictl-daemon/src/tools/observe.rs b/crates/ictl-daemon/src/tools/observe.rs
index c98f132..4cbc619 100644
--- a/crates/ictl-daemon/src/tools/observe.rs
+++ b/crates/ictl-daemon/src/tools/observe.rs
@@ -4,14 +4,14 @@ use super::*;
impl Daemon {
/// 当前界面的元素树。缓存不超过 `max_age` 就直接用(0 = 总是重读);重读的结果写回缓存
- pub(super) async fn tree(&self, g: &mut Inner, max_age: Duration) -> Result<Tree, String> {
+ pub(super) async fn tree(&self, g: &mut Inner, max_age: Duration) -> crate::error::Result<Tree> {
if !max_age.is_zero()
&& let Some((t, tree)) = &g.elements_cache
&& t.elapsed() <= max_age
{
return Ok(tree.clone());
}
- let tree = self.require_wda(g)?.tree().await.map_err(|e| e.to_string())?;
+ let tree = self.require_wda(g)?.tree().await?;
g.elements_cache = Some((Instant::now(), tree.clone()));
Ok(tree)
}
@@ -23,11 +23,11 @@ impl Daemon {
limit: usize,
max_age: Duration,
keep_locked: bool,
- ) -> Result<(String, Vec<ElementData>), String> {
+ ) -> crate::error::Result<(String, Vec<ElementData>)> {
if keep_locked {
// only looking (a read-only viewer): the passcode isn't typed for it
if let Some(w) = self.wda(g)
- && w.locked().await.map_err(|e| e.to_string())?
+ && w.locked().await?
{
return Err(ictl_l10n::tr!(
"手机锁着:只看不操作时不会替你解锁",
@@ -62,7 +62,7 @@ impl Daemon {
/// 截图约 0.2 秒一张,两帧之间再隔一点,避免两帧落在同一段静止的过渡里
///
/// 屏幕上有弹窗时在结果里提醒(读树时顺带看,不多花时间)
- pub(crate) async fn settle(&self, g: &mut Inner, max: Duration) -> Result<String, String> {
+ pub(crate) async fn settle(&self, g: &mut Inner, max: Duration) -> crate::error::Result<String> {
let t0 = Instant::now();
// 刚滑完读到的树:只作比较的起点,是不是真稳定还要看下一次读到的
let seed = g.swiped_tree.take().filter(|(at, _)| at.elapsed() < SWIPED_TREE_FRESH).map(|(_, t)| t);
@@ -70,7 +70,7 @@ impl Daemon {
tokio::time::sleep(max.min(Duration::from_millis(500))).await;
return Ok(ictl_l10n::tr!("WDA 不可用,等了 0.5 秒", "WDA unavailable, waited 0.5 s").into());
};
- w.begin_polling().await.map_err(|e| e.to_string())?;
+ w.begin_polling().await?;
let r = poll_stable(w, t0, max, seed).await;
w.end_polling().await;
let (msg, settled, tree) = match r? {
@@ -91,12 +91,17 @@ impl Daemon {
Ok(msg + &note)
}
- pub(super) async fn settle_visually(&self, g: &mut Inner, t0: Instant, max: Duration) -> Result<String, String> {
+ pub(super) async fn settle_visually(
+ &self,
+ g: &mut Inner,
+ t0: Instant,
+ max: Duration,
+ ) -> crate::error::Result<String> {
let deadline = t0 + max;
let w = self.require_wda(g)?;
let mut prev: Option<Vec<u8>> = None;
loop {
- let png = w.screenshot_png().await.map_err(|e| e.to_string())?;
+ let png = w.screenshot_png().await?;
let cur = thumbnail(png).await?;
if let Some(p) = &prev {
let m = imaging::thumb_motion(p, &cur);
@@ -153,9 +158,9 @@ impl Daemon {
/// 不带 then 的操作做完后调:弹窗挡着时点击、滑动都会落在弹窗上,WDA 却照样报成功。
/// 前台是 App 时只多一次约 0.13 秒的查询;在主屏上再多约 0.4 秒
/// A system alert in front: the note for the agent, and the alert's own text
- pub(crate) async fn alert_check(&self, g: &mut Inner) -> Result<(String, Option<String>), String> {
+ pub(crate) async fn alert_check(&self, g: &mut Inner) -> crate::error::Result<(String, Option<String>)> {
let Some(w) = self.wda(g) else { return Ok((String::new(), None)) };
- if w.active_app().await.map_err(|e| e.to_string())? != SPRINGBOARD {
+ if w.active_app().await? != SPRINGBOARD {
return Ok((String::new(), None));
}
Ok(match w.alert_text().await {
@@ -165,12 +170,12 @@ impl Daemon {
}
/// 等包含 `text` 的元素出现
- pub(crate) async fn wait_for(&self, g: &mut Inner, text: &str, timeout: Duration) -> Result<String, String> {
+ pub(crate) async fn wait_for(&self, g: &mut Inner, text: &str, timeout: Duration) -> crate::error::Result<String> {
self.ensure_unlocked(g).await?;
let t0 = Instant::now();
let w = self.require_wda(g)?;
// 轮询时不等界面空闲:页面还在加载、播放动画时每次读树也只要约 0.2 秒
- w.begin_polling().await.map_err(|e| e.to_string())?;
+ w.begin_polling().await?;
let r = async {
loop {
let els = w.elements().await.map_err(|e| e.to_string())?;
@@ -186,7 +191,7 @@ impl Daemon {
}
.await;
w.end_polling().await;
- r
+ Ok(r?)
}
}
@@ -204,10 +209,10 @@ pub(super) async fn poll_stable(
t0: Instant,
max: Duration,
seed: Option<Tree>,
-) -> Result<Polled, String> {
+) -> crate::error::Result<Polled> {
let first = match seed {
Some(t) => t,
- None => w.tree().await.map_err(|e| e.to_string())?,
+ None => w.tree().await?,
};
if first.elements.len() < VISUAL_SETTLE_BELOW {
return Ok(Polled::FewElements(first));
@@ -232,7 +237,7 @@ pub(super) async fn poll_stable(
}
// 一次读树本身约 0.2 秒,两次之间不用再多等
tokio::time::sleep(Duration::from_millis(30)).await;
- let cur = w.tree().await.map_err(|e| e.to_string())?;
+ let cur = w.tree().await?;
let same = cur.close_to(&prev, STILL_TOLERANCE);
prev = cur;
if same && !prev.loading {
diff --git a/crates/ictl-daemon/src/web.rs b/crates/ictl-daemon/src/web.rs
index 6f6cfdf..26e0bfe 100644
--- a/crates/ictl-daemon/src/web.rs
+++ b/crates/ictl-daemon/src/web.rs
@@ -33,7 +33,11 @@ const MAX_RESULT_CHARS: usize = 50_000;
impl Daemon {
/// `slot` is [`Daemon::web`], already locked by the caller (see `Daemon::handle`)
- pub(crate) async fn web_targets(&self, slot: &mut Option<WebConn>, device: &Device) -> Result<String, String> {
+ pub(crate) async fn web_targets(
+ &self,
+ slot: &mut Option<WebConn>,
+ device: &Device,
+ ) -> crate::error::Result<String> {
let (apps, pages) = web_pages(slot, device).await?;
if pages.is_empty() {
return Ok(ictl_l10n::tr!(
@@ -61,7 +65,7 @@ impl Daemon {
target: &str,
expression: &str,
timeout: Duration,
- ) -> Result<String, String> {
+ ) -> crate::error::Result<String> {
let (apps, pages) = web_pages(slot, device).await?;
let page = pick(&pages, target).map_err(|e| match e {
Pick::None => ictl_l10n::trf!(
@@ -83,13 +87,13 @@ impl Daemon {
if breaks_connection(&e) {
*slot = None;
}
- return Err(page_error(&e));
+ return Err(page_error(&e).into());
}
};
Ok(match r {
Eval::Value(None) => "undefined".into(),
Eval::Value(Some(v)) => truncate(v.to_string()),
- Eval::Thrown(d) => return Err(ictl_l10n::trf!("页面里抛出异常:{d}", "The page threw: {d}")),
+ Eval::Thrown(d) => return Err(ictl_l10n::trf!("页面里抛出异常:{d}", "The page threw: {d}").into()),
})
}
@@ -106,7 +110,7 @@ impl Daemon {
/// The pages, on the kept connection (opened if there is none, or it belongs to another device). A connection that
/// turns out to be broken is replaced once: listing pages changes nothing on the phone
-async fn web_pages(slot: &mut Option<WebConn>, device: &Device) -> Result<(Vec<App>, Vec<Page>), String> {
+async fn web_pages(slot: &mut Option<WebConn>, device: &Device) -> crate::error::Result<(Vec<App>, Vec<Page>)> {
if slot.as_ref().is_some_and(|c| c.udid != device.udid) {
*slot = None;
}
@@ -125,11 +129,11 @@ async fn web_pages(slot: &mut Option<WebConn>, device: &Device) -> Result<(Vec<A
Err(e) if breaks_connection(&e) => {
*slot = None;
if attempt == 1 {
- return Err(page_error(&e));
+ return Err(page_error(&e).into());
}
tracing::debug!("Web Inspector connection broken, opening a new one: {e}");
}
- Err(e) => return Err(page_error(&e)),
+ Err(e) => return Err(page_error(&e).into()),
}
}
unreachable!("the second attempt returns")
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index fac52c5..98c54d9 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -567,8 +567,14 @@ pub const ALERT_BLOCKING: &str = "屏幕上有系统弹窗";
/// `iphone_tap_element` 没点到时结果开头的几种写法(不算出错,单独调用时是普通结果;批量里要停下)
pub const TAP_MISSED: [&str; 3] = ["没找到", "只匹配到", "被挡住"];
+/// The version from which clients and daemons no longer read results by their wording, only by [`Outcome`]
+/// (every one since 0.1.5 sends it): remove the text fallbacks then
+pub const TEXT_FALLBACK_UNTIL: (u64, u64) = (0, 3);
+
/// Did `iphone_tap_element` tap nothing? Daemons that send [`Outcome`] say so there; older ones only write
-/// Chinese text, recognised by its [`TAP_MISSED`] prefix
+/// Chinese text, recognised by its [`TAP_MISSED`] prefix. [`Outcome`] came with 0.1.5: the text fallback (here,
+/// in [`alert_reported`], and the fixed Chinese prefixes the daemon keeps for older MCP servers) goes in 0.3.0
+/// ([`TEXT_FALLBACK_UNTIL`])
pub fn tapped_nothing(text: &str, outcome: Option<Outcome>) -> bool {
match outcome {
Some(o) => o.tapped_nothing,
@@ -899,6 +905,14 @@ mod tests {
assert!(!serde_json::to_string(&Response::text_with("x", Outcome::default())).unwrap().contains("data"));
}
+ /// A reminder that fails on time: from [`TEXT_FALLBACK_UNTIL`] on, delete the text fallbacks (`tapped_nothing`,
+ /// `alert_reported`, the daemon's fixed Chinese prefixes) and this test
+ #[test]
+ fn the_text_fallback_is_removed_in_time() {
+ let v: Vec<u64> = env!("CARGO_PKG_VERSION").split('.').map(|n| n.parse().unwrap()).collect();
+ assert!((v[0], v[1]) < TEXT_FALLBACK_UNTIL, "remove the text fallbacks: every supported version sends Outcome");
+ }
+
/// The field decides; without it (older daemon) the Chinese text is read
#[test]
fn outcome_wins_over_text() {