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

Filter by extension

Filter by extension


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

## [Unreleased]

### New

- Agents can read across several screens of a list and stop at a matching row without tapping it (#170).
- Tap, swipe and text input results now distinguish a sent input from one that never went out or whose delivery is uncertain (#170).

## [0.2.11] - 2026-11-23

### Fixes
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@

## [Unreleased]

### 新功能

- Agent 可以跨屏收集列表内容,找到目标行后停留在当前页面(#170)。
- 点击、滑动和输入文字会区分已发送、未发送和结果未知,方便 Agent 判断是否先读屏再重试(#170)。

## [0.2.11] - 2026-11-23

### 修复
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<a href="https://github.com/Derrors/iphone-control/releases/latest"><img src="https://img.shields.io/github/v/release/Derrors/iphone-control?style=flat" alt="Release"></a>
<img src="https://img.shields.io/badge/iOS-27%2B%20recommended%20%C2%B7%2017%2B%20supported-black?style=flat&logo=apple" alt="iOS: 27+ recommended, 17+ supported">
<img src="https://img.shields.io/badge/platform-Linux%20%7C%20macOS-0E7490?style=flat" alt="Platform: Linux | macOS">
<img src="https://img.shields.io/badge/MCP-17%20tools-8A2BE2?style=flat" alt="MCP">
<img src="https://img.shields.io/badge/MCP-18%20tools-8A2BE2?style=flat" alt="MCP">
<a href="Cargo.toml"><img src="https://img.shields.io/badge/Rust-1.89%2B-CE422B?style=flat&logo=rust&logoColor=white" alt="Rust"></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/Derrors/iphone-control?style=flat" alt="License"></a>
<a href="https://m8ven.ai/mcp/derrors-iphone-control-1pcmse?s=readme"><img src="https://m8ven.ai/badge/mcp/derrors-iphone-control-1pcmse?variant=verified" alt="M8ven verified"></a>
Expand Down Expand Up @@ -66,7 +66,7 @@ Device control has two routes, picked by iOS version:
## Features

<p align="center">
<img src="docs/images/features.svg" alt="Device control (core): native on iOS 27+, 17 MCP tools, fewer round trips, runs unattended, a person in charge, doctor and alerts. Access: on this machine, remotely. Control page (optional)" width="900">
<img src="docs/images/features.svg" alt="Device control (core): native on iOS 27+, 18 MCP tools, fewer round trips, runs unattended, a person in charge, doctor and alerts. Access: on this machine, remotely. Control page (optional)" width="900">
</p>

**Device control (core)**
Expand Down
4 changes: 2 additions & 2 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<a href="https://github.com/Derrors/iphone-control/releases/latest"><img src="https://img.shields.io/github/v/release/Derrors/iphone-control?style=flat" alt="Release"></a>
<img src="https://img.shields.io/badge/iOS-27%2B%20%E6%8E%A8%E8%8D%90%20%C2%B7%2017%2B%20%E5%8F%AF%E7%94%A8-black?style=flat&logo=apple" alt="iOS:推荐 27+,17+ 可用">
<img src="https://img.shields.io/badge/platform-Linux%20%7C%20macOS-0E7490?style=flat" alt="平台:Linux | macOS">
<img src="https://img.shields.io/badge/MCP-17%20tools-8A2BE2?style=flat" alt="MCP">
<img src="https://img.shields.io/badge/MCP-18%20tools-8A2BE2?style=flat" alt="MCP">
<a href="Cargo.toml"><img src="https://img.shields.io/badge/Rust-1.89%2B-CE422B?style=flat&logo=rust&logoColor=white" alt="Rust"></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/Derrors/iphone-control?style=flat" alt="License"></a>
<a href="https://m8ven.ai/mcp/derrors-iphone-control-1pcmse?s=readme"><img src="https://m8ven.ai/badge/mcp/derrors-iphone-control-1pcmse?variant=verified" alt="M8ven 已验证"></a>
Expand Down Expand Up @@ -66,7 +66,7 @@ iphone-control 在 Linux 或 macOS 上用**一个 Rust 二进制**把这些事
## 功能特性

<p align="center">
<img src="docs/images/features.zh-CN.svg" alt="设备控制(核心):iOS 27 原生控制、17 个 MCP 工具、少走往返、无人值守、人工把关、诊断与通知。接入:本机接入、远程接入。控制台(可选)" width="900">
<img src="docs/images/features.zh-CN.svg" alt="设备控制(核心):iOS 27 原生控制、18 个 MCP 工具、少走往返、无人值守、人工把关、诊断与通知。接入:本机接入、远程接入。控制台(可选)" width="900">
</p>

**设备控制(核心)**
Expand Down
155 changes: 139 additions & 16 deletions apps/iphone-control/src/mcp_bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,17 @@ where
Ok(())
}

struct ForwardError {
message: String,
delivery: protocol::Delivery,
}

impl From<String> for ForwardError {
fn from(message: String) -> Self {
Self { message, delivery: protocol::Delivery::Unknown }
}
}

struct Link {
remote: Remote,
task: Option<String>,
Expand Down Expand Up @@ -123,26 +134,61 @@ impl Link {
if let Err(e) = self.send(&msg, id.as_ref()).await {
match id {
Some(id) => {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: every send() failure for an input tool is reported as delivery: unknown, stage: transport, including cases where the remote certainly didn't act: r.send() failing to connect, or a non-2xx status such as 401/403/404 from remote::failure. The agent is then told to inspect the screen when it could simply fix auth and retry. Consider returning a distinct error from send() for "request not delivered / rejected" and mapping that to not_sent.

let _ = self.tx.send(rpc_error(id, -32603, &e));
let reply = if msg["method"] == "tools/call"
&& msg["params"]["name"].as_str().is_some_and(ictl_mcp::reports_input)
{
let hint = if e.delivery == protocol::Delivery::NotSent {
ictl_l10n::tr!("输入未发出", "The input was not sent")
} else {
ictl_l10n::tr!(
"未收到远端工具结果;先读屏确认,再决定是否重试",
"No remote tool result; inspect the screen before retrying"
)
};
json!({"jsonrpc": "2.0", "id": id, "error": {
"code": -32603,
"message": ictl_l10n::trf!(
"{}。{hint}",
"{}. {hint}",
e.message.trim_end_matches(['.', '。'])
),
"data": {"delivery": e.delivery, "stage": "transport"}
}})
.to_string()
} else {
rpc_error(id, -32603, &e.message)
};
let _ = self.tx.send(reply);
}
// a notification has nobody to tell but the log (stdout is the protocol)
None => eprintln!("iphone-control mcp --url: {e}"),
None => eprintln!("iphone-control mcp --url: {}", e.message),
}
}
}

async fn send(&self, msg: &Value, id: Option<&Value>) -> Result<(), String> {
async fn send(&self, msg: &Value, id: Option<&Value>) -> Result<(), ForwardError> {
let r = self.remote.request(reqwest::Method::POST, "/mcp");
let r = self.with_headers(r).header(reqwest::header::ACCEPT, "application/json, text/event-stream").json(msg);
let resp = r.send().await.map_err(|e| format!("{}: {e}", self.remote.base()))?;
let resp = r.send().await.map_err(|e| ForwardError {
delivery: if e.is_connect() || e.is_builder() {
protocol::Delivery::NotSent
} else {
protocol::Delivery::Unknown
},
message: format!("{}: {e}", self.remote.base()),
})?;
if let Some(sid) = resp.headers().get("mcp-session-id").and_then(|v| v.to_str().ok()) {
self.session().id = Some(sid.to_owned());
}
if resp.status() == reqwest::StatusCode::ACCEPTED {
return Ok(());
return missing_reply(id);
}
if !resp.status().is_success() {
return Err(remote::failure(resp).await);
let delivery = match resp.status().as_u16() {
401 | 403 | 404 => protocol::Delivery::NotSent,
_ => protocol::Delivery::Unknown,
};
return Err(ForwardError { message: remote::failure(resp).await, delivery });
}
let initialize = msg["method"] == "initialize";
let pass = |v: Value| {
Expand All @@ -165,24 +211,26 @@ impl Link {
if let Ok(v) = serde_json::from_str::<Value>(&data)
&& pass(v)
{
break;
return Ok(());
}
}
return Ok(());
return missing_reply(id);
}
let text = resp.text().await.map_err(|e| e.to_string())?;
if text.trim().is_empty() {
return Ok(());
return missing_reply(id);
}
match serde_json::from_str::<Value>(&text).map_err(|e| e.to_string())? {
Value::Array(batch) => batch.into_iter().for_each(|v| {
pass(v);
}),
v => {
pass(v);
let reply = serde_json::from_str::<Value>(&text).map_err(|e| e.to_string())?;
let mut answered = false;
match reply {
Value::Array(messages) => {
for message in messages {
answered |= pass(message);
}
}
message => answered = pass(message),
}
Ok(())
if answered { Ok(()) } else { missing_reply(id) }
}

/// Ends the session on the viewer (best effort)
Expand All @@ -195,6 +243,81 @@ impl Link {
}
}

/// Notifications and client responses have no corresponding JSON-RPC response.
fn missing_reply(id: Option<&Value>) -> Result<(), ForwardError> {
if id.is_some() {
Err(ictl_l10n::tr!(
"控制台关闭了响应,没有对应的 JSON-RPC 回复",
"viewer closed the response without a matching JSON-RPC reply"
)
.to_owned()
.into())
} else {
Ok(())
}
}

fn rpc_error(id: Value, code: i64, message: &str) -> String {
json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}}).to_string()
}

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

#[tokio::test]
async fn rejected_or_unreachable_input_is_not_sent_but_a_gateway_failure_is_unknown() {
for (status, delivery) in [
(None, "not_sent"),
(Some(401), "not_sent"),
(Some(403), "not_sent"),
(Some(404), "not_sent"),
(Some(502), "unknown"),
] {
let server = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", server.local_addr().unwrap());
if let Some(status) = status {
tokio::spawn(async move {
let (mut socket, _) = server.accept().await.unwrap();
let mut buf = [0; 4096];
assert!(socket.read(&mut buf).await.unwrap() > 0);
socket
.write_all(format!("HTTP/1.1 {status} Error\r\nContent-Length: 0\r\n\r\n").as_bytes())
.await
.unwrap();
});
} else {
drop(server);
}
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let link =
Link { remote: Remote::new(&url, None, None).unwrap(), task: None, session: Mutex::default(), tx };
link.forward(json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"iphone_tap"}})).await;
let reply: Value = serde_json::from_str(&rx.try_recv().unwrap()).unwrap();
assert_eq!(reply["error"]["data"]["delivery"], delivery);
}
}

#[tokio::test]
async fn interrupted_tool_reply_reports_unknown_instead_of_hanging_or_retrying() {
let server = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", server.local_addr().unwrap());
let peer = tokio::spawn(async move {
let (mut socket, _) = server.accept().await.unwrap();
let mut buf = [0; 4096];
assert!(socket.read(&mut buf).await.unwrap() > 0);
socket
.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: 0\r\n\r\n")
.await
.unwrap();
});
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let link = Link { remote: Remote::new(&url, None, None).unwrap(), task: None, session: Mutex::default(), tx };
link.forward(json!({"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"iphone_tap"}})).await;
let reply: Value = serde_json::from_str(&rx.try_recv().expect("client must receive a terminal reply")).unwrap();
assert_eq!(reply["id"], 7);
assert_eq!(reply["error"]["data"]["delivery"], "unknown");
peer.await.unwrap();
}
}
5 changes: 3 additions & 2 deletions apps/iphone-control/src/viewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1391,7 +1391,7 @@ fn action_result(req: &Request, result: Result<Response, impl std::fmt::Display>
json!({"ok": !missed, "message": text})
}
Ok(Response::Image { caption, .. }) => json!({"ok": true, "message": caption}),
Ok(Response::Error { message, retry_as_gesture }) => json!({"ok": false, "message": message,
Ok(Response::Error { message, retry_as_gesture, .. }) => json!({"ok": false, "message": message,
"retry_as_gesture": retry_as_gesture && matches!(req, Request::Touch { phase: TouchPhase::Down, .. })}),
Err(e) => json!({"ok": false, "message": e.to_string()}),
}
Expand Down Expand Up @@ -1913,7 +1913,8 @@ mod tests {
let ctx = test_ctx(temp.path(), &socket);
for (phase, daemon_retry, allow) in [("down", false, false), ("down", true, true), ("move", true, false)] {
let body = json!({"phase":phase, "x":1, "y":2, "view":"portrait"});
let reply = Response::Error { message: "touch failed".into(), retry_as_gesture: daemon_retry };
let reply =
Response::Error { message: "touch failed".into(), retry_as_gesture: daemon_retry, failure: None };
// The result comes directly from the action, with no follow-up status request.
let ((_, result), req) = tokio::time::timeout(Duration::from_secs(3), async {
tokio::join!(
Expand Down
Loading
Loading