From 9f0a18745e02fddcaabc2f786694f8bcd2787521 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:53:31 +0800 Subject: [PATCH 1/5] fix(viewer): escape task ids in the task list A task's id is the page's own (`t`), but it is read back from localStorage on reload and was put into attributes unescaped (turnHtml, the run bar) and into querySelector strings (the elapsed-time timer). It now goes through esc() in HTML and CSS.escape() in selectors, so an edited stored record can't add attributes or break the timer. Co-authored-by: Claude Opus 5.5 --- apps/iphone-control/web/js/layout.js | 4 ++-- apps/iphone-control/web/js/tasks.js | 16 +++++++++------- tests/viewer/summary.test.mjs | 18 ++++++++++++++++++ 3 files changed, 29 insertions(+), 9 deletions(-) diff --git a/apps/iphone-control/web/js/layout.js b/apps/iphone-control/web/js/layout.js index 2e02f81..2188c7b 100644 --- a/apps/iphone-control/web/js/layout.js +++ b/apps/iphone-control/web/js/layout.js @@ -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 三个标签页 ---------- */ diff --git a/apps/iphone-control/web/js/tasks.js b/apps/iphone-control/web/js/tasks.js index 3896ebb..f3a907e 100644 --- a/apps/iphone-control/web/js/tasks.js +++ b/apps/iphone-control/web/js/tasks.js @@ -342,22 +342,24 @@ function agentLabel(t) { return isExternal(t) ? `${name} · ${tr('外部任务')}` : name; } function turnHtml(t) { + // the id is the page's own (`t`), but read back from localStorage: escaped like everything else put in HTML + const id = esc(t.id); const st = TASK_STATUS[t.status], active = ACTIVE.includes(t.status), open = S.expanded.has(t.id) || active; const busy = !!activeTask(); const actions = active ? '' : S.pendingDelete === t.id - ? `` - : `${isExternal(t) ? '' : ``}`; + ? `` + : `${isExternal(t) ? '' : ``}`; const answer = !active && t.summary ? `
${icon(st.icon)}
${st.label}
${mdLite(t.summary)}
` : ''; - const toggle = !active && t.steps.length ? `` : ''; + const toggle = !active && t.steps.length ? `` : ''; return `
  • - ${isExternal(t) ? `
    ${esc(t.prompt)}
    ` : ``} + ${isExternal(t) ? `
    ${esc(t.prompt)}
    ` : ``}
    ${hhmm(new Date(t.startedAt))}${t.apps?.length ? `${icon('grid')}${esc(tr('只在') + ' ' + scopeText(t.apps))}` : ''}${actions}
    -
    ${icon('bot')}${esc(agentLabel(t))}${t.steps.length} ${tr('步')} · ${mmss((t.endedAt || Date.now()) - t.startedAt)}${badge(st)}
    +
    ${icon('bot')}${esc(agentLabel(t))}${t.steps.length} ${tr('步')} · ${mmss((t.endedAt || Date.now()) - t.startedAt)}${badge(st)}
    ${answer}${toggle} - ${t.steps.length ? `
      ${t.steps.map(stepHtml).join('')}
    ` : ''} + ${t.steps.length ? `
      ${t.steps.map(stepHtml).join('')}
    ` : ''}
  • `; } function renderTurns(follow) { @@ -379,7 +381,7 @@ function renderRunbar() { if (t.status === 'takeover') b.push(btn('handback', tr('交还 AI'), 'play', 'btn-primary')); if (t.status === 'waiting') b.push(btn('goto-confirm', tr('去确认'), 'arrow', 'btn-primary')); b.push(btn('stop', tr('停止'), 'stop', 'btn-danger')); - bar.innerHTML = `${icon(st.icon, st.icon === 'loader' ? 'spin' : '')}${st.label}${mmss(Date.now() - t.startedAt)}${b.join('')}`; + bar.innerHTML = `${icon(st.icon, st.icon === 'loader' ? 'spin' : '')}${st.label}${mmss(Date.now() - t.startedAt)}${b.join('')}`; bar.hidden = false; } const busy = !!t; diff --git a/tests/viewer/summary.test.mjs b/tests/viewer/summary.test.mjs index 8e69743..6393603 100644 --- a/tests/viewer/summary.test.mjs +++ b/tests/viewer/summary.test.mjs @@ -45,3 +45,21 @@ test('nothing gets through as HTML', () => { assert.equal(mdLite(''), ''); assert.equal(mdLite(null), ''); }); + +// A task's id is the page's own (`t`), but it comes back from localStorage on reload: an edited record can't +// break out of the attributes it is put in +test('a task id from storage stays inside its attributes', () => { + const pick = re => { const m = html.match(re); assert.ok(m, String(re)); return m[0]; }; + const fns = [/^const esc = .*$/m, /^function turnHtml\([^]*?^}/m].map(pick).join('\n'); + const ctx = { + TASK_STATUS: { done: { tone: 'ok', icon: 'check', label: 'done' } }, ACTIVE: ['running'], BUILTIN_AGENTS: {}, + S: { expanded: new Set(), pendingDelete: null, agents: [] }, activeTask: () => null, isExternal: () => false, + icon: () => '', tr: String, hhmm: () => '00:00', mmss: () => '0:00', badge: () => '', mdLite: String, + agentLabel: () => 'AI', scopeText: () => '', stepHtml: () => '
  • ', + }; + const { turnHtml } = runInNewContext(fns + '\n({ turnHtml })', ctx); + const evil = 't1" onmouseover="alert(1)'; + const out = turnHtml({ id: evil, status: 'done', prompt: 'p', steps: [{}], startedAt: 0, endedAt: 1, source: 'live' }); + assert.ok(!out.includes('" onmouseover='), out); + assert.ok(out.includes('data-id="t1" onmouseover="alert(1)"')); +}); From 64027857ba4180baf5d603e14afeb19c12e668f3 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:55:21 +0800 Subject: [PATCH 2/5] fix(viewer): at most 4 pages get the phone's HEVC transcoded at once A page whose browser can't decode HEVC gets the phone's own video (iOS 27+) as H.264 from an ffmpeg of its own, which decodes 60 fps HEVC and encodes again: a core or more each without a hardware decoder, and hardware encoders only take a few sessions. There was no limit. Now `transcode::Slots` gives out 4 places; a page past that gets 503 with Retry-After, shows "picture lost, retrying" and gets in once another page closes. Logged at most once a minute. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 1 + CHANGELOG.zh-CN.md | 1 + apps/iphone-control/src/video/transcode.rs | 54 ++++++++++++++++++++++ apps/iphone-control/src/viewer.rs | 15 ++++++ docs/dev/regression-cases.md | 1 + website/en/guide/cli.md | 1 + website/guide/cli.md | 1 + 7 files changed, 74 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index be75c2a..e537425 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ 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. - 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. diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 25a7279..157e5bc 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -18,6 +18,7 @@ - 控制台没人观看时不再把手机的屏幕视频拼成帧,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,之前它们会自己继续运行。 diff --git a/apps/iphone-control/src/video/transcode.rs b/apps/iphone-control/src/video/transcode.rs index c009a3f..06e5919 100644 --- a/apps/iphone-control/src/video/transcode.rs +++ b/apps/iphone-control/src/video/transcode.rs @@ -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, + /// When "all taken" was last logged + logged: Mutex>, +} + +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 { + 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>, @@ -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)); + } +} diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs index 649c30d..3bc1b87 100644 --- a/apps/iphone-control/src/viewer.rs +++ b/apps/iphone-control/src/viewer.rs @@ -77,6 +77,8 @@ struct Ctx { video: Option>, /// How much of each H.264 stream its page has read acks: Arc, + /// 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 @@ -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())), @@ -783,6 +786,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, @@ -1526,6 +1540,7 @@ mod tests { device_video_allowed: true, video: None, acks: Arc::default(), + transcoders: Default::default(), mjpeg: Default::default(), feeds: Mutex::default(), tls: None, diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index 908fd2d..07885b2 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -187,3 +187,4 @@ | 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:两路原生视频开着锁屏再自动解锁,连接不断,解锁后从关键帧恢复) | | 183 | 低版本(WDA)的控制台 MJPEG 画面由 viewer 自己经 usbmuxd 连手机 9100:除了 `wda-bridge`,只有这里绕过守护进程碰手机(D2),也只能走 USB | viewer 向守护进程要(`Request::MjpegStream`):守护进程按页面给的 UDID 核对正在控制的设备,向 WDA 要流,原样转给 viewer,页面走了就关;不拿设备锁 | 单测 `the_phone_s_bytes_pass_through_until_the_page_goes`、`another_device_than_the_controlled_one_is_refused` + 真机(iPad mini 5,iPadOS 26.7.3:3 路 `/stream` 时 viewer 没有一条到 usbmuxd 的连接、只多 1 条到守护进程的,守护进程多 2 条;三路各约 150 帧;页面关掉后守护进程到手机的连接也关了;`/video` 经同一路源出 VAAPI 编码的 H.264) | +| 184 | 浏览器解不了 HEVC 时,每个看手机原生视频的控制台页面各起一个 ffmpeg 解 60 帧的 HEVC 再编 H.264,没有上限:开几个页面就能把主机 CPU 或显卡的编码会话占满 | 同时最多 4 个页面转码(`transcode::Slots`),再多的回 503(`Retry-After`),页面显示「画面断开 · 自动重试中」、等有页面关掉后接上;日志每分钟最多记一次 | 单测 `transcoding_pages_are_limited_and_their_places_come_back` + 真机 | diff --git a/website/en/guide/cli.md b/website/en/guide/cli.md index 4c33ef4..a050090 100644 --- a/website/en/guide/cli.md +++ b/website/en/guide/cli.md @@ -154,6 +154,7 @@ On macOS, and on Linux with ffmpeg installed, the control page's picture is H.26 - **Encoder:** `viewer` tries them in order when it starts, uses the first that works and says which in the terminal: NVENC on NVIDIA; VAAPI on AMD and Intel (the JPEG is decoded by the GPU too); QSV on Intel as well; V4L2 on ARM boards such as the Raspberry Pi; VideoToolbox on macOS (called directly, the JPEG decoded by the hardware too; with ffmpeg installed, its VideoToolbox is the fallback); otherwise x264 in software (uses the CPU). One that fails on the real picture is replaced by the next. On Linux the user must be in the `render` group to use the GPU; `doctor` checks it. - **Slow links:** the page tells viewer every 100 ms how much it has received. When the link can't keep up, fewer frames are encoded: the frame rate drops, but the picture doesn't fall further and further behind. On a 200 KB/s link, for example, the picture catches up about 0.6 s after scrolling stops. +- **iOS 27 and later as H.264:** when the browser can't decode HEVC, ffmpeg on this machine turns the phone's video into H.264, one ffmpeg process per page. At most 4 pages watch this way at once; more show "Picture lost · retrying" until one of them closes. - **Falling back to MJPEG:** on Linux without ffmpeg, without a working encoder, or in a browser without WebCodecs (older ones), the page uses MJPEG. It no longer repeats the same frame while the screen is still, and on a slow link it only sends the newest frame. - **Low-bandwidth mode:** a switch in the control page's Settings, for use over the internet or a weak signal. About half the picture's traffic at the same frame rate; a still screen looks the same, while things move edges get a little blocky, clear again about half a second after they stop. The phone's own video (HEVC) is one stream per phone, its bitrate cap agreed with the phone when it starts, so while the mode is on every page watching that phone gets it (a 6 Mbit/s cap becomes 2 Mbit/s), and the first page to turn it on and the last to turn it off interrupt everyone's picture for about half a second and end a touch under way. H.264 only changes for the page that turned it on (qp 26). While it is on, the line under the picture says "Low-bandwidth mode". - **Which one is in use:** shown under the picture, e.g. "Live · Native · HEVC iPhone 312 KB/s" (native control, the phone's own video), "Live · WDA · HEVC iPhone 312 KB/s" or "Live · WDA · H.264 VAAPI 254 KB/s". diff --git a/website/guide/cli.md b/website/guide/cli.md index 702774c..4857b70 100644 --- a/website/guide/cli.md +++ b/website/guide/cli.md @@ -154,6 +154,7 @@ macOS 上,以及 Linux 上装了 ffmpeg 时,控制台的画面是 H.264, - **编码器:** `viewer` 启动时按顺序试,第一个能用的就用,并在终端里显示:NVIDIA 用 NVENC;AMD、Intel 用 VAAPI(JPEG 也交给显卡解码);Intel 还可以用 QSV;树莓派一类的 ARM 板用 V4L2;macOS 用 VideoToolbox(本程序直接调用,JPEG 也由硬件解码;装了 ffmpeg 时,它的 VideoToolbox 作备用);都不行就用 x264 软件编码(占 CPU)。处理真实画面时出错,会换下一个。Linux 上要用显卡,用户得在 `render` 组里,`doctor` 会检查。 - **链路慢时:** 页面每 100 毫秒告诉 viewer 收到了多少。链路跟不上时少编几帧,画面帧率下降,但不会越来越滞后。比如每秒 200 KB 的链路,滚动停下后约 0.6 秒画面追上。 +- **iOS 27 及以上转成 H.264:** 浏览器解不了 HEVC 时,手机的视频由本机的 ffmpeg 转成 H.264,每个页面一个 ffmpeg 进程。同时最多 4 个页面这样看,再多的页面显示「画面断开 · 自动重试中」,等有页面关掉再接上。 - **自动改用 MJPEG:** Linux 上没有 ffmpeg、没有能用的编码器、浏览器不支持 WebCodecs(较旧的浏览器)时自动改用 MJPEG;画面静止时不再重复发同一张图,链路慢时只发最新的一张。 - **弱网模式:** 控制台「设置」里的开关,适合外网或信号差时用。画面流量减少约一半,帧率不变;画面静止时看不出区别,动起来时边缘会有些糊块,停下约半秒后恢复。手机自己的视频(HEVC)每台手机只有一路,码率上限在开始时和手机协商,所以开着时所有在看这台手机的页面都会一起降(约 6 Mbit/s 上限降到 2 Mbit/s),第一个开它和最后一个关它的页面会让所有人的画面断开半秒左右再接上,进行中的触摸也会中断。H.264 只影响开它的那个页面(qp 提到 26)。开着时画面下方会写「弱网模式」。 - **看现在用的是哪种:** 画面下方写着,例如「实时画面 · 原生 · HEVC iPhone 312 KB/s」(原生控制,手机自己的视频)、「实时画面 · WDA · HEVC iPhone 312 KB/s」或「实时画面 · WDA · H.264 VAAPI 254 KB/s」。 From 158322b07cd8a5fd79308a5c1649d795442c1eb7 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:58:18 +0800 Subject: [PATCH 3/5] perf(viewer): fewer polls from the control page Each page polled /api/info every 2 s, the task list every 3 s and the device panel every 10 s with three requests, two of which (/api/daemon, /api/devices) read the same daemon snapshot, and kept doing so in a background tab. Now: - the task list comes with /api/info (`?tasks=1`, asked only while the page wants to pick up a task: the same condition adoptTask had), so it has no poll of its own; adoptTask takes the list it is given - /api/daemon carries the device list (`devices`, `fixed`, `auto`, as /api/devices, which stays), so the device panel asks two requests - a page in a background tab doesn't poll /api/info or the device panel (the alert check already didn't) and catches up when shown again Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 1 + CHANGELOG.zh-CN.md | 1 + apps/iphone-control/src/viewer.rs | 7 +++++++ apps/iphone-control/src/viewer/api.rs | 18 ++++++++++++++---- apps/iphone-control/web/js/device.js | 4 +++- apps/iphone-control/web/js/i18n.js | 4 ++-- apps/iphone-control/web/js/info.js | 7 +++++-- apps/iphone-control/web/js/layout.js | 7 +++++-- apps/iphone-control/web/js/tasks.js | 12 ++++++++---- docs/dev/regression-cases.md | 1 + tests/viewer/tasks.test.mjs | 12 +++++++++++- 11 files changed, 58 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e537425..8b1b133 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ What changed in each release, one line per change. Versions follow [Semantic Ver - 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. - 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. diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 157e5bc..0aaaaad 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -19,6 +19,7 @@ - 用 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,之前它们会自己继续运行。 diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs index 3bc1b87..7639f52 100644 --- a/apps/iphone-control/src/viewer.rs +++ b/apps/iphone-control/src/viewer.rs @@ -641,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()}); diff --git a/apps/iphone-control/src/viewer/api.rs b/apps/iphone-control/src/viewer/api.rs index e0e7473..d5430ca 100644 --- a/apps/iphone-control/src/viewer/api.rs +++ b/apps/iphone-control/src/viewer/api.rs @@ -74,11 +74,12 @@ 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 { 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, @@ -86,12 +87,21 @@ pub(super) async fn daemon(ctx: &Ctx) -> Result { "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 { 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 = s .devices @@ -102,7 +112,7 @@ pub(super) async fn devices(ctx: &Ctx) -> Result { 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 }` diff --git a/apps/iphone-control/web/js/device.js b/apps/iphone-control/web/js/device.js index eda4152..5c08b68 100644 --- a/apps/iphone-control/web/js/device.js +++ b/apps/iphone-control/web/js/device.js @@ -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; diff --git a/apps/iphone-control/web/js/i18n.js b/apps/iphone-control/web/js/i18n.js index 0f0294d..c8d25f0 100644 --- a/apps/iphone-control/web/js/i18n.js +++ b/apps/iphone-control/web/js/i18n.js @@ -63,12 +63,12 @@ language.addEventListener('change', () => { * * 画面与手动操作,都经守护进程,和 MCP 工具一样排队、自动解锁、只作用于这个页面跟着的设备: * GET /stream → WebDriverAgent 的 MJPEG 画面 - * GET /api/info → { width, height, udid, device, warning? } + * GET /api/info → { width, height, udid, device, warning?, tasks? } // ?tasks=1 时带上任务列表(同 GET /api/agent/tasks 的 tasks) * 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/daemon → { state, state_text, last_error?, device: { name, model, ios, udid }, auto_unlock, devices, fixed, auto } // 设备列表同 /api/devices * 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" diff --git a/apps/iphone-control/web/js/info.js b/apps/iphone-control/web/js/info.js index 733a55a..04e12c6 100644 --- a/apps/iphone-control/web/js/info.js +++ b/apps/iphone-control/web/js/info.js @@ -226,15 +226,18 @@ document.addEventListener('visibilitychange', refreshVisibleUpdates); 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) }); + const tasks = wantsTasks(); + 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); } diff --git a/apps/iphone-control/web/js/layout.js b/apps/iphone-control/web/js/layout.js index 2188c7b..42f99ae 100644 --- a/apps/iphone-control/web/js/layout.js +++ b/apps/iphone-control/web/js/layout.js @@ -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); } diff --git a/apps/iphone-control/web/js/tasks.js b/apps/iphone-control/web/js/tasks.js index f3a907e..6c1d320 100644 --- a/apps/iphone-control/web/js/tasks.js +++ b/apps/iphone-control/web/js/tasks.js @@ -147,14 +147,18 @@ function lostTask(t) { t.summary = tr('页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。'); t.steps.forEach(st => { if (st.status === 'running' || st.status === 'waiting') st.status = 'stopped'; }); } -/* 正在进行、但这个页面还没跟着的任务(页面刷新过,或者是在别处开的):接上,事件会从头重放 */ +/* 正在进行、但这个页面还没跟着的任务(页面刷新过,或者是在别处开的):接上,事件会从头重放。 + * 任务列表随 /api/info 的轮询一起来(loadInfo 在 wantsTasks() 时带 tasks=1),不再单独轮询 */ let adopting = false; -async function adoptTask() { +function wantsTasks() { + return S.mode === 'live' && !adopting && (S.tasks.some(t => t.reattach) || !activeTask()); +} +async function adoptTask(given) { + if (!wantsTasks()) return; const pending = S.tasks.filter(t => t.reattach); - if (S.mode !== 'live' || adopting || (!pending.length && activeTask())) return; adopting = true; try { - const list = (await api('/api/agent/tasks')).tasks || []; + const list = (Array.isArray(given) ? given : (await api('/api/agent/tasks')).tasks) || []; pending.forEach(t => { if (list.some(x => x.id === t.remoteId)) { t.reattach = false; follow(t, t.remoteId); } else lostTask(t); }); if (pending.length) renderAll(); const t = list.find(x => ACTIVE.includes(x.state)); diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index 07885b2..f7f963b 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -188,3 +188,4 @@ | 182 | 原生自动解锁读锁屏时要关 HID 会话(开着媒体流时 iOS 把密码键盘藏起来),码率切换也要重开:每次关掉都让控制台的原生视频连接结束,页面重连 | 连接留着,等设备空闲后在同一设备、同一码率上接回下一路媒体流并要关键帧;连续 10 次没收到帧就放弃、设备换了也结束 | 真机(iPhone 15 Pro Max iOS 27.2.1:两路原生视频开着锁屏再自动解锁,连接不断,解锁后从关键帧恢复) | | 183 | 低版本(WDA)的控制台 MJPEG 画面由 viewer 自己经 usbmuxd 连手机 9100:除了 `wda-bridge`,只有这里绕过守护进程碰手机(D2),也只能走 USB | viewer 向守护进程要(`Request::MjpegStream`):守护进程按页面给的 UDID 核对正在控制的设备,向 WDA 要流,原样转给 viewer,页面走了就关;不拿设备锁 | 单测 `the_phone_s_bytes_pass_through_until_the_page_goes`、`another_device_than_the_controlled_one_is_refused` + 真机(iPad mini 5,iPadOS 26.7.3:3 路 `/stream` 时 viewer 没有一条到 usbmuxd 的连接、只多 1 条到守护进程的,守护进程多 2 条;三路各约 150 帧;页面关掉后守护进程到手机的连接也关了;`/video` 经同一路源出 VAAPI 编码的 H.264) | | 184 | 浏览器解不了 HEVC 时,每个看手机原生视频的控制台页面各起一个 ffmpeg 解 60 帧的 HEVC 再编 H.264,没有上限:开几个页面就能把主机 CPU 或显卡的编码会话占满 | 同时最多 4 个页面转码(`transcode::Slots`),再多的回 503(`Retry-After`),页面显示「画面断开 · 自动重试中」、等有页面关掉后接上;日志每分钟最多记一次 | 单测 `transcoding_pages_are_limited_and_their_places_come_back` + 真机 | +| 185 | 控制台页面各自定时轮询:`/api/info` 每 2 秒、任务列表每 3 秒、设备面板每 10 秒三个请求(`/api/daemon`、`/api/devices` 读的是同一份快照),后台标签页也照常轮询;几个页面开着时守护进程的请求成倍增加 | 任务列表随 `/api/info?tasks=1` 一起取(只在页面要接任务时带上);`/api/daemon` 带上设备列表,一轮两个请求;页面在后台时 `/api/info`、设备面板、弹窗检查都不问,切回前台立刻补一次 | 页面测试 `a task list from the info poll is used as it is` 和原有的任务接续测试 + 真机 | diff --git a/tests/viewer/tasks.test.mjs b/tests/viewer/tasks.test.mjs index b5136e1..b193022 100644 --- a/tests/viewer/tasks.test.mjs +++ b/tests/viewer/tasks.test.mjs @@ -29,7 +29,7 @@ function page(tasks, serverTasks) { calls: 0, async api(path) { context.calls++; assert.equal(path, '/api/agent/tasks'); return { tasks: serverTasks }; }, }; - return { S, followed, shown, context, ...handlers(['isExternal', 'lostTask', 'adoptTask'], context) }; + return { S, followed, shown, context, ...handlers(['isExternal', 'lostTask', 'wantsTasks', 'adoptTask'], context) }; } test('a task that was running before the reload is followed again', async () => { @@ -99,3 +99,13 @@ test('a task opened elsewhere is never run again as a prompt', () => { rerunTask('t2'); assert.deepEqual(started, ['打开设置']); }); + +// The list comes with the page's /api/info poll (`?tasks=1` while it wants one): no request of its own then +test('a task list from the info poll is used as it is', async () => { + const { followed, context, wantsTasks, adoptTask } = page([], []); + assert.equal(wantsTasks(), true, 'no task followed: the poll asks for the list'); + await adoptTask([{ id: 'xyz', state: 'running', title: 'from elsewhere', owner: 'external' }]); + assert.equal(context.calls, 0, 'no request of its own'); + assert.deepEqual(followed.map(([, id]) => id), ['xyz']); + assert.equal(wantsTasks(), false, 'following one now: the poll stops asking'); +}); From e8e011f3d3c13c4e0d954292cf722ee6fa79e4d8 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:10:10 +0800 Subject: [PATCH 4/5] fix(daemon): clear the phone's "viewed remotely" a dead daemon left behind A daemon that ends with the HID session open (the watchdog's exit(1) while a request is stuck holding the device lock, a crash, SIGKILL) never stops the screen media stream. On an iPhone 15 Pro Max (iOS 27.2.1) the Dynamic Island then kept the "viewed" icon and the phone didn't auto-lock for 5 minutes and more, until something opened a HID session again and closed it properly, which clears it. The watchdog can't close the session first: the lock it is behind is held by the stuck request. So the next daemon does it: a marker `hid-open/` is written when a session opens and removed when it closes properly (close_hid, drop_tunnel, and so shutdown). Markers found at start are cleared in the supervision round once that phone is ready, by opening a session and closing it (3 tries at most), with a line in the event log. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 1 + CHANGELOG.zh-CN.md | 1 + crates/ictl-daemon/src/config.rs | 4 ++ crates/ictl-daemon/src/core.rs | 20 +++++++++ crates/ictl-daemon/src/hidmark.rs | 66 +++++++++++++++++++++++++++++ crates/ictl-daemon/src/lib.rs | 1 + crates/ictl-daemon/src/supervise.rs | 34 +++++++++++++++ crates/ictl-daemon/src/tools/mod.rs | 6 +++ crates/ictl-daemon/src/watchdog.rs | 4 +- docs/architecture.md | 1 + docs/dev/regression-cases.md | 1 + website/deploy/backup.md | 1 + website/en/deploy/backup.md | 1 + 13 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 crates/ictl-daemon/src/hidmark.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b1b133..dc88e0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ What changed in each release, one line per change. Versions follow [Semantic Ver - 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. diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 0aaaaad..e2b23c9 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -20,6 +20,7 @@ - 观看手机原生视频的多个页面共用每秒一次的屏幕方向检查,不再每个页面各查一次。 - 浏览器解不了 HEVC、要把手机原生视频转成 H.264 的控制台页面(每页一个 ffmpeg)同时最多 4 个,再多的等有页面关掉后重试,不再每多一页就多开一个 ffmpeg。 - 控制台页面的轮询更少:任务列表随设备信息的轮询一起取,不再单独轮询;设备面板每轮两个请求而不是三个;页面在后台标签页时停止轮询,切回来再接着。 +- 守护进程开着屏幕媒体流就退出(卡死被看门狗重启、崩溃或被结束)后,手机不再一直显示「正在被查看」、一直不自动锁屏:新的守护进程在手机就绪后清掉它。 - HTTP 上的 MCP(`/mcp`)接受分块(chunked)发送的请求体,之前会回 411 Length Required(有的客户端和反向代理这样发)。流式的回答改为分块发送,代理能分清正常结束和连接中断。 - 控制台服务的连接上限从 32 个提高到 64 个,满了时回 503 并记日志,不再悄悄断开。 - 停止控制台(`systemctl stop`、升级、Ctrl-C)时一并结束从页面启动的 AI 任务的 agent,之前它们会自己继续运行。 diff --git a/crates/ictl-daemon/src/config.rs b/crates/ictl-daemon/src/config.rs index dca4f38..4f8a083 100644 --- a/crates/ictl-daemon/src/config.rs +++ b/crates/ictl-daemon/src/config.rs @@ -183,6 +183,10 @@ impl Config { pub fn state_file(&self) -> PathBuf { self.data_dir.join("state.json") } + /// A marker per phone with a HID session open ([`crate::hidmark`]) + pub fn hid_marker_dir(&self) -> PathBuf { + self.data_dir.join("hid-open") + } /// 建好数据目录并收紧权限:账号私钥、锁屏密码都在里面(配对记录归系统的 usbmuxd 管) pub fn prepare_dirs(&self) -> std::io::Result<()> { diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs index 216accb..c6adca9 100644 --- a/crates/ictl-daemon/src/core.rs +++ b/crates/ictl-daemon/src/core.rs @@ -504,6 +504,11 @@ pub(crate) struct Inner { pub offline_target: Option, /// HID 会话最近一次使用的时间;空闲超过 [`crate::supervise::HID_IDLE`] 就关掉(它持有屏幕媒体流) pub hid_used: Option, + /// The marker of the HID session open now ([`crate::hidmark`]), removed when it closes properly + pub hid_marker: Option, + /// Phones an earlier daemon left "viewed remotely" (it ended with a HID session open), and the tries at clearing + /// that so far ([`crate::hidmark`]) + pub hid_orphans: HashMap, /// 原生控制:无障碍会话最近一次使用的时间;空闲超过 [`crate::supervise::AX_IDLE`] 就关掉 pub ax_used: Option, /// 原生控制:后台挂开发者镜像(结果:挂上的版本,已挂载为 None;失败时带上「是不是挂载这一步」) @@ -572,6 +577,18 @@ pub(crate) async fn close_hid(g: &mut Inner) { if let Some(t) = g.tunnel.as_mut() { t.close_hid().await; } + hid_closed(g); +} + +/// The HID session was closed properly: its marker goes, and with it any state an earlier daemon left on that phone +/// (closing a session clears it, see [`crate::hidmark`]) +fn hid_closed(g: &mut Inner) { + if let Some(p) = g.hid_marker.take() { + if let Some(udid) = p.file_name().and_then(|n| n.to_str()) { + g.hid_orphans.remove(udid); + } + let _ = std::fs::remove_file(p); + } } /// 丢掉隧道。一律走这里:先停 HID 媒体流再断(见 [`close_hid`]) @@ -581,6 +598,7 @@ pub(crate) async fn drop_tunnel(g: &mut Inner) { // boxed: the future holds the whole tunnel, and every tool that may drop it would carry that Box::pin(t.close()).await; } + hid_closed(g); } /// 一台设备的简短说明:`名字(型号 iOS 版本,UDID)`,英文是 `name (model iOS version, UDID)`;读不到名字时只有 UDID @@ -684,6 +702,8 @@ impl Daemon { offline_since: Some(now), offline_target: None, hid_used: None, + hid_marker: None, + hid_orphans: crate::hidmark::left_over(&cfg.hid_marker_dir()), ax_used: None, preparing: None, screen_viewers: 0, diff --git a/crates/ictl-daemon/src/hidmark.rs b/crates/ictl-daemon/src/hidmark.rs new file mode 100644 index 0000000..45800eb --- /dev/null +++ b/crates/ictl-daemon/src/hidmark.rs @@ -0,0 +1,66 @@ +//! The phone's "viewed remotely" state left behind by a daemon that ended with a HID session open. +//! +//! The HID session holds the phone's screen media stream; closing it stops the stream, and the phone drops the +//! Dynamic Island's "viewed" icon and may auto-lock again. A daemon that ends without closing it (the watchdog's exit +//! while a request is stuck holding the device lock, a crash, SIGKILL) leaves the phone thinking it is still viewed: +//! the icon stays and the phone doesn't auto-lock, for minutes at least (iPhone16,2, iOS 27.2.1: still so 5 minutes +//! after a SIGKILL). Opening a session and closing it properly clears it. +//! +//! The watchdog can't close the session itself (the stuck request holds the lock it is behind), so the next daemon +//! does: a marker file per phone (`hid-open/` in the data directory) is written when a session opens and +//! removed when it closes properly. Markers found at start are cleared by opening and closing a session once the +//! phone is ready again ([`crate::Daemon`]'s supervision round). + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +/// Tries at clearing a phone's state before giving up on it +pub(crate) const TRIES: u32 = 3; + +/// The marker for `udid` in `dir`, written now. `None` if it couldn't be (nothing else depends on it) +pub(crate) fn mark(dir: &Path, udid: &str) -> Option { + let name = sanitize(udid)?; + std::fs::create_dir_all(dir).ok()?; + let p = dir.join(name); + std::fs::write(&p, b"").ok()?; + Some(p) +} + +/// The phones whose marker an earlier daemon left behind, each with no tries yet +pub(crate) fn left_over(dir: &Path) -> HashMap { + let Ok(entries) = std::fs::read_dir(dir) else { return HashMap::new() }; + entries.flatten().filter_map(|e| e.file_name().to_str().and_then(sanitize)).map(|u| (u, 0)).collect() +} + +/// The marker for `udid` in `dir`, if any, removed +pub(crate) fn clear(dir: &Path, udid: &str) { + if let Some(name) = sanitize(udid) { + let _ = std::fs::remove_file(dir.join(name)); + } +} + +/// A UDID as a file name: letters, digits and dashes only +fn sanitize(udid: &str) -> Option { + (!udid.is_empty() && udid.len() <= 64 && udid.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')) + .then(|| udid.to_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn markers_outlive_the_process_until_cleared() { + let dir = std::env::temp_dir().join(format!("ictl-hidmark-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + assert!(left_over(&dir).is_empty(), "no directory yet"); + let p = mark(&dir, "00008130-0019295E012B803A").unwrap(); + assert!(p.is_file()); + assert!(mark(&dir, "../escape").is_none(), "not a UDID"); + // the next daemon finds it + assert_eq!(left_over(&dir), HashMap::from([("00008130-0019295E012B803A".to_owned(), 0)])); + clear(&dir, "00008130-0019295E012B803A"); + assert!(left_over(&dir).is_empty()); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs index 7b99845..ec01c0d 100644 --- a/crates/ictl-daemon/src/lib.rs +++ b/crates/ictl-daemon/src/lib.rs @@ -14,6 +14,7 @@ mod devtools; mod doctor; pub mod error; pub mod eventlog; +mod hidmark; pub mod imaging; pub mod machine; pub mod maintenance; diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rs index 92986ac..e5b57ca 100644 --- a/crates/ictl-daemon/src/supervise.rs +++ b/crates/ictl-daemon/src/supervise.rs @@ -162,6 +162,7 @@ impl Daemon { Some(d) => { self.online(g, &d).await; self.adopt_legacy_passcode(g); + self.clear_left_viewed(g).await; } } @@ -577,6 +578,39 @@ impl Daemon { } } + /// The phone in use was left "viewed remotely" by an earlier daemon that ended with a HID session open + /// ([`crate::hidmark`]): once it is ready, a session opened and closed clears that. A session open now clears it + /// when it closes; after [`crate::hidmark::TRIES`] failed tries it is left alone + async fn clear_left_viewed(&self, g: &mut Inner) { + let Some(udid) = g.device.as_ref().map(|d| d.udid.clone()) else { return }; + let Some(&tries) = g.hid_orphans.get(&udid) else { return }; + if g.state != DeviceState::Ready + || !crate::core::hid_supported(g.info.as_ref()) + || g.tunnel.as_ref().is_some_and(Tunnel::hid_open) + { + return; + } + match Box::pin(self.hid(g)).await { + Ok(_) => { + // removes the marker and the entry (`close_hid`) + close_hid(g).await; + self.log.log(ictl_l10n::log_tr!( + "上次守护进程退出时没有停掉屏幕媒体流(卡死或被结束):已清掉手机上残留的「正在被查看」", + "The last daemon ended without stopping the screen media stream (stuck or killed): cleared the phone's leftover \"viewed remotely\"" + )); + } + Err(e) => { + tracing::warn!("clearing the leftover HID state of {udid} failed: {e}"); + if tries + 1 >= crate::hidmark::TRIES { + g.hid_orphans.remove(&udid); + crate::hidmark::clear(&self.cfg.hid_marker_dir(), &udid); + } else { + g.hid_orphans.insert(udid, tries + 1); + } + } + } + } + /// Keep an active view and finger through the same transient status misses as the runner. pub(crate) async fn confirm_wda_loss(&self, g: &mut Inner, runner_alive: bool) -> bool { if runner_alive && !g.wda_misses.hit() { diff --git a/crates/ictl-daemon/src/tools/mod.rs b/crates/ictl-daemon/src/tools/mod.rs index 27c2881..a3cac7a 100644 --- a/crates/ictl-daemon/src/tools/mod.rs +++ b/crates/ictl-daemon/src/tools/mod.rs @@ -203,11 +203,17 @@ impl Daemon { .ensure_tunnel(g, &device) .await .map_err(|e| ictl_l10n::trf!("HID 后备路线不可用:{e}", "HID fallback unavailable: {e}"))?; + let was_open = t.hid_open(); // boxed, as the screenshot above: opening the session is a large future if let Err(e) = Box::pin(t.hid(screen, max_bitrate)).await { drop_tunnel(g).await; return Err(ictl_l10n::trf!("HID 后备路线不可用:{e}", "HID fallback unavailable: {e}").into()); } + // a new session: marked until it closes properly, so a daemon that ends without closing it is noticed by the + // next one ([`crate::hidmark`]) + if !was_open { + g.hid_marker = crate::hidmark::mark(&self.cfg.hid_marker_dir(), &device.udid); + } // 第二次调用直接返回已开好的会话(这样写是为了绕开借用检查对条件返回的限制) Ok(Box::pin(g.tunnel.as_mut().expect("刚建好").hid(screen, max_bitrate)).await?) } diff --git a/crates/ictl-daemon/src/watchdog.rs b/crates/ictl-daemon/src/watchdog.rs index f9cb766..feac273 100644 --- a/crates/ictl-daemon/src/watchdog.rs +++ b/crates/ictl-daemon/src/watchdog.rs @@ -5,7 +5,9 @@ //! Everything that finishes work under the device lock (a request, a full supervision round) goes through //! [`crate::Daemon`]'s `publish`, which beats the heartbeat. A round that finds the lock busy skips without beating, //! so a stuck lock holder shows up as silence. The check runs on its own thread, so a blocked runtime is caught too. -//! The service manager (systemd `Restart=on-failure`, launchd `KeepAlive`) starts a fresh daemon. +//! The service manager (systemd `Restart=on-failure`, launchd `KeepAlive`) starts a fresh daemon. The exit can't +//! close a HID session first (the stuck request holds the lock it is behind): the fresh daemon clears what that +//! leaves on the phone ([`crate::hidmark`]). use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; diff --git a/docs/architecture.md b/docs/architecture.md index 61ce4e5..6b3ece3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -167,6 +167,7 @@ | `viewer-tokens.json` | 控制台的登录令牌(名字、权限、令牌) | 0600 | 否 | | `viewer-tls/` | 控制台局域网 HTTPS 的自签证书和私钥 | 0700 | 否 | | `tasks/` | 最近 50 个 AI 任务的事件记录,每个任务一个 `.jsonl` | 默认 | 否 | +| `hid-open/` | 空文件:这台设备的 HID 会话开着,正常关掉时删除;守护进程没收尾就退出(看门狗、崩溃、kill -9)留下的,下次启动时开关一次 HID 清掉手机上残留的「正在被查看」(`hidmark.rs`) | 默认 | 否 | 守护进程的配置全部来自环境变量(`crates/ictl-daemon/src/config.rs`),都有默认值。整个项目的环境变量都登记在 `crates/ictl-protocol/src/env.rs`(名字、用途、是否在设置文件模板里),代码只经它的常量读;它的测试核对代码、配置页和 `packaging/env.example` 三者一致。设置文件 `~/.config/iphone-control/env`(`KEY=value`,0600,模板 `packaging/env.example`)由首次运行引导和 `setup --reconfigure` 写(`envfile.rs`:改一项就地替换,注释和其他项保留);后台服务(launchd、systemd、`brew services`)把它读进守护进程的环境,其他命令启动时也读一遍,已有的环境变量优先。通知渠道的密钥也在这个文件里;其余秘密只放数据目录里的文件。 diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index f7f963b..eaf9b32 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -189,3 +189,4 @@ | 183 | 低版本(WDA)的控制台 MJPEG 画面由 viewer 自己经 usbmuxd 连手机 9100:除了 `wda-bridge`,只有这里绕过守护进程碰手机(D2),也只能走 USB | viewer 向守护进程要(`Request::MjpegStream`):守护进程按页面给的 UDID 核对正在控制的设备,向 WDA 要流,原样转给 viewer,页面走了就关;不拿设备锁 | 单测 `the_phone_s_bytes_pass_through_until_the_page_goes`、`another_device_than_the_controlled_one_is_refused` + 真机(iPad mini 5,iPadOS 26.7.3:3 路 `/stream` 时 viewer 没有一条到 usbmuxd 的连接、只多 1 条到守护进程的,守护进程多 2 条;三路各约 150 帧;页面关掉后守护进程到手机的连接也关了;`/video` 经同一路源出 VAAPI 编码的 H.264) | | 184 | 浏览器解不了 HEVC 时,每个看手机原生视频的控制台页面各起一个 ffmpeg 解 60 帧的 HEVC 再编 H.264,没有上限:开几个页面就能把主机 CPU 或显卡的编码会话占满 | 同时最多 4 个页面转码(`transcode::Slots`),再多的回 503(`Retry-After`),页面显示「画面断开 · 自动重试中」、等有页面关掉后接上;日志每分钟最多记一次 | 单测 `transcoding_pages_are_limited_and_their_places_come_back` + 真机 | | 185 | 控制台页面各自定时轮询:`/api/info` 每 2 秒、任务列表每 3 秒、设备面板每 10 秒三个请求(`/api/daemon`、`/api/devices` 读的是同一份快照),后台标签页也照常轮询;几个页面开着时守护进程的请求成倍增加 | 任务列表随 `/api/info?tasks=1` 一起取(只在页面要接任务时带上);`/api/daemon` 带上设备列表,一轮两个请求;页面在后台时 `/api/info`、设备面板、弹窗检查都不问,切回前台立刻补一次 | 页面测试 `a task list from the info poll is used as it is` 和原有的任务接续测试 + 真机 | +| 186 | 守护进程开着 HID 会话就退出(看门狗判定卡死后 `exit(1)`、崩溃、kill -9):屏幕媒体流没停,手机一直显示「正在被查看」、一直不自动锁屏(iPhone 15 Pro Max iOS 27.2.1:kill -9 后 5 分钟仍是这样),直到下次有程序开了再正常关 HID。看门狗退出时拿不到设备锁,没法先收尾 | 开 HID 时写 `hid-open/`,正常关掉时删;启动时发现残留的,等那台手机就绪后开一下 HID 再正常关掉(最多试 3 次),事件日志记一笔 | 单测 `markers_outlive_the_process_until_cleared` + 真机(开着 HID 时 kill -9 守护进程,看灵动岛的图标) | diff --git a/website/deploy/backup.md b/website/deploy/backup.md index 0378d43..dde692a 100644 --- a/website/deploy/backup.md +++ b/website/deploy/backup.md @@ -11,6 +11,7 @@ | `viewer-tokens.json` | 控制台的登录令牌(像密码一样保管,别放进会同步到别处的备份) | 控制台第一次启动时生成新的 `owner`;之前的令牌、登录过的浏览器和 MCP 客户端都要换新的 | | `viewer-tls/` | 控制台局域网 HTTPS 用的自签证书和私钥(同样要保密) | 重新生成,证书指纹变了:浏览器会再提示一次,`--ca` 要换新证书 | | `tasks/` | 最近 50 个 AI 任务的记录 | 控制台上看不到以前的任务,不影响使用 | +| `hid-open/` | 哪台手机的屏幕媒体流开着(空文件) | 不用备份 | | `state.json` | 签好的 WDA 包信息(Team ID、Bundle ID、描述文件到期时间)、选定的设备、每台设备的屏幕尺寸、上次重签结果 | 守护进程按「WDA 还没签名」启动:要重新 `sign` 或 `setup`,选过设备的要重新 `select` | | `logs/` | 日志、自动解锁的停用标记 `UNLOCK-DISABLED` | 日志没了不要紧。但停用标记没了就撤销了这层保护:之前输错过的话,可能再用同一个错误密码输一遍 | diff --git a/website/en/deploy/backup.md b/website/en/deploy/backup.md index 54c68ad..febcfaf 100644 --- a/website/en/deploy/backup.md +++ b/website/en/deploy/backup.md @@ -11,6 +11,7 @@ | `viewer-tokens.json` | The viewer's login tokens (keep them like passwords, out of backups that sync elsewhere) | The viewer makes a new `owner` on its next start; browsers and MCP clients that logged in need the new one | | `viewer-tls/` | The self-signed certificate and key for the viewer's HTTPS on the local network (secret too) | Made again with a new fingerprint: browsers warn once more, and `--ca` needs the new certificate | | `tasks/` | The last 50 AI tasks | The page no longer shows earlier tasks; nothing else | +| `hid-open/` | Which phones have the screen media stream open (empty files) | Nothing to back up | | `state.json` | Signed WDA details (Team ID, bundle id, profile expiry), selected device, each device's screen size, last signing result | The daemon starts as if WDA isn't signed: run `sign` or `setup` again, and `select` again if you had selected a device | | `logs/` | Logs, auto-unlock's stop marker `UNLOCK-DISABLED` | The logs don't matter. Losing the marker removes a safeguard: after a wrong passcode, the same one could be entered again | From 575bb26a3af1eca6df3441204df5ffcf41fd2f07 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:14:21 +0800 Subject: [PATCH 5/5] perf(viewer): the task list with the info poll at most every 3 s With the list in /api/info on every poll an idle page fetched its 10 KB (50 tasks) every 2 s instead of every 3 s. It is asked for at most every 3 s again, as when it had a poll of its own. Co-authored-by: Claude Opus 5.5 --- apps/iphone-control/web/js/info.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/iphone-control/web/js/info.js b/apps/iphone-control/web/js/info.js index 04e12c6..8382b42 100644 --- a/apps/iphone-control/web/js/info.js +++ b/apps/iphone-control/web/js/info.js @@ -223,10 +223,13 @@ refreshVisibleUpdates(); setInterval(refreshVisibleUpdates, 60000); document.addEventListener('visibilitychange', refreshVisibleUpdates); +let tasksAskedAt = 0; async function loadInfo() { const seq = ++infoSequence, epoch = feedEpoch; try { - const tasks = wantsTasks(); + // 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();