diff --git a/CHANGELOG.md b/CHANGELOG.md index dff61bd3..be75c2a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,10 @@ What changed in each release, one line per change. Versions follow [Semantic Ver - 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. +### Improvements + +- On iOS 17–26 the control page's picture comes through the daemon instead of the viewer opening WebDriverAgent's picture port on the phone itself; apart from `wda-bridge`, only the daemon talks to the phone now. + ## [0.2.14] - 2026-11-24 ### New diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 031b9bd2..25a7279b 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -24,6 +24,10 @@ - 空闲的 `iphone-control mcp`(Claude Desktop、Cursor、Claude Code 等一直开着)不再挡住更新安装:它只在工具调用期间占用维护锁,升级后下一次调用自动连上新的守护进程。 - 手机自动解锁或码率切换时,控制台里的手机原生画面只是暂停,不再断开重连。 +### 改进 + +- iOS 17–26 上控制台的画面改经守护进程取,viewer 不再自己连手机上 WebDriverAgent 的画面端口;除了 `wda-bridge`,现在只有守护进程和手机打交道。 + ## [0.2.14] - 2026-11-24 ### 新功能 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aa335257..8848505d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,6 +21,8 @@ cargo test --workspace --all-features --locked # Linux/macOS PTY regression; temporary settings only, no daemon or device actions python3 tests/terminal.py --binary target/debug/iphone-control --test-dir target/debug/deps cargo clippy --workspace --all-targets --all-features --locked -- -D warnings +# the control page's tests (Node 22, no packages): the page is apps/iphone-control/web/, put together by build.rs +node --test tests/viewer/*.test.mjs # vendor/ is upstream code and isn't formatted; check only this repository's packages: for p in ictl-l10n ictl-webinspector ictl-device ictl-wda ictl-sign ictl-unlock ictl-daemon ictl-mcp ictl-protocol iphone-control; do cargo fmt -p $p -- --check; done ``` diff --git a/DESIGN.md b/DESIGN.md index 0cd705d2..3c527857 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1,6 +1,6 @@ # Web 控制台设计规范 -桌面从左到右排列 AI 助手、设备画面、设备面板。窄窗口用抽屉或标签切换。接入新控件时沿用这套结构,优先把可用空间留给设备画面。[页面实现](apps/iphone-control/src/viewer.html) +桌面从左到右排列 AI 助手、设备画面、设备面板。窄窗口用抽屉或标签切换。接入新控件时沿用这套结构,优先把可用空间留给设备画面。[页面实现](apps/iphone-control/web/) ## 输入与排版 diff --git a/apps/iphone-control/build.rs b/apps/iphone-control/build.rs new file mode 100644 index 00000000..36801270 --- /dev/null +++ b/apps/iphone-control/build.rs @@ -0,0 +1,28 @@ +//! Puts the control page together: `web/index.html` with each `@include ` line replaced by that file (the +//! stylesheet, then the scripts in order), written to `$OUT_DIR/viewer.html`, which `viewer.rs` embeds. The scripts +//! share one scope, as they did in the single file, so the order in `index.html` is the order they run in. No other +//! tool is needed (tests/viewer/page.mjs does the same for the page tests). + +use std::path::Path; + +fn main() { + let web = Path::new("web"); + let index = web.join("index.html"); + println!("cargo:rerun-if-changed={}", index.display()); + let text = std::fs::read_to_string(&index).unwrap_or_else(|e| panic!("{}: {e}", index.display())); + let mut page = String::with_capacity(256 * 1024); + for line in text.split_inclusive('\n') { + let Some(rel) = line.strip_prefix("@include ") else { + page.push_str(line); + continue; + }; + let part = web.join(rel.trim()); + println!("cargo:rerun-if-changed={}", part.display()); + let body = std::fs::read_to_string(&part).unwrap_or_else(|e| panic!("{}: {e}", part.display())); + assert!(body.ends_with('\n'), "{} must end with a line break", part.display()); + assert!(!body.lines().any(|l| l.starts_with("@include ")), "{}: includes don't nest", part.display()); + page.push_str(&body); + } + let out = Path::new(&std::env::var_os("OUT_DIR").expect("OUT_DIR")).join("viewer.html"); + std::fs::write(&out, page).unwrap_or_else(|e| panic!("{}: {e}", out.display())); +} diff --git a/apps/iphone-control/src/video/mod.rs b/apps/iphone-control/src/video/mod.rs index 05d97c4f..d687c4ea 100644 --- a/apps/iphone-control/src/video/mod.rs +++ b/apps/iphone-control/src/video/mod.rs @@ -631,7 +631,7 @@ mod tests { (Instant::now(), phone) }); - // the page, over a real TCP connection, reporting what it read every 100 ms like viewer.html + // the page, over a real TCP connection, reporting what it read every 100 ms like the control page let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let mut page = tokio::net::TcpStream::connect(l.local_addr().unwrap()).await.unwrap(); let (server_side, _) = l.accept().await.unwrap(); diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.html deleted file mode 100644 index 855364ac..00000000 --- a/apps/iphone-control/src/viewer.html +++ /dev/null @@ -1,3689 +0,0 @@ - - - - - -iphone-control 控制台 - - - - -
- - -
-
- -
iphone-control控制台
-
-
- - - -
-
- - - - - -
-
-
-
- -
- -
-
-
-
-
-
- - - - -
- - -
-
-
-
-
-
- - - - - -
正在连接 iphone-control 服务…
-
-
-
-

-
-
-
- -
-
- - - - -
-
- - - - -
- -
-
-
-
正在连接…
-
-
-
- - - -
- - -

设置

-
-
-
-
-
-

画面流量减少约一半,帧率不变,适合外网或信号差时用;画面动起来时会略糊。手机自己的画面(HEVC)只有一路,开着时所有在看这台手机的页面都会一起降,切换时画面会断开半秒左右。

-
-
-
- -

清空全部操作记录?

-

只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。

-
- - -
-
- - -

停止这个任务?

-

AI 会立刻停下。已经在设备上做完的操作不会撤销。

-
- - -
-
- - - - diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs index cd84a884..649c30de 100644 --- a/apps/iphone-control/src/viewer.rs +++ b/apps/iphone-control/src/viewer.rs @@ -47,9 +47,8 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt}; use crate::agent::{self, Agents}; -const PAGE: &str = include_str!("viewer.html"); -/// WDA's MJPEG server on the phone -const MJPEG_PORT: u16 = 9100; +/// The control page, put together from `web/` by build.rs +const PAGE: &str = include_str!(concat!(env!("OUT_DIR"), "/viewer.html")); const MAX_BODY: usize = 16 * 1024; /// Most elements the Elements tab lists const ELEMENT_LIMIT: usize = 300; @@ -770,11 +769,13 @@ async fn picture(mut client: Conn, ctx: &Ctx, req: &Head) -> anyhow::Result<()> } else { None }; - // shared with the other pages on this phone: WDA captures a picture for each connection to its MJPEG port + // shared with the other pages on this phone: WDA captures a picture for each connection to its MJPEG port. The + // daemon opens it (the viewer doesn't reach for the phone itself, D2) and passes WDA's answer on as it comes let connect = || async { - let mut r = ictl_device::Device::find(Some(&udid)).await?.connect_port(MJPEG_PORT).await?; - r.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n").await?; - anyhow::Ok(r) + match protocol::open_mjpeg_stream(&ctx.socket, Some(&udid)).await? { + Ok(stream) => anyhow::Ok(stream), + Err(why) => anyhow::bail!(why), + } }; let remote = match tokio::time::timeout(crate::video::STREAM_IDLE, ctx.mjpeg.subscribe(&udid, connect)).await { Ok(Ok(r)) => r, @@ -2075,6 +2076,16 @@ mod tests { } } + /// build.rs put the page together whole: every include expanded, one stylesheet and one script, in order + #[test] + fn the_embedded_page_is_assembled() { + assert!(!PAGE.lines().any(|l| l.starts_with("@include "))); + assert!(PAGE.starts_with("") && PAGE.trim_end().ends_with("")); + assert_eq!((PAGE.matches(" + + +
+ + +
+
+ +
iphone-control控制台
+
+
+ + + +
+
+ + + + + +
+
+
+
+ +
+ +
+
+
+
+
+
+ + + + +
+ + +
+
+
+
+
+
+ + + + + +
正在连接 iphone-control 服务…
+
+
+
+

+
+
+
+ +
+
+ + + + +
+
+ + + + +
+ +
+
+
+
正在连接…
+
+
+
+ + + +
+ + +

设置

+
+
+
+
+
+

画面流量减少约一半,帧率不变,适合外网或信号差时用;画面动起来时会略糊。手机自己的画面(HEVC)只有一路,开着时所有在看这台手机的页面都会一起降,切换时画面会断开半秒左右。

+
+
+
+ +

清空全部操作记录?

+

只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。

+
+ + +
+
+ + +

停止这个任务?

+

AI 会立刻停下。已经在设备上做完的操作不会撤销。

+
+ + +
+
+ + + + diff --git a/apps/iphone-control/web/js/alert.js b/apps/iphone-control/web/js/alert.js new file mode 100644 index 00000000..5acb5df0 --- /dev/null +++ b/apps/iphone-control/web/js/alert.js @@ -0,0 +1,50 @@ +const SA = { busy: false, key: '', quietUntil: 0 }; +function alertQuiet() { SA.quietUntil = Date.now() + 3000; } +async function alertLoop() { + const t0 = performance.now(); + await pollAlert(); + const slow = performance.now() - t0 > 300; + setTimeout(alertLoop, S.sysAlert ? 1500 : slow ? 6000 : 2000); +} +async function pollAlert() { + if (SA.busy || Date.now() < SA.quietUntil) return; + if (S.mode !== 'live' || document.hidden || !V.device) { + if (S.sysAlert) { S.sysAlert = null; renderSysAlert(); } + return; + } + SA.busy = true; + // busy:手机正在执行操作,这次没查(让操作先走),保留上次的结果 + try { const v = await api('/api/alert'); if (!v.busy) S.sysAlert = v.alert || null; } catch { /* 下一轮再问 */ } finally { SA.busy = false; } + renderSysAlert(); +} +function renderSysAlert() { + const el = $('#sys-alert'), a = S.sysAlert, locked = guarded(); + const f = a && a.frame, d = f ? dims() : null; + const key = a ? JSON.stringify([a, locked, d]) : ''; + if (key === SA.key) return; + SA.key = key; + el.hidden = !a; + if (!a) { el.innerHTML = ''; return; } + // 真实弹窗的位置(点 → 画面的百分比),竖直方向对齐它的中心;画面尺寸还不知道时放在中间 + const pct = v => `${(v * 100).toFixed(2)}%`; + const pos = d ? `left:${pct(f.x / d.W)};width:${pct(f.width / d.W)};top:${pct((f.y + f.height / 2) / d.H)}` : 'left:18%;width:64%;top:50%'; + // 整行宽的是弹窗的操作按钮;窄的(「精确位置:打开」这类开关)做成小标签 + const wide = b => !f || !b.width || b.width >= f.width * 0.6; + const btn = (b, i, cls) => ``; + const chips = a.buttons.map((b, i) => wide(b) ? '' : btn(b, i, 'sa-chip')).join(''); + const acts = a.buttons.map((b, i) => wide(b) ? btn(b, i, 'sa-btn') : '').join(''); + const [title, ...rest] = String(a.text).split('\n'); + el.innerHTML = `
+

${esc(title)}

${rest.length ? `

${esc(rest.join('\n'))}

` : ''} + ${chips ? `
${chips}
` : ''}${acts ? `
${acts}
` : ''} +

${icon('alert')}${locked ? tr('AI 任务进行中:要自己点,先接管。') : tr('实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮')}

`; +} +async function tapSysAlert(i) { + const b = S.sysAlert && S.sysAlert.buttons[i]; + if (!b || !S.display || guarded()) return; + await act('/api/tap', { x: b.x, y: b.y, view: S.display.id }); + S.sysAlert = null; renderSysAlert(); + setTimeout(pollAlert, 800); +} +/* ---------- 任务的 App 范围:开任务时可以限定只在哪些 App 里操作(守护进程强制,见 docs/task-control.md 5.5)。 + * 选择在本次页面里一直保留,按钮上始终显示;刷新后不保留,免得忘了而让任务被悄悄限制。演示模式里没有 ---------- */ diff --git a/apps/iphone-control/web/js/demo.js b/apps/iphone-control/web/js/demo.js new file mode 100644 index 00000000..60152198 --- /dev/null +++ b/apps/iphone-control/web/js/demo.js @@ -0,0 +1,183 @@ +const APPS = [ + { id: 'clock', name: tr('时钟'), bundle: 'com.apple.mobiletimer', glyph: tr('时'), bg: '#1c1c1e', fg: '#fff' }, + { id: 'calendar', name: tr('日历'), bundle: 'com.apple.mobilecal', glyph: String(new Date().getDate()), bg: '#fff', fg: '#ff3b30' }, + { id: 'photos', name: tr('照片'), bundle: 'com.apple.mobileslideshow', glyph: tr('照'), bg: '#fff', fg: '#ff9500' }, + { id: 'camera', name: tr('相机'), bundle: 'com.apple.camera', glyph: tr('摄'), bg: '#8e8e93', fg: '#1c1c1e' }, + { id: 'messages', name: tr('信息'), bundle: 'com.apple.MobileSMS', glyph: tr('信'), bg: '#34c759', fg: '#fff' }, + { id: 'notes', name: tr('备忘录'), bundle: 'com.apple.mobilenotes', glyph: tr('记'), bg: '#ffcc00', fg: '#1c1c1e' }, + { id: 'weather', name: tr('天气'), bundle: 'com.apple.weather', glyph: tr('晴'), bg: '#2f80ed', fg: '#fff' }, + { id: 'maps', name: tr('地图'), bundle: 'com.apple.Maps', glyph: tr('图'), bg: '#7cc576', fg: '#1c1c1e' }, + { id: 'settings', name: tr('设置'), bundle: 'com.apple.Preferences', glyph: tr('设'), bg: '#8e8e93', fg: '#fff' }, + { id: 'appstore', name: 'App Store', bundle: 'com.apple.AppStore', glyph: 'A', bg: '#0a84ff', fg: '#fff' }, + { id: 'health', name: tr('健康'), bundle: 'com.apple.Health', glyph: tr('康'), bg: '#fff', fg: '#ff2d55' }, + { id: 'wallet', name: tr('钱包'), bundle: 'com.apple.Passbook', glyph: tr('钱'), bg: '#1c1c1e', fg: '#fff' } +]; +const DOCK = [ + { id: 'phone', name: tr('电话'), bundle: 'com.apple.mobilephone', glyph: tr('话'), bg: '#34c759', fg: '#fff' }, + { id: 'safari', name: 'Safari', bundle: 'com.apple.mobilesafari', glyph: 'S', bg: '#fff', fg: '#0a84ff' }, + { id: 'mail', name: tr('邮件'), bundle: 'com.apple.mobilemail', glyph: tr('邮'), bg: '#2f80ed', fg: '#fff' }, + { id: 'music', name: tr('音乐'), bundle: 'com.apple.Music', glyph: tr('乐'), bg: '#fa2d48', fg: '#fff' } +]; +const ALL_APPS = [...APPS, ...DOCK]; +const appById = id => ALL_APPS.find(a => a.id === id); +const appByAny = s => ALL_APPS.find(a => a.name === s || a.bundle === s || a.id === s); +const CLOCK_TABS = [['world', tr('世界时钟')], ['alarm', tr('闹钟')], ['stopwatch', tr('秒表')], ['timer', tr('计时器')]]; +const ALARMS = [{ time: '07:00', note: tr('工作日'), on: true }, { time: '08:30', note: tr('周末'), on: false }]; +const SETTINGS = { + root: { title: tr('设置'), back: null, groups: [[[tr('无线局域网'), tr('已连接'), 'set:none'], [tr('蓝牙'), tr('打开'), 'set:none']], [[tr('通用'), '', 'set:general'], [tr('显示与亮度'), '', 'set:none'], [tr('电池'), '', 'set:none'], [tr('隐私与安全性'), '', 'set:none']]] }, + general: { title: tr('通用'), back: [tr('设置'), 'set:root'], groups: [[[tr('关于本机'), '', 'set:about'], [tr('软件更新'), '', 'set:none']], [[tr('日期与时间'), '', 'set:none'], [tr('键盘'), '', 'set:none']]] }, + about: { title: tr('关于本机'), back: [tr('通用'), 'set:general'], groups: [[[tr('名称'), 'iPhone', null], [tr('iOS 版本'), '18.1', null], [tr('型号名称'), 'iPhone 15 Pro', null], [tr('容量'), '256 GB', null]]] } +}; +const DEMO_DEVICES = [ + { udid: '00008130-001A2B3C4D5E001E', name: 'iPhone 15 Pro', model: 'iPhone16,1', model_name: 'iPhone 15 Pro', family: 'iphone', ios: '18.1', kind: 'iphone', w: 393, h: 852 }, + { udid: '00008112-000C1D2E3F4A5B6C', name: tr('iPad mini(第 6 代)'), model: 'iPad14,1', model_name: tr('iPad mini(第 6 代)'), family: 'ipad', ios: '18.1', kind: 'ipad', w: 1133, h: 744 } // iPad 默认横屏 +]; +let demoDev = DEMO_DEVICES[0]; +const DW = () => demoDev.w, DH = () => demoDev.h; +function osVersion(device) { + const family = device.family ?? (/^iPad[0-9]+,[0-9]+$/.test(device.model) ? 'ipad' : /^iPhone[0-9]+,[0-9]+$/.test(device.model) ? 'iphone' : 'unknown'); + const system = family === 'ipad' ? 'iPadOS' : family === 'iphone' ? 'iOS' : ''; + return device.ios ? [system, device.ios].filter(Boolean).join(' ') : ''; +} +function deviceOptionLabel(device) { + const model = device.model_name || device.model; + if (device.name && model && device.name !== model) return device.name + ' · ' + model; + return device.name || model || device.udid; +} + +const D = { + screen: 'home', clockTab: 'world', setPage: 'root', generic: '', genericSub: '', + sw: { running: false, start: 0, acc: 0, laps: [] }, + chats: { + [tr('妈妈')]: [{ me: false, text: tr('晚上回来吃饭吗?'), t: '18:12' }], + [tr('王磊')]: [{ me: false, text: tr('明天的评审改到上午十点了'), t: '17:40' }], + [tr('快递通知')]: [{ me: false, text: tr('您的包裹已到驿站,凭取件码取件'), t: tr('昨天') }] + }, + chatWho: tr('妈妈'), draft: '', focused: false +}; +const swElapsed = () => D.sw.acc + (D.sw.running ? performance.now() - D.sw.start : 0); +function screenName() { + switch (D.screen) { + case 'home': return tr('主屏幕'); + case 'lock': return tr('锁定屏幕'); + case 'clock': return `${tr('时钟')} · ${CLOCK_TABS.find(t => t[0] === D.clockTab)[1]}`; + case 'settings': return D.setPage === 'root' ? tr('设置') : `${tr('设置')} · ${SETTINGS[D.setPage].title}`; + case 'messages': return tr('信息'); + case 'chat': return `${tr('与「')}${D.chatWho}${tr('」的对话')}`; + default: return D.generic; + } +} +function foreground() { return { home: tr('主屏幕'), lock: tr('主屏幕'), clock: tr('时钟'), settings: tr('设置'), messages: tr('信息'), chat: tr('信息') }[D.screen] || D.generic; } + +function appTile(a, dock) { + return `
${esc(a.glyph)}
${dock ? '' : `
${esc(a.name)}
`}
`; +} +const tz = zone => new Date().toLocaleTimeString('zh-CN', { timeZone: zone, hour: '2-digit', minute: '2-digit', hour12: false }); +function clockBody() { + if (D.clockTab === 'stopwatch') { + const run = D.sw.running; + const laps = D.sw.laps.map((ms, i) => `
${tr('计次')} ${i + 1}${fmtSw(ms)}
`).reverse().join(''); + return `
${fmtSw(swElapsed())}
+
${run ? tr('计次') : tr('复位')}
${run ? tr('停止') : tr('启动')}
+
${laps}
`; + } + if (D.clockTab === 'world') { + const rows = [[tr('北京'), 'Asia/Shanghai', tr('今天')], [tr('伦敦'), 'Europe/London', tr('今天,−8 小时')], [tr('纽约'), 'America/New_York', tr('今天,−13 小时')]]; + return `
${tr('世界时钟')}
${rows.map(([c, z, sub]) => `
${sub}${c}
${tz(z)}
`).join('')}`; + } + if (D.clockTab === 'alarm') { + return `
${tr('闹钟')}
${ALARMS.map(a => `
${a.time}${tr('闹钟,')}${a.note}
`).join('')}`; + } + return `
${tr('计时器')}
05:00
+
${tr('取消')}
${tr('启动')}
`; +} +function screenHtml() { + switch (D.screen) { + case 'home': return `
${APPS.map(a => appTile(a)).join('')}
${DOCK.map(a => appTile(a, true)).join('')}
`; + case 'lock': { const d = new Date(); return `
${d.toLocaleDateString(LANG === 'en' ? 'en-US' : 'zh-CN', { month: 'long', day: 'numeric', weekday: 'long' })}
${hhmm(d)}
${tr('向上轻扫以打开')}
`; } + case 'clock': return `
${clockBody()}
${CLOCK_TABS.map(([k, l]) => `
${l}
`).join('')}
`; + case 'settings': { + const pg = SETTINGS[D.setPage]; + return `
${pg.back ? `
‹ ${pg.back[0]}
` : ''}
${pg.title}
${pg.groups.map(g => `
${g.map(([l, v, act]) => `
${l}${v}${act ? ' ›' : ''}
`).join('')}
`).join('')}
`; + } + case 'messages': return `
${tr('信息')}
${Object.entries(D.chats).map(([who, msgs]) => { const last = msgs[msgs.length - 1]; return `
${esc(who[0])}
${esc(who)}${esc(last.text)}
${esc(last.t)}
`; }).join('')}
`; + case 'chat': { + const msgs = D.chats[D.chatWho] || [], has = D.draft.length > 0; + return `
‹ ${tr('信息')}
${esc(D.chatWho[0])}
${esc(D.chatWho)}
+
${msgs.map(m => `
${esc(m.text)}
`).join('')}
+
${has ? esc(D.draft) : tr('iMessage 信息')}
${tr('发送')}
+ ${D.focused ? tr('
键盘
') : ''}
`; + } + default: return `
${esc(D.generic)}

${esc(D.genericSub || tr('演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。'))}

`; + } +} +function renderDemo() { + const tone = ['messages', 'chat', 'generic'].includes(D.screen) ? ' ph--light' : D.screen === 'settings' ? ' ph--gray' : D.screen === 'clock' ? ' ph--black' : ''; + demoEl.className = 'ph' + tone + (demoDev.kind === 'ipad' ? ' ph--ipad' : ''); + demoEl.innerHTML = `
${hhmm()}5G
${screenHtml()}
`; + if (S.mode === 'demo') { + if (S.dstatus) { S.dstatus.foreground = foreground(); S.dstatus.locked = D.screen === 'lock'; } + S.elements = []; S.elState = 'stale'; renderChips(); if (S.devTab === 'status') renderStatusPanel(); if (S.devTab === 'elements') renderElements(); } +} +function demoOpen(screen) { D.screen = screen; if (screen !== 'chat') D.focused = false; renderDemo(); } +function demoLaunch(a) { + if (a.id === 'clock') { demoOpen('clock'); } + else if (a.id === 'settings') { D.setPage = 'root'; demoOpen('settings'); } + else if (a.id === 'messages') { demoOpen('messages'); } + else { D.generic = a.name; D.genericSub = ''; demoOpen('generic'); } + return `${tr('打开了「')}${a.name}${tr('」')}`; +} +function demoAct(act) { + const i = act.indexOf(':'), k = act.slice(0, i), v = act.slice(i + 1); + switch (k) { + case 'app': return demoLaunch(appById(v)); + case 'tab': D.clockTab = v; renderDemo(); return `${tr('切到「')}${CLOCK_TABS.find(t => t[0] === v)[1]}${tr('」')}`; + case 'set': if (v === 'none') return tr('演示模式没有模拟这一页'); D.setPage = v; renderDemo(); return `${tr('进入「')}${SETTINGS[v].title}${tr('」')}`; + case 'sw': + if (v === 'toggle') { + if (D.sw.running) { D.sw.acc = swElapsed(); D.sw.running = false; renderDemo(); return tr('秒表已停止'); } + D.sw.start = performance.now(); D.sw.running = true; renderDemo(); return tr('秒表开始计时'); + } + if (v === 'lap') { D.sw.laps.push(swElapsed()); renderDemo(); return `${tr('记了第')} ${D.sw.laps.length} ${tr('次计次')}`; } + D.sw = { running: false, start: 0, acc: 0, laps: [] }; renderDemo(); return tr('秒表已复位'); + case 'open-chat': D.chatWho = v; D.draft = ''; D.focused = false; demoOpen('chat'); return `${tr('打开了与「')}${v}${tr('」的对话')}`; + case 'chat': + if (v === 'back') { demoOpen('messages'); return tr('回到「信息」列表'); } + if (v === 'focus') { D.focused = true; renderDemo(); return tr('输入框获得焦点,弹出了键盘'); } + return demoSend(); + case 'timer': return tr('演示模式没有模拟计时器'); + } + return tr('这里没有可点的东西'); +} +function demoSend() { + if (!D.draft) return tr('输入框是空的,没有发出任何内容'); + (D.chats[D.chatWho] ||= []).push({ me: true, text: D.draft, t: hhmm() }); + const sent = D.draft; D.draft = ''; renderDemo(); + return `${tr('已发送给「')}${D.chatWho}${tr('」:')}${sent}`; +} +function demoType(text, submit) { + if (!(D.screen === 'chat' && D.focused)) return { ok: false, message: tr('没有弹出键盘:先在画面里点一下输入框。') }; + D.draft += text; renderDemo(); + return submit ? { ok: true, message: demoSend() } : { ok: true, message: `${tr('已输入「')}${text}${tr('」')}` }; +} +function demoKey(key) { + if (key === 'home') { const wasLocked = D.screen === 'lock'; demoOpen('home'); return wasLocked ? tr('已自动解锁,回到主屏幕') : tr('回到主屏幕'); } + if (key === 'lock') { demoOpen('lock'); return tr('已锁屏'); } + return key === 'volume_up' ? tr('音量加(演示画面没有变化)') : tr('音量减(演示画面没有变化)'); +} +setInterval(() => { + if (S.mode === 'demo' && D.screen === 'clock' && D.clockTab === 'stopwatch' && D.sw.running) { + const el = $('.sw-time', demoEl); if (el) el.textContent = fmtSw(swElapsed()); + } +}, 50); +function demoElements() { + const R = demoEl.getBoundingClientRect(), k = R.width / DW() || 0; + return $$('[data-label]', demoEl).map(e => { + const r = e.getBoundingClientRect(); + return { type: e.dataset.type || 'StaticText', label: e.dataset.label, x: k ? round1((r.left - R.left) / k) : 0, y: k ? round1((r.top - R.top) / k) : 0, width: k ? round1(r.width / k) : 0, height: k ? round1(r.height / k) : 0 }; + }); +} + +/* ================================================================ + * 画面几何 + * ================================================================ */ diff --git a/apps/iphone-control/web/js/device.js b/apps/iphone-control/web/js/device.js new file mode 100644 index 00000000..eda41525 --- /dev/null +++ b/apps/iphone-control/web/js/device.js @@ -0,0 +1,295 @@ +const CHECKS = [ + { name: tr('USB 连接'), fail: ['Absent'], hint: tr('用 USB 连上设备,确认数据线能传数据。') }, + { name: tr('信任这台电脑'), fail: ['NeedsTrust'], hint: tr('运行 iphone-control setup --reconfigure 选「手机」,在设备上点「信任」。') }, + { name: tr('开发者模式'), fail: ['DeveloperModeOff'], hint: tr('在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。') }, + { name: tr('WDA 已签名安装'), fail: ['NeedsSigning'], hint: tr('运行 iphone-control sign,用免费 Apple ID 签名并安装。'), action: 'sign' }, + { name: tr('WDA 运行中'), fail: ['WdaStarting', 'NeedsUnlock', 'NeedsAutomationPin'], hint: '' } +]; +/* 原生控制(iOS 27 起不用 WDA):不签名、不启动 WDA,只挂开发者镜像、连无障碍服务 */ +const NATIVE_CHECKS = [...CHECKS.slice(0, 3), + { name: tr('开发者镜像、无障碍服务'), fail: ['Preparing', 'NeedsUnlock'], hint: '' } +]; +const STARTING_NO_HID = tr('正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。'); +const STARTING_HINT = { + WdaStarting: tr('正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。'), + NeedsUnlock: tr('设备重启后还没解锁过,需要在设备上手动解锁一次。'), + NeedsAutomationPin: tr('设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。'), + Preparing: tr('正在挂开发者镜像、连接无障碍服务,通常几秒到半分钟。') +}; +let statusTimerId = 0, statusSequence = 0; +function refreshStatusSoon() { clearTimeout(statusTimerId); statusTimerId = setTimeout(loadDeviceState, 600); } +async function loadDeviceState() { + if (S.mode === 'demo') { + S.daemon = { state: 'Ready', device: demoDev, auto_unlock: true }; + S.dstatus = { wda_ready: true, locked: D.screen === 'lock', foreground: foreground(), width: DW(), height: DH(), route: 'wda' }; + 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')]); + // 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; + // busy: the phone was busy with one of the user's actions, so the check gave way; what was shown stays, asked again soon + if (s.status === 'fulfilled' && s.value.busy) refreshStatusSoon(); + else S.dstatus = s.status === 'fulfilled' ? s.value : null; + S.statusErr = d.status === 'rejected' ? String(d.reason.message) : s.status === 'rejected' ? String(s.reason.message) : ''; + if (l.status === 'fulfilled') { S.devices = l.value.devices || []; S.devicesFixed = !!l.value.fixed; S.devicesErr = ''; } else { S.devices = []; S.devicesErr = String(l.reason.message); } + } + $('#pane-dev').dataset.noDevice = String(S.mode === 'live' && !S.udid); + renderDevices(); renderChips(); renderFeed(); if (S.devTab === 'status') renderStatusPanel(); +} +/* 新设备上还没装 WDA:用已登录的 Apple ID 签名并安装,大约 1–2 分钟 */ +async function signWda() { + if (S.signing) return; + S.signing = true; renderFeed(); if (S.devTab === 'status') renderStatusPanel(); + show(tr('正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…')); + try { await act('/api/sign', {}); } finally { S.signing = false; await loadDeviceState(); } +} +function renderDevices() { + if (S.mode === 'detecting') return; + if (!S.devices.length) { + deviceEl.innerHTML = ``; deviceEl.disabled = true; + deviceEl.title = S.devicesErr || ''; pickerSync.device(); return; + } + const cur = S.devices.find(d => d.controlled); + const labels = S.devices.map(deviceOptionLabel); + deviceEl.innerHTML = S.devices.map((d, index) => { + const name = labels[index]; + const duplicate = labels.indexOf(name) !== labels.lastIndexOf(name); + const label = duplicate ? name + ' · ' + d.udid : name; + return ``; + }).join('') + + ``; + deviceEl.disabled = guarded() || S.switching || S.devicesFixed; + deviceEl.title = [deviceEl.selectedOptions[0]?.textContent, S.devicesFixed && tr('已用 IPHONE_UDID 固定设备,不能切换')].filter(Boolean).join(' · '); + pickerSync.device(); +} +deviceEl.addEventListener('change', () => selectDevice(deviceEl.value)); +$('#nav-devices').addEventListener('click', ev => { + const row = ev.target.closest('button[data-device]'); + if (row && !row.disabled && row.getAttribute('aria-current') !== 'true') selectDevice(row.dataset.device); +}); +async function selectDevice(v) { + if (guarded() || S.switching || S.devicesFixed) return; + if (S.mode === 'demo') { + const next = v === 'auto' ? demoDev : DEMO_DEVICES.find(d => d.udid === v); + if (!next || next === demoDev) { show(v === 'auto' ? `${tr('已改为自动选择:继续控制')} ${demoDev.name}` : tr('已经在控制这台设备')); return; } + demoDev = next; D.screen = 'home'; D.focused = false; + applyDemoGeometry(); renderDemo(); await loadDeviceState(); + S.appsState = 'idle'; if (S.devTab === 'apps') loadApps(); + show(`${tr('已切换到')} ${next.name}${tr('(演示)')}`); + return; + } + cancelGestures(); S.switching = true; deviceEl.disabled = true; pickerSync.device(); + try { + const r = await act('/api/select', { device: v }, true); + // /api/info 确认当前设备后才重新启用输入 + if (r.ok) { const u = S.udid; await loadInfo(); if (S.udid === u) show(r.message || tr('已经在控制这台设备')); } + } finally { S.switching = false; renderFeed(); renderElements(); await loadDeviceState(); } +} +function renderChips() { + const c = $('#chips'), d = S.daemon, s = S.dstatus; + if (S.mode === 'detecting') { c.innerHTML = ''; return; } + const chips = []; + if (frame.hasAttribute('data-absent')) { c.replaceChildren(); return; } + const ready = d?.state === 'Ready'; + chips.push(`${ready ? tr('就绪') : d ? tr('未就绪') : S.stream === 'error' ? tr('画面断开') : tr('连接中')}`); + // 不知道锁没锁(WDA 没起来、又没有 HID)时不显示 + if (s && s.locked != null) { + chips.push(`${tr('屏幕')}${s.locked ? tr('已锁定') : tr('未锁定')}`); + } + // first: the most important to see, and the row may be cut off on the right + if (S.readOnly) chips.unshift(`${tr('只读')}`); + c.innerHTML = chips.join(''); +} +// Keep the native disclosures and focused device buttons intact between status polls. +function navigatorHTML(id, html) { + const node = $(id); + if (node.navMarkup !== html) { node.innerHTML = html; node.navMarkup = html; } +} +function renderStatusPanel() { + const d = S.daemon, s = S.dstatus, dev = d?.device; + const list = S.devices.length ? S.devices : dev?.udid ? [dev] : []; + const selected = dev?.udid || S.udid; + const entries = list.map(item => { + const active = !!item.controlled || item.udid === selected; + const title = item.name || item.model_name || item.model || item.udid; + const model = item.model_name || item.model; + const duplicate = list.some(other => other.udid !== item.udid && deviceOptionLabel(other) === deviceOptionLabel(item)); + const sub = [model && model !== title && model, osVersion(item), duplicate && item.udid].filter(Boolean).join(' · '); + return `
  • `; + }); + const empty = S.mode === 'detecting' ? tr('正在查找…') : S.devicesErr ? tr('不可用') : tr('没有设备'); + navigatorHTML('#nav-devices', entries.join('') || ``); + + const screen = dims(); + const fact = ([k, v], mono = false) => `
    ${esc(k)}
    ${esc(v)}
    `; + const facts = [ + [tr('前台 App'), s?.foreground], [tr('屏幕'), s?.locked != null && (s.locked ? tr('已锁定') : tr('未锁定'))], + [tr('操作通道'), s?.route === 'wda' ? 'WDA' : s?.route === 'hid' ? tr('HID 后备') : s?.route === 'native' ? tr('原生') : null], + [tr('屏幕尺寸'), screen && `${screen.W} × ${screen.H} pt`], [tr('自动解锁'), d && (d.auto_unlock ? tr('已设置密码') : tr('未设置'))] + ].filter(([,v]) => v); + $('#nav-facts').hidden = !selected || !facts.length; + navigatorHTML('#nav-facts', facts.map(row => fact(row)).join('')); + const ids = [['ProductType', dev?.model], ['UDID', selected]].filter(([,v]) => v); + $('#device-identifiers').hidden = !ids.length; + navigatorHTML('#nav-ids', ids.map(row => fact(row, true)).join('')); + + const error = S.statusErr || S.devicesErr; + const allChecks = d?.state === 'Preparing' || s?.route === 'native' ? NATIVE_CHECKS : CHECKS; + const failAt = allChecks.findIndex(check => check.fail.includes(d?.state)); + const checks = d?.state === 'Ready' ? allChecks : allChecks.slice(0, failAt + 1); + const rows = checks.map((c,i) => { + const issue = i === failAt; + const busy = issue && (d.state === 'WdaStarting' || d.state === 'Preparing'); + const hint = issue && (c.hint || (busy && s?.route === 'none' ? STARTING_NO_HID : STARTING_HINT[d.state])); + const label = issue ? (busy ? tr('进行中') : tr('需要处理')) : tr('已完成'); + const sign = issue && c.action === 'sign' && d.signed_in; + return `
  • ${icon(issue ? (busy ? 'loader' : 'info') : 'check', issue ? (busy ? 'spin' : '') : 'check-ok')} +
    ${c.name}${tr(':')}${label} + ${hint ? `${hint}` : ''} + ${sign ? `` : ''} + ${issue && d.last_error ? `${esc(d.last_error)}` : ''}
  • `; + }); + navigatorHTML('#nav-checks', (rows.length ? `` : '') + + (error || !d ? `

    ${esc(error || tr('还没有拿到守护进程状态。'))}

    ` : '')); +} + +/* ================================================================ + * 应用 + * ================================================================ */ +async function loadApps() { + S.appsState = 'loading'; renderApps(); + const sys = $('#app-sys').checked, target = S.udid; + try { + if (S.mode === 'demo') { await sleep(350); S.apps = sys ? ALL_APPS.map(a => ({ name: a.name, bundle_id: a.bundle })) : []; } + else { + const result = await api(`/api/apps?system=${sys ? 1 : 0}`); + if (target !== S.udid || sys !== $('#app-sys').checked) return; + S.apps = result.apps || []; + } + S.appsState = 'ok'; + } catch (e) { if (target !== S.udid || sys !== $('#app-sys').checked) return; S.appsState = 'error'; S.appsErr = String(e.message || e); } + renderApps(); +} +function renderApps() { + const ul = $('#apps'), q = $('#app-q').value.trim().toLowerCase(), lock = guarded(); + const list = S.apps.filter(a => !q || a.name.toLowerCase().includes(q) || a.bundle_id.toLowerCase().includes(q)); + $('#apps-count').textContent = S.appsState === 'ok' ? `${list.length} ${tr('个')}${S.mode === 'demo' ? tr(' · 演示数据') : ''}` : ''; + if (S.appsState === 'loading') { ul.innerHTML = tr('
  • 正在读取 App 列表…
  • ') + ''.repeat(6); return; } + if (S.appsState === 'error') { ul.innerHTML = `
  • ${esc(S.appsErr)}
  • `; return; } + if (S.appsState !== 'ok') { ul.innerHTML = tr('
  • 打开这一页时会读取已安装的 App。
  • '); return; } + if (!list.length) { ul.innerHTML = `
  • ${q ? `${tr('没有名称或 bundle id 含「')}${esc(q)}${tr('」的 App。')}` : $('#app-sys').checked ? tr('没有读到 App。') : tr('没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。')}
  • `; return; } + ul.innerHTML = list.map(a => { + const meta = appByAny(a.bundle_id); + const tile = meta ? `style="background:${meta.bg};color:${meta.fg}"` : 'style="background:var(--sunken);color:var(--text-2)"'; + return `
  • + ${esc(a.name)}${esc(a.bundle_id)} + +
  • `; + }).join(''); +} +$('#app-q').addEventListener('input', renderApps); +$('#app-sys').addEventListener('change', loadApps); +async function launchApp(bundle, name) { + if (guarded()) { nudgeGuard(); return; } + if (S.mode === 'live') return act('/api/launch_app', { app: bundle }); + show(demoLaunch(appByAny(bundle) || { id: bundle, name })); +} +async function terminateApp(bundle, name) { + if (guarded()) { nudgeGuard(); return; } + if (S.mode === 'live') return act('/api/terminate_app', { app: bundle }); + if (foreground() === name) demoOpen('home'); + show(`${tr('已结束「')}${name}${tr('」')}`); +} +async function openUrl() { + if (guarded()) { nudgeGuard(); return; } + const inp = $('#url'), url = inp.value.trim(); + if (!url) { show(tr('先填要打开的链接'), 'err'); inp.focus(); return; } + if (S.mode === 'live') { if ((await act('/api/open_url', { url })).ok) inp.value = ''; return; } + if (/^https?:\/\//i.test(url)) { D.generic = 'Safari'; D.genericSub = `${tr('正在打开')} ${url}${tr('(演示画面不加载网页)')}`; demoOpen('generic'); show(`${tr('已用 Safari 打开')} ${url}`); inp.value = ''; } + else show(tr('演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试'), 'err'); +} +$('#url').addEventListener('keydown', ev => { if (ev.key === 'Enter' && !ev.isComposing) { ev.preventDefault(); openUrl(); } }); + +/* ================================================================ + * 元素 + * ================================================================ */ +async function loadElements() { + const epoch = feedEpoch; + S.elState = 'loading'; renderElements(); + try { + if (S.mode === 'demo') { await sleep(300); S.elements = demoElements(); } + else { + const result = await api('/api/elements?filter='); + if (epoch !== feedEpoch) return; + S.elements = result.elements || []; + } + S.elState = 'ok'; + } catch (e) { if (epoch !== feedEpoch) return; S.elState = 'error'; S.elErr = String(e.message || e); } + renderElements(); +} +function renderElements() { + const ul = $('#elements'), q = $('#el-q').value.trim().toLowerCase(), lock = guarded() || (S.mode === 'live' && (!S.udid || S.switching)); + const list = S.elements.map((e, i) => ({ ...e, i })).filter(e => !q || e.label.toLowerCase().includes(q) || e.type.toLowerCase().includes(q)); + $('#el-count').textContent = S.elState === 'ok' ? `${list.length} ${tr('个')}${S.mode === 'demo' ? tr(' · 演示数据') : ''}` : ''; + if (S.elState === 'loading') { ul.innerHTML = tr('
  • 正在读取元素…
  • ') + ''.repeat(6); return; } + if (S.elState === 'error') { ul.innerHTML = `
  • ${esc(S.elErr)}
  • `; return; } + if (S.elState === 'stale' || S.elState === 'idle') { ul.innerHTML = `
  • ${S.elState === 'stale' ? tr('界面变了,') : ''}${tr('点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。')}
  • `; return; } + if (!list.length) { ul.innerHTML = `
  • ${q ? `${tr('没有含「')}${esc(q)}${tr('」的元素。')}` : tr('当前界面没有带文字的元素。')}
  • `; return; } + ul.innerHTML = list.map(e => `
  • + ${esc(e.label)}${esc(e.type)} · ${Math.round(e.x + e.width / 2)}, ${Math.round(e.y + e.height / 2)} +
  • `).join(''); +} +$('#el-q').addEventListener('input', renderElements); +const elList = $('#elements'); +elList.addEventListener('pointerover', ev => { const row = ev.target.closest('[data-el]'); if (row) highlight(S.elements[+row.dataset.el]); }); +elList.addEventListener('pointerleave', () => highlight(null)); +elList.addEventListener('focusin', ev => { const row = ev.target.closest('[data-el]'); if (row) highlight(S.elements[+row.dataset.el]); }); +elList.addEventListener('focusout', () => highlight(null)); +async function tapElement(i) { + if (guarded()) { nudgeGuard(); return; } + const e = S.elements[i]; if (!e) return; + const same = S.elements.slice(0, i).filter(x => x.label === e.label).length; + highlight(null); + if (dims()) drawMark('tap', 'user', { x: round1(e.x + e.width / 2), y: round1(e.y + e.height / 2) }); + if (S.mode === 'live') await act('/api/tap_element', { text: e.label, index: same }); + else { + const el = $$('[data-label]', demoEl).filter(x => x.dataset.label === e.label)[same]; + show(`${tr('按名字点「')}${e.label}${tr('」:')}${el && el.dataset.act ? demoAct(el.dataset.act) : tr('它不是可点的控件,界面没有变化')}`); + } + S.elState = 'stale'; renderElements(); +} +async function waitFor() { + const inp = $('#wait-q'), text = inp.value.trim(), out = $('#wait-result'), btn = $('#wait-btn'); + if (!text) { inp.focus(); out.hidden = false; out.className = 'wait-result t-danger'; out.textContent = tr('先填要等的文字。'); return; } + btn.disabled = true; btn.textContent = tr('等待中…'); out.hidden = false; out.className = 'wait-result t-muted'; out.textContent = `${tr('等「')}${text}${tr('」出现,最多 5 秒')}…`; + let ok = false, msg = ''; + try { + if (S.mode === 'live') { const v = await api('/api/wait_for', { text, timeout: 5 }); ok = !!v.ok; msg = v.message || ''; } + else { + const t0 = Date.now(); + while (Date.now() - t0 < 5000) { if (demoElements().some(e => e.label.includes(text) && e.type !== 'TextField')) { ok = true; break; } await sleep(200); } + msg = ok ? `${tr('「')}${text}${tr('」已经出现(')}${((Date.now() - t0) / 1000).toFixed(1)} ${tr('秒)')}` : `5 ${tr('秒内没有出现「')}${text}${tr('」')}`; + } + } catch (e) { msg = String(e.message || e); } + out.className = `wait-result ${ok ? 't-ok' : 't-danger'}`; out.textContent = msg; + btn.disabled = false; btn.textContent = tr('等待 5 秒'); +} +$('#wait-q').addEventListener('keydown', ev => { if (ev.key === 'Enter' && !ev.isComposing) { ev.preventDefault(); waitFor(); } }); + +function setDevTab(tab) { + S.devTab = tab; + ['status', 'apps', 'elements'].forEach(t => { + $(`#tab-${t}`).setAttribute('aria-selected', String(t === tab)); + $(`#tp-${t}`).hidden = t !== tab; + }); + if (tab === 'status') renderStatusPanel(); + if (tab === 'apps' && S.appsState === 'idle' && (S.mode === 'demo' || S.udid)) loadApps(); else if (tab === 'apps') renderApps(); + if (tab === 'elements') renderElements(); +} + +/* ================================================================ + * AI 任务:演示脚本 + * ================================================================ */ diff --git a/apps/iphone-control/web/js/i18n.js b/apps/iphone-control/web/js/i18n.js new file mode 100644 index 00000000..0f0294d3 --- /dev/null +++ b/apps/iphone-control/web/js/i18n.js @@ -0,0 +1,99 @@ +'use strict'; + +/* ================================================================ + * 语言:页面的文字中英两套。默认跟着 viewer(IPHONE_CONTROL_LANG,服务端写在 ),页面上切换后记在浏览器里。 + * 每个请求带上 X-Ictl-Lang,守护进程的回复和 AI 任务也用这种语言 + * ================================================================ */ +const LANG = (() => { + let v = null; + try { v = localStorage.getItem('ictl.lang'); } catch { /* 预览环境可能禁用存储 */ } + return v === 'en' || v === 'zh' ? v : document.documentElement.dataset.lang === 'en' ? 'en' : 'zh'; +})(); +document.documentElement.lang = LANG === 'en' ? 'en' : 'zh-CN'; +const EN = {"登录已过期":"Login expired","只读登录":"Read-only login",":能看画面、设备状态和任务,不能操作手机,也不能开始、暂停或确认任务。":": you can watch the picture, the device's state and tasks, but not act on the phone or start, pause or confirm tasks.","只读":"Read-only","只读登录:只能看,不能操作":"Read-only login: you can watch, not act","任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","
    键盘
    ":"
    Keyboard
    ","
  • 打开这一页时会读取已安装的 App。
  • ":"
  • The installed apps are read when this tab opens.
  • ","
  • 正在读取 App 列表…
  • ":"
  • Reading the app list…
  • ","
  • 正在读取元素…
  • ":"
  • Reading elements…
  • ","":"","

    正在连接 iphone-control 服务…

    ":"

    Connecting to the iphone-control service…

    ","演示模式":"Demo","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","原生":"Native","正在准备设备(挂载开发者镜像、连接无障碍服务)…":"Preparing the device (mounting the developer disk image, connecting to the accessibility service)…",":准备设备失败,会自动重试":": preparing the device failed, retrying automatically","开发者镜像、无障碍服务":"Developer disk image, accessibility service","正在挂开发者镜像、连接无障碍服务,通常几秒到半分钟。":"Mounting the developer disk image and connecting to the accessibility service, usually a few seconds to half a minute.","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 iphone-control sign,用免费 Apple ID 签名并安装。":"Run iphone-control sign to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 iphone-control setup --reconfigure 选「手机」,在设备上点「信任」。":"Run iphone-control setup --reconfigure, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress","弱网模式":"Low-bandwidth mode","画面流量减少约一半,帧率不变,适合外网或信号差时用;画面动起来时会略糊。手机自己的画面(HEVC)只有一路,开着时所有在看这台手机的页面都会一起降,切换时画面会断开半秒左右。":"About half the picture's traffic at the same frame rate, for use over the internet or a weak signal; moving content gets a little blurry. The phone's own picture (HEVC) is one stream, so while this is on every page watching this phone gets it too, and switching interrupts the picture for about half a second.","已开启弱网模式,正在重新连接画面…":"Low-bandwidth mode on, reconnecting the picture…","已关闭弱网模式,正在重新连接画面…":"Low-bandwidth mode off, reconnecting the picture…"}; +Object.assign(EN, { + '未连接设备':'No device connected', '用数据线连接 iPhone 或 iPad。':'Connect an iPhone or iPad with a USB cable.', '等待设备连接':'Waiting for a device', + '外观':'Appearance', '界面字号':'Text size', '标准':'Standard', '大':'Large', '特大':'Extra large', + '暂无任务':'No tasks yet', '执行步骤和确认请求会显示在这里。':'Steps and approval requests appear here.', + '可以先写下任务,连接设备后再执行。':'Draft a task while waiting for a device.', + '任务将在模拟设备上运行。':'Tasks run on the simulated device.', '开始任务(Enter)':'Start task (Enter)', + '明暗':'Theme', '跟随系统':'System', '浅色':'Light', '深色':'Dark', '完成':'Done' +}); +Object.assign(EN, { + '设备列表':'Devices', '设备标识':'Device identifiers', '连接检查':'Connection checks', + '连接设备后可查看应用。':'Connect a device to view its apps.', + '连接设备后可查看界面元素。':'Connect a device to inspect its interface.' +}); +Object.assign(EN, { + '设备画面':'Device view', '连接你的设备':'Connect your device', '连接帮助':'Connection help', + '用 USB 数据线连接 iPhone 或 iPad,并在设备上轻点「信任」。':'Connect your iPhone or iPad with a USB cable, then tap Trust on the device.', + '等待设备画面':'Waiting for the screen', '正在连接本地服务':'Connecting to the local service' +}); +Object.assign(EN, {'版本详情':'Details','复制升级命令':'Copy upgrade command','关闭版本信息':'Close version information','关于与更新':'About & updates','完成':'Done','检查更新':'Check for updates','检查中…':'Checking…','发行说明':'Release notes','升级命令':'Upgrade command','复制命令':'Copy command','已复制':'Copied','请选中命令并手动复制。':'Select the command and copy it manually.'}); +/* 中文原文 → 当前语言 */ +Object.assign(EN, { '画面已连接 · 等待屏幕尺寸和方向,仅可观看':'Picture connected · waiting for screen dimensions and orientation (view only)', '没有收到设备画面,3 秒后自动重试。':'No picture received. Retrying in 3 seconds.' }); +Object.assign(EN, { + '设置': 'Settings', '界面语言': 'Language', '没有可用的 AI': 'No AI available' +}); +function tr(zh) { return LANG === 'en' ? (EN[zh] ?? zh) : zh; } +/* 静态标记里的文字和提示(aria-label、title、placeholder、alt)开始时译一次 */ +(function translateStatic() { + if (LANG !== 'en') return; + document.title = tr(document.title); + const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); + for (let n = walk.nextNode(); n; n = walk.nextNode()) { + const s = n.nodeValue.trim(); + if (s && EN[s] !== undefined) n.nodeValue = n.nodeValue.replace(s, EN[s]); + } + document.querySelectorAll('[aria-label],[title],[placeholder],[alt]').forEach(el => { + for (const a of ['aria-label', 'title', 'placeholder', 'alt']) { const v = el.getAttribute(a); if (v && EN[v] !== undefined) el.setAttribute(a, EN[v]); } + }); +})(); +const language = document.getElementById('language-value'); +language.value = LANG; +language.addEventListener('change', () => { + try { + localStorage.setItem('ictl.lang', language.value); + sessionStorage.setItem('ictl.languageDraft', document.getElementById('prompt').value); + } catch { /* Storage can be unavailable in a local preview. */ } + location.reload(); +}); +/* ================================================================ + * 接口(apps/iphone-control/src/viewer.rs、agent.rs) + * + * 画面与手动操作,都经守护进程,和 MCP 工具一样排队、自动解锁、只作用于这个页面跟着的设备: + * GET /stream → WebDriverAgent 的 MJPEG 画面 + * GET /api/info → { width, height, udid, device, warning? } + * 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/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" + * GET /api/apps?system=1 → { apps: [{ name, bundle_id }] } + * GET /api/elements?filter= → { elements: [{ type, label, x, y, width, height }] } // x、y 是左上角,单位点 + * GET /api/alert → { alert: null | { text, frame?: { x, y, width, height }, buttons: [{ label, x, y, width }] } } // 系统弹窗,单位点:弹窗的框(左上角)、按钮中心和宽;画面是手机自己的视频时页面定时问(2~6 秒,见 alertLoop) + * state 取值:Absent | NeedsTrust | DeveloperModeOff | NeedsSigning | WdaStarting | NeedsUnlock | NeedsAutomationPin | Preparing | Ready + * + * AI 任务:交给本机的 Claude Code 或 Codex,它只能用 iphone-control 的 MCP 工具;每一步都经守护进程过一道闸, + * 所以暂停、接管、确认在那里生效,和用哪个 agent 无关: + * GET /api/agent/backends → { backends: [{ id, name, available }] } + * GET /api/agent/tasks → { tasks: [{ id, title, owner, udid, state, started, ended?, steps }] } + * 守护进程里的全部任务,含在别处开的(iphone-control task run);有正在进行的就接上它的事件 + * POST /api/agent/tasks { prompt, agent } → { id } + * GET /api/agent/tasks/{id}/events SSE:step | confirm | state | done(连上时先重放已有的事件) + * step { id, thought?, tool?, args?, status: running|ok|error|waiting|rejected|stopped, ms?, result?, screenshot?, gesture? } + * confirm { step, action, detail } + * state { state: running|paused|takeover|waiting } + * done { ok, stopped?, outcome, summary } outcome:completed|failed|cancelled|rejected|abandoned|interrupted + * POST /api/agent/tasks/{id}/pause | resume | takeover | handback | stop + * POST /api/agent/tasks/{id}/confirm { step, approve } + * 任务在守护进程里(docs/task-control.md):任务进行中(没有接管时)守护进程拒绝别人的操作,结果里说明原因。 + * + * 所有 POST 要求同源 Origin + JSON。打不开 /api/info 时(例如直接打开这个文件)进入演示模式,所有数据都在本地模拟。 + * ================================================================ */ + +const $ = (s, r = document) => r.querySelector(s); +const $$ = (s, r = document) => Array.from(r.querySelectorAll(s)); diff --git a/apps/iphone-control/web/js/info.js b/apps/iphone-control/web/js/info.js new file mode 100644 index 00000000..733a55ae --- /dev/null +++ b/apps/iphone-control/web/js/info.js @@ -0,0 +1,240 @@ +function applyInfo(v) { + const udid = v.udid || null; + S.login = v.login || null; S.readOnly = S.login?.role === 'view'; + document.documentElement.toggleAttribute('data-readonly', S.readOnly); + if (S.readOnly) $('#readonly-note').textContent = `${tr('只读登录')}(${S.login.name})${tr(':能看画面、设备状态和任务,不能操作手机,也不能开始、暂停或确认任务。')}`; + S.video = v.video || null; S.deviceVideo = !!v.device_video; + S.size = v.width > 0 && v.height > 0 ? { w: v.width, h: v.height } : null; + frame.toggleAttribute('data-absent', v.state === 'Absent' && !udid); + const changed = S.udid !== udid, display = v.display || null; + if (changed || S.display?.id !== display?.id) { + cancelGestures(); // queue a release for the original device and view + T.fails = 0; + S.rtt = null; S.elements = []; S.elState = 'idle'; + highlight(null); marks.replaceChildren(); hoverDot = null; + if (changed) { + S.daemon = null; S.dstatus = null; S.apps = []; S.appsState = 'idle'; appNames.map = null; appNames.loading = false; + T.warm = 0; V.noDevice = false; V.devRetries = 0; + } + } + const reconnect = feedId && (changed || S.display?.id !== display?.id); + S.udid = udid; S.display = display; + if (changed) { renderManual(); syncSend(); } + S.family = v.family || 'unknown'; frame.dataset.kind = S.family; S.deviceName = v.device || ''; + S.liveTouch = T.fails < 2 && !!v.live_touch; + if (reconnect) { + connect(); + loadDeviceState(); + if (changed && S.devTab === 'apps') loadApps(); + } else if (v.feed_open === false && S.stream === 'ok') { + feedError(); + } + if (v.warning && !S.infoWarning) show(v.warning, 'err'); + S.infoWarning = v.warning || ''; +} +function signButton(label) { + return ``; +} +/* 没有画面时,按守护进程的状态说清楚卡在哪、怎么办 */ +function stageNote() { + const d = S.daemon, name = d?.device?.name || S.deviceName || tr('设备'); + switch (d?.state || (frame.hasAttribute('data-absent') ? 'Absent' : null)) { + case 'Absent': return '' + tr('未连接设备') + '' + tr('用数据线连接 iPhone 或 iPad。'); + case 'NeedsTrust': case 'DeveloperModeOff': + return `${esc(name)} ${esc(tr('还没设置好(配对、开发者模式)。在终端运行'))} iphone-control setup --reconfigure${esc(tr(',选「手机」。'))}`; + case 'NeedsSigning': + return d.signed_in + ? `${esc(name)} ${esc(tr('上还没装 WebDriverAgent。'))}
    ${signButton(tr('签名并安装 WDA'))}` + : `${esc(name)} ${esc(tr('上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行'))} iphone-control setup --reconfigure${esc(tr(',选「Apple ID」。'))}`; + case 'WdaStarting': + // 启动失败过就把原因摆出来(守护进程会自动重试),不要一直说「通常 10–60 秒」 + // 启动失败常见的一种是签名证书变了(给另一台设备重签时换了证书),重签这台就好;登录了 Apple ID 就给个按钮 + if (d.last_error) return `${esc(name)}${esc(tr(':WebDriverAgent 启动失败,会自动重试'))}
    ${esc(d.last_error)}${d.signed_in ? `
    ${signButton(tr('重新签名并安装 WDA'))}` : ''}`; + return `${esc(tr('正在'))} ${esc(name)} ${esc(tr('上启动 WebDriverAgent,通常 10–60 秒…'))}`; + case 'Preparing': + // 原生控制(iOS 27 起不用 WDA):只要挂开发者镜像、连无障碍服务 + if (d.last_error) return `${esc(name)}${esc(tr(':准备设备失败,会自动重试'))}
    ${esc(d.last_error)}`; + return esc(tr('正在准备设备(挂载开发者镜像、连接无障碍服务)…')); + case 'NeedsUnlock': return esc(tr('设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。')); + case 'NeedsAutomationPin': return esc(tr('设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。')); + default: return esc(tr('没有收到设备画面,3 秒后自动重试。')); + } +} +function showStageNote() { + if (S.mode !== 'live' || S.stream !== 'error') return; + const html = stageNote(); if (stageMsg.dataset.note !== html) { stageMsg.innerHTML = html; stageMsg.dataset.note = html; } // 不变就不重画,免得按钮丢了焦点 + stageMsg.hidden = false; +} +// Opening the popover reads the host's cached report, even when no device is connected. +const updateDialog = $('#updates-dialog'), updateCheck = $('#update-check'); +const aboutUpdates = $('#about-updates'), updateCommand = $('#update-command'), copyStatus = $('#update-copy-status'); +let updatePoll, readingUpdates = false; +const updateText = (zh, en) => LANG === 'en' ? en : zh; +function newerRelease(r) { + return r.available_version && ['available', 'brew_check', 'platform_pending', 'manual_only', 'unsupported'].includes(r.availability); +} +function drawUpdateBadge(r) { + const newer = newerRelease(r); + $('#update-dot').hidden = !newer; + const label = tr('关于与更新') + (newer ? updateText(' · 新版本 ', ' · New release ') + r.available_version : ''); + aboutUpdates.title = label; + aboutUpdates.setAttribute('aria-label', label); +} +function setUpdateCommand(command) { + if (updateCommand.textContent !== command) { + copyStatus.textContent = ''; + updateCommand.textContent = command; + } + $('#update-command-block').hidden = $('#update-copy').hidden = !command; +} +// The first changelog item is an excerpt. The release page has the full notes. +function updateExcerpt(markdown) { + const line = markdown.split(/\r?\n/).map(s => s.trim()).find(s => s && !/^#|^---|^