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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ What changed in each release, one line per change. Versions follow [Semantic Ver
- With nobody watching the control page, the phone's screen video is no longer assembled into frames, which saves CPU while an agent works.
- Several control pages on one phone running WebDriverAgent share one picture stream from the phone instead of opening one each, which could push WebDriverAgent over the CPU limit at which iOS stops it.
- Pages watching the phone's own video share one rotation check a second instead of one per page.
- At most 4 control pages at once get the phone's own video transcoded to H.264 (browsers without HEVC, one ffmpeg each); more retry until one closes, instead of starting another ffmpeg each.
- The control page polls less: the task list comes with the device-info poll instead of a poll of its own, the device panel asks two requests a round instead of three, and a page in a background tab stops polling until it is shown again.
- A daemon that ended with the screen media stream open (stuck and restarted by its watchdog, crashed or killed) no longer leaves the phone showing "viewed remotely" and never auto-locking: the next daemon clears it once the phone is ready.
- 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.
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
- 控制台没人观看时不再把手机的屏幕视频拼成帧,Agent 操作期间更省 CPU。
- 用 WebDriverAgent 的手机开着多个控制台页面时,共用手机上的一路画面,不再每个页面各开一路(多开时可能让 WebDriverAgent 超出 CPU 上限被 iOS 结束)。
- 观看手机原生视频的多个页面共用每秒一次的屏幕方向检查,不再每个页面各查一次。
- 浏览器解不了 HEVC、要把手机原生视频转成 H.264 的控制台页面(每页一个 ffmpeg)同时最多 4 个,再多的等有页面关掉后重试,不再每多一页就多开一个 ffmpeg。
- 控制台页面的轮询更少:任务列表随设备信息的轮询一起取,不再单独轮询;设备面板每轮两个请求而不是三个;页面在后台标签页时停止轮询,切回来再接着。
- 守护进程开着屏幕媒体流就退出(卡死被看门狗重启、崩溃或被结束)后,手机不再一直显示「正在被查看」、一直不自动锁屏:新的守护进程在手机就绪后清掉它。
- HTTP 上的 MCP(`/mcp`)接受分块(chunked)发送的请求体,之前会回 411 Length Required(有的客户端和反向代理这样发)。流式的回答改为分块发送,代理能分清正常结束和连接中断。
- 控制台服务的连接上限从 32 个提高到 64 个,满了时回 503 并记日志,不再悄悄断开。
- 停止控制台(`systemctl stop`、升级、Ctrl-C)时一并结束从页面启动的 AI 任务的 agent,之前它们会自己继续运行。
Expand Down
54 changes: 54 additions & 0 deletions apps/iphone-control/src/video/transcode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,44 @@ const TRIES: usize = 3;
/// Asking for a keyframe again while none came to start ffmpeg at
const ASK_EVERY: Duration = Duration::from_millis(500);

/// Transcoding pages at once, at most: each runs its own ffmpeg that decodes the phone's 60 fps HEVC and encodes it
/// again, a core or more apiece without a hardware decoder (and hardware encoders take only a few sessions)
pub const MAX_TRANSCODERS: usize = 4;

/// The places for transcoding pages ([`MAX_TRANSCODERS`]), shared by the viewer's connections
pub struct Slots {
free: Arc<tokio::sync::Semaphore>,
/// When "all taken" was last logged
logged: Mutex<Option<Instant>>,
}

impl Default for Slots {
fn default() -> Self {
Self::new(MAX_TRANSCODERS)
}
}

impl Slots {
pub fn new(n: usize) -> Self {
Self { free: Arc::new(tokio::sync::Semaphore::new(n)), logged: Mutex::new(None) }
}

/// A place for one page, held for as long as it watches; `None` when all are taken (logged once a minute)
pub fn take(&self) -> Option<tokio::sync::OwnedSemaphorePermit> {
let slot = self.free.clone().try_acquire_owned().ok();
if slot.is_none() {
let mut last = self.logged.lock().unwrap_or_else(|p| p.into_inner());
if last.is_none_or(|t| t.elapsed() >= Duration::from_secs(60)) {
*last = Some(Instant::now());
tracing::warn!(
"viewer: {MAX_TRANSCODERS} pages already get the phone's video transcoded to H.264; more get 503 until one closes"
);
}
}
slot
}
}

/// One ffmpeg process: HEVC in, H.264 in FLV out
struct Transcoder {
input: mpsc::Sender<Vec<u8>>,
Expand Down Expand Up @@ -299,3 +337,19 @@ pub async fn serve(
}
}
}

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

#[test]
fn transcoding_pages_are_limited_and_their_places_come_back() {
let slots = Slots::new(2);
let (a, b) = (slots.take().unwrap(), slots.take().unwrap());
assert!(slots.take().is_none(), "all taken");
drop(a);
let c = slots.take().expect("a page left: its place is free");
assert!(slots.take().is_none());
drop((b, c));
}
}
22 changes: 22 additions & 0 deletions apps/iphone-control/src/viewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ struct Ctx {
video: Option<Arc<crate::video::Encoders>>,
/// How much of each H.264 stream its page has read
acks: Arc<crate::video::Acks>,
/// Places for pages getting the phone's HEVC transcoded ([`crate::video::transcode::MAX_TRANSCODERS`])
transcoders: crate::video::transcode::Slots,
/// The phones' MJPEG streams, one per phone for all its pages
mjpeg: crate::video::hub::MjpegHub,
/// HTTPS on the same port (`--lan`); plain HTTP from the network is then sent there
Expand Down Expand Up @@ -284,6 +286,7 @@ pub async fn run(
device_video_allowed,
video,
acks: Arc::default(),
transcoders: Default::default(),
mjpeg: Default::default(),
tls,
mcp: mcp.then(|| ictl_mcp::http_service(socket.to_path_buf())),
Expand Down Expand Up @@ -638,6 +641,13 @@ async fn route(
if let Some(id) = req.query("feed") {
v["feed_open"] = json!(ctx.feeds.lock().unwrap_or_else(|p| p.into_inner()).contains(&id));
}
// the task list, for a page that wants to pick up a task under way: with this poll instead of
// one of its own (absent when it couldn't be read: the page asks again next time)
if req.query("tasks").as_deref() == Some("1")
&& let Ok(t) = protocol::task_list(&ctx.socket).await
{
v["tasks"] = json!(t);
}
// who the page is logged in as: a read-only token hides what it can't do
if let Some(w) = &pass.who {
v["login"] = json!({"name": w.name, "role": w.role.name()});
Expand Down Expand Up @@ -783,6 +793,17 @@ async fn picture(mut client: Conn, ctx: &Ctx, req: &Head) -> anyhow::Result<()>
// that can't decode HEVC
_ if ctx.device_video_allowed && video.is_some() => {
let Some(enc) = video else { unreachable!("checked") };
// one ffmpeg per page: past the limit the page retries shortly (it shows "retrying")
let Some(_slot) = ctx.transcoders.take() else {
return reply_with(
&mut client,
503,
"text/plain",
b"too many pages transcoding the phone's video",
"Retry-After: 10\r\n",
)
.await;
};
let (src, w) = match crate::video::device::open(&ctx.socket, &udid, low).await {
Ok(s) => s,
Err(e) => return reply(&mut client, 502, "text/plain; charset=utf-8", e.as_bytes()).await,
Expand Down Expand Up @@ -1526,6 +1547,7 @@ mod tests {
device_video_allowed: true,
video: None,
acks: Arc::default(),
transcoders: Default::default(),
mjpeg: Default::default(),
feeds: Mutex::default(),
tls: None,
Expand Down
18 changes: 14 additions & 4 deletions apps/iphone-control/src/viewer/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,24 +74,34 @@ pub(super) fn device_json(d: &ictl_device::DeviceInfo) -> Value {
})
}

/// `{ state, last_error?, device: { name, model, model_name, family, ios, udid }, auto_unlock }`
/// `{ state, last_error?, device: { name, model, model_name, family, ios, udid }, auto_unlock, devices, fixed, auto }`:
/// with [`devices`]'s list too (the same snapshot), so the device panel asks one request less each round
pub(super) async fn daemon(ctx: &Ctx) -> Result<Value, String> {
let s = crate::client::snapshot(&ctx.socket).await.map_err(|e| e.to_string())?;
let (state, last_error) = state_of(&s.state);
Ok(json!({
let mut v = json!({
"state": state,
"state_text": s.state.describe(),
"last_error": last_error,
"device": s.device.as_ref().map(device_json),
"auto_unlock": s.auto_unlock && !s.unlock_disabled,
// the page offers to sign and install WDA (NeedsSigning) only with an Apple ID to sign with
"signed_in": crate::client::account_dir(&ctx.data_dir).selected_email().await.is_ok(),
}))
});
let list = devices_of(&s);
for k in ["devices", "fixed", "auto"] {
v[k] = list[k].clone();
}
Ok(v)
}

/// `{ devices: [{ udid, name, model, model_name, family, ios, controlled }], fixed }`
pub(super) async fn devices(ctx: &Ctx) -> Result<Value, String> {
let s = crate::client::snapshot(&ctx.socket).await.map_err(|e| e.to_string())?;
Ok(devices_of(&s))
}

fn devices_of(s: &ictl_daemon::Snapshot) -> Value {
let cur = s.device.as_ref().map(|d| d.udid.to_ascii_lowercase());
let list: Vec<Value> = s
.devices
Expand All @@ -102,7 +112,7 @@ pub(super) async fn devices(ctx: &Ctx) -> Result<Value, String> {
v
})
.collect();
Ok(json!({"devices": list, "fixed": s.pinned_by_env, "auto": s.pinned.is_none()}))
json!({"devices": list, "fixed": s.pinned_by_env, "auto": s.pinned.is_none()})
}

/// `{ wda_ready, locked, foreground, foreground_id, width, height, route }`
Expand Down
4 changes: 3 additions & 1 deletion apps/iphone-control/web/js/device.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ async function loadDeviceState() {
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')]);
// /api/daemon 也带着设备列表(和它读同一份快照):一轮两个请求
const [d, s] = await Promise.allSettled([api('/api/daemon'), api('/api/status')]);
const l = d;
// 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;
Expand Down
4 changes: 2 additions & 2 deletions apps/iphone-control/web/js/i18n.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions apps/iphone-control/web/js/info.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,18 +223,24 @@ refreshVisibleUpdates();
setInterval(refreshVisibleUpdates, 60000);
document.addEventListener('visibilitychange', refreshVisibleUpdates);

let tasksAskedAt = 0;
async function loadInfo() {
const seq = ++infoSequence, epoch = feedEpoch;
try {
const r = await fetch('/api/info?feed=' + encodeURIComponent(feedId), { headers: { 'X-Ictl-Lang': LANG }, signal: AbortSignal.timeout(4800) });
// at most every 3 s as when it had a poll of its own (the list is about 10 KB with 50 tasks)
const tasks = wantsTasks() && Date.now() - tasksAskedAt >= 3000;
if (tasks) tasksAskedAt = Date.now();
const r = await fetch('/api/info?feed=' + encodeURIComponent(feedId) + (tasks ? '&tasks=1' : ''), { headers: { 'X-Ictl-Lang': LANG }, signal: AbortSignal.timeout(4800) });
if (loggedOut(r) || !r.ok) throw new Error('offline');
const v = await r.json();
if (seq === infoSequence && epoch === feedEpoch) applyInfo(v);
if (tasks && Array.isArray(v.tasks)) adoptTask(v.tasks);
} catch {
if (seq === infoSequence && epoch === feedEpoch) feedError();
}
}
/* 标签页在后台时不问(看不见的页面不用跟),回到前台马上补一次(见 layout.js 的 visibilitychange) */
async function pollInfo() {
await loadInfo();
if (!document.hidden) await loadInfo();
setTimeout(pollInfo, 2000);
}
11 changes: 7 additions & 4 deletions apps/iphone-control/web/js/layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ function keepFocus(fn) {
}
setInterval(() => {
const t = activeTask(); if (!t) return;
const el = $(`[data-runtime="${t.id}"]`); if (el) el.textContent = mmss(Date.now() - t.startedAt);
const m = $(`[data-elapsed="${t.id}"]`); if (m) m.textContent = `${t.steps.length} ${tr('步')} · ${mmss(Date.now() - t.startedAt)}`;
const el = $(`[data-runtime="${CSS.escape(t.id)}"]`); if (el) el.textContent = mmss(Date.now() - t.startedAt);
const m = $(`[data-elapsed="${CSS.escape(t.id)}"]`); if (m) m.textContent = `${t.steps.length} ${tr('步')} · ${mmss(Date.now() - t.startedAt)}`;
}, 1000);

/* ---------- 视图:≥1280 三栏;1024–1279 右栏抽屉;<1024 三个标签页 ---------- */
Expand Down Expand Up @@ -151,8 +151,11 @@ async function detect() {
setInterval(refreshFrame, 250);
setTimeout(pollInfo, 2000);
alertLoop();
setInterval(loadDeviceState, 10000);
adoptTask(); setInterval(adoptTask, 3000);
setInterval(() => { if (!document.hidden) loadDeviceState(); }, 10000);
// 之后的任务列表随 /api/info 的轮询来
adoptTask();
// 后台标签页不轮询(pollInfo、上面的设备状态、alertLoop 都看 document.hidden):回到前台时马上补一次
document.addEventListener('visibilitychange', () => { if (!document.hidden) { loadInfo(); loadDeviceState(); } });
} else {
S.tasks.filter(t => t.reattach).forEach(lostTask);
}
Expand Down
Loading
Loading