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(cli): keep input echo off while setup menus redraw (#73)
MSK3a61933a686a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 851e804..aa9fec7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,7 @@ All notable changes to this project are documented here. The format is based on### Fixed+- Holding an arrow key in a setup menu keeps moving the selection without echoing key sequences into the menu.- AI task summaries on the control page are formatted: bold, lists, inline code and line breaks show as such instead of raw Markdown.- On iOS 27 and later, a system alert (a permission prompt such as "Allow Calendar to use your location?") that the live picture on the control page doesn't show is now drawn on the picture where it is, with its buttons; a button there taps it on the phone.- 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).diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex 632eace..e422831 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -28,6 +28,7 @@### 修复+- 在设置菜单中长按方向键时,选项会连续移动,按键序列不会回显到菜单里。- 控制台上 AI 任务的总结按格式显示:粗体、列表、行内代码和换行不再显示成 Markdown 原文。- iOS 27 及以上,控制台实时画面里看不到的系统弹窗(例如「允许“日历”使用你的位置?」这类权限请求)现在画在画面里它所在的位置,带着弹窗的按钮,点按钮就是点手机上的那个按钮。- 部分 iPhone(如 iPhone 15 Pro Max,iOS 27.0.1)上锁屏不再每次要 10 秒左右:经 IOHID 短按电源键在这些设备上不起作用,守护进程会按设备记住,之后先用 WDA 的锁屏(约 2 秒)。diff --git a/Cargo.toml b/Cargo.tomlindex 12aa23a..7159523 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -59,6 +59,8 @@ quick-xml = "=0.42.0"image = { version = "=0.25.10", default-features = false, features = ["png", "jpeg"] }clap = { version = "=4.6.7", features = ["derive", "env"] }clap_complete = "=4.6.11"+console = "=0.15.11"+termion = "=4.0.6"serde = { version = "=1.0.229", features = ["derive"] }serde_json = "=1.0.154"thiserror = "=2.0.21"diff --git a/apps/iphone-control/Cargo.toml b/apps/iphone-control/Cargo.tomlindex 1ca44b1..bf0fbdb 100644--- a/apps/iphone-control/Cargo.toml+++ b/apps/iphone-control/Cargo.toml@@ -18,8 +18,8 @@ ictl-sign.workspace = trueictl-wda = { workspace = true, optional = true }clap = { workspace = true, features = ["string"] }clap_complete.workspace = true-console = "=0.15.11"-termion = "=4.0.6"+console.workspace = true+termion.workspace = truetokio.workspace = trueanyhow.workspace = truerustls.workspace = truediff --git a/apps/iphone-control/src/completions.rs b/apps/iphone-control/src/completions.rsindex a8ceae7..51fb153 100644--- a/apps/iphone-control/src/completions.rs+++ b/apps/iphone-control/src/completions.rs@@ -41,6 +41,9 @@ pub fn write(shell: Shell, output: &mut dyn Write) -> anyhow::Result<()> {let mut command = public_command(&super::Cli::command());command.build();let mut script = Vec::new();+ // clap_complete 4.6.11 builds inconsistent Bash subcommand names for a+ // hyphenated binary. Its Fish nested-command checks also match option+ // values (e.g. the directory in `--data-dir check update`).match shell {Shell::Zsh => clap_complete::generate(clap_complete::Shell::Zsh, &mut command, "iphone-control", &mut script),Shell::Bash => bash::generate(&command, &mut script)?,diff --git a/apps/iphone-control/src/guide/terminal.rs b/apps/iphone-control/src/guide/terminal.rsindex d836deb..f0e0fc8 100644--- a/apps/iphone-control/src/guide/terminal.rs+++ b/apps/iphone-control/src/guide/terminal.rs@@ -1,6 +1,6 @@//! Small, local menus for the guide. Text and secret input stay with the CLI.//!-//! termion decodes complete key sequences and restores termios after each read.+//! termion decodes complete key sequences and restores termios when the menu exits.//! We never hide the cursor or enter an alternate screen.use std::fmt;use std::io::{self, IsTerminal, Read};@@ -54,7 +54,7 @@ impl MenuSignals {impl Drop for MenuSignals {fn drop(&mut self) {- // Restore before re-delivering, after read_key's raw terminal guard has dropped.+ // Restore before re-delivering, after the menu's raw terminal guard has dropped.unsafe {for (signal, previous) in self.0.iter().rev() {libc::sigaction(*signal, previous, std::ptr::null_mut());@@ -164,15 +164,11 @@ fn decode(bytes: &[u8]) -> Key {/// terminal is simply idle, so the caller can skip repainting an unchanged/// frame. A byte that arrives but forms an unknown/partial sequence still/// returns `Some(Key::Unknown)`, as does every later timeout.-fn read_key(utf8: &mut Vec<u8>, queued: &mut Option<u8>) -> io::Result<Option<Key>> {- // The input and output may be separate terminals. Read keys in raw mode- // on stdin and restore it before rendering the next frame.- let input = std::fs::File::from(std::io::stdin().as_fd().try_clone_to_owned()?);- let mut input = input.into_raw_mode()?;+fn read_key(input: &mut std::fs::File, utf8: &mut Vec<u8>, queued: &mut Option<u8>) -> io::Result<Option<Key>> {// Periodic wakeups let the caller notice a resize, even without keys.let first = match queued.take() {Some(byte) => byte,- None => match read_byte(&mut input, Instant::now() + Duration::from_millis(100))? {+ None => match read_byte(input, Instant::now() + Duration::from_millis(100))? {Some(byte) => byte,None => return Ok(None),},@@ -197,12 +193,12 @@ fn read_key(utf8: &mut Vec<u8>, queued: &mut Option<u8>) -> io::Result<Option<Kelet deadline = Instant::now() + SEQUENCE_WAIT;let mut bytes = vec![first];if first == 0x1b {- let Some(second) = read_byte(&mut input, deadline)? else { return Ok(Some(Key::Escape)) };+ let Some(second) = read_byte(input, deadline)? else { return Ok(Some(Key::Escape)) };bytes.push(second);if matches!(second, b'[' | b'O') {let mut overflow = false;loop {- let Some(next) = read_byte(&mut input, deadline)? else {+ let Some(next) = read_byte(input, deadline)? else {return Ok(Some(Key::Unknown));};if bytes.len() < 32 {@@ -221,7 +217,7 @@ fn read_key(utf8: &mut Vec<u8>, queued: &mut Option<u8>) -> io::Result<Option<Ke}// An Alt-modified character is part of the ESC sequence.while std::str::from_utf8(&bytes).is_err_and(|error| error.error_len().is_none()) && bytes.len() < 6 {- let Some(next) = read_byte(&mut input, deadline)? else { return Ok(Some(Key::Unknown)) };+ let Some(next) = read_byte(input, deadline)? else { return Ok(Some(Key::Unknown)) };bytes.push(next);}Ok(Some(decode(&bytes)))@@ -443,6 +439,9 @@ fn frame(prompt: &str, options: &[&str], state: &Selection, size: (u16, u16)) ->fn menu(term: &Term, prompt: &str, options: &[&str], default: usize, confirmation: bool) -> anyhow::Result<usize> {let _signals = MenuSignals::install()?;+ // Keep echo off during redraws too. Drop the input guard before MenuSignals+ // re-delivers a signal. stdin and stdout may point to different terminals.+ let mut input = std::fs::File::from(std::io::stdin().as_fd().try_clone_to_owned()?).into_raw_mode()?;let mut utf8 = Vec::with_capacity(4);let mut queued = None;let mut state = Selection::new(default, options.len(), confirmation);@@ -465,16 +464,19 @@ fn menu(term: &Term, prompt: &str, options: &[&str], default: usize, confirmatio// menu must never discard invalid input or accept a stale default.// The prompt is written once per size; idle wakeups must not spam.if resized {- term.write_line(&fit(- ictl_l10n::tr!("放大窗口;Esc 取消", "Enlarge window; Esc cancels"),- usize::from(size.1.saturating_sub(1)),- ))?;+ write_menu_line(+ term,+ &fit(+ ictl_l10n::tr!("放大窗口;Esc 取消", "Enlarge window; Esc cancels"),+ usize::from(size.1.saturating_sub(1)),+ ),+ )?;}previous = Some((size, 0));} else {let lines = frame(prompt, options, &state, size);for line in &lines {- term.write_line(line)?;+ write_menu_line(term, line)?;}previous = Some((size, lines.len()));}@@ -482,19 +484,25 @@ fn menu(term: &Term, prompt: &str, options: &[&str], default: usize, confirmatio}// An idle wait (no key) leaves the on-screen frame untouched; the next// iteration still re-checks term.size(), so resizes keep working.- let Some(key) = read_key(&mut utf8, &mut queued)? else { continue };+ let Some(key) = read_key(&mut input, &mut utf8, &mut queued)? else { continue };needs_render = true;let current_size = term.size();if (current_size.0 < 6 || current_size.1 < 40) && !matches!(key, Key::Escape | Key::CtrlC) {continue;}if let Some(index) = state.key(key, capacity(current_size.0))? {- term.write_line(&format!("{}: {}", clean(prompt), clean(options[index])))?;+ write_menu_line(term, &format!("{}: {}", clean(prompt), clean(options[index])))?;return Ok(index);}}}+fn write_menu_line(term: &Term, line: &str) -> io::Result<()> {+ // Raw mode disables the terminal's automatic carriage return on newline.+ term.write_str(line)?;+ term.write_str("\r\n")+}+#[cfg(test)]mod tests {use super::*;diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.mdindex 31c92fd..42a5d45 100644--- a/docs/dev/regression-cases.md+++ b/docs/dev/regression-cases.md@@ -117,5 +117,5 @@| 111 | 控制台上 AI 任务的总结直接显示 Markdown 原文(`**iOS 27.0.1**`、`- **设置**:…`),换行也被合并成一行 | 总结先整体转义,再按一小部分 Markdown 显示(粗体、斜体、行内代码、列表、标题、分隔线、换行、http(s) 链接),原始 HTML 一律当文字 | 页面测试(`tests/viewer/summary.test.mjs`)+ 真机(Claude Code、Codex 任务的总结) || 112 | iOS 27 上控制台用手机自己的视频时,系统权限弹窗(「允许“日历”使用你的位置?」)在画面里只剩变暗的屏幕,看不到弹窗本身,接管的人不知道该点哪里;agent 的截图里有 | 画面是手机自己的视频时,页面问守护进程有没有系统弹窗(`AlertCheck`;在 App 里每 2 秒,主屏幕上查一次约 0.6 秒,没弹窗时放慢到 6 秒,刚触摸后 3 秒内不问),有就照 iOS 弹窗的样子把它画在画面里它所在的位置(文字、按钮);按钮按坐标点(按名字点「允许」会点到「不允许」);AI 任务进行中按钮要先接管 | 单测(`a_system_alert_with_its_own_buttons`)+ 页面测试(`tests/viewer/alert.test.mjs`)+ 真机(弹出权限请求时页面显示弹窗和按钮,点按钮生效) || 113 | 在控制台画面上拖动、滑动时,触控板双指一碰就变成了缩放画面(双指捏合在浏览器里是按住 Ctrl 的滚轮) | 画面只用上方的加减号缩放;画面区域里的 Ctrl/⌘ + 滚轮、Safari 的 gesture 事件都拦下,既不缩放画面也不缩放整页;触屏上画面周围不允许双指缩放(`touch-action: pan-x pan-y`) | 页面测试(`tests/viewer/zoom.test.mjs`)+ 真机(在画面上双指捏合,缩放比例不变) |-| 114 | 设置菜单不能用方向键,取消后可能留下终端输入模式 | 方向键和编号选择一致,Esc/Ctrl+C 不提交当前选择并恢复终端;基础终端保留逐行输入 | 菜单状态单测 + PTY 回归(不连接设备) |+| 114 | 设置菜单不能用方向键,长按方向键时重画期间会打开回显,取消后可能留下终端输入模式 | 菜单从第一帧到退出都关闭输入回显;方向键和编号选择一致,Esc/Ctrl+C 恢复原模式;基础终端保留逐行输入 | 菜单状态单测 + PTY 回归(含长按 ↓、输入输出在不同终端、取消和外部信号) || 115 | 生成 Shell 补全触发配置读取或设备维护锁,脚本与 CLI 定义不同步 | Bash/Zsh/Fish 从实际命令树生成,生成路径不读取设置、不连接设备、不申请维护锁 | 补全单测、CLI 子进程回归、Bash/Fish 候选断言及 Zsh 交互验证 |diff --git a/tests/terminal.py b/tests/terminal.pyindex fe3956e..bc27cb9 100644--- a/tests/terminal.py+++ b/tests/terminal.py@@ -129,6 +129,27 @@ def escape_with_separate_input_terminal(command, env):os.close(fd)+def held_arrow_during_redraw(command, env):+ session = Session(command, env)+ try:+ session.expect("Ctrl+C cancel")+ session.wait_for_raw()+ # Do not drain output between repeats. A slow renderer must keep echo+ # disabled even when the next arrow arrives during a frame write.+ for _ in range(50):+ os.write(session.master, b"\x1b[B")+ time.sleep(0.025)+ assert not termios.tcgetattr(session.slave)[3] & termios.ECHO, "TTY echo enabled during a held Down key"+ session.send(b"\x1b", raw=False)+ session.finish("Setup cancelled.")+ assert b"^[[B" not in session.output and b"\x1b[B" not in session.output, "Down was echoed into the menu"+ # Fifty Down presses wrap the nine-item menu five times and select item 6.+ assert session.output.rsplit(b"What do you want to set up again?", 1)[-1].count(b"> 6) Phone") == 1+ assert b"\n" not in session.output.replace(b"\r\n", b""), "a menu line did not return to column one"+ finally:+ session.close()++MENU_TEST = "guide::terminal::tests::pty_menu"@@ -180,6 +201,7 @@ def main():command = [str(args.binary.resolve()), "--data-dir", str(root / "data"),"--socket", str(root / "daemon.sock"), "setup", "--reconfigure"]escape_with_separate_input_terminal(command, env)+ held_arrow_during_redraw(command, env)for key, status in [(b"\x1b", 0), (b"\x03", 130)]:output = exercise(command, env, key, "Saved settings and completed steps are kept", status=status)assert b"Done." not in output