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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ What changed in each release, one line per change. Versions follow [Semantic Ver
- MCP over HTTP (`/mcp`) accepts request bodies sent chunked, which some clients and reverse proxies do; they got 411 Length Required. Streamed answers are sent chunked, so a proxy can tell their end from a dropped connection.
- The control page's server allows 64 connections instead of 32, and answers 503 (and logs it) when they are all taken instead of dropping the connection silently.
- Stopping the viewer (`systemctl stop`, an update, Ctrl-C) also stops the agents of AI tasks started from the page; they kept running on their own.
- An idle `iphone-control mcp` (kept running by Claude Desktop, Cursor, Claude Code…) no longer keeps updates from installing: it holds the maintenance lock only during a tool call, and its next call reaches the new daemon.
- The phone's own video on the control page pauses while the phone unlocks itself or the bitrate changes, instead of dropping and reconnecting.

## [0.2.14] - 2026-11-24

Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
- HTTP 上的 MCP(`/mcp`)接受分块(chunked)发送的请求体,之前会回 411 Length Required(有的客户端和反向代理这样发)。流式的回答改为分块发送,代理能分清正常结束和连接中断。
- 控制台服务的连接上限从 32 个提高到 64 个,满了时回 503 并记日志,不再悄悄断开。
- 停止控制台(`systemctl stop`、升级、Ctrl-C)时一并结束从页面启动的 AI 任务的 agent,之前它们会自己继续运行。
- 空闲的 `iphone-control mcp`(Claude Desktop、Cursor、Claude Code 等一直开着)不再挡住更新安装:它只在工具调用期间占用维护锁,升级后下一次调用自动连上新的守护进程。
- 手机自动解锁或码率切换时,控制台里的手机原生画面只是暂停,不再断开重连。

## [0.2.14] - 2026-11-24

Expand Down
8 changes: 6 additions & 2 deletions apps/iphone-control/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,12 +324,14 @@ async fn run() -> anyhow::Result<()> {
.init();

// Lifetime clients hold this through pauses and confirmations, and direct-device CLI
// commands participate even when they bypass the daemon.
// commands participate even when they bypass the daemon. The MCP server, which agents keep running for hours,
// takes it for each tool call instead (`ictl_mcp::serve_stdio`); over --url it talks to another machine.
let _client = match &cli.command {
Some(
Command::Daemon
| Command::Update { .. }
| Command::McpConfig
| Command::Mcp { .. }
| Command::Status
| Command::Completions { .. },
) => None,
Expand All @@ -346,7 +348,9 @@ async fn run() -> anyhow::Result<()> {
ictl_daemon::run(cfg).await
}
Command::Mcp { url: Some(url), ca } => mcp_bridge::run(&url, ca.as_deref()).await,
Command::Mcp { url: None, .. } => ictl_mcp::serve_stdio(cli.socket).await,
Command::Mcp { url: None, .. } => {
ictl_mcp::serve_stdio(cli.socket, Some(ictl_daemon::maintenance::shared)).await
}
Command::McpConfig => {
println!("{}", mcp_config(&cli.socket)?);
Ok(())
Expand Down
37 changes: 35 additions & 2 deletions apps/iphone-control/src/update/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,15 @@ fn check_clients(daemon: Option<u32>) -> Result<()> {
continue;
}
let command = parts.collect::<Vec<_>>().join(" ");
ensure!(
!Path::new(&command).file_name().is_some_and(|s| s == "iphone-control"),
if !Path::new(&command).file_name().is_some_and(|s| s == "iphone-control") {
continue;
}
// an MCP server of this version holds the lease only during a tool call, which the exclusive lease already
// waited for; idle, it just reconnects to the new daemon on the next call
if process_args(pid).is_some_and(|a| idles_without_lease(&a)) {
continue;
}
bail!(
"{}",
ictl_l10n::trf!(
"正忙:另一个 iphone-control 进程({pid})在运行",
Expand All @@ -242,6 +249,32 @@ fn check_clients(daemon: Option<u32>) -> Result<()> {
Ok(())
}

/// The command line of `pid` (`ps -o args=`), if it can be read
fn process_args(pid: u32) -> Option<String> {
let out = std::process::Command::new("ps")
.args(["-o", "args=", "-p", &pid.to_string()])
.env("LC_ALL", "C")
.output()
.ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
}

/// `iphone-control [--data-dir D] [--socket S] mcp …`: the MCP server, which from this version on takes the
/// maintenance lease for each tool call only. Older ones hold it for their whole life, so they never get this far
fn idles_without_lease(args: &str) -> bool {
let mut words = args.split_whitespace().skip(1);
while let Some(w) = words.next() {
match w {
"--data-dir" | "--socket" => {
words.next();
}
w if w.starts_with("--data-dir=") || w.starts_with("--socket=") => {}
w => return w == "mcp",
}
}
false
}

impl Host<'_> {
fn owns_pid(&self, pid: u32) -> bool {
process_path(pid)
Expand Down
23 changes: 23 additions & 0 deletions apps/iphone-control/src/update/transaction/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,3 +351,26 @@ fn a_release_without_unattended_mark_is_not_a_failure() {
assert!(e.to_string().ends_with("iphone-control update"), "{e}");
assert_eq!(failure_status(&anyhow::anyhow!("archive digest mismatch")), "failed");
}

/// Idle MCP servers of this version don't keep an update waiting; anything else named iphone-control does
#[test]
fn only_mcp_servers_idle_without_the_lease() {
for args in [
"iphone-control mcp",
"/home/u/.local/bin/iphone-control mcp",
"iphone-control --socket /run/x.sock mcp",
"iphone-control --data-dir=/d --socket=/s mcp --url https://h:8200",
] {
assert!(idles_without_lease(args), "{args}");
}
for args in [
"iphone-control",
"iphone-control viewer",
"iphone-control mcp-config",
"iphone-control setup",
"iphone-control --socket mcp viewer",
"iphone-control task run claude mcp",
] {
assert!(!idles_without_lease(args), "{args}");
}
}
75 changes: 64 additions & 11 deletions crates/ictl-daemon/src/screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,13 @@
//! [`ictl_device::LOW_BANDWIDTH_BITRATE`] while it watches. There is one stream per phone and its cap is set when it
//! starts, so the HID session is closed and opened again when the cap has to change: when the first such page comes,
//! and when the last one goes while others still watch (they get the full rate back). Every page's picture stops for
//! about half a second then and reconnects, and a touch under way ends ([`crate::tools::video_bitrate`]). The video is always portrait; the rotation of the
//! about half a second then, and a touch under way ends ([`crate::tools::video_bitrate`]). The video is always portrait; the rotation of the
//! interface is sent alongside ([`ScreenMsg::Info`]) and the page turns the picture.
//!
//! When the HID session closes under a stream (a bitrate change; unlocking natively, which reads the lock screen with
//! it closed seven or eight times, because iOS hides the keypad from accessibility while the screen is streamed),
//! the connection stays and waits for the next media stream ([`Daemon::reopen_feed`]): the page sees the picture
//! pause instead of losing it and reconnecting each time.

use std::sync::Arc;
use std::time::{Duration, Instant};
Expand All @@ -32,6 +37,12 @@ use crate::tools::video_bitrate;
/// free). Once for all the pages watching ([`Daemon::sample_rotation`]), not once per page
const ROTATION_EVERY: Duration = Duration::from_secs(1);

/// A media stream that closed under a page is waited for again after this long ([`Daemon::reopen_feed`])
const REOPEN_AFTER: Duration = Duration::from_millis(200);
/// … this many times in a row without a frame in between; then the page reconnects. Unlocking holds the device until
/// it is done, so a page waits for it once however often the session closes meanwhile
const REOPEN_TRIES: u32 = 10;

fn degrees(r: Rotation) -> u32 {
match r {
Rotation::Portrait => 0,
Expand Down Expand Up @@ -99,9 +110,12 @@ impl Daemon {
return;
}
let _viewer = viewer;
let mut feed = feed;
// stopped already (the HID session closed meanwhile): the viewer reconnects
let Some(mut frames) = feed.subscribe() else { return };
feed.request_keyframe();
// media streams that closed one after the other without a frame in between
let mut reopened = 0;
// nothing decodes before a keyframe (and the config message it brings)
let mut need_key = true;
let mut codec: Option<String> = None;
Expand All @@ -116,6 +130,7 @@ impl Daemon {
let out = tokio::select! {
r = frames.recv() => match r {
Ok(f) => {
reopened = 0;
if need_key && !f.key {
continue;
}
Expand All @@ -141,8 +156,19 @@ impl Daemon {
feed.request_keyframe();
continue;
}
// the HID session (and its media stream) closed: the viewer reconnects
Err(RecvError::Closed) => return,
// the HID session (and its media stream) closed: wait for the next one on this connection. Not
// forever: a stream that closes again and again without a frame is given up (the viewer reconnects)
Err(RecvError::Closed) => {
reopened += 1;
if reopened > REOPEN_TRIES {
return;
}
let Some((f, sub)) = self.reopen_feed(expect_udid.as_deref(), low_bandwidth).await else { return };
(feed, frames) = (f, sub);
need_key = true;
feed.request_keyframe();
continue;
}
},
r = reader.read(&mut buf) => match r {
Ok(0) | Err(_) => return,
Expand Down Expand Up @@ -219,6 +245,23 @@ impl Daemon {
rotation.map(degrees)
}

/// The next media stream after the last one closed under a watching page (see the module docs): taken once the
/// device is free (unlocking holds it until done), for the same device and rate. `None` when there is none to be
/// had: the device changed or went, the HID session can't be opened
async fn reopen_feed(
self: &Arc<Self>,
expect_udid: Option<&str>,
low_bandwidth: bool,
) -> Option<(ictl_device::ScreenFeed, tokio::sync::broadcast::Receiver<ictl_device::ScreenFrame>)> {
// whoever closed it may go on with the device for a moment (the next digit of the passcode)
tokio::time::sleep(REOPEN_AFTER).await;
let mut g = self.inner.lock().await;
let feed = self.open_feed(&mut g, expect_udid, low_bandwidth).await.ok()?;
g.hid_used = Some(Instant::now());
let frames = feed.subscribe()?;
Some((feed, frames))
}

/// The screen feed of the controlled device, opening the HID session for it if needed (again, at the lower rate,
/// for a page in low-bandwidth mode: see the module docs)
async fn screen_feed(
Expand All @@ -228,6 +271,22 @@ impl Daemon {
) -> crate::error::Result<(ictl_device::ScreenFeed, Viewer)> {
let mut g = self.inner.lock().await;
let g = &mut *g;
let feed = self.open_feed(g, expect_udid, low_bandwidth).await?;
g.screen_viewers += 1;
if low_bandwidth {
g.low_bandwidth_viewers += 1;
}
g.hid_used = Some(Instant::now());
Ok((feed, Viewer(self.clone(), low_bandwidth)))
}

/// [`Self::screen_feed`] without counting the page
async fn open_feed(
&self,
g: &mut crate::core::Inner,
expect_udid: Option<&str>,
low_bandwidth: bool,
) -> crate::error::Result<ictl_device::ScreenFeed> {
let udid =
g.device.as_ref().map(|d| d.udid.clone()).ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
if expect_udid.is_some_and(|u| !u.eq_ignore_ascii_case(&udid)) {
Expand Down Expand Up @@ -256,17 +315,11 @@ impl Daemon {
}
);
}
let feed = self
Ok(self
.hid_at(g, rate)
.await?
.screen_feed()
.ok_or(ictl_l10n::tr!("屏幕媒体流已停止", "The screen media stream stopped"))?;
g.screen_viewers += 1;
if low_bandwidth {
g.low_bandwidth_viewers += 1;
}
g.hid_used = Some(Instant::now());
Ok((feed, Viewer(self.clone(), low_bandwidth)))
.ok_or(ictl_l10n::tr!("屏幕媒体流已停止", "The screen media stream stopped"))?)
}
}

Expand Down
38 changes: 34 additions & 4 deletions crates/ictl-mcp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1173,6 +1173,29 @@ pub struct McpServer {
/// 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<Lease>,
}

/// 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<std::fs::File>;

/// 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<std::fs::File> {
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
Expand All @@ -1193,7 +1216,7 @@ pub fn http_service(socket: PathBuf) -> HttpService {
use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
let config = StreamableHttpServerConfig::default().with_allowed_hosts(Vec::<String>::new());
StreamableHttpService::new(
move || Ok(McpServer { socket: socket.clone(), task: false }),
move || Ok(McpServer { socket: socket.clone(), task: false, lease: None }),
std::sync::Arc::default(),
config,
)
Expand Down Expand Up @@ -1221,6 +1244,11 @@ impl ServerHandler for McpServer {
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, ErrorData> {
// 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;
Expand Down Expand Up @@ -1560,8 +1588,10 @@ impl McpServer {
}

/// 在 stdin/stdout 上运行 MCP 服务直到客户端断开
pub async fn serve_stdio(socket: PathBuf) -> anyhow::Result<()> {
let running = McpServer { socket, task: task::join_from_env() }.serve(rmcp::transport::stdio()).await?;
/// 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<Lease>) -> anyhow::Result<()> {
let running = McpServer { socket, task: task::join_from_env(), lease }.serve(rmcp::transport::stdio()).await?;
running.waiting().await?;
Ok(())
}
Expand All @@ -1578,7 +1608,7 @@ mod tests {
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 };
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;
Expand Down
2 changes: 2 additions & 0 deletions docs/dev/regression-cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,5 @@
| 178 | `/mcp` 只认 Content-Length:MCP 客户端或反向代理用 `Transfer-Encoding: chunked` 发请求体就回 411;流式回答(SSE)去掉了分块编码、只靠关连接结束,代理分不清正常结束和中途断开 | chunked 请求体照读并解码(最多 1 MB,忽略块扩展、丢弃尾部字段);同时带长度和 chunked、或别的传输编码回 400(防请求走私);没有长度的回答分块发送、以结束块收尾 | 单测 `chunked_bodies_decode`、`streams_are_chunked`、`mcp_over_http_takes_a_chunked_body` + 真机主机(curl 分块 POST 初始化会话得到 200,`tools/list` 的回答以结束块收尾) |
| 179 | 控制台服务连接满 32 个时新连接被悄悄丢掉(没有回应也没有日志),一个页面占 3~5 个,几个人一起看就满 | 上限 64;满了每次最多 4 个新连接回 503 并带 `Retry-After`,日志每分钟最多记一次 | 代码审查(单测未覆盖接满的情形) |
| 180 | 控制台停止(`systemctl stop`、升级、Ctrl-C)时不处理信号:从页面启动的 AI 任务的 agent 在自己的进程组里,变成孤儿继续跑 | SIGTERM/SIGINT 时停止接受连接,给每个 agent 的进程组发 SIGTERM,3 秒后还在就 SIGKILL,然后退出 | 单测 `stopping_and_waiting_ends_every_group` + 真机主机(`systemctl --user restart iphone-control-viewer` 日志有「viewer: stopping」并立即退出;没有在跑的 agent,结束进程组未实测) |
| 181 | 常驻的 `iphone-control mcp`(Claude Desktop、Cursor、Claude Code 一直开着)整个进程期间持有维护共享锁,更新(尤其 `auto-patch`)在桌面上几乎总是「正忙」 | stdio 的 MCP 服务只在工具调用期间持锁(更新占着锁时最多等 15 秒);更新器的旧客户端检查放过 `iphone-control [--socket S] mcp`;`mcp --url` 不持锁 | 单测 `only_mcp_servers_idle_without_the_lease` + 真机主机(Debian 12:新版空闲的 `mcp` 不在 `/proc/locks` 的持锁名单里,旧版的 5 个都在) |
| 182 | 原生自动解锁读锁屏时要关 HID 会话(开着媒体流时 iOS 把密码键盘藏起来),码率切换也要重开:每次关掉都让控制台的原生视频连接结束,页面重连 | 连接留着,等设备空闲后在同一设备、同一码率上接回下一路媒体流并要关键帧;连续 10 次没收到帧就放弃、设备换了也结束 | 真机(iPhone 15 Pro Max iOS 27.2.1:两路原生视频开着锁屏再自动解锁,连接不断,解锁后从关键帧恢复) |
Loading
Loading