Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools
Rust ai-agentautomationclaudeclaude-codedockeriosiphonelinuxmcpmcp-servermodel-context-protocolrustwebdriveragent
fix(viewer): format AI task summaries instead of showing raw Markdown (#66)
Qinghe Li683419af2a16
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex df004f4..f47c2d8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ All notable changes to this project are documented here. The format is based on### Fixed+- AI task summaries on the control page are formatted: bold, lists, inline code and line breaks show as such instead of raw Markdown.- Locking no longer takes about 10 s every time on some iPhones (e.g. iPhone 15 Pro Max, iOS 27.0.1): pressing the power key via IOHID does nothing there, so the daemon remembers it per device and uses WDA's lock first (about 2 s).- Locking now works on iPads below iOS 27 (iPad mini 5, iPadOS 26.7.3: it never locked) and takes about 2 s instead of 10 s the first time on an iPhone 15 Pro Max: the power key via IOHID is now held 0.15 s instead of 0.1 s, which those devices ignored.- A WDA that still answers `/status` but no longer answers anything that goes through XCTest (foreground app, screenshots, elements, lock state all time out) is now noticed and restarted within about 30 s, also while tool calls keep the device busy (requests through XCTest stop waiting out their timeouts once three in a row went unanswered). Before, the daemon kept showing it as ready, and in background mode (`ICTL_WDA_DETACHED`) even a daemon restart attached to the stuck WDA again.diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex e63a283..ed23e35 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -8,6 +8,7 @@### 修复+- 控制台上 AI 任务的总结按格式显示:粗体、列表、行内代码和换行不再显示成 Markdown 原文。- 部分 iPhone(如 iPhone 15 Pro Max,iOS 27.0.1)上锁屏不再每次要 10 秒左右:经 IOHID 短按电源键在这些设备上不起作用,守护进程会按设备记住,之后先用 WDA 的锁屏(约 2 秒)。- iOS 27 以下的 iPad 现在能锁屏了(iPad mini 5,iPadOS 26.7.3:一直锁不上),iPhone 15 Pro Max 第一次锁屏也从约 10 秒变成约 2 秒:经 IOHID 按电源键改成按 0.15 秒,原来的 0.1 秒这些设备不认。- WDA 还应答 `/status`、经 XCTest 的请求却全都不应答(前台 App、截图、读元素、锁屏状态全部超时)时,现在约 30 秒内就会发现并重启它,工具调用接连不断时也一样(经 XCTest 的请求连续 3 次没有应答后,不再一次次等满时限)。以前守护进程一直显示「就绪」,后台模式(`ICTL_WDA_DETACHED`)下连重启守护进程都会把卡死的 WDA 接回来。diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.htmlindex 961a1d1..9166c71 100644--- a/apps/iphone-control/src/viewer.html+++ b/apps/iphone-control/src/viewer.html@@ -291,6 +291,12 @@ body.resizing .stage, body.resizing iframe { pointer-events: none; }.answer-text { display: grid; gap: 2px; }.answer-title { display: block; font-weight: 600; font-size: var(--fs-sm); }.answer-body { display: block; color: var(--text); overflow-wrap: anywhere; }+.answer-body > * + * { margin-top: 6px; }+.answer-body p, .answer-body ul, .answer-body ol { margin: 0; }+.answer-body ul, .answer-body ol { padding-left: 1.3em; }+.answer-body li + li { margin-top: 2px; }+.answer-body code { font-size: 0.92em; padding: 0 4px; border-radius: 4px; background: var(--accent-soft); }+.answer-body a { color: var(--accent); }.agent-foot { min-width: 0; padding: 8px var(--sp-4); display: flex; flex-direction: column; gap: var(--sp-2); }.composer { display: flex; flex-direction: column; min-width: 0; border: 1px solid var(--glass-border); border-radius: 16px; background: var(--panel); box-shadow: var(--shadow-xs); overflow: hidden; transition: border-color var(--dur-fast) var(--ease-out); }@@ -1146,6 +1152,41 @@ const sleep = ms => new Promise(res => setTimeout(res, ms));const round1 = v => Math.round(v * 10) / 10;const pad = n => String(n).padStart(2, '0');const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+/* 任务总结:Claude Code、Codex 都爱用 Markdown(粗体、列表)。整段先转义,再只认一小部分写法,任何原始 HTML 都进不来:+ * 粗体(只认 **,免得把 __init__ 这类名字当成粗体)、斜体、行内代码、无序和有序列表、标题(显示成粗体段落)、分隔线、空行分段、单个换行,以及 http(s) 链接 */+function mdInline(s) {+ // s 已经转义过;行内代码里的字原样显示,不再认粗体之类+ return s.split(/(`[^`\n]+`)/).map((part, i) => i % 2 ? `<code>${part.slice(1, -1)}</code>` : part+ .replace(/\*\*([^*\n]+?)\*\*/g, '<strong>$1</strong>')+ .replace(/(^|[^*\w])\*(?=\S)([^*\n]+?)\*(?![*\w])/g, '$1<em>$2</em>')+ .replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>')).join('');+}+function mdLite(text) {+ const out = [];+ let para = [], list = null;+ const flushPara = () => { if (para.length) out.push(`<p>${para.map(mdInline).join('<br>')}</p>`); para = []; };+ const flushList = () => { if (list) out.push(`<${list.tag}>${list.items.map(i => `<li>${mdInline(i)}</li>`).join('')}</${list.tag}>`); list = null; };+ for (const raw of esc(String(text ?? '').replace(/\r\n?/g, '\n').trim()).split('\n')) {+ const line = raw.trim();+ let m;+ if (!line || /^([-*_])(\s*\1){2,}$/.test(line)) { flushPara(); flushList(); continue; }+ if ((m = line.match(/^#{1,6}\s+(.+)$/))) { flushPara(); flushList(); out.push(`<p><strong>${mdInline(m[1])}</strong></p>`); continue; }+ const item = line.match(/^[-*+]\s+(.*)$/) || line.match(/^\d{1,3}[.)]\s+(.*)$/);+ if (item) {+ const tag = /^\d/.test(line) ? 'ol' : 'ul';+ flushPara();+ if (!list || list.tag !== tag) { flushList(); list = { tag, items: [] }; }+ list.items.push(item[1]);+ continue;+ }+ // a list item's next, indented line belongs to it+ if (list && /^\s/.test(raw)) { list.items[list.items.length - 1] += ' ' + line; continue; }+ flushList();+ para.push(line);+ }+ flushPara(); flushList();+ return out.join('');+}const hhmm = (d = new Date()) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;const mmss = ms => { const s = Math.max(0, Math.floor(ms / 1000)); return `${pad(Math.floor(s / 60))}:${pad(s % 60)}`; };const fmtSw = ms => { const cs = Math.floor(ms / 10); return `${pad(Math.floor(cs / 6000))}:${pad(Math.floor(cs / 100) % 60)}.${pad(cs % 100)}`; };@@ -2898,7 +2939,7 @@ function turnHtml(t) {const actions = active ? '' : S.pendingDelete === t.id? `<button type="button" class="mini confirm-del" data-action="del-yes" data-id="${t.id}" data-focus="dely-${t.id}">${icon('trash')}<span>${tr('确认删除')}</span></button><button type="button" class="mini" data-action="del-no" data-id="${t.id}" data-focus="deln-${t.id}">${tr('取消')}</button>`: `<button type="button" class="mini" data-action="rerun" data-id="${t.id}" data-focus="rerun-${t.id}" ${busy ? 'disabled' : ''}>${icon('refresh')}<span>${tr('重新执行')}</span></button><button type="button" class="mini danger" data-action="del-ask" data-id="${t.id}" data-focus="del-${t.id}" aria-label="${tr('删除这条记录')}" title="${tr('删除这条记录')}">${icon('trash')}<span>${tr('删除')}</span></button>`;- const answer = !active && t.summary ? `<div class="answer tone-${st.tone}">${icon(st.icon)}<div class="answer-text"><span class="answer-title">${st.label}</span><span class="answer-body">${esc(t.summary)}</span></div></div>` : '';+ const answer = !active && t.summary ? `<div class="answer tone-${st.tone}">${icon(st.icon)}<div class="answer-text"><span class="answer-title">${st.label}</span><div class="answer-body">${mdLite(t.summary)}</div></div></div>` : '';const toggle = !active && t.steps.length ? `<button type="button" class="toggle-steps" data-action="toggle-steps" data-id="${t.id}" data-focus="ts-${t.id}" aria-expanded="${open}" aria-controls="steps-${t.id}"><span>${open ? tr('收起步骤') : `${tr('查看')} ${t.steps.length} ${tr('个步骤')}`}</span>${icon('chevron')}</button>` : '';return `<li class="turn"><div class="msg-user">diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.mdindex 8f57d46..5b78b69 100644--- a/docs/dev/regression-cases.md+++ b/docs/dev/regression-cases.md@@ -109,3 +109,4 @@| 103 | WDA 半死:`/status` 照常 200,前台 App、截图、读元素、`/wda/locked` 全部超时(iPad mini 5,iPadOS 26.7.3,后台启动的 WDA 跑 20~40 分钟后)。守护进程只看 `/status`,一直显示「就绪」,不重启;后台模式下守护进程重启还会把它接回来。只靠巡检探测也不够:卡死时工具调用一个接一个等满超时(每个 10~30 秒),设备被占好几分钟,巡检抢不到锁 | WDA 客户端数经 XCTest 的请求(`/status` 之外都是,工具调用和巡检探测 `/wda/activeAppInfo` 一样算)连续几次送到了却没有应答,有应答(哪怕是错误)就清零;连续 3 次就算卡死:之后经 XCTest 的请求直接报不可用,巡检和每个设备请求开头都会忘掉记下的后台 WDA、丢掉会话重新启动 | 单测 three_unanswered_requests_mean_stalled、xctest_probe_counts_only_missing_answers;真机:绕过守护进程让 WDA 长按(期间 `/status` 5 毫秒 200,`/wda/activeAppInfo` 超时)。空闲时 0.2.3 一直「就绪」,修复后约 28 秒判定卡死、34 秒恢复;同时经守护进程背靠背发工具调用时,main(#60)180 秒里 8 次调用各等 10~30 秒、不重启,修复后第 3 次超时(约 50 秒)就重启,13 秒后就绪,其间的调用立即返回;经守护进程连续长按 6×10 秒不误判 || 104 | iOS 27 以下(iPad mini 5,iPadOS 26.7.3)锁屏没锁上:经 IOHID 按电源键 3 秒后未锁、`/wda/lock` 报「Timed out while waiting until the screen gets locked」,之后退到 HID 后备路线,而低版本没有 HID,报的是「WDA 不可用(刚掉线)」,WDA 其实正常 | WDA 在、两种办法都没锁上、又没有 HID 后备时,报「没锁上屏」和两种办法各自的原因;有 HID 后备时照旧退到 HID | 单测 a_failed_lock_says_why_not_that_wda_is_down;真机:见 PR || 105 | iPad mini 5(iPadOS 26.7.3)一直锁不上屏:经 IOHID 按电源键 0.1 秒调用卡约 5.4 秒、不锁;`/wda/lock`(iOS 27 以下是 XCTest 的 `pressLockButton`)10 秒后报「Timed out while waiting until the screen gets locked」。iPhone 15 Pro Max(iOS 27.0.1)上 0.1 秒同样不认,每台第一次锁屏要退到 `/wda/lock`,约 10 秒 | 电源键按 0.15 秒(`POWER_PRESS_SECS`):iPad mini 5、iPhone 15 Pro Max 上 0.15~0.3 秒都能锁,iPhone 18 Pro Max(iOS 27.2.1)上 0.05~0.15 秒能锁、0.5 秒不行 | 单测 hid_buttons_send_consumer_page_events;真机:经 `wda-bridge` 每次先解锁再按不同时长,看 `/wda/locked`;经守护进程连续锁屏 3 次 |+| 111 | 控制台上 AI 任务的总结直接显示 Markdown 原文(`**iOS 27.0.1**`、`- **设置**:…`),换行也被合并成一行 | 总结先整体转义,再按一小部分 Markdown 显示(粗体、斜体、行内代码、列表、标题、分隔线、换行、http(s) 链接),原始 HTML 一律当文字 | 页面测试(`tests/viewer/summary.test.mjs`)+ 真机(Claude Code、Codex 任务的总结) |diff --git a/tests/viewer/summary.test.mjs b/tests/viewer/summary.test.mjsnew file mode 100644index 0000000..0dd5120--- /dev/null+++ b/tests/viewer/summary.test.mjs@@ -0,0 +1,47 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { test } from 'node:test';+import { runInNewContext } from 'node:vm';++const html = readFileSync(new URL('../../apps/iphone-control/src/viewer.html', import.meta.url), 'utf8');++// The page's summary renderer on its own (same approach as actions.test.mjs)+const code = [/^const esc = .*$/m, /^function mdInline\([^]*?^}/m, /^function mdLite\([^]*?^}/m].map(re => {+ const m = html.match(re);+ assert.ok(m, String(re));+ return m[0];+});+const { mdLite } = runInNewContext(code.join('\n') + '\n({ mdLite })', {});++test('what agents write: bold, lists, line breaks', () => {+ assert.equal(mdLite('系统版本是 **iOS 27.0.1**。'), '<p>系统版本是 <strong>iOS 27.0.1</strong>。</p>');+ assert.equal(+ mdLite('五个 App 都打开了:\n\n- **设置**:停在「关于本机」\n- **照片**:显示「精选集」'),+ '<p>五个 App 都打开了:</p><ul><li><strong>设置</strong>:停在「关于本机」</li><li><strong>照片</strong>:显示「精选集」</li></ul>'+ );+ assert.equal(mdLite('1. 打开设置\n2. 点通用'), '<ol><li>打开设置</li><li>点通用</li></ol>');+ assert.equal(mdLite('第一行\n第二行'), '<p>第一行<br>第二行</p>');+ assert.equal(mdLite('## 结果\n完成'), '<p><strong>结果</strong></p><p>完成</p>');+ assert.equal(mdLite('上面\n---\n下面'), '<p>上面</p><p>下面</p>');+ assert.equal(mdLite('- 一项\n 接着这一项\n- 二项'), '<ul><li>一项 接着这一项</li><li>二项</li></ul>');+});++test('code, italics and links, without mangling ordinary text', () => {+ assert.equal(mdLite('运行 `iphone-control **status**`'), '<p>运行 <code>iphone-control **status**</code></p>');+ assert.equal(mdLite('这是 *重点*,2*3=6 不变'), '<p>这是 <em>重点</em>,2*3=6 不变</p>');+ assert.equal(mdLite('com.apple.mobile_cal 和 snake_case_name'), '<p>com.apple.mobile_cal 和 snake_case_name</p>');+ assert.equal(mdLite('Python 的 __init__ 方法'), '<p>Python 的 __init__ 方法</p>');+ assert.equal(+ mdLite('[文档](https://example.com/a?b=1&c=2)'),+ '<p><a href="https://example.com/a?b=1&c=2" target="_blank" rel="noopener noreferrer">文档</a></p>'+ );+});++test('nothing gets through as HTML', () => {+ assert.equal(mdLite('<img src=x onerror=alert(1)>'), '<p><img src=x onerror=alert(1)></p>');+ assert.equal(mdLite('[x](javascript:alert(1))'), '<p>[x](javascript:alert(1))</p>');+ assert.equal(mdLite('[x](https://a" onmouseover="b)'), '<p>[x](https://a" onmouseover="b)</p>');+ assert.equal(mdLite('**<b>粗</b>**'), '<p><strong><b>粗</b></strong></p>');+ assert.equal(mdLite(''), '');+ assert.equal(mdLite(null), '');+});