noracu 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,62 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.1.3] — 2026-11-04
4
+
5
+ ### Fixed
6
+ - `phone_open` is far more reliable: it opens Spotlight from the Home Screen
7
+ using Spotlight's own shortcut (trying once more if the phone ignores it),
8
+ clears the field and re-reads results, matches very short app names such as
9
+ "X", and confirms the app actually came to the foreground — tapping the app
10
+ icon when tapping its name does nothing.
11
+ - One- and two-letter names such as "X" no longer run past the 30-second tool
12
+ limit: short labels are read with a fast multi-scale OCR pass instead of slow
13
+ strip-by-strip reads. `phone_find` and the `expect` guard find them too.
14
+ - `phone_open` no longer taps the wrong result when OCR momentarily misses a
15
+ short app name. In testing, opening "X" could open a web search instead while
16
+ reporting success.
17
+ - `phone_type` keeps the typed text on the clipboard until the phone shows it
18
+ (verified by OCR) and only then restores your previous clipboard; it also
19
+ restores the clipboard if an error happens before the paste. For a single
20
+ character the restore also happens when the phone shows the paste several
21
+ seconds late — and never before. Nothing is pasted if another app or device
22
+ (Universal Clipboard) changes the clipboard just before the paste. Adds a
23
+ `replace` option to overwrite an existing field.
24
+ - `phone_scroll` validates its distance (in screen-heights) and reports when
25
+ nothing on screen moved.
26
+ - `phone_launch` reports whether the mirror is actually live, and says so when
27
+ the session is still paused.
28
+ - Moving the pointer over the iPhone Mirroring window no longer looks like a
29
+ paused session, and resuming a paused session never clicks the window's own
30
+ close or minimize buttons.
31
+ - Screenshots never silently fall back to grabbing an arbitrary screen region;
32
+ a capture failure is reported as unconfirmed instead of acting on the wrong
33
+ pixels. After bringing iPhone Mirroring to the front, noracu waits for a real
34
+ frame instead of failing on a blank transition frame.
35
+ - Before every input event, noracu asks macOS afresh whether iPhone Mirroring
36
+ is still the frontmost window, and sends nothing otherwise.
37
+
38
+ ### Security
39
+ - Phone screenshots taken for OCR were written to the shared temp directory,
40
+ readable by other local users, and never deleted. They now go to an
41
+ owner-only directory and are deleted as soon as they have been read. If you
42
+ ran an earlier version, delete leftover `imctl_*.png` files from your temp
43
+ directory (for example `/tmp`).
44
+
45
+ ### Added
46
+ - Optional `expect` guard on phone input tools: nothing is sent unless the
47
+ expected text is currently on screen.
48
+ - The server reports when its running process is older than the files on disk,
49
+ so a stale server is visible to the client.
50
+
51
+ ### Known issues
52
+ - Unchanged from 0.1.2: on iPhone 17 Pro Max + macOS 26, iPhone Mirroring draws
53
+ the phone larger than its window; the right column and bottom row stay out of
54
+ reach. Still under investigation.
55
+ - A single character typed with `phone_type` that leaves no new character on
56
+ screen (for example replacing "X" with "X") cannot be confirmed; the clipboard
57
+ then keeps the typed character rather than risk pasting your previous
58
+ clipboard into the phone.
59
+
3
60
  ## [0.1.2] — 2026-11-02
4
61
 
5
62
  ### Fixed
package/README.md CHANGED
@@ -112,7 +112,7 @@ noracu can operate a real iPhone through Apple's **iPhone Mirroring**. The agent
112
112
 
113
113
  **First success:** `phone_status` → `phone_launch` if `live` is not `true` → `phone_screenshot` → `phone_ocr` → `phone_find` + `phone_tap`.
114
114
 
115
- **Known limits:** a tap goes where OCR saw the text, so repeated or misread labels can be hit wrong; `phone_scroll` moves lists with trackpad-style scroll events (a vertical `phone_swipe` drag does not scroll a list — use it for gestures such as Home Screen paging); on one tested setup (iPhone 17 Pro Max, macOS 26) iPhone Mirroring draws the phone larger than its window at every View size, so the right column and bottom row are cut off and cannot be reached — check `phone_screenshot` if taps near the edges miss; `phone_open` types the app name into Spotlight and taps an exact match, otherwise returns to the Home Screen; `phone_home` / `phone_app_switcher` use the iPhone Mirroring menu (English macOS) and work without python while connected.
115
+ **Known limits:** a tap goes where OCR saw the text, so repeated or misread labels can be hit wrong; `phone_scroll` moves lists with trackpad-style scroll events (a vertical `phone_swipe` drag does not scroll a list — use it for gestures such as Home Screen paging); on one tested setup (iPhone 17 Pro Max on iOS 27.0.1, Mac on macOS 26.6.2) iPhone Mirroring draws the phone about 17% larger than its window at every View size, so the right column and bottom row are cut off and cannot be reached; moving the window between displays, changing the main display and relaunching made no difference, and the iOS 27 / macOS 26 version mismatch is the main suspect — check `phone_screenshot` if taps near the edges miss; `phone_open` types the app name into Spotlight and taps an exact match, otherwise returns to the Home Screen; `phone_home` / `phone_app_switcher` use the iPhone Mirroring menu (English macOS) and work without python while connected.
116
116
 
117
117
  ## Environment variables
118
118
 
package/README.zh-CN.md CHANGED
@@ -112,7 +112,7 @@ noracu 可以经 Apple 的 **iPhone Mirroring** 操作真实 iPhone。agent 在
112
112
 
113
113
  **首次成功路径:** `phone_status` → 若 `live` 不是 `true` 先 `phone_launch` → `phone_screenshot` → `phone_ocr` → `phone_find` + `phone_tap`。
114
114
 
115
- **已知限制:** 点击落在 OCR 识别到文字的位置,重复或识别错的标签可能点错;`phone_scroll` 用触控板式的滚动事件移动列表(竖向的 `phone_swipe` 拖拽不会滚动列表——它用于主屏翻页这类手势);在一套实测环境(iPhone 17 Pro Max、macOS 26)上,iPhone Mirroring 在所有 View 尺寸下都把手机画面画得比窗口大,右列和最底行被裁掉、无法点到——边缘附近点不中时先看 `phone_screenshot`;`phone_open` 把 App 名输入 Spotlight 并只点击完全匹配的结果,找不到就回到主屏;`phone_home` / `phone_app_switcher` 走 iPhone Mirroring 菜单(英文 macOS),镜像连接时无需 python。
115
+ **已知限制:** 点击落在 OCR 识别到文字的位置,重复或识别错的标签可能点错;`phone_scroll` 用触控板式的滚动事件移动列表(竖向的 `phone_swipe` 拖拽不会滚动列表——它用于主屏翻页这类手势);在一套实测环境(iPhone 17 Pro Max 运行 iOS 27.0.1,Mac 运行 macOS 26.6.2)上,iPhone Mirroring 在所有 View 尺寸下都把手机画面画得比窗口大约 17%,右列和最底行被裁掉、无法点到;在显示器之间移动窗口、切换主屏、重开 App 都无效,主要怀疑是 iOS 27 与 macOS 26 版本错位——边缘附近点不中时先看 `phone_screenshot`;`phone_open` 把 App 名输入 Spotlight 并只点击完全匹配的结果,找不到就回到主屏;`phone_home` / `phone_app_switcher` 走 iPhone Mirroring 菜单(英文 macOS),镜像连接时无需 python。
116
116
 
117
117
  ## 环境变量
118
118
 
package/docs/tools.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Tool reference
2
2
 
3
3
  > Auto-generated from the running server (`node scripts/gen-tools.mjs`) — always in sync with the implementation.
4
- > noracu v0.1.2 · 35 tools
4
+ > noracu v0.1.3 · 35 tools
5
5
 
6
6
  ## Mac layer (computer-use)
7
7
 
@@ -46,16 +46,16 @@
46
46
  |---|---|---|
47
47
  | `phone_status` | — | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Return the iPhone Mirroring session status as JSON (running, window, onscreen, frontmost, live, overlay, paused). |
48
48
  | `phone_launch` | — | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Ensure iPhone Mirroring is running, brought to the front, and clicks Resume when the connection is paused. |
49
- | `phone_screenshot` | — | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Screenshot the iPhone screen (the Mirroring window, captured by window id so it works even when covered). |
50
- | `phone_ocr` | — | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. OCR the iPhone screen into text with coordinates. |
51
- | `phone_find` | text:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Locate text on the iPhone screen. |
52
- | `phone_tap` | x:number?, y:number? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Tap at {x, y} in normalized 0-1 coordinates. Refused with mirror_not_live when the mirror is paused. |
53
- | `phone_longpress` | x:number?, y:number?, duration:number? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Long-press at {x, y} for an optional duration in seconds. |
54
- | `phone_swipe` | from:array?, to:array?, ms:number? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Swipe (mouse drag) from [x,y] to [x,y] over an optional duration in ms, for gestures such as Home Screen paging; to move a list use phone_scroll. |
49
+ | `phone_screenshot` | — | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Screenshot the iPhone screen (the Mirroring window, captured by window id so it works even when covered). Fails with capture_failed instead of returning another window's pixels. |
50
+ | `phone_ocr` | — | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. OCR the iPhone screen into text with coordinates. Fails with capture_failed instead of returning another window's pixels. |
51
+ | `phone_find` | text:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Locate text on the iPhone screen. Fails with capture_failed instead of returning another window's pixels. |
52
+ | `phone_tap` | x:number?, y:number?, expect:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Tap at {x, y} in normalized 0-1 coordinates. Refused with mirror_not_live when the mirror is paused. Optional expect: text that must be on screen (OCR) first, else nothing is sent. |
53
+ | `phone_longpress` | x:number?, y:number?, duration:number?, expect:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Long-press at {x, y} for an optional duration in seconds. Optional expect: text that must be on screen (OCR) first, else nothing is sent. |
54
+ | `phone_swipe` | from:array?, to:array?, ms:number?, expect:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Swipe (mouse drag) from [x,y] to [x,y] over an optional duration in ms, for gestures such as Home Screen paging; to move a list use phone_scroll. Optional expect: text that must be on screen (OCR) first, else nothing is sent. |
55
55
  | `phone_home` | — | EXPERIMENTAL. Go to the iPhone Home Screen via the iPhone Mirroring menu (works without python/pyobjc when the mirror is connected); falls back to an imctl swipe. |
56
56
  | `phone_app_switcher` | — | EXPERIMENTAL. Open the iPhone App Switcher via the iPhone Mirroring menu (works without python/pyobjc when the mirror is connected); falls back to an imctl gesture. |
57
- | `phone_scroll` | direction:string?, distance:number? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Scroll the list under the mirror up or down by about `distance` window heights (default 0.5), using trackpad-style scroll events. |
58
- | `phone_type` | text:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Type text via the clipboard (IME-safe). |
59
- | `phone_key` | key:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Press a key: return, delete, up, down, left, or right. |
60
- | `phone_open` | app:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Open an app via the mirroring Spotlight menu command/shortcut, type the name, OCR-pick the matching app row and tap it; returns to the home screen when not found. |
57
+ | `phone_scroll` | direction:string?, distance:number?, expect:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Scroll up or down by `distance` window heights (0 < distance <= 3, default 0.5) using trackpad-style scroll events. Reports scroll_no_effect when the screen did not change (list end, or the view does not scroll). Optional expect: text that must be on screen (OCR) first, else nothing is sent. |
58
+ | `phone_type` | text:string?, replace:boolean?, expect:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Type text via the clipboard (IME-safe). Restores the clipboard only after OCR sees the text, else reports type_not_confirmed and keeps the text. replace=true selects all and overwrites the field. Optional expect: on-screen text (OCR), else nothing is sent. |
59
+ | `phone_key` | key:string?, expect:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Press a key: return, delete, up, down, left, or right. Optional expect: text that must be on screen (OCR) first, else nothing is sent. |
60
+ | `phone_open` | app:string? | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Open an app: Home Screen, Spotlight via the menu, clear, type the name, OCR-pick the exact row and tap it; confirms the app opened (frame diff + OCR), taps the Top Hit icon when the label tap does nothing, else open_not_confirmed, back on the Home Screen. |
61
61
 
@@ -21,10 +21,34 @@ from __future__ import annotations
21
21
 
22
22
  import argparse
23
23
  import json
24
+ import os
25
+ import signal
24
26
  import sys
27
+ import tempfile
25
28
 
26
29
  from . import gestures, input, verify, vision
27
- from .window import WindowError, get_overlay
30
+ from .vision import CaptureError
31
+ from .window import WindowError, ensure_frontmost, get_overlay
32
+
33
+ # F31: every phone input command starts in _require_live(), which first brings
34
+ # the mirror to the front — switching Spaces if needed and waiting for a real
35
+ # frame — so the expect OCR and scroll baseline that follow read the phone, not
36
+ # another Space or a transition frame. Module-level so tests can swap it.
37
+ _bring_front = ensure_frontmost
38
+
39
+ # F25: one line, one exit code for every capture failure. The pixels a check
40
+ # needed are not the phone's — report that, never guess from whatever
41
+ # another window happened to show inside the region.
42
+ _CAPTURE_FAILED_LINE = (
43
+ "capture_failed: could not capture the iPhone Mirroring window "
44
+ "(it may be hidden, minimized or on another Space); no image was returned"
45
+ )
46
+
47
+
48
+ def _capture_failed() -> int:
49
+ """Print the F25 capture-failure line; exit code 7."""
50
+ print(_CAPTURE_FAILED_LINE, file=sys.stderr)
51
+ return 7
28
52
 
29
53
 
30
54
  def _require_live() -> int | None:
@@ -32,7 +56,9 @@ def _require_live() -> int | None:
32
56
 
33
57
  Returns exit code 3 after printing a `mirror_not_live:` line when the mirror is
34
58
  verifiably not live; returns None (allow) when live or unknown (fail-open).
59
+ F31: brings the mirror to the front first (see _bring_front).
35
60
  """
61
+ _bring_front()
36
62
  overlay = get_overlay()
37
63
  if overlay["live"] is False:
38
64
  label = overlay["overlay"] or "overlay shown"
@@ -44,6 +70,47 @@ def _require_live() -> int | None:
44
70
  return None
45
71
 
46
72
 
73
+ def _require_expect(args, read_screen=None, read_sweep=None) -> int | None:
74
+ """Refuse input when the --expect anchor text is not on screen.
75
+
76
+ Between two phone_* calls the iPhone foreground can change (the user
77
+ picked up the phone, tapped a notification); the mirror cannot report
78
+ the phone's foreground app identity, so an OCR text anchor is the
79
+ only available guard — the iPhone-side counterpart of mac_key's app
80
+ focus guard. Returns None when no --expect was passed or the text is
81
+ on screen; returns exit code 5 after printing an ``expect_not_found:``
82
+ line when it is not, in which case nothing is sent. A capture failure
83
+ refuses the same way with ``capture_failed:`` and exit code 7 — an
84
+ unreadable screen is not a match, so nothing is sent then either.
85
+ """
86
+ expect = getattr(args, "expect", None)
87
+ if expect is None:
88
+ return None
89
+ if read_screen is None:
90
+ read_screen = vision.read_screen
91
+ if read_sweep is None:
92
+ def read_sweep():
93
+ return vision.read_screen(language_correction=False, sweep=True)
94
+ try:
95
+ hits = read_screen()
96
+ if (read_sweep is not None and verify.is_short_text(expect)
97
+ and not verify.screen_contains(expect, hits)):
98
+ # F27: a one- or two-character anchor (the app "X") can be invisible
99
+ # to the default OCR pass; read again with the sweep before refusing.
100
+ hits = read_sweep()
101
+ except (WindowError, CaptureError):
102
+ # F25: an unreadable screen is not a match — refuse exactly like
103
+ # expect_not_found; nothing is sent.
104
+ return _capture_failed()
105
+ if verify.screen_contains(expect, hits):
106
+ return None
107
+ print(
108
+ f"expect_not_found: {expect!r} is not on screen; nothing was sent",
109
+ file=sys.stderr,
110
+ )
111
+ return 5
112
+
113
+
47
114
  def _warn_if_not_live() -> None:
48
115
  """Print a heads-up before ocr/find output when the mirror is not live.
49
116
 
@@ -64,6 +131,9 @@ def _cmd_status(_args) -> int:
64
131
 
65
132
  def _cmd_tap(args) -> int:
66
133
  guard = _require_live()
134
+ if guard is not None:
135
+ return guard
136
+ guard = _require_expect(args)
67
137
  if guard is not None:
68
138
  return guard
69
139
  input.tap(args.x, args.y)
@@ -73,6 +143,9 @@ def _cmd_tap(args) -> int:
73
143
 
74
144
  def _cmd_longpress(args) -> int:
75
145
  guard = _require_live()
146
+ if guard is not None:
147
+ return guard
148
+ guard = _require_expect(args)
76
149
  if guard is not None:
77
150
  return guard
78
151
  input.long_press(args.x, args.y, args.duration)
@@ -82,6 +155,9 @@ def _cmd_longpress(args) -> int:
82
155
 
83
156
  def _cmd_swipe(args) -> int:
84
157
  guard = _require_live()
158
+ if guard is not None:
159
+ return guard
160
+ guard = _require_expect(args)
85
161
  if guard is not None:
86
162
  return guard
87
163
  input.swipe(args.fx, args.fy, args.tx, args.ty, args.ms)
@@ -105,10 +181,27 @@ def _cmd_scroll(args) -> int:
105
181
  guard = _require_live()
106
182
  if guard is not None:
107
183
  return guard
108
- if args.direction == "down":
109
- gestures.scroll_down(args.distance)
110
- else:
111
- gestures.scroll_up(args.distance)
184
+ guard = _require_expect(args)
185
+ if guard is not None:
186
+ return guard
187
+ try:
188
+ moved = gestures.scroll_checked(args.direction, args.distance)
189
+ except ValueError:
190
+ print(
191
+ "phone_scroll: distance is in window heights, "
192
+ "0 < distance <= 3 (default 0.5)",
193
+ file=sys.stderr,
194
+ )
195
+ return 2
196
+ except (WindowError, CaptureError):
197
+ return _capture_failed()
198
+ if not moved:
199
+ print(
200
+ "scroll_no_effect: the screen did not change (end of the list, "
201
+ "or the view under the cursor does not scroll)",
202
+ file=sys.stderr,
203
+ )
204
+ return 4
112
205
  print(f"scrolled {args.direction} {args.distance}")
113
206
  return 0
114
207
 
@@ -129,13 +222,26 @@ def _cmd_type(args) -> int:
129
222
  guard = _require_live()
130
223
  if guard is not None:
131
224
  return guard
132
- input.type_text(args.text)
133
- print(f"typed {args.text!r}")
134
- return 0
225
+ guard = _require_expect(args)
226
+ if guard is not None:
227
+ return guard
228
+ if input.type_text(args.text, replace=args.replace):
229
+ print(f"typed {args.text!r}")
230
+ return 0
231
+ print(
232
+ "type_not_confirmed: the paste did not show on screen within 2.5s; "
233
+ "the clipboard still holds the typed text and your previous clipboard "
234
+ "was not restored",
235
+ file=sys.stderr,
236
+ )
237
+ return 4
135
238
 
136
239
 
137
240
  def _cmd_key(args) -> int:
138
241
  guard = _require_live()
242
+ if guard is not None:
243
+ return guard
244
+ guard = _require_expect(args)
139
245
  if guard is not None:
140
246
  return guard
141
247
  input.press_key(args.key)
@@ -145,7 +251,10 @@ def _cmd_key(args) -> int:
145
251
 
146
252
  def _cmd_ocr(_args) -> int:
147
253
  _warn_if_not_live()
148
- hits = gestures.read_text()
254
+ try:
255
+ hits = gestures.read_text()
256
+ except (WindowError, CaptureError):
257
+ return _capture_failed()
149
258
  for h in hits:
150
259
  print(h)
151
260
  print(f"-- {len(hits)} hits")
@@ -154,7 +263,10 @@ def _cmd_ocr(_args) -> int:
154
263
 
155
264
  def _cmd_find(args) -> int:
156
265
  _warn_if_not_live()
157
- hit = vision.find(args.text, exact=args.exact)
266
+ try:
267
+ hit = vision.find(args.text, exact=args.exact)
268
+ except (WindowError, CaptureError):
269
+ return _capture_failed()
158
270
  if hit is None:
159
271
  print(f"not found: {args.text!r}", file=sys.stderr)
160
272
  return 1
@@ -168,12 +280,34 @@ def _cmd_open(args) -> int:
168
280
  return guard
169
281
  # Open Spotlight here (not inside open_app) so a failure can be
170
282
  # reported as its own condition instead of a bogus "app not found".
171
- if not gestures.open_spotlight():
172
- print("spotlight unavailable")
283
+ try:
284
+ # F34: one retry — on the device the Spotlight command was once
285
+ # ignored right after an app closed. Each try starts from the Home
286
+ # Screen, so a second try cannot toggle an open Spotlight shut.
287
+ if not (gestures.open_spotlight_checked()
288
+ or gestures.open_spotlight_checked()):
289
+ result = "spotlight_unavailable"
290
+ else:
291
+ result = gestures.open_app(args.app, spotlight_open=True)
292
+ except (WindowError, CaptureError):
293
+ # F25: the Spotlight gate and the result matching both read the
294
+ # mirroring window's pixels; without them nothing about the
295
+ # phone is known — refuse rather than guess.
296
+ return _capture_failed()
297
+ if result == "opened":
298
+ print(f"opened {args.app!r}")
299
+ return 0
300
+ if result == "not_found":
301
+ print(f"app not found: {args.app!r}")
173
302
  return 1
174
- ok = gestures.open_app(args.app, spotlight_open=True)
175
- print(f"opened {args.app!r}" if ok else f"app not found: {args.app!r}")
176
- return 0 if ok else 1
303
+ if result == "spotlight_unavailable":
304
+ print("spotlight unavailable (could not reach the Home Screen, the menu command failed, or the screen did not change)")
305
+ return 1
306
+ # "not_confirmed" (F24): the row — and possibly the Top Hit icon —
307
+ # was tapped but the app never verifiably opened; the phone is
308
+ # back on the Home Screen.
309
+ print(f"open_not_confirmed: tapped {args.app!r} in Spotlight but the app did not open; back on the Home Screen", file=sys.stderr)
310
+ return 4
177
311
 
178
312
 
179
313
  def _cmd_verify(args) -> int:
@@ -192,20 +326,43 @@ def _cmd_verify(args) -> int:
192
326
 
193
327
 
194
328
  def _cmd_launch(_args) -> int:
195
- gestures.launch()
196
- print("iPhone Mirroring ready")
329
+ live = gestures.launch()
330
+ if live is False:
331
+ # F29: never report "ready" while the overlay is still up.
332
+ print(
333
+ "mirror_not_live: iPhone Mirroring is still paused — lock the iPhone, keep it "
334
+ "near the Mac, then call phone_launch again",
335
+ file=sys.stderr,
336
+ )
337
+ return 3
338
+ print("iPhone Mirroring ready" if live else "iPhone Mirroring launched (stream state unknown)")
197
339
  return 0
198
340
 
199
341
 
200
342
  def _cmd_screenshot(args) -> int:
201
- path = vision.capture_window(args.path)
343
+ path = args.path
344
+ if path is None:
345
+ # A screenshot asked for outlives this process: an owner-only (0600)
346
+ # file in the temp directory, unlike the OCR frames, which are
347
+ # deleted once read.
348
+ fd, path = tempfile.mkstemp(prefix="imctl_screenshot_", suffix=".png")
349
+ os.close(fd)
350
+ try:
351
+ path = vision.capture_window(path)
352
+ except (WindowError, CaptureError):
353
+ if args.path is None:
354
+ try:
355
+ os.remove(path) # the empty placeholder made above
356
+ except OSError:
357
+ pass
358
+ return _capture_failed()
202
359
  print(path)
203
360
  return 0
204
361
 
205
362
 
206
363
  def _cmd_resume(_args) -> int:
207
364
  ok = gestures.resume()
208
- print("resumed" if ok else "still paused (unlock the iPhone, then retry)")
365
+ print("resumed" if ok else "still paused (lock the iPhone, keep it near the Mac, then retry)")
209
366
  return 0 if ok else 1
210
367
 
211
368
 
@@ -226,12 +383,14 @@ def build_parser() -> argparse.ArgumentParser:
226
383
  sp = sub.add_parser("tap", help="tap at normalized coords")
227
384
  sp.add_argument("x", type=float)
228
385
  sp.add_argument("y", type=float)
386
+ sp.add_argument("--expect", help="refuse to act unless this text is on screen (OCR)")
229
387
  sp.set_defaults(func=_cmd_tap)
230
388
 
231
389
  sp = sub.add_parser("longpress", help="long-press at normalized coords")
232
390
  sp.add_argument("x", type=float)
233
391
  sp.add_argument("y", type=float)
234
392
  sp.add_argument("--duration", type=float, default=0.8)
393
+ sp.add_argument("--expect", help="refuse to act unless this text is on screen (OCR)")
235
394
  sp.set_defaults(func=_cmd_longpress)
236
395
 
237
396
  sp = sub.add_parser("swipe", help="swipe between two normalized points")
@@ -240,6 +399,7 @@ def build_parser() -> argparse.ArgumentParser:
240
399
  sp.add_argument("tx", type=float)
241
400
  sp.add_argument("ty", type=float)
242
401
  sp.add_argument("--ms", type=int, default=300)
402
+ sp.add_argument("--expect", help="refuse to act unless this text is on screen (OCR)")
243
403
  sp.set_defaults(func=_cmd_swipe)
244
404
 
245
405
  sub.add_parser("home", help="home gesture").set_defaults(func=_cmd_home)
@@ -248,6 +408,7 @@ def build_parser() -> argparse.ArgumentParser:
248
408
  sp = sub.add_parser("scroll", help="scroll up/down")
249
409
  sp.add_argument("direction", choices=["up", "down"])
250
410
  sp.add_argument("distance", type=float, nargs="?", default=0.5)
411
+ sp.add_argument("--expect", help="refuse to act unless this text is on screen (OCR)")
251
412
  sp.set_defaults(func=_cmd_scroll)
252
413
 
253
414
  sp = sub.add_parser("page", help="page left/right on home screen")
@@ -256,10 +417,14 @@ def build_parser() -> argparse.ArgumentParser:
256
417
 
257
418
  sp = sub.add_parser("type", help="type text (clipboard-based, IME-safe)")
258
419
  sp.add_argument("text")
420
+ sp.add_argument("--replace", action="store_true",
421
+ help="select all in the focused field first, then overwrite it")
422
+ sp.add_argument("--expect", help="refuse to act unless this text is on screen (OCR)")
259
423
  sp.set_defaults(func=_cmd_type)
260
424
 
261
425
  sp = sub.add_parser("key", help="press a key (return/delete/up/down/left/right)")
262
426
  sp.add_argument("key")
427
+ sp.add_argument("--expect", help="refuse to act unless this text is on screen (OCR)")
263
428
  sp.set_defaults(func=_cmd_key)
264
429
 
265
430
  sub.add_parser("ocr", help="OCR the screen").set_defaults(func=_cmd_ocr)
@@ -280,11 +445,28 @@ def build_parser() -> argparse.ArgumentParser:
280
445
  return p
281
446
 
282
447
 
448
+ def _on_sigterm(signum, _frame):
449
+ # The server ends a call that runs past its time limit with SIGTERM. As
450
+ # SystemExit it unwinds normally: OCR frames are deleted, and a paste
451
+ # that never went out puts the clipboard back (type_text decides).
452
+ raise SystemExit(128 + signum)
453
+
454
+
283
455
  def main(argv: list[str] | None = None) -> int:
456
+ signal.signal(signal.SIGTERM, _on_sigterm)
284
457
  parser = build_parser()
285
458
  args = parser.parse_args(argv)
286
459
  try:
287
460
  return args.func(args)
461
+ except input.FocusLost:
462
+ # F26: the frontmost check failed right before an event — either
463
+ # nothing was sent at all, or (mid-scroll) nothing further was.
464
+ print(
465
+ "focus_lost: iPhone Mirroring is not the frontmost app; "
466
+ "nothing (or nothing further) was sent",
467
+ file=sys.stderr,
468
+ )
469
+ return 6
288
470
  except WindowError as exc:
289
471
  print(f"window error: {exc}", file=sys.stderr)
290
472
  return 3