Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

fix(setup): a key typed after an unfinished sequence isn't swallowed (#131)

Qinghe Li49e6eee8aa03
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 015ebf0..e6a91f2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,7 @@ What changed in each release, one line per change. Versions follow [Semantic Ver
### Fixes
+- Ctrl+C in setup menus is no longer ignored after a half-typed key on a busy machine (#131).
- `iphone-control status` on a phone under native control shows "native" instead of asking you to install WDA (#127).
- `service stop` and `service uninstall` also end a WDA launched in the background, and each phone keeps its own (#124).
- Text pasted on the phone no longer reaches your Mac through Universal Clipboard (#122).
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 294940b..e2c7d40 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -23,6 +23,7 @@
### 修复
+- 机器很忙时,引导菜单里在半个按键之后按的 Ctrl+C 不再被忽略(#131)。
- 原生控制的手机上,`iphone-control status` 显示「原生」,不再提示去装 WDA(#127)。
- `service stop`、`service uninstall` 也会结束后台启动的 WDA,每台手机各用各的(#124)。
- 粘贴到手机上的文字不再经「通用剪贴板」传到 Mac(#122)。
diff --git a/apps/iphone-control/src/guide/terminal.rs b/apps/iphone-control/src/guide/terminal.rs
index f0faeee..bd9f025 100644
--- a/apps/iphone-control/src/guide/terminal.rs
+++ b/apps/iphone-control/src/guide/terminal.rs
@@ -161,6 +161,11 @@ fn decode(bytes: &[u8]) -> Key {
}
}
+/// C0 controls and DEL: keys of their own (Enter, Ctrl+C, Backspace, Esc), never inside an escape sequence
+fn is_control(byte: u8) -> bool {
+ byte < 0x20 || byte == 0x7f
+}
+
/// Returns `Ok(None)` when no byte arrives within the first-read window: the
/// terminal is simply idle, so the caller can skip repainting an unchanged
/// frame. A byte that arrives but forms an unknown/partial sequence still
@@ -195,6 +200,11 @@ fn read_key(input: &mut std::fs::File, utf8: &mut Vec<u8>, queued: &mut Option<u
let mut bytes = vec![first];
if first == 0x1b {
let Some(second) = read_byte(input, deadline)? else { return Ok(Some(Key::Escape)) };
+ // Esc and then Ctrl+C, Enter and so on, read together because this process was late: two keys, not one
+ if is_control(second) {
+ *queued = Some(second);
+ return Ok(Some(Key::Escape));
+ }
bytes.push(second);
if matches!(second, b'[' | b'O') {
let mut overflow = false;
@@ -202,6 +212,12 @@ fn read_key(input: &mut std::fs::File, utf8: &mut Vec<u8>, queued: &mut Option<u
let Some(next) = read_byte(input, deadline)? else {
return Ok(Some(Key::Unknown));
};
+ // A control character can't be part of the sequence: it is the next key, after a sequence that
+ // never finished. Taken into the sequence, a Ctrl+C there would be lost
+ if is_control(next) {
+ *queued = Some(next);
+ return Ok(Some(Key::Unknown));
+ }
if bytes.len() < 32 {
bytes.push(next);
} else {
@@ -680,4 +696,32 @@ mod tests {
assert_eq!(read_byte(&mut input, past).unwrap(), Some(b'B'));
assert_eq!(read_byte(&mut input, past).unwrap(), None);
}
+
+ /// Keys this process gets to late, all at once: an unfinished sequence or a lone Esc doesn't swallow the
+ /// control key typed after it
+ #[test]
+ fn a_control_key_after_an_unfinished_sequence_is_its_own_key() {
+ use std::io::Write;
+ for (typed, keys) in [
+ (&b"\x1b[\x03"[..], vec![Key::Unknown, Key::CtrlC]),
+ (b"\x1bO\x03", vec![Key::Unknown, Key::CtrlC]),
+ (b"\x1b[1\r", vec![Key::Unknown, Key::Enter]),
+ (b"\x1b\x03", vec![Key::Escape, Key::CtrlC]),
+ (b"\x1b\x1b", vec![Key::Escape, Key::Escape]),
+ // complete sequences and the key after them are read as before
+ (b"\x1b[B\r", vec![Key::ArrowDown, Key::Enter]),
+ (b"\x1b[5~\x03", vec![Key::PageUp, Key::CtrlC]),
+ ] {
+ let (mut input, mut writer) = pipe();
+ // the writing end stays open: a closed one would end the input after these bytes
+ writer.write_all(typed).unwrap();
+ let (mut utf8, mut queued) = (Vec::new(), None);
+ let mut read = Vec::new();
+ for _ in &keys {
+ read.push(read_key(&mut input, &mut utf8, &mut queued).unwrap().unwrap());
+ }
+ assert_eq!(read, keys, "{typed:?}");
+ assert_eq!(queued, None, "{typed:?}");
+ }
+ }
}
diff --git a/tests/terminal.py b/tests/terminal.py
index de56757..a8c0e1a 100644
--- a/tests/terminal.py
+++ b/tests/terminal.py
@@ -121,7 +121,7 @@ def escape_with_separate_input_terminal(command, env):
try:
output = b""
while b"Ctrl+C cancel" not in output:
- assert select.select([display], [], [], 5)[0], "split-terminal menu did not appear"
+ assert select.select([display], [], [], 8)[0], "split-terminal menu did not appear"
output += os.read(display, 8192)
os.write(key_stream, b"\x1b")
assert proc.wait(timeout=3) == 0
@@ -336,20 +336,34 @@ def main():
session.close()
# Send one byte at a time, well apart: a single write is not a
# fragmented-input test. Every fragment stays within the 250ms budget.
+ # That holds only if this script itself isn't held up between the
+ # writes (a busy macOS runner stalled it past the budget, and ↓ came
+ # out as "B"): an attempt whose writes took longer proves nothing
+ # and is run again.
+ spread = 0.2
for fragmented_env, keys, result in [(env, b"\x1b[B", 2),
(env, b"\x1bOB", 2),
(yes_env, "否".encode(), 0),
(yes_env, "不".encode(), 0)]:
- session = Session(command, fragmented_env)
- try:
- session.expect("Esc")
- for byte in keys:
- session.send(bytes([byte]))
- time.sleep(0.04)
- session.send(b"\r")
- session.finish(f"MENU_RESULT={result}")
- finally:
- session.close()
+ took = []
+ while len(took) < 5:
+ session = Session(command, fragmented_env)
+ try:
+ session.expect("Esc")
+ started = time.monotonic()
+ for i, byte in enumerate(keys):
+ if i:
+ time.sleep(0.04)
+ session.send(bytes([byte]))
+ took.append(time.monotonic() - started)
+ session.send(b"\r")
+ if took[-1] <= spread:
+ session.finish(f"MENU_RESULT={result}")
+ break
+ finally:
+ session.close()
+ else:
+ raise AssertionError(f"could not send {keys!r} within {spread}s: took {took}")
# A partial control sequence that times out is ignored, not Esc.
session = Session(command, env)
try: