noracu 0.2.7 → 0.3.0

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/docs/usage.md CHANGED
@@ -10,7 +10,7 @@ the *flow*.
10
10
  > If you set `NORACU_READ_ONLY=1`, the action steps below (`mac_click`,
11
11
  > `mac_type`, `browser_click`, …) are refused, along with `mac_clipboard_read`,
12
12
  > `mac_notifications`, and `mac_wait` on `condition: "notification"` — that mode
13
- > allows only the 18 observe + browser-lifecycle tools (and skips toggling
13
+ > allows only the observe + browser-lifecycle tools (and skips toggling
14
14
  > `web_accessibility` on apps). Unset it to run the full loop.
15
15
 
16
16
  ## 1. The core pattern: observe, then act by `element_index`
@@ -149,12 +149,28 @@ Notes:
149
149
 
150
150
  - **One session, no tab API** in v0.2 — `browser_launch` reuses the existing
151
151
  session if one is open, and a tab the page opens itself (`window.open`,
152
- `target=_blank`) is not switched to. Close with `browser_close {}`.
152
+ `target=_blank`) is not switched to. `browser_tabs {}` lists the tabs and `browser_tabs {"action":"select","tab_id":"t2"}` switches to one; Close with `browser_close {}`.
153
+ - **The active page is an http(s) page**, or a tab still on the blank page that
154
+ `browser_launch` or `browser_tabs` opened it on (`file://` with
155
+ `NORACU_ALLOW_FILE_URL=1`). When it comes to show anything else — a blob the
156
+ page made, Chromium's page for a load that failed, a blank page after another
157
+ page — the page tools return `active_page_not_allowed`: `browser_navigate`
158
+ takes the tab to a page again, and `browser_tabs` can open or select another.
159
+ When no open tab may be the active page they return `no_active_page`.
153
160
  - The index re-check compares tag, name, href, and position at click time, and
154
161
  a snapshot is invalidated if the page navigated since. A mismatch returns
155
162
  `element_no_longer_valid` — re-snapshot.
163
+ - `browser_snapshot` returns `page_changed`, and nothing of the page, when the
164
+ page navigated while the snapshot was being taken (another address, a
165
+ fragment, a reload, `history.pushState`) — call it again. `browser_read`
166
+ without a selector does the same. With a selector it returns its text (a
167
+ read that waits for a selector goes on across the page's own move to the
168
+ next page), under a first line that says the page navigated and gives both
169
+ addresses. `browser_evaluate` and `browser_screenshot` hand their result
170
+ over with a note that the page navigated.
156
171
  - Don't use `browser_evaluate` just to read a page (`browser_read` does that,
157
- and `browser_evaluate` can be disabled with `NORACU_DISABLE_EVAL=1`).
172
+ and `browser_evaluate` is off unless the server runs with `NORACU_ENABLE_EVAL=1`;
173
+ `NORACU_DISABLE_EVAL=1` keeps it off, and it never runs in a `chrome: true` session).
158
174
  - `file://` URLs are blocked unless `NORACU_ALLOW_FILE_URL=1`.
159
175
 
160
176
  ## 4. Menu commands
@@ -213,6 +229,28 @@ mac_notifications {} # ban
213
229
  mac_notifications { "action": "dismiss", "id": "BC2BF929-…" } # notification_not_found if gone
214
230
  ```
215
231
 
232
+ ## 5b2. Your own Chrome, with its sign-ins
233
+
234
+ With `NORACU_ALLOW_CHROME=1` on the server and Chrome's remote-debugging
235
+ switch on (`chrome://inspect/#remote-debugging`, Chrome 144+), the browser
236
+ tools work in the Chrome you use. Chrome asks you to allow the connection.
237
+ noracu opens a window of its own and works only in the tabs it opens there;
238
+ your other tabs are not listed, read or touched. With `NORACU_CHROME_TABS=all`
239
+ your http(s) tabs are listed too (`noracu_tab: false`) and `browser_tabs` `select`
240
+ makes one the active page (nothing else does); noracu still closes only its own tabs. `browser_evaluate` never runs in this session,
241
+ even with `NORACU_ENABLE_EVAL=1`.
242
+
243
+ ```
244
+ browser_launch { "chrome": true } # Chrome shows its dialog: allow
245
+ browser_navigate { "url": "https://github.com/notifications" } # signed in as you
246
+ browser_tabs { "action": "new", "url": "https://mail.google.com" } # a tab in noracu's window
247
+ browser_close {} # closes noracu's tabs; Chrome keeps running
248
+ ```
249
+
250
+ Errors: `chrome_not_reachable` (the switch is off, or Chrome is not running),
251
+ `chrome_attach_failed` (the dialog was not answered within 60 s),
252
+ `policy_denied` (`NORACU_ALLOW_CHROME` is not set).
253
+
216
254
  ## 5c. Electron and Chromium apps: web contents through Playwright
217
255
 
218
256
  With `NORACU_ALLOW_CDP=1` on the server, start the app fresh with a DevTools
@@ -248,7 +286,7 @@ model — don't let it override the task.
248
286
 
249
287
  | Variable | Default | Effect |
250
288
  |---|---|---|
251
- | `NORACU_READ_ONLY` | unset | `=1` observation-only (allowlist of 18); all input-synthesis tools plus `mac_clipboard_read`, `mac_notifications`, and `mac_wait` on `condition: "notification"` are refused (`mac_ax_state` / `mac_find` also skip `web_accessibility`) |
289
+ | `NORACU_READ_ONLY` | unset | `=1` observation-only (an allowlist of observe + browser-lifecycle tools); all input-synthesis tools plus `mac_clipboard_read`, `mac_notifications`, and `mac_wait` on `condition: "notification"` are refused (`mac_ax_state` / `mac_find` also skip `web_accessibility`) |
252
290
  | `NORACU_DISABLE_EVAL` | unset | `=1` makes `browser_evaluate` return an error when called (stays listed) |
253
291
  | `NORACU_ALLOW_FILE_URL` | unset | `=1` allows `browser_navigate` to open `file://` |
254
292
  | `NORACU_DISABLE_AUTO_INSTALL` | unset | `=1` skips Chromium auto-install on first `browser_launch` |
@@ -258,8 +296,18 @@ model — don't let it override the task.
258
296
  | `NORACU_PHONE_TIMEOUT_MS` | 30000 (45000 for `phone_open` / `phone_type`) | time limit for each iPhone-layer step, 1000–600000 ms (`imctl_timeout` on expiry) |
259
297
  | `NORACU_OCR_LANGUAGES` | `zh-Hans,en-US` | comma-separated Vision OCR language codes for the iPhone screen, in priority order |
260
298
  | `NORACU_TOPHIT_LABELS` | `Top Hit` | comma-separated Spotlight Top Hit section label(s) that `phone_open` looks for |
299
+ | `NORACU_OCR_MIN_CONFIDENCE` | unset (off) | opt-in, experimental: a number above 0 and at most 1. With it, `phone_open` does not tap a Spotlight label the recognizer read with a lower confidence and answers `open_not_confirmed` with nothing tapped; a value that is set and is not such a number makes `phone_open` refuse (`invalid_args`, nothing sent). Set or not, `phone_open`'s result line names the confidence of the label it tapped |
300
+ | `NORACU_ALLOW_CHROME` | unset | `=1` lets `browser_launch` with `chrome: true` work in your own Chrome (see 5b2); refused under `NORACU_READ_ONLY=1` |
301
+ | `NORACU_CHROME_TABS` | unset | `all`: with `chrome: true`, your other tabs are listed and can be selected, read and acted on (never closed) |
302
+ | `NORACU_CHROME_DIR` | `~/Library/Application Support/Google/Chrome` | profile folder whose `DevToolsActivePort` `chrome: true` reads |
261
303
  | `NORACU_ALLOW_CDP` | unset | `=1` allows `mac_app` launch with `cdp_port` and `browser_launch` with `cdp_port` for ports opened by this `noracu` process (`=any` for external loopback ports; refused under `NORACU_READ_ONLY=1`) |
262
304
  | `NORACU_TRACE` | unset | file path for a JSON-lines call log (`{ts, tool, args, ms, error, code}` — argument names/sizes and error code prefix only, never result or error text; opened `0600` with `O_NOFOLLOW`) |
305
+ | `NORACU_USER_IDLE_S` | `2` | seconds without the person's keyboard or mouse input before a Mac or iPhone Mirroring (`phone_*`) input tool acts (the `ios_*` tools do not wait: they do not use this Mac's keyboard or mouse) (`user_active` sooner); also puts the pointer back after pointer actions; `0` turns both off |
306
+ | `NORACU_NO_BGPOST` | unset | `=1` turns off background input (physical clicks and named keys use the real pointer and the HID key path) |
307
+ | `NORACU_STOP_FILE` | unset | file path: while it exists, every input tool — Mac, iPhone and the browser's input tools (navigate, click, type, fill, press_key, scroll, evaluate, `browser_tabs` new/close) — returns `user_stopped` and sends nothing; set but blank, it refuses all input |
308
+ | `NORACU_DENY_APPS` | the common terminal apps and IDEs with a built-in terminal | comma-separated bundle ids / app names (`*`, `?`) that never get input; a list of your own adds to the default, blank keeps the default, a list starting with `none` drops it |
309
+ | `NORACU_APPROVAL_FILE` | unset | `0600` JSON `{allow, ask, deny}` of bundle-id / app-name patterns, judged on the app that receives the input; `ask` or unlisted → `approval_required`; a broken file refuses all Mac and iPhone input (app rules do not judge the browser layer) |
310
+ | `NORACU_LAYERS` | unset (`mac,browser`) | comma-separated `mac`, `browser`, `iphone`: only those layers' tools are listed and callable (the experimental iPhone layer only when `iphone` is named); a call to a tool of a layer that is off says how to turn it on; a name that is not one of the three stops the server at start |
263
311
  | `NORACU_CI` | unset | `=1` only affects `npm test` (skips hardware-gated checks) |
264
312
 
265
313
  ## 8. Error reference
@@ -292,7 +340,8 @@ model — don't let it override the task.
292
340
 
293
341
  ## 9. iPhone layer
294
342
 
295
- Experimental. The driver (imctl, Python) ships inside the package. The tools
343
+ Experimental and off by default: `NORACU_LAYERS=mac,browser,iphone` turns it on
344
+ (section 7). The driver (imctl, Python) ships inside the package. The tools
296
345
  need Apple's iPhone Mirroring with the iPhone **locked and near the Mac**
297
346
  (unlocking it ends the session; not available in the EU) and a python3 with
298
347
  pyobjc (`NORACU_PYTHON`, or the automatic probe described in the README).
@@ -382,3 +431,47 @@ live — working without python/pyobjc on English macOS, refusing when paused or
382
431
  closed, returning `menu_unknown` without a fallback swipe on timeout, and
383
432
  falling back to `imctl` when the English menu item is absent on non-English
384
433
  macOS.
434
+
435
+ ## 10. iPhone: the XCUITest backend
436
+
437
+ Experimental and opt-in (`NORACU_PHONE_BACKEND=xcuitest`, with the iPhone layer on); the `ios_*` tools then
438
+ replace `phone_*`. Requirements and the one-time `npx noracu ios-setup` are in the
439
+ README. The iPhone must be unlocked.
440
+
441
+ ```
442
+ ios_status → device, locked?, runner built?, runner running?
443
+ ios_launch { bundle_id: "com.apple.Preferences" } → in front (delivered_verified)
444
+ ios_snapshot { interactive: true } → elements: [{ i, type, label, value, frame }]
445
+ ios_type { element_index: 12, text: "wifi" } → verified when a field shows the text
446
+ ios_tap { element_index: 31 } → sent; look again
447
+ ios_snapshot → the new screen, new indexes
448
+ ios_home → Home Screen; earlier indexes end
449
+ ```
450
+
451
+ - Indexes last 30 s and are unique across snapshots. Before one is used the app
452
+ is read again; `element_no_longer_valid` means the element moved, changed, or
453
+ its app left the front — take a new `ios_snapshot`. An app that has just come
454
+ to the front may still be filling in its rows: snapshot again after a moment.
455
+ - `bundle_id` defaults to the app of the last call (`ios_launch` sets it;
456
+ `ios_home` sets it to `com.apple.springboard`).
457
+ - Coordinates (`ios_tap` x,y, `ios_swipe` from/to, element frames, the size
458
+ `ios_screenshot` reports) are screen points.
459
+ - Scroll with `ios_swipe` (a list moves a little less than the finger); press
460
+ return or delete with `ios_key`; a long press is `ios_tap` with `duration_ms`.
461
+
462
+ | Error | Meaning / fix |
463
+ |---|---|
464
+ | `ios_setup_required` | no runner build for this device — run the `npx noracu ios-setup …` command it names |
465
+ | `device_not_found` / `device_ambiguous` | no connected iPhone, or several: connect and unlock one, or set `NORACU_IOS_UDID` |
466
+ | `device_locked` / `lock_unknown` | the iPhone is locked, or its lock state could not be read — nothing was sent or read; unlock it |
467
+ | `input_denied: … while app rules are in force` | app rules are set (`NORACU_APPROVAL_FILE` or `NORACU_DENY_APPS`): no input that names `com.apple.springboard` is sent — not even one tap on a button of a system prompt (answer those on the phone). It is refused before a runner is started, so the refusal changes nothing on the phone. Open apps with `ios_launch`, go home with `ios_home` |
468
+ | `home_not_confirmed` | Home was pressed but the app is still in front — after 3 s, or when its state was last read before a read failed (the result says which); look with `ios_screenshot` |
469
+ | `runner_not_started` | `NORACU_READ_ONLY=1` is set: observation-only mode does not start the runner (starting it puts the runner's app in front on the iPhone) — unset it to read the screen |
470
+ | `xctest_issue` | XCTest reported a failure while the command ran, or after an earlier one had answered. The test session is ended either way and the next call starts a new one. For an input that may have gone out the delivery is unknown; a command that was not run says `delivery=not_delivered`. Look with `ios_snapshot` before acting again |
471
+ | `app_not_running` / `app_not_foreground` | the app is not in front — `ios_launch` it first; nothing was sent |
472
+ | `no_keyboard` | no keyboard is up — tap a text field, or give `ios_type` an `element_index` |
473
+ | `type_not_confirmed` | the text was typed but the field that took it does not hold its old value with the text put in at one place (autocorrection or completion changed it, the field hides its value, part of the text was lost, or the text went to another field) — read the field before typing again |
474
+ | `launch_not_confirmed` | the app was started but is not in front after 10 s (a system prompt may cover it), or its state could not be read to the end of that wait — the result says which; `ios_screenshot` |
475
+ | `launch_failed` | `devicectl` / `simctl` refused (not installed, wrong bundle id) — nothing was sent |
476
+ | `ios_timeout` | the phone did not answer in time — delivery unknown, never re-sent; look before acting again |
477
+ | `runner_start_failed` / `runner_start_timeout` / `runner_version_mismatch` | the runner did not start (the message says why) — a version mismatch means the runner on the device was built by another noracu version (it names its build, and so does the message): run `ios-setup` again; `the runner that was stopped has not exited yet` means the last test session is still ending: try again in a moment |
@@ -28,17 +28,20 @@ import sys
28
28
  import tempfile
29
29
  import time
30
30
 
31
- from . import gestures, input, pointer, verify, vision
31
+ from . import gestures, input, pointer, screenrect, verify, vision
32
32
  from .vision import CaptureError
33
33
  import subprocess
34
34
 
35
- from .window import WindowError, ensure_frontmost, get_overlay, is_frontmost
35
+ from .window import WindowError, ensure_frontmost, get_overlay, get_window_info, is_frontmost
36
36
 
37
37
  # F31 / R13 §3: every phone input command starts in _require_live(), which probes
38
38
  # get_overlay() first so a paused or stopped mirror refuses without stealing focus,
39
39
  # then brings the mirror to the front (switching Spaces if needed and waiting for a
40
40
  # real frame) before any capture or input. Module-level callables so tests can swap them.
41
41
  _bring_front = ensure_frontmost
42
+ _screen_rect = verify.screen_rect # where the phone screen sits in the window (one capture); swappable in tests
43
+ _window_info = get_window_info # the mirror window's CGWindow record (its size keys the remembered edges); swappable in tests
44
+ _rect_file = None # where the screen's edges are remembered (None: screenrect.cache_file()); swappable in tests
42
45
  _is_front = is_frontmost
43
46
  sleep = time.sleep
44
47
 
@@ -66,12 +69,119 @@ _CAPTURE_FAILED_EXPECT_LINE = (
66
69
  )
67
70
 
68
71
 
72
+ # 2026-11-10: the same failure while measuring where the phone screen sits in the window, before a swipe
73
+ _CAPTURE_FAILED_EDGES_LINE = (
74
+ "capture_failed: could not read the iPhone Mirroring window's image to find the phone screen's edges "
75
+ "(it may be hidden, minimized or on another Space); nothing was sent"
76
+ )
77
+
78
+
69
79
  def _capture_failed() -> int:
70
80
  """Print the F25 capture-failure line; exit code 7."""
71
81
  print(_CAPTURE_FAILED_LINE, file=sys.stderr)
72
82
  return 7
73
83
 
74
84
 
85
+ def _phone_screen(*, retry_untrusted: bool):
86
+ """Where the phone screen sits in the mirror window as it is now: (rect or None, how).
87
+
88
+ Remembered per window size and macOS version (screenrect); the window is captured only when
89
+ nothing trusted is remembered for this size. Raises WindowError / CaptureError from that capture.
90
+ """
91
+ wi = _window_info()
92
+ if not wi:
93
+ raise WindowError("iPhone Mirroring window not found")
94
+ return screenrect.resolve(screenrect.key(wi["w"], wi["h"]), _screen_rect,
95
+ retry_untrusted=retry_untrusted, path=_rect_file)
96
+
97
+
98
+ _EDGES_UNTRUSTED = ("the window's image showed no strip above the screen, as it does while the pointer rests on "
99
+ "the window's top edge")
100
+ _EDGES_UNREADABLE = "the window's image could not be read"
101
+
102
+
103
+ _edges_note = "" # what a tap's result line adds when it went out with the screen's edges not known
104
+
105
+
106
+ def _refuse_off_screen(x: float, y: float, *, measure: bool) -> int | None:
107
+ """Refuse a tap or long press aimed at the mirror window's margin (exit 2); None lets it go on.
108
+
109
+ Called twice: first with measure=False, before the mirror is brought forward, from remembered
110
+ edges only (a refused point then takes no focus and makes no capture); then with measure=True,
111
+ once the mirror is live and in front, where the edges are measured if nothing is remembered.
112
+
113
+ When the measurement cannot be trusted (the pointer resting on the strip above the screen), a
114
+ point where the margin may be is refused as well — everything outside screenrect.fallback(): the
115
+ top of the window and a band along its other sides. The strip above the screen holds the
116
+ window's own controls, and a click there is a click on the Mac, not on the phone. Before a point
117
+ is refused on an untrusted measurement made earlier, the window is measured once more. A point
118
+ that goes out anyway says so in its result (_edges_note).
119
+
120
+ When nothing is remembered and the window's image cannot be read at all, nothing says where the
121
+ phone screen is: capture_failed (exit 7) and nothing is sent, as for a swipe. The same when the
122
+ window has no record once the mirror is live: without its size the bands cannot be measured.
123
+ """
124
+ global _edges_note
125
+ if measure:
126
+ _edges_note = ""
127
+ wi = None
128
+ try:
129
+ wi = _window_info()
130
+ if not measure:
131
+ rect = screenrect.remembered(screenrect.key(wi["w"], wi["h"]), path=_rect_file) if wi else None
132
+ if rect is None:
133
+ return None # nothing remembered: decided once the mirror is live and in front
134
+ elif not wi:
135
+ # the live check has just seen the window and now there is no record of it: nothing says where the
136
+ # phone screen is, and without the window's size the bands cannot be measured (pre-review P5)
137
+ raise WindowError("iPhone Mirroring window not found")
138
+ else:
139
+ rect, how = _phone_screen(retry_untrusted=False)
140
+ if rect is None and how == "not_measured":
141
+ safe = screenrect.fallback(wi["w"], wi["h"])
142
+ if safe is None or not screenrect.contains(safe, x, y):
143
+ # an earlier measurement could not be trusted and this point is where the margin may
144
+ # be: one more capture now, rather than a refusal on that old doubt
145
+ rect, how = _phone_screen(retry_untrusted=True)
146
+ except (WindowError, CaptureError):
147
+ if not measure:
148
+ return None
149
+ print(_CAPTURE_FAILED_EDGES_LINE, file=sys.stderr)
150
+ return 7
151
+ if rect is not None:
152
+ if screenrect.contains(rect, x, y):
153
+ return None
154
+ x0, y0, x1, y1 = rect
155
+ print(
156
+ f"out_of_screen: ({_num(x)},{_num(y)}) is on the iPhone Mirroring window's margin, not on the "
157
+ f"phone screen (x {x0:.3f}-{x1:.3f}, y {y0:.3f}-{y1:.3f}): a click there goes to the window's "
158
+ f"own controls or nowhere; nothing was sent",
159
+ file=sys.stderr,
160
+ )
161
+ return 2
162
+ safe = screenrect.fallback(wi["w"], wi["h"])
163
+ if safe is not None and screenrect.contains(safe, x, y):
164
+ _edges_note = (" — the phone screen's edges are not known; the point is clear of where the window's "
165
+ "margin may be")
166
+ return None
167
+ if safe is None:
168
+ print(
169
+ f"out_of_screen: the phone screen's edges are not known ({_EDGES_UNTRUSTED}) and the iPhone Mirroring window is too "
170
+ f"small to have a part that is certainly clear of its margin; nothing was sent",
171
+ file=sys.stderr,
172
+ )
173
+ return 2
174
+ x0, y0, x1, y1 = safe
175
+ print(
176
+ f"out_of_screen: ({_num(x)},{_num(y)}) may be on the iPhone Mirroring window's margin: the phone "
177
+ f"screen's edges are not known ({_EDGES_UNTRUSTED}), and while they are not, a point outside x {x0:.3f}-{x1:.3f}, "
178
+ f"y {y0:.3f}-{y1:.3f} is not sent — the strip above the screen holds the window's own controls; "
179
+ f"nothing was sent. Move the pointer off the top of the mirror window and try again, or aim further inside",
180
+ file=sys.stderr,
181
+ )
182
+ return 2
183
+
184
+
75
185
  def _mirror_not_live(overlay: dict) -> int:
76
186
  label = overlay.get("overlay") or "overlay shown"
77
187
  print(
@@ -201,14 +311,20 @@ def _cmd_status(_args) -> int:
201
311
 
202
312
 
203
313
  def _cmd_tap(args) -> int:
314
+ guard = _refuse_off_screen(args.x, args.y, measure=False)
315
+ if guard is not None:
316
+ return guard
204
317
  guard = _require_live()
318
+ if guard is not None:
319
+ return guard
320
+ guard = _refuse_off_screen(args.x, args.y, measure=True)
205
321
  if guard is not None:
206
322
  return guard
207
323
  guard = _require_expect(args)
208
324
  if guard is not None:
209
325
  return guard
210
326
  input.tap(args.x, args.y)
211
- print(f"tapped ({args.x}, {args.y})")
327
+ print(f"tapped ({args.x}, {args.y}){_edges_note}")
212
328
  return 0
213
329
 
214
330
 
@@ -223,7 +339,13 @@ def _cmd_longpress(args) -> int:
223
339
  input._check_duration(_longpress_duration(args), 0.01, 10, "long-press duration (s)")
224
340
  except ValueError as exc:
225
341
  return _invalid_duration(exc)
342
+ guard = _refuse_off_screen(args.x, args.y, measure=False)
343
+ if guard is not None:
344
+ return guard
226
345
  guard = _require_live()
346
+ if guard is not None:
347
+ return guard
348
+ guard = _refuse_off_screen(args.x, args.y, measure=True)
227
349
  if guard is not None:
228
350
  return guard
229
351
  guard = _require_expect(args)
@@ -231,7 +353,7 @@ def _cmd_longpress(args) -> int:
231
353
  return guard
232
354
  duration = _longpress_duration(args)
233
355
  input.long_press(args.x, args.y, duration)
234
- print(f"long-pressed ({args.x}, {args.y}) for {duration}s")
356
+ print(f"long-pressed ({args.x}, {args.y}) for {duration}s{_edges_note}")
235
357
  return 0
236
358
 
237
359
 
@@ -252,11 +374,108 @@ def _cmd_swipe(args) -> int:
252
374
  guard = _require_expect(args)
253
375
  if guard is not None:
254
376
  return guard
255
- input.swipe(args.fx, args.fy, args.tx, args.ty, args.ms)
256
- print(f"swiped ({args.fx},{args.fy}) -> ({args.tx},{args.ty})")
377
+ asked = (args.fx, args.fy, args.tx, args.ty)
378
+ try:
379
+ rect, _how = _phone_screen(retry_untrusted=True)
380
+ except (WindowError, CaptureError):
381
+ print(_CAPTURE_FAILED_EDGES_LINE, file=sys.stderr)
382
+ return 7
383
+ if rect is None:
384
+ # the capture could not tell the phone screen from the window's margin: both points are kept clear of
385
+ # where that margin may be (the top of the window holds its own controls: a drag from there acts on the
386
+ # window, not on the phone)
387
+ try:
388
+ wi = _window_info()
389
+ except (WindowError, CaptureError):
390
+ wi = None
391
+ if not wi:
392
+ # the window was there for the measurement and has no record now: nothing is sent (pre-review P5)
393
+ print(_CAPTURE_FAILED_EDGES_LINE, file=sys.stderr)
394
+ return 7
395
+ safe = screenrect.fallback(wi["w"], wi["h"])
396
+ if safe is None:
397
+ print("out_of_screen: the phone screen's edges are not known and the iPhone Mirroring window is too small to "
398
+ "have a part that is certainly clear of its margin; nothing was sent", file=sys.stderr)
399
+ return 2
400
+ fx, fy = input.clamp_to_rect(args.fx, args.fy, safe, inset=0.0)
401
+ tx, ty = input.clamp_to_rect(args.tx, args.ty, safe, inset=0.0)
402
+ if _collapsed(asked, (fx, fy, tx, ty)):
403
+ return _refuse_collapsed(asked)
404
+ input.swipe(fx, fy, tx, ty, args.ms)
405
+ print(_swipe_line(asked, (fx, fy, tx, ty), safe, known=False))
406
+ return 0
407
+ fx, fy = input.clamp_to_rect(args.fx, args.fy, rect)
408
+ tx, ty = input.clamp_to_rect(args.tx, args.ty, rect)
409
+ if _collapsed(asked, (fx, fy, tx, ty)):
410
+ return _refuse_collapsed(asked)
411
+ input.swipe(fx, fy, tx, ty, args.ms)
412
+ print(_swipe_line(asked, (fx, fy, tx, ty), rect))
257
413
  return 0
258
414
 
259
415
 
416
+ def _num(v: float) -> str:
417
+ return f"{round(v, 3):g}"
418
+
419
+
420
+ # A swipe whose points were moved clear of the margin and that is left shorter than this (in points of the
421
+ # 280x620 pt mirror window measured on 2026-11-10) is refused: iOS starts a pan only after about 10 pt, so a
422
+ # shorter drag lands as a tap or press on whatever is under it (review S4A-s10-gemini-1).
423
+ _MIN_MOVED_SWIPE_PT = 10.0
424
+ _REF_WINDOW_PT = (280.0, 620.0)
425
+
426
+
427
+ def _collapsed(asked, sent) -> bool:
428
+ """True when moving a point clear of the margin left the swipe too short to be a swipe: a press, not a
429
+ swipe — whatever length it was asked for with (a pull-down from the margin that ends just inside the
430
+ screen would otherwise go out as a tap at the top of the app). That covers a swipe whose two ends read
431
+ as the same point in the result line. A swipe that was not moved goes out as it was asked."""
432
+ moved = any(abs(p - q) > 1e-9 for p, q in zip(asked, sent))
433
+ if not moved:
434
+ return False
435
+ if (_num(sent[0]), _num(sent[1])) == (_num(sent[2]), _num(sent[3])):
436
+ return True
437
+ w, h = _REF_WINDOW_PT
438
+ return math.hypot((sent[2] - sent[0]) * w, (sent[3] - sent[1]) * h) < _MIN_MOVED_SWIPE_PT
439
+
440
+
441
+ def _refuse_collapsed(asked) -> int:
442
+ print(
443
+ f"out_of_screen: the swipe from ({_num(asked[0])},{_num(asked[1])}) to ({_num(asked[2])},{_num(asked[3])}) "
444
+ f"starts or ends on the iPhone Mirroring window's margin, or where it may be: with its points moved "
445
+ f"onto the phone screen it would be shorter than a swipe (under about {_MIN_MOVED_SWIPE_PT:g} pt) — a press, "
446
+ f"not a swipe; nothing was sent",
447
+ file=sys.stderr,
448
+ )
449
+ return 2
450
+
451
+
452
+ def _swipe_line(asked, sent, rect, known: bool = True) -> str:
453
+ """The phone_swipe result line; names every point that was moved. ``rect`` is the phone screen, or —
454
+ with known=False, while its edges are not known — the part of the window clear of where the margin may be."""
455
+ line = f"swiped ({_num(sent[0])},{_num(sent[1])}) -> ({_num(sent[2])},{_num(sent[3])})"
456
+ moved = [
457
+ f"{name} ({_num(a[0])},{_num(a[1])})"
458
+ for name, a, b in (("start", asked[:2], sent[:2]), ("end", asked[2:], sent[2:]))
459
+ if any(abs(p - q) > 1e-9 for p, q in zip(a, b))
460
+ ]
461
+ x0, y0, x1, y1 = rect
462
+ if not known:
463
+ what = (f"moved the {' and '.join(moved)} clear of where the window's margin may be, into x {x0:.3f}-{x1:.3f} "
464
+ f"y {y0:.3f}-{y1:.3f}" if moved else "both points are clear of where the window's margin may be")
465
+ return line + (
466
+ " (the phone screen's edges are not known: the window's image showed no strip above the "
467
+ f"screen, as it does while the pointer rests on the window's top edge; {what}; iOS cancels a "
468
+ "drag that starts or ends on the transparent window margin)"
469
+ )
470
+ if moved:
471
+ line += (
472
+ f" (moved the {' and '.join(moved)} inside the phone screen, x {x0:.3f}-{x1:.3f} "
473
+ f"y {y0:.3f}-{y1:.3f}: iOS cancels a drag that starts or ends on the transparent "
474
+ f"window margin around it)"
475
+ )
476
+ return line
477
+
478
+
260
479
  def _cmd_home(_args) -> int:
261
480
  guard = _require_live()
262
481
  if guard is not None:
@@ -531,6 +750,12 @@ def _open_deadline_kwargs(now=time.time) -> dict:
531
750
 
532
751
 
533
752
  def _cmd_open(args) -> int:
753
+ # a minimum that was meant to be on but cannot be read is not run without: said before anything is touched
754
+ problem = getattr(gestures, "OCR_MIN_CONFIDENCE_PROBLEM", None)
755
+ if problem is not None:
756
+ print(f"invalid_args: NORACU_OCR_MIN_CONFIDENCE is set to {str(problem)[:40]!r}, which is not a number above 0 "
757
+ f"and at most 1 — correct it or unset it; nothing was sent", file=sys.stderr)
758
+ return 2
534
759
  guard = _require_live()
535
760
  if guard is not None:
536
761
  return guard
@@ -543,6 +768,21 @@ def _cmd_open(args) -> int:
543
768
  return _open_and_report(args)
544
769
 
545
770
 
771
+ def _fmt_confidence(value) -> str:
772
+ return f"{value:.2f}" if isinstance(value, (int, float)) and not isinstance(value, bool) else "?"
773
+
774
+
775
+ def _confidence_note(report: dict) -> str:
776
+ """' (label read with confidence 0.90)' for phone_open's line; '' when open_app recorded none.
777
+ The opt-in minimum (NORACU_OCR_MIN_CONFIDENCE) is named when it is in force."""
778
+ conf = report.get("confidence")
779
+ if not isinstance(conf, (int, float)) or isinstance(conf, bool):
780
+ return ""
781
+ floor = report.get("min_confidence")
782
+ tail = f"; minimum {_fmt_confidence(floor)}" if floor is not None else ""
783
+ return f" (label read with confidence {_fmt_confidence(conf)}{tail})"
784
+
785
+
546
786
  def _open_and_report(args) -> int:
547
787
  tidy = {} # open_app records whether its trip back to the Home Screen worked
548
788
  try:
@@ -562,7 +802,7 @@ def _open_and_report(args) -> int:
562
802
  # phone is known — refuse rather than guess.
563
803
  return _capture_failed()
564
804
  if result == "opened":
565
- print(f"opened {args.app!r}")
805
+ print(f"opened {args.app!r}{_confidence_note(tidy)}")
566
806
  return 0
567
807
  # every unsuccessful path ends with a trip back to the Home Screen; say so only
568
808
  # when it worked
@@ -598,6 +838,12 @@ def _open_and_report(args) -> int:
598
838
  f"spot, so nothing was tapped; {home_note} — open it from its Home Screen icon "
599
839
  "instead (phone_screenshot, then phone_tap)", file=sys.stderr)
600
840
  return 4
841
+ if result == "low_confidence":
842
+ print(f"open_not_confirmed: Spotlight showed {args.app!r} but the label was read with "
843
+ f"confidence {_fmt_confidence(tidy.get('confidence'))}, below "
844
+ f"NORACU_OCR_MIN_CONFIDENCE={_fmt_confidence(tidy.get('min_confidence'))}, so "
845
+ f"nothing was tapped; {home_note}", file=sys.stderr)
846
+ return 4
601
847
  if result == "short_unreadable":
602
848
  print(f"open_not_confirmed: could not read {args.app!r} in Spotlight — OCR often misses a "
603
849
  "one- or two-letter name, in the Top Hit card and in the search field alike, so "
@@ -633,7 +879,7 @@ def _open_and_report(args) -> int:
633
879
  # "not_confirmed" (F24): the row — and possibly the Top Hit icon —
634
880
  # was tapped but the app never verifiably opened; the phone is
635
881
  # back on the Home Screen.
636
- print(f"open_not_confirmed: tapped {args.app!r} in Spotlight but the app did not open; {home_note}", file=sys.stderr)
882
+ print(f"open_not_confirmed: tapped {args.app!r} in Spotlight{_confidence_note(tidy)} but the app did not open; {home_note}", file=sys.stderr)
637
883
  return 4
638
884
 
639
885
 
@@ -610,6 +610,27 @@ def _tophit_labels(raw):
610
610
  TOP_HIT_LABELS = _tophit_labels(os.environ.get("NORACU_TOPHIT_LABELS"))
611
611
 
612
612
 
613
+ # NORACU_OCR_MIN_CONFIDENCE (opt-in, off by default): phone_open does not tap a label the
614
+ # recognizer read with a lower confidence than this. Unset or empty: no label is refused on its
615
+ # confidence. Set to anything but a number above 0 and at most 1 (text, 0, 90, nan): the person
616
+ # meant a check to be on and it cannot be, so phone_open refuses (cli._cmd_open) rather than run
617
+ # without it. → (minimum or None, the unusable text or None)
618
+ def _min_confidence(raw):
619
+ text = (raw or "").strip()
620
+ if not text:
621
+ return None, None
622
+ try:
623
+ value = float(text)
624
+ except ValueError:
625
+ return None, text
626
+ if math.isfinite(value) and 0.0 < value <= 1.0:
627
+ return value, None
628
+ return None, text
629
+
630
+
631
+ OCR_MIN_CONFIDENCE, OCR_MIN_CONFIDENCE_PROBLEM = _min_confidence(os.environ.get("NORACU_OCR_MIN_CONFIDENCE"))
632
+
633
+
613
634
  def _field_echo(hits, name) -> bool:
614
635
  """True when the search field shows ``name`` (F42).
615
636
 
@@ -834,7 +855,7 @@ def open_app(name: str, *, spotlight_open: bool = False,
834
855
  "deadline" (the OPEN_DEADLINE_S budget ran out before a tap; back on
835
856
  the Home Screen); "ambiguous" (Y6: the Top Hit card showed the name at
836
857
  two or more spots and no read showed it at one — nothing was tapped;
837
- back on the Home Screen); "focus_lost" (another app came to the front
858
+ back on the Home Screen); "low_confidence" (NORACU_OCR_MIN_CONFIDENCE is set and the label was read below it: nothing tapped; back on the Home Screen); "focus_lost" (another app came to the front
838
859
  during type_text's wait after the clipboard write: the paste was called
839
860
  off and nothing was tapped; Spotlight is left as it is — going Home
840
861
  would pull the mirror forward again); "clipboard_changed" (another app or
@@ -1012,6 +1033,13 @@ def open_app(name: str, *, spotlight_open: bool = False,
1012
1033
  if out_of_time():
1013
1034
  tidy()
1014
1035
  return "deadline"
1036
+ if report is not None:
1037
+ # how sure the recognizer was of the label about to be tapped, and the opt-in minimum
1038
+ report["confidence"] = hit.confidence
1039
+ report["min_confidence"] = OCR_MIN_CONFIDENCE
1040
+ if OCR_MIN_CONFIDENCE is not None and not (hit.confidence >= OCR_MIN_CONFIDENCE):
1041
+ tidy()
1042
+ return "low_confidence" # opt-in: a label read below the minimum is not tapped
1015
1043
  # ② tap the row (the label inside the Top Hit card) and confirm.
1016
1044
  # The post-tap read uses reread(): for a short name it also sweeps,
1017
1045
  # so ③ can find the label again (F32/F35).
@@ -1026,7 +1054,12 @@ def open_app(name: str, *, spotlight_open: bool = False,
1026
1054
  # card NOW (choose_app_hit, F35) — never the first read's position:
1027
1055
  # the results may have changed. No such label → no second tap.
1028
1056
  again = choose_app_hit(hits, name)
1057
+ if (again is not None and OCR_MIN_CONFIDENCE is not None
1058
+ and not (again.confidence >= OCR_MIN_CONFIDENCE)):
1059
+ again = None # opt-in: no second tap aimed at a label read below the minimum
1029
1060
  if again is not None and not out_of_time():
1061
+ if report is not None:
1062
+ report["confidence"] = again.confidence
1030
1063
  opened, _ = _tap_and_confirm_open(
1031
1064
  again.nx, again.ny - SPOTLIGHT_ICON_ABOVE_LABEL,
1032
1065
  luma=luma, sleep=sleep, tap=tap, read_screen=reread, name=name)
@@ -232,6 +232,20 @@ def long_press(nx: float = 0.5, ny: float = 0.5, duration_s: float = LONG_PRESS_
232
232
  _mouse_event(kCGEventLeftMouseUp, x, y, src)
233
233
 
234
234
 
235
+ # 2026-11-10: every point of a phone_swipe stays this far inside the phone screen (verify.screen_rect),
236
+ # in window units (0.01 is about 6 pt of a 620 pt window), because iOS cancels a drag that starts or
237
+ # ends on the transparent window margin around the screen.
238
+ SCREEN_INSET = 0.01
239
+
240
+
241
+ def clamp_to_rect(nx: float, ny: float, rect, inset: float = SCREEN_INSET) -> tuple[float, float]:
242
+ """Move (nx, ny) to the nearest point at least `inset` inside rect = (x0, y0, x1, y1)."""
243
+ x0, y0, x1, y1 = rect
244
+ if x1 - x0 <= 2 * inset or y1 - y0 <= 2 * inset:
245
+ raise ValueError(f"phone screen rect too small to swipe in: {rect!r}")
246
+ return (min(max(nx, x0 + inset), x1 - inset), min(max(ny, y0 + inset), y1 - inset))
247
+
248
+
235
249
  def _ease_in_out(t: float) -> float:
236
250
  """Quadratic ease-in-out: slow start, fast middle, slow end."""
237
251
  if t < 0.5: