noracu 0.2.4 → 0.2.5

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,74 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.5] — 2026-11-07
4
+
5
+ ### Changed
6
+ - `phone_scroll` that changed the screen is reported `delivered_unverified`
7
+ instead of `delivered_verified`: a changed screen is all it sees, and a
8
+ notification or an animation changes the screen too. Take
9
+ `phone_screenshot` to see where the list is. `scroll_no_effect` is
10
+ unchanged.
11
+ - `phone_type` is `delivered_verified` only when OCR sees the typed text at a
12
+ spot where it was not before the paste, below the strip at the top where the
13
+ status bar and notification banners are drawn. A rise in how often the text
14
+ shows anywhere on screen (a banner carrying the same words, a label
15
+ elsewhere) no longer confirms the paste, and no longer licenses putting the
16
+ user's clipboard back. Text that shows up only after the 2.5 s window is
17
+ `delivered_unverified`, and the result no longer says the paste landed: in
18
+ a device test a second paste of the same text into the Settings search
19
+ field was "seen late" while the field still showed the text once. The
20
+ clipboard keeps the typed text. One character that OCR saw appear is
21
+ `delivered_unverified` and no longer puts the user's clipboard back. A text
22
+ of two or three characters (spaces and case aside) is never confirmed by a
23
+ sighting — "in" is part of "Sign in" — so it is `delivered_unverified` and
24
+ leaves the typed text on the clipboard.
25
+ - `mac_scroll` without `element_index` scrolls at the center of the
26
+ frontmost app's front window on screen, and only when that app's window is
27
+ on top at that point — otherwise it reports `occluded` (or `no_window`) and
28
+ scrolls nothing. Before, the pointer went to the first window System Events
29
+ named, or stayed wherever it was when that lookup failed.
30
+ - `phone_open` taps nothing when Spotlight's Top Hit card shows the app name
31
+ at two or more different spots: it reports `open_not_confirmed` and goes
32
+ back to the Home Screen. Before, it tapped the topmost one.
33
+
34
+ ### Fixed
35
+ - `mac_paste` sends ⌘V as the V key (key code 9) with ⌘ held, posted by the
36
+ accessibility engine, instead of cliclick's `kd:cmd t:v ku:cmd`. On macOS
37
+ 27.2 with the Pinyin keyboard layout, cliclick's version reached TextEdit as
38
+ nothing, or as a plain "v" typed into the document, so `mac_paste` reported
39
+ `delivered_unverified` and the text was never pasted. Under a Dvorak layout,
40
+ where key code 9 is K, `mac_paste` now refuses (`not_delivered`) instead of
41
+ sending ⌘K; "Dvorak - QWERTY ⌘" layouts are fine. `mac_paste` no longer needs
42
+ cliclick.
43
+ - A point under the Dock no longer counts as the window behind it. On macOS
44
+ 27.2 (the version tested) the Dock is one full-display window that lets
45
+ clicks through, and the check of which window is on top skipped it, so
46
+ `mac_scroll` without `element_index` scrolled a window whose center was
47
+ under the Dock, and a `mac_click` at x,y there would have been sent. The
48
+ strip each display keeps for the Dock (its whole width, the gaps beside the
49
+ icons included) now counts as covered by the Dock: `occluded`, nothing
50
+ sent. The same check guards physical clicks and drags on an element.
51
+ - While a notification banner shows, a point away from it is no longer
52
+ `occluded` by Notification Center. On macOS 27.2 Notification Center then
53
+ keeps a full-display window above everything, and every raw click, drag or
54
+ scroll anywhere on the screen was refused until the banner left. Now only
55
+ the banner's or alert's own frame (read through accessibility, plus a small
56
+ margin) counts as covered; when those frames cannot be read, or the
57
+ notification list is open, the whole screen still counts as covered.
58
+
59
+ ### Docs
60
+ - SECURITY.md opens with what noracu hands to your model and what it can
61
+ reach — text returned to the model, the clipboard, privacy-consent and
62
+ authorization dialogs, secrets an app displays, browser cookies, the iPhone
63
+ Mirroring session — with who receives each and what noracu does and does
64
+ not do, plus its boundaries: macOS permissions belong to the host app,
65
+ noracu does not constrain the host's own shell, and tool annotations
66
+ restrict nothing. New threat 18 covers the clipboard on the phone path: the
67
+ iPhone fetches a paste late, so `phone_type` puts the clipboard back only on
68
+ screen evidence. The iPhone Mirroring row notes that the mirror delivers
69
+ pointer input, not touches (Apple TN3210), so swiping in from the left edge
70
+ to go back does nothing through it.
71
+
3
72
  ## [0.2.4] — 2026-11-07
4
73
 
5
74
  ### Changed
package/README.md CHANGED
@@ -49,7 +49,7 @@ First success is `mac_ax_state` (or a browser snapshot) — not a click, and not
49
49
 
50
50
  ```bash
51
51
  npm install noracu # server at node_modules/noracu/src/server.mjs
52
- brew install cliclick # needed for physical Mac input (mac_key, mac_paste, mac_drag, and physical mac_click/mac_type)
52
+ brew install cliclick # needed for physical Mac input (mac_key, mac_drag, and physical mac_click/mac_type)
53
53
  ```
54
54
 
55
55
  Or from source: `git clone https://github.com/sgInnora/noracu.git && cd noracu && npm install && npm test` (add `NORACU_CI=1` to skip hardware-gated checks).
package/README.zh-CN.md CHANGED
@@ -49,7 +49,7 @@ noracu 是本地的"手",不是"脑"。决策由你的 MCP client(Claude Des
49
49
 
50
50
  ```bash
51
51
  npm install noracu # server 位于 node_modules/noracu/src/server.mjs
52
- brew install cliclick # 物理 Mac 输入所需(mac_key、mac_paste、mac_drag 及物理路径的 mac_click/mac_type)
52
+ brew install cliclick # 物理 Mac 输入所需(mac_key、mac_drag 及物理路径的 mac_click/mac_type)
53
53
  ```
54
54
 
55
55
  或从源码:`git clone https://github.com/sgInnora/noracu.git && cd noracu && npm install && npm test`(加 `NORACU_CI=1` 可跳过依赖硬件的检查)。
package/SECURITY.md CHANGED
@@ -4,12 +4,44 @@ noracu gives an MCP client control over your **real machine** — mouse,
4
4
  keyboard, clipboard, browser, and (via iPhone Mirroring) your phone.
5
5
  Treat every tool call as privileged.
6
6
 
7
+ ## What noracu hands to your model, and what it can reach
8
+
9
+ noracu acts inside your real, logged-in session. It does not sandbox what it
10
+ touches, and it does not sanitize, filter or rate what it observes: the MCP
11
+ client and its model decide what to do with every result. The threat table
12
+ below has the per-tool detail.
13
+
14
+ | Asset | How noracu touches it | Who receives it | What noracu does and does not do |
15
+ |---|---|---|---|
16
+ | Text returned to the model — AX values and titles, ARIA snapshots, page text, iPhone OCR, screenshots | Every observation tool returns it as read | The MCP client and its model provider | Not sanitized or filtered. A web page, document, message or notification can carry instructions aimed at the model; treat every result as untrusted data (threat 11) |
17
+ | Clipboard | `mac_paste`, `phone_type` and `phone_open` put the text on the Mac clipboard and paste it | Apps on the Mac; the iPhone, which fetches the paste from the Mac clipboard through iPhone Mirroring | `mac_paste` sets every item aside and puts it back once the paste shows, but not while the app does not answer — then the pasted text stays on the clipboard (threat 10). The iPhone fetches a paste late, from whatever the Mac clipboard holds at that moment, so `phone_type` puts the clipboard back only on screen evidence and otherwise leaves the typed text on it; `phone_open` never puts it back (threat 18). Items a password manager marks concealed are never copied |
18
+ | macOS privacy-consent prompts and administrator authorization dialogs | A synthesized click or keystroke can be aimed at them like any other window | — | noracu does not recognize these dialogs or refuse input to them, and whether macOS accepts a synthesized click on each of them has not been measured. Keep a person present for any run that may raise one |
19
+ | Secrets an app displays (Keychain items an app shows, passwords shown in clear, one-time codes) | AX reads, OCR and screenshots read what is on screen | The model provider | Reading is not blocked. `mac_set_value` never echoes a value in a secure text field, and concealed clipboard items are never returned (threat 16) |
20
+ | Browser cookies | The browser layer keeps one persistent Playwright profile at `~/.noracu/browser-profile` | Every site the browser opens; page text goes to the model | Not isolated between runs; clear the profile between untrusted runs |
21
+ | iPhone Mirroring session | Phone tools see and act through the iPhone Mirroring window | The model sees the phone screen, including notifications, messages and codes | Biometric authentication requests fail during iPhone Mirroring by default (Apple TN3210), but a Mac set to authenticate automatically gives anyone at the unlocked Mac the phone (threats 6, 12). Input reaches iOS as indirect pointer events, not touches (TN3210), so a touch-only system gesture such as swiping in from the left edge to go back does nothing through the mirror — that is the mirror's behaviour, not a noracu fault |
22
+
23
+ Boundaries:
24
+
25
+ - macOS grants Accessibility and Screen Recording to the host app that starts
26
+ noracu (Claude Desktop, Cursor, a terminal), not to noracu. Whether macOS
27
+ attributes events from helper binaries such as `cliclick` and `python3`
28
+ separately is unverified.
29
+ - noracu does not constrain the host's own shell or file tools. Blocking an
30
+ app inside noracu would not stop a host that can run commands, so noracu
31
+ keeps no such list.
32
+ - Tool annotations (`readOnlyHint`, `destructiveHint`, `idempotentHint`,
33
+ `openWorldHint`) are hints for the client and restrict nothing.
34
+ `NORACU_READ_ONLY=1`, `NORACU_DISABLE_EVAL=1` and the opt-in `NORACU_ALLOW_*`
35
+ variables are what the server enforces.
36
+ - No telemetry and no network use at run time, except the one-time Playwright
37
+ Chromium download, which `NORACU_DISABLE_AUTO_INSTALL=1` turns off.
38
+
7
39
  ## Threat model
8
40
 
9
41
  | # | Threat | Vector | Status | Mitigation / notes |
10
42
  |---|---|---|---|---|
11
43
  | 1 | **Prompt injection → arbitrary code execution** | Observed content (web page text, AX tree titles, OCR output) contains instructions that trick the agent into calling tools with malicious arguments | **Mitigated** | The Mac accessibility engine `src/mac-ax.js` is a static script that takes its whole request as JSON on stdin — parameters are data, never script source (regression-tested in `test/e2e.mjs`); the remaining inline JXA (scroll wheel) takes clamped numbers through argv |
12
- | 2 | **Arbitrary local control** | `mac_click` / `mac_type` / `mac_paste` can operate password managers, banking pages, terminals | **Inherent** | Use client-side confirmation gates for high-stakes targets; see recommendations below. Optional `app` focus guard on `mac_paste` / `mac_key` (and `mac_type` keystrokes) refuses input unless that app — compared by process, not by name — is frontmost; `mac_type` keystrokes after a click on an `element_index` go out only if the element's app is then frontmost. An `element_index` is re-identified inside the window it came from (by CGWindowID) before any action, and a physical click or drag (both ends) is sent only when a hit test shows the point reaches the element, or — when the hit test is inconclusive — when the topmost on-screen window at the point is that same window (by CGWindowID, not covered by another window of the same app; `occluded` otherwise). Right before a physical click or drag is sent, the window on top at each point is checked again (by CGWindowID); afterwards a physical click counts as `delivered_verified` only if the element is still there, changed, and its own window is still on top at the click point. An element read with `surface: "app"` is bound to its window's CGWindowID, and an element in a window without a CGWindowID (other than Finder's desktop) is refused with `policy_denied`. A `mac_click` at raw x,y is sent only when the topmost on-screen window at the point belongs to `app` (default: the frontmost app; the menu bar counts as the frontmost app's), unless `force: true`; a short gap remains between that check and the click. `mac_key` refuses quit / log-out / lock / force-quit / delete-immediately / empty-Trash chords without `force`; `mac_menu_command` applies the same chord list, refuses Apple-menu items without `force`, and never quits the MCP host or a session process. |
44
+ | 2 | **Arbitrary local control** | `mac_click` / `mac_type` / `mac_paste` can operate password managers, banking pages, terminals | **Inherent** | Use client-side confirmation gates for high-stakes targets; see recommendations below. Optional `app` focus guard on `mac_paste` / `mac_key` (and `mac_type` keystrokes) refuses input unless that app — compared by process, not by name — is frontmost; `mac_type` keystrokes after a click on an `element_index` go out only if the element's app is then frontmost. An `element_index` is re-identified inside the window it came from (by CGWindowID) before any action, and a physical click or drag (both ends) is sent only when a hit test shows the point reaches the element, or — when the hit test is inconclusive — when the topmost on-screen window at the point is that same window (by CGWindowID, not covered by another window of the same app; `occluded` otherwise). Right before a physical click or drag is sent, the window on top at each point is checked again (by CGWindowID); afterwards a physical click counts as `delivered_verified` only if the element is still there, changed, and its own window is still on top at the click point. An element read with `surface: "app"` is bound to its window's CGWindowID, and an element in a window without a CGWindowID (other than Finder's desktop) is refused with `policy_denied`. A `mac_click` at raw x,y is sent only when the topmost on-screen window at the point belongs to `app` (default: the frontmost app; the menu bar counts as the frontmost app's, and the strip a display keeps for the Dock counts as the Dock's; Notification Center's full-display overlay counts only over a banner or alert it draws, or everywhere when their frames cannot be read), unless `force: true`; a short gap remains between that check and the click. `mac_key` refuses quit / log-out / lock / force-quit / delete-immediately / empty-Trash chords without `force`; `mac_menu_command` applies the same chord list, refuses Apple-menu items without `force`, and never quits the MCP host or a session process. |
13
45
  | 3 | **Arbitrary JS in browser** | `browser_evaluate` executes any JavaScript in the page context | **Partially mitigated** | Set `NORACU_DISABLE_EVAL=1`; `browser_evaluate` then returns an error on every call (it stays listed in `tools/list`) |
14
46
  | 4 | **Input validation gaps** | Malformed arguments (NaN coordinates, oversized strings, `javascript:` URLs) | **Mitigated** | `validateArgs` validates every tool's arguments (types, ranges, enums, string lengths, URL schemes) before any subprocess runs; `tools/list` emits `required` arrays derived from non-optional arguments |
15
47
  | 5 | **Screenshot privacy** | `mac_screenshot` / `phone_screenshot` capture the full screen / phone display | **Inherent** | Run in a dedicated macOS user account or virtual display for untrusted automation. `NORACU_READ_ONLY=1` prevents side effects (and skips `enableWebAccessibility` on apps), not screen secrecy: `mac_screenshot` still shows visible notification banners on screen, and Notification Center accessibility reads via `mac_ax_state` / `mac_find` are not blocked by bundle id |
@@ -24,6 +56,7 @@ Treat every tool call as privileged.
24
56
  | 15 | **DevTools port exposure** | `mac_app` launch with `cdp_port` opens a Chromium/Electron app's remote-debugging port on `127.0.0.1` (no per-user isolation); any local process can then control that app | **Partially mitigated** | Off unless `NORACU_ALLOW_CDP=1` (or `=any`); `browser_launch` with `cdp_port` is refused under `NORACU_READ_ONLY=1` even with `NORACU_ALLOW_CDP` set; bound to `127.0.0.1`; only for a fresh launch after canonicalizing `.app` paths (`realpath`, trailing slash stripped — a running app is refused, never quit for you); with `NORACU_ALLOW_CDP=1`, `browser_launch` attaches only when the port was recorded by this `noracu` process, its PID is still alive, and `/json/version`'s `webSocketDebuggerUrl` matches (attaching to any other loopback port requires `NORACU_ALLOW_CDP=any`); `~/.noracu` and `cdp-profiles` are created `0700`; Chrome-family browsers get a separate profile under `~/.noracu/cdp-profiles`; standalone `browser_launch` is refused while a CDP session is open; the port closes when the app quits |
25
57
  | 16 | **Clipboard and notification content** | `mac_clipboard_read` / `mac_notifications` return clipboard text, images, file paths and notification text to the model | **Partially mitigated** | Items marked `org.nspasteboard.ConcealedType` (password managers) are never returned; `mac_clipboard_read`, `mac_notifications`, and `mac_wait` with `condition: "notification"` are refused under `NORACU_READ_ONLY=1` (`NORACU_READ_ONLY=1` prevents side effects, not screen secrecy: `mac_screenshot` still shows visible notification banners and Notification Center AX reads are not blocked by bundle id); notification actions reject empty `id` / `expected_app` / `expected_title`, return `notification_not_found` when absent, and require an id or an index plus a re-checked app/title fingerprint; `mac_set_value` on `AXSecureTextField` never echoes the value |
26
58
  | 17 | **Text in process arguments** | Text sent as keystrokes (`mac_type` physical path: `cliclick t:…`) is visible in the process list while it runs | **Partially mitigated** | The accessibility path (`mac_type` default, `mac_set_value`), `mac_paste`, and `phone_type` / `phone_find` / `phone_open` (imctl reads the text from stdin) pass text on stdin, and `mac_set_value` on `AXSecureTextField` and `imctl type` never echo typed text; only the keystroke fallback uses argv. A phone call's `expect` text is still an argument |
59
+ | 18 | **Clipboard on the phone path** | `phone_type` / `phone_open` paste through the Mac clipboard; iPhone Mirroring fetches the paste asynchronously, sometimes more than 10 s after ⌘V, from whatever the clipboard holds then, so putting the user's clipboard back too early could paste it into the phone | **Partially mitigated** | `phone_type` copies every clipboard item aside and puts them back only on screen evidence read within its 2.5 s check while no "Pasting from" progress box shows: OCR sees the text at a new spot below the status-bar strip in two reads. A text of one to three characters (spaces and case aside) never licenses it, and neither does a paste seen only later. An item marked concealed or transient is never copied (the clipboard is cleared instead). Without that evidence the typed text stays on the clipboard and the result says so. An error before ⌘V is sent restores the clipboard; an error once ⌘V may be on its way never does. `phone_open` never restores it. Remaining: the user's previous clipboard is lost whenever the evidence is missing; Universal Clipboard content and clipboards over 64 MB are not copied, so they are replaced by the typed text |
27
60
  | 11 | **Untrusted observation content** | ARIA snapshots, AX trees, OCR, page text contain attacker-controlled text | **Not mitigated** | The MCP client must treat tool results as data, never as instructions |
28
61
 
29
62
  ## Hardening recommendations
@@ -28,7 +28,7 @@ Accessibility goes through `src/mac-ax.js`, a static JXA script run as `osascrip
28
28
  | `mac_scroll` | no index: wheel event at the frontmost window; scroll area: wheel event at its center (hit-tested); other element: `AXScrollToVisible` |
29
29
  | `mac_drag` | `cliclick` dd/dm/du between `from_index` and `to_index` (no raw coordinates); both ends are re-identified and hit-tested |
30
30
  | `mac_key` | named keys (return, esc, tab, space, delete, arrows, home/end, page keys, F1–F16), with or without modifiers: engine `key` — `CGEventPost` at the HID tap from a HID-state source, each modifier pressed and released (flags-changed events) around the key, flags always set explicitly, and any modifier the call pressed that the system still reports held released once more; character chords (`cmd-c`): `cliclick` kd/t/ku. Quit / log-out / lock / force-quit / delete-immediately / empty-Trash chords need `force` |
31
- | `mac_paste` | one engine call (`opPaste`): focus guard, clipboard items copied aside in-process, text written (transient), ⌘V via `cliclick` (NSTask, argv), restore after evidence or a 1 s hold, guarded by the change count |
31
+ | `mac_paste` | one engine call (`opPaste`): focus guard, clipboard items copied aside in-process, text written (transient), ⌘V posted as key code 9 with the ⌘ modifier (refused under a Dvorak layout), restore after evidence or a 1 s hold, guarded by the change count |
32
32
  | `mac_menu_command` | engine `menu`: `AXPress` on the item found by title or `Menu > Item` path in the app's own menu bar; Apple-menu items and refused shortcut chords need `force`, and session processes or the MCP host are never quit |
33
33
  | `mac_wait` | engine `wait`: polls a window / text / element / menu / sheet / app / notification condition (`notification` refused under `NORACU_READ_ONLY=1`) every 250 ms inside one process |
34
34
  | `mac_app` | `open` for launch / activate; `NSRunningApplication` hide / unhide / terminate / forceTerminate; quit is verified by the pid ending. `cdp_port`: `open -n -a … --args --remote-debugging-port=… --remote-debugging-address=127.0.0.1` |
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. Hints are the four MCP tool annotations each tool reports — R read-only, D destructive, I idempotent, O open-world, – false — hints for the client, not permissions.
4
- > noracu v0.2.4 · 46 tools
4
+ > noracu v0.2.5 · 46 tools
5
5
 
6
6
  ## Mac layer (computer-use)
7
7
 
@@ -13,7 +13,7 @@
13
13
  | `mac_ax_state` | app:string?, interactive:boolean?, compact:boolean?, skeleton:boolean?, root:integer?, snapshot_id:string?, surface:string?, window:string?, window_id:integer?, depth:number?, max_nodes:integer?, web_accessibility:boolean? | R – I O | Read an app's accessibility tree through the macOS Accessibility API (default: the frontmost app's focused window). Returns {app, snapshot_id, window, complete, elements:[{i, d, role, title, value, states, actions, frame}]}; i is the element_index for mac_click, mac_get, mac_set_value, mac_type, mac_scroll and mac_drag — unique across snapshots (an index never names an element of a later snapshot) and valid 30 s; an action first re-identifies the element and returns element_no_longer_valid if it is gone, moved or replaced. Options: interactive (only actionable elements), compact (default true: skip empty layout wrappers), skeleton (shallow map with children_count) then root (an element_index to drill into; adds new indexes to the same snapshot), surface (window\|menubar\|menu\|sheet\|alert\|dialog\|popover\|focused\|app), window (index or title) or window_id (from mac_windows), depth (logical depth, default 12, 1-40), max_nodes (default 400), web_accessibility (default true, false under NORACU_READ_ONLY=1: sets AXManualAccessibility on Electron/Chromium apps to expose web content, never AXEnhancedUserInterface which alters window behaviour; the result's web_accessibility is enabled / already_on, exposed when the app refused but its pages are in the tree anyway, or unsupported with a web_accessibility_hint — Google Chrome refuses it). window_identity unverifiable marks a window without a window ID: element_index actions in it are refused. ax_empty when the app has no readable window. |
14
14
  | `mac_click` | element_index:integer?, snapshot_id:string?, x:number?, y:number?, app:string?, force:boolean?, button:string?, count:number?, mechanism:string?, timeout_ms:integer? | – – – O | Click a UI element by element_index (from mac_ax_state / mac_find; valid 30 s) or at raw {x,y}. With element_index the element is re-identified first (element_no_longer_valid if gone or changed). mechanism auto (default): its own accessibility action (press / show menu / select — no pointer, no focus change, works in background windows) when it has one, else a physical click that is sent only if a hit test shows the point reaches the element (occluded otherwise); semantic / physical force one path. count 2-3 and button middle are physical. A physical click is re-checked right before it is sent, and is delivered_verified only if the element is still there, changed, and its window is still on top at the point. A raw {x,y} click is sent only when the window on top at that point belongs to app (default: the frontmost app; the menu bar counts as the frontmost app's) — otherwise occluded names what covers it and nothing is sent; force:true skips that check. Results state delivery (delivered_verified / delivered_unverified / not_delivered / unknown) and whether a retry is safe, plus newly opened sheets, dialogs or menus. |
15
15
  | `mac_drag` | **from_index**:integer, **to_index**:integer, snapshot_id:string? | – – – O | Drag from one UI element to another (sliders, selections, list items) with the physical pointer; from_index/to_index come from mac_ax_state or mac_find (valid 30 s). Both ends are re-identified and hit-tested first (either one gone or covered: nothing sent). Check the drop target afterwards. |
16
- | `mac_scroll` | direction:string?, pages:number?, element_index:integer?, snapshot_id:string? | – – – O | Scroll up/down/left/right by a number of pages (default 1). Without element_index: the frontmost window (the pointer moves there). With element_index: a scroll area is scrolled at its own center (hit-tested; reports when the position did not change), any other element is scrolled into view (AXScrollToVisible). |
16
+ | `mac_scroll` | direction:string?, pages:number?, element_index:integer?, snapshot_id:string? | – – – O | Scroll up/down/left/right by a number of pages (default 1). Without element_index: the center of the frontmost app's front window (the pointer moves there), only when that app's window is on top at that point (else occluded, nothing scrolled). With element_index: a scroll area is scrolled at its own center (hit-tested; reports when the position did not change), any other element is scrolled into view (AXScrollToVisible). |
17
17
  | `mac_key` | **key**:string, app:string?, force:boolean? | – D – O | Press a key or modifier chord, e.g. 'return', 'esc', 'cmd-c', 'cmd-shift-v', 'arrow-up'. Named keys (return, esc, tab, space, delete, arrows, home/end, page keys, F1-F16), with or without modifiers, go out as HID key events with each modifier pressed and released around the key; chords on a character key (cmd-c) go through cliclick. Pass app to refuse input unless that app is frontmost (focus guard). Chords that quit, log out, lock, force-quit, delete immediately or empty the Trash (cmd-q, alt-cmd-q, cmd-shift-q, cmd-alt-esc, ctrl-cmd-q, cmd-alt-delete, cmd-shift-delete…) are refused unless force:true. |
18
18
  | `mac_type` | **text**:string, element_index:integer?, snapshot_id:string?, app:string?, replace:boolean?, mechanism:string?, timeout_ms:integer? | – – – O | Type text into element_index, or into the focused element (of app, if given). mechanism auto (default): inserted through accessibility at the caret (AXSelectedText) — IME-safe, clipboard untouched, works in a background app; delivered_verified only when the value reads back as exactly the old value with the text over the selection that was there (unreadable caret: delivered_unverified). replace:true sets the whole value instead (already that text: nothing sent). If the focused element takes no text through accessibility, auto falls back to physical keystrokes (not IME-safe; app is then a focus guard: refused unless that app is frontmost). mechanism physical forces keystrokes (clicking element_index first). |
19
19
  | `mac_paste` | **text**:string, app:string?, force:boolean? | – – – O | Paste text with Cmd+V through the clipboard, then put the user's clipboard back: every item and type is copied aside and restored within one call, only after the paste shows in the focused element (else after a 1 s hold) and only if nothing else wrote to the clipboard meanwhile — not while the app does not answer, so a late paste cannot insert the user's own clipboard; delivered_verified only when the focused field's value becomes exactly the text pasted over its selection; a password manager's concealed item is never copied — the clipboard is cleared after the paste instead. The pasted text is marked transient for clipboard managers. Pass app to refuse input unless that app is frontmost (focus guard). Refused when the clipboard holds Universal Clipboard content or more than 64 MB (force:true pastes anyway and leaves the pasted text on the clipboard). mac_type does not touch the clipboard. |
@@ -65,8 +65,8 @@
65
65
  | `phone_swipe` | **from**:array, **to**:array, ms:number?, expect:string? | – – – O | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Swipe (mouse drag) from [x,y] to [x,y] over an optional duration in ms; to move a list use phone_scroll. The mirror delivers a drag as pointer input, so a swipe that starts on an app icon picks the icon up and moves it (it can rearrange the Home Screen or make a folder): page the Home Screen from the empty strip just above the Dock (y about 0.80), never across the icon rows. Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed. Optional expect: text that must be on screen (OCR) first, else nothing is sent. Reports delivery and retry. |
66
66
  | `phone_home` | — | – – – O | EXPERIMENTAL. Send the Home Screen command via the iPhone Mirroring menu (works without python/pyobjc on English macOS while the mirror is live), falling back to an imctl swipe (needs python/pyobjc) only when that English menu item is absent (non-English macOS). Reports only that the command or gesture was sent — nothing on the iPhone screen is verified; refuses with mirror_not_live or mirror_state_unknown (or menu_unknown on timeout) when the mirror is not live or its state cannot be confirmed. Reports delivery and retry. |
67
67
  | `phone_app_switcher` | — | – – – O | EXPERIMENTAL. Send the App Switcher command via the iPhone Mirroring menu (works without python/pyobjc on English macOS while the mirror is live), falling back to an imctl gesture (needs python/pyobjc) only when that English menu item is absent (non-English macOS). Reports only that the command or gesture was sent — nothing on the iPhone screen is verified; refuses with mirror_not_live or mirror_state_unknown (or menu_unknown on timeout) when the mirror is not live or its state cannot be confirmed. Reports delivery and retry. |
68
- | `phone_scroll` | direction:string?, distance:number?, expect:string? | – – – O | 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. Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed; 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. Reports delivery and retry. |
69
- | `phone_type` | **text**:string, replace:boolean?, expect:string? | – – – O | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Type text via the clipboard (IME-safe; never echoes the typed text). Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed. Saves every clipboard item and type, clearing concealed or transient items instead of copying, and restores only after OCR sees the text appear within its 2.5 s check (Universal Clipboard or >64 MB items are not copied and leave the typed text on the clipboard; a paste confirmed late or type_not_confirmed also leaves the typed text on the clipboard). replace=true selects all and overwrites the field. Optional expect: on-screen text (OCR), else nothing is sent. Reports delivery and retry. |
68
+ | `phone_scroll` | direction:string?, distance:number?, expect:string? | – – – O | 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. Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed; reports scroll_no_effect when the screen did not change (list end, or the view does not scroll); a scroll that changed the screen is delivered_unverified, since a notification or an animation changes it too — take phone_screenshot to see where the list is. Optional expect: text that must be on screen (OCR) first, else nothing is sent. Reports delivery and retry. |
69
+ | `phone_type` | **text**:string, replace:boolean?, expect:string? | – – – O | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Type text via the clipboard (IME-safe; never echoes the typed text). Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed. Saves every clipboard item and type, clearing concealed or transient items instead of copying, and restores only after OCR sees the text appear within its 2.5 s check at a spot where it was not before, below the status bar and notification strip — only that sighting makes the result delivered_verified (Universal Clipboard or >64 MB items are not copied and leave the typed text on the clipboard; a text under four characters, spaces and case aside, a paste seen only after the 2.5 s check, and type_not_confirmed are never verified and also leave the typed text on the clipboard). replace=true selects all and overwrites the field. Optional expect: on-screen text (OCR), else nothing is sent. Reports delivery and retry. |
70
70
  | `phone_key` | **key**:string, expect:string? | – – – O | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Press a key: return, delete, up, down, left, or right. Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed. Optional expect: text that must be on screen (OCR) first, else nothing is sent. Reports delivery and retry. |
71
- | `phone_open` | **app**:string | – – – O | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed. Open an app: Home Screen, Spotlight via the menu, clear, type the name (the clipboard keeps it), then tap only an exact label inside the Spotlight Top Hit card (suggestion, website and Settings rows of the same name are ignored, so a name the Top Hit card does not show is app not found; reads the English "Top Hit" label unless NORACU_TOPHIT_LABELS names the phone's own; a pasted name that never shows up in Spotlight, even after up to 15 s, is open_not_confirmed — retry; a one- or two-letter name such as "X" that OCR cannot read in the Top Hit card is open_not_confirmed without the 15 s wait, nothing tapped — open it from its Home Screen icon); 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. Reports delivery and retry. |
71
+ | `phone_open` | **app**:string | – – – O | EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed. Open an app: Home Screen, Spotlight via the menu, clear, type the name (the clipboard keeps it), then tap only an exact label inside the Spotlight Top Hit card (suggestion, website and Settings rows of the same name are ignored, so a name the Top Hit card does not show is app not found, and one it shows at two or more spots is open_not_confirmed with nothing tapped; reads the English "Top Hit" label unless NORACU_TOPHIT_LABELS names the phone's own; a pasted name that never shows up in Spotlight, even after up to 15 s, is open_not_confirmed — retry; a one- or two-letter name such as "X" that OCR cannot read in the Top Hit card is open_not_confirmed without the 15 s wait, nothing tapped — open it from its Home Screen icon); 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. Reports delivery and retry. |
72
72
 
package/docs/usage.md CHANGED
@@ -344,11 +344,17 @@ can rearrange the Home Screen or drop the icon on another one and make a folder.
344
344
  `phone_type` pastes through the clipboard with a real Command-V chord (never
345
345
  echoing the typed text), saving every clipboard item and type, clearing
346
346
  concealed or transient items instead of copying, and restoring the clipboard
347
- once OCR sees the pasted text appear on the phone (more often than before the
348
- paste — text already on screen does not count). Universal Clipboard or >64 MB
349
- items are not copied and leave the typed text on the clipboard; if the paste
350
- only shows up a few seconds late (still reported as typed — do not type it
351
- again) or ends in `type_not_confirmed`, the clipboard also keeps the typed text.
347
+ once OCR sees the pasted text appear on the phone at a spot where it was not
348
+ before the paste, below the strip at the top where the status bar and
349
+ notification banners are drawn (text already on screen, or the same words in a
350
+ banner, do not count); only that sighting makes the result
351
+ `delivered_verified`. Universal Clipboard or >64 MB items are not copied and
352
+ leave the typed text on the clipboard. A text shorter than four characters
353
+ (spaces and case aside) is never confirmed and never restores the clipboard. If
354
+ the text only shows up a few seconds late (reported as typed but
355
+ `delivered_unverified` — OCR cannot tell the paste from a line that repeats it,
356
+ such as a search result, so read the field before typing again) or the call
357
+ ends in `type_not_confirmed`, the clipboard also keeps the typed text.
352
358
  `phone_open {"app": "Calculator"}` opens Spotlight through iPhone Mirroring's
353
359
  own shortcut, pastes the name, and taps it only when Spotlight's Top Hit card
354
360
  shows exactly that name (a web suggestion or Settings row with the same name
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "imctl"
7
- version = "0.2.4"
7
+ version = "0.2.5"
8
8
  description = "Control iPhone Mirroring on macOS from the CLI — CGEvent input, Vision OCR, pixel verification"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -27,5 +27,5 @@ Key design decisions (each backed by empirical testing):
27
27
  between actions, so we re-resolve bounds before each gesture.
28
28
  """
29
29
 
30
- __version__ = "0.2.4"
30
+ __version__ = "0.2.5"
31
31
  __all__ = ["cli", "window", "input", "vision", "verify", "gestures"]
@@ -326,6 +326,13 @@ def _cmd_type(args) -> int:
326
326
  report = {}
327
327
  if input.type_text(args.text, replace=args.replace, report=report):
328
328
  if report.get("seen", True):
329
+ if _late_paste_probe(args.text) is None:
330
+ # 0.2.5 (review Y6): one character that OCR saw appear is no proof of where it went,
331
+ # and (review R38) no license to put the clipboard back
332
+ print(f"typed {len(args.text)} chars (one character: OCR saw it appear, which is no "
333
+ "proof of where it landed — check the field; the clipboard still holds the "
334
+ "typed text)")
335
+ return 0
329
336
  print(f"typed {len(args.text)} chars")
330
337
  return 0
331
338
  if _late_paste_probe(args.text) is None:
@@ -340,15 +347,20 @@ def _cmd_type(args) -> int:
340
347
  count_before = report.get("count_before")
341
348
  late = _watch_late_paste(args.text, baseline=count_before)
342
349
  if late is not None:
343
- # F38: the paste did land, just late — report it so the caller does not
344
- # retype it. The clipboard is deliberately NOT restored here: type_text()
350
+ # F38: the text showed up late — report it so the caller reads the field before
351
+ # retyping. The clipboard is deliberately NOT restored here: type_text()
345
352
  # restores only under its own checks (a rise seen inside its window, the
346
353
  # minimum hold, an untouched changeCount); after the fact, leaving the
347
354
  # typed text on the clipboard is the choice that can never hand the phone
348
355
  # the user's original clipboard (possibly a password).
349
- print(f"typed {len(args.text)} chars (the paste showed up late, during an extra "
350
- f"{late:.0f}s check after the 2.5s confirmation window; the clipboard "
351
- "still holds the typed text)")
356
+ # E2 run 2026-11-07 (T15): a second paste of the same text into the Settings search
357
+ # field was "seen late" while the field still showed the text once — a line repeating
358
+ # the query can rise too — so the wording claims no landing (the server reports it
359
+ # delivered_unverified, review R38).
360
+ print(f"typed {len(args.text)} chars (the text showed up late, during an extra "
361
+ f"{late:.0f}s check after the 2.5s confirmation window — OCR cannot tell whether "
362
+ "that is the paste or a line repeating it, such as a search result: check the "
363
+ "field before typing again; the clipboard still holds the typed text)")
352
364
  return 0
353
365
  watched = (f" or a further {LATE_PASTE_WATCH_S:.0f}s check"
354
366
  if _late_paste_probe(args.text) else
@@ -546,6 +558,11 @@ def _open_and_report(args) -> int:
546
558
  print(f"open_not_confirmed: ran out of time opening {args.app!r} (the Mac may be "
547
559
  f"under heavy load); {home_note}", file=sys.stderr)
548
560
  return 4
561
+ if result == "ambiguous":
562
+ print(f"open_not_confirmed: Spotlight's Top Hit card showed {args.app!r} at more than one "
563
+ f"spot, so nothing was tapped; {home_note} — open it from its Home Screen icon "
564
+ "instead (phone_screenshot, then phone_tap)", file=sys.stderr)
565
+ return 4
549
566
  if result == "short_unreadable":
550
567
  print(f"open_not_confirmed: could not read {args.app!r} in Spotlight — OCR often misses a "
551
568
  "one- or two-letter name, in the Top Hit card and in the search field alike, so "
@@ -433,7 +433,11 @@ def _norm_label(s: str) -> str:
433
433
  return "".join(_LABEL_LOOKALIKES.get(ch, ch) for ch in s)
434
434
 
435
435
 
436
- def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
436
+ # Two matching labels closer than this in both axes are one label read twice (choose_app_hit, Y6).
437
+ SAME_SPOT_EPS = 0.03
438
+
439
+
440
+ def choose_app_hit(hits: list, name: str, ambiguous: list | None = None) -> vision.OCRHit | None:
437
441
  """Pick the Spotlight result row for ``name`` from OCR hits.
438
442
 
439
443
  iOS 26 draws the Spotlight search field at the BOTTOM of the screen
@@ -445,9 +449,15 @@ def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
445
449
  "x", "×", "X." or full-width "X"), and
446
450
  - lie above the bottom search-field zone (ny < 0.88).
447
451
  The comparison stays EXACT — substring/prefix matching is
448
- forbidden: "X" must never hit "Xcode" or "X Corp". When several
449
- rows match, the topmost (smallest ny) wins. Returns None when
450
- nothing qualifies.
452
+ forbidden: "X" must never hit "Xcode" or "X Corp". Returns None
453
+ when nothing qualifies.
454
+
455
+ Y6 (review R37, 2026-11-07): when labels that match sit at two or
456
+ more different spots inside the card (more than SAME_SPOT_EPS apart
457
+ in either axis), nothing says which one is the app, so none is
458
+ chosen: the result is None and, when the caller passes a list as
459
+ ``ambiguous``, True is appended to it. Matches at one spot (the same
460
+ label read twice) are one label; the topmost of them is returned.
451
461
 
452
462
  F35 (2026-11-05 real-device): an exact label is not an app. The
453
463
  query "Pinduoduo" matched a Chrome *suggestion* row of that name
@@ -464,7 +474,7 @@ def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
464
474
  header = _tophit_header(hits)
465
475
  if header is None:
466
476
  return None
467
- best = None
477
+ found = []
468
478
  for hit in hits:
469
479
  if _norm_label(hit.text) != want:
470
480
  continue
@@ -472,13 +482,19 @@ def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
472
482
  continue # the search field echoing the query
473
483
  if not header.ny < hit.ny <= header.ny + TOP_HIT_CARD_SPAN:
474
484
  continue # outside the Top Hit card (F35)
475
- if best is None or hit.ny < best.ny:
476
- best = hit
485
+ found.append(hit)
486
+ if not found:
487
+ return None
488
+ best = min(found, key=lambda h: h.ny)
489
+ if any(abs(h.nx - best.nx) > SAME_SPOT_EPS or abs(h.ny - best.ny) > SAME_SPOT_EPS for h in found):
490
+ if ambiguous is not None:
491
+ ambiguous.append(True)
492
+ return None # Y6: several labels of the same name are never tapped
477
493
  return best
478
494
 
479
495
 
480
496
  def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep,
481
- deadline=None, clock=time.monotonic):
497
+ deadline=None, clock=time.monotonic, ambiguous=None):
482
498
  """Read the screen up to ``attempts`` times for a Spotlight result row.
483
499
 
484
500
  Each pass calls ``read_screen()`` for OCR hits and hands them to
@@ -501,6 +517,7 @@ def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep,
501
517
  stays exact either way. Long names keep the exact original
502
518
  read/sleep sequence. ``deadline`` (a ``clock()`` value) is checked
503
519
  before every read; once reached, no further read happens.
520
+ ``ambiguous`` is handed to every choose_app_hit() call (Y6).
504
521
  """
505
522
  short = len(_norm_label(name)) <= 2
506
523
 
@@ -522,7 +539,7 @@ def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep,
522
539
  for kwargs in reads:
523
540
  if expired():
524
541
  return None # out of time before this read (open_app reports it)
525
- hit = choose_app_hit(read_screen(**kwargs), name)
542
+ hit = choose_app_hit(read_screen(**kwargs), name, ambiguous)
526
543
  if hit is not None:
527
544
  return hit
528
545
  return None
@@ -712,8 +729,10 @@ def open_app(name: str, *, spotlight_open: bool = False,
712
729
  Top Hit card and the search field alike, so whether it was typed or
713
730
  the app exists is unknown — nothing was tapped; back on the Home Screen);
714
731
  "deadline" (the OPEN_DEADLINE_S budget ran out before a tap; back on
715
- the Home Screen); or "spotlight_unavailable" (Spotlight could not be
716
- opened; nothing was typed or tapped).
732
+ the Home Screen); "ambiguous" (Y6: the Top Hit card showed the name at
733
+ two or more spots and no read showed it at one — nothing was tapped;
734
+ back on the Home Screen); or "spotlight_unavailable" (Spotlight could
735
+ not be opened; nothing was typed or tapped).
717
736
 
718
737
  ``read_screen`` (default vision.read_screen), ``luma`` (default
719
738
  verify.window_luma), ``sleep``, ``tap`` (default inp.tap),
@@ -751,6 +770,7 @@ def open_app(name: str, *, spotlight_open: bool = False,
751
770
  deadline = None if deadline_s is None else clock() + deadline_s
752
771
  saw_top_hit = [False]
753
772
  saw_echo = [False]
773
+ ambiguous: list = [] # Y6: a read showed the name at two or more spots in the card
754
774
 
755
775
  def read_screen(**kwargs):
756
776
  # F33: every later read is also evidence for a clipboard restore an
@@ -794,7 +814,7 @@ def open_app(name: str, *, spotlight_open: bool = False,
794
814
  hit = None
795
815
  if typed is not False:
796
816
  hit = find_app_hit(read_screen, name, attempts=2, sleep=sleep,
797
- deadline=deadline, clock=clock)
817
+ deadline=deadline, clock=clock, ambiguous=ambiguous)
798
818
  if hit is None and not saw_echo[0]:
799
819
  # F33/F42: the name is not in the search field yet — the paste may still be on its
800
820
  # way, whether type_text missed it or took another change for it (a clear that
@@ -813,7 +833,8 @@ def open_app(name: str, *, spotlight_open: bool = False,
813
833
  break
814
834
  sleep(1.0)
815
835
  hit = find_app_hit(read_screen, name, attempts=1, sleep=sleep,
816
- deadline=deadline if confirming else limit, clock=clock)
836
+ deadline=deadline if confirming else limit, clock=clock,
837
+ ambiguous=ambiguous)
817
838
  if hit is not None:
818
839
  break
819
840
  # only the search field showing the name proves the paste arrived — a Top Hit
@@ -827,6 +848,8 @@ def open_app(name: str, *, spotlight_open: bool = False,
827
848
  tidy()
828
849
  if out_of_time():
829
850
  return "deadline"
851
+ if ambiguous:
852
+ return "ambiguous" # Y6: the card showed the name at more than one spot
830
853
  if short:
831
854
  # OCR misses one- and two-letter text in the card and in the field alike: neither
832
855
  # "not typed" nor "not found" is known — say that instead (2026-11-06 device run)
@@ -842,13 +865,21 @@ def open_app(name: str, *, spotlight_open: bool = False,
842
865
  # ① the Spotlight results can still be reflowing when
843
866
  # find_app_hit returns; re-read after 0.5s and re-pick.
844
867
  sleep(0.5)
845
- again = choose_app_hit(reread(), name)
868
+ split: list = []
869
+ again = choose_app_hit(reread(), name, split)
870
+ if split:
871
+ # Y6: this read shows the name at two or more spots — tap none of them
872
+ tidy()
873
+ return "ambiguous"
846
874
  if again is not None:
847
875
  if math.hypot(again.nx - hit.nx, again.ny - hit.ny) > 0.02:
848
876
  # the row moved: the second read wins, with at most
849
877
  # one more read — still moving → the last one wins
850
878
  hit = again
851
- once_more = choose_app_hit(reread(), name)
879
+ once_more = choose_app_hit(reread(), name, split)
880
+ if split:
881
+ tidy()
882
+ return "ambiguous"
852
883
  if (once_more is not None
853
884
  and math.hypot(once_more.nx - hit.nx,
854
885
  once_more.ny - hit.ny) > 0.02):
@@ -473,6 +473,11 @@ class PendingRestore:
473
473
  against the still pre-paste baseline); once it confirms, the user's
474
474
  clipboard goes back, under the same changeCount rule as type_text().
475
475
  Nothing else restores it.
476
+
477
+ Since review R38 (Andy's call, 2026-11-07) type_text() creates none: a
478
+ one-character paste never puts the clipboard back. The class stays for
479
+ its own tests and for open_app's offer loop, which still takes any
480
+ PendingRestore an injected type_text hands over.
476
481
  """
477
482
 
478
483
  def __init__(self, pasteboard, saved, saved_change, confirm, *, sent_at,
@@ -539,7 +544,8 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
539
544
  the typed text over any chance of the user's original clipboard
540
545
  being pasted into the phone.
541
546
 
542
- The restore therefore happens only when the paste landed, OCR
547
+ The restore therefore happens only when the text has four or more
548
+ characters (spaces and case aside), the paste landed, OCR
543
549
  saw the text, at least ``min_hold_s`` has passed since Cmd+V
544
550
  (the phone's asynchronous read must see the paste first), and
545
551
  the changeCount shows nothing else touched the pasteboard.
@@ -604,14 +610,12 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
604
610
  this one or an earlier one, is still on its way and could fetch the
605
611
  restored clipboard — and the box's own words never count as the text.
606
612
 
607
- ``pending`` (F33): when a one-character paste was not licensed for a
608
- restore here — not seen within the checks, or landed while OCR stayed
609
- blind — and the caller passes a list, a PendingRestore is appended to
610
- it. The caller offers it the screen reads it makes anyway; it restores
611
- only on the evidence the checks above require (the same new position
612
- in two separate reads), under the same changeCount rule. Longer texts
613
- never get one: without a pre-paste read, text already on screen could
614
- pose as the paste.
613
+ ``pending`` (F33): kept for callers that pass one, but nothing is
614
+ appended to it any more. A one-character paste used to hand over a
615
+ PendingRestore for a later restore on evidence; since Andy's call
616
+ (2026-11-07, review R38) a one-character paste never puts the user's
617
+ clipboard back, here or later — like a text of two or three
618
+ characters, it leaves the clipboard holding ``text``.
615
619
 
616
620
  Requires the calling terminal to have Accessibility permission
617
621
  (same as every other imctl input).
@@ -628,38 +632,24 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
628
632
  # F27: a single character is invisible to the default OCR probe
629
633
  # (screen_shows_text never matches it) and may already be on screen, so
630
634
  # the default checks wait for a still screen, read it with the
631
- # minimumTextHeight sweep before Cmd+V, and license a restore only when
635
+ # minimumTextHeight sweep before Cmd+V, and confirm the paste only when
632
636
  # the character shows up at the same NEW position in two separate
633
637
  # reads, looking for up to 4 s (the paste can land while Spotlight
634
638
  # redraws its results; the field echo blinks with the cursor). A screen
635
- # that never holds still gets no baseline and so no restore; otherwise
636
- # too the clipboard keeps holding ``text``, as before.
639
+ # that never holds still gets no baseline and so no such sighting. Since
640
+ # review R38 the sighting never licenses a restore: the clipboard keeps
641
+ # holding ``text``.
637
642
  single = verify.is_short_text(text, limit=1)
638
643
  sweep_before = [None]
639
644
  # F41: the probe count of a 2+ character text before the paste (None = unknown)
640
645
  multi = not single and verify.text_probe(text) is not None
641
646
  count_before = [None]
647
+ # 0.2.5: where the probe showed before the paste (None = unknown → no confirmation)
648
+ spots_before = [None]
642
649
 
643
650
  def sweep_read():
644
651
  return vision.read_screen(language_correction=False, sweep=True)
645
652
 
646
- def defer_restore():
647
- # F33: hand the caller what it needs to restore later, on evidence.
648
- before = sweep_before[0]
649
- if pending is None or not single or before is None or not restore:
650
- return
651
-
652
- sighting = verify.RepeatedSighting(text, before)
653
-
654
- def confirm(hits):
655
- # F44: as in ocr_check — a read showing the paste-progress box is
656
- # no evidence (a paste is still on its way)
657
- return not verify.shows_paste_hud(hits) and sighting.add(hits)
658
-
659
- pending.append(PendingRestore(pasteboard, saved, saved_change, confirm,
660
- sent_at=t0, clock=clock,
661
- min_hold_s=min_hold_s))
662
-
663
653
  pre_read = single and before_check is None
664
654
  pre_count = multi and ocr_check is None
665
655
  if hud_check is None:
@@ -714,7 +704,9 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
714
704
  # F44: no license while the paste-progress box shows — a paste
715
705
  # (this one or an earlier one) is still on its way
716
706
  if (verify.shows_paste_hud(hits)
717
- or verify.probe_count(text, hits) <= count_before[0]):
707
+ or verify.probe_count(text, hits) <= count_before[0]
708
+ or spots_before[0] is None
709
+ or not verify.has_new_spot(spots_before[0], verify.probe_spots(text, hits))):
718
710
  return False
719
711
  return True
720
712
  return verify.screen_shows_text(text, vision.read_screen)
@@ -747,13 +739,18 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
747
739
  # occurrence from one read). A capture failure in either leaves it
748
740
  # unknown: then OCR can never license a restore for this paste.
749
741
  try:
750
- first = verify.probe_count(text, vision.read_screen())
742
+ r1 = vision.read_screen()
743
+ first = verify.probe_count(text, r1)
751
744
  sleep(0.3)
752
- count_before[0] = max(first, verify.probe_count(text, vision.read_screen()))
745
+ r2 = vision.read_screen()
746
+ count_before[0] = max(first, verify.probe_count(text, r2))
747
+ # both reads: a spot either one saw is not new after the paste
748
+ spots_before[0] = verify.probe_spots(text, r1) + verify.probe_spots(text, r2)
753
749
  except Exception as exc:
754
750
  if not verify.is_capture_error(exc):
755
751
  raise
756
752
  count_before[0] = None
753
+ spots_before[0] = None
757
754
  if report is not None:
758
755
  report["count_before"] = count_before[0]
759
756
 
@@ -841,10 +838,12 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
841
838
  if not landed:
842
839
  # F18 invariant: never restore unconfirmed — a late paste
843
840
  # must at worst repeat `text`, never the user's own clipboard.
844
- defer_restore()
845
841
  return False
846
842
 
847
- if restore_ok and restore:
843
+ # Andy's call (2026-11-07, review R38): one character seen on screen
844
+ # confirms the paste but never licenses a restore — like a text of two or
845
+ # three characters (VERIFY_MIN_PROBE), it keeps the clipboard holding `text`.
846
+ if restore_ok and restore and not single:
848
847
  # Hold the paste long enough for the asynchronous
849
848
  # pasteboard read before putting the user's data back.
850
849
  elapsed = clock() - t0
@@ -853,11 +852,9 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
853
852
  # Restore the user's clipboard only if nothing else changed it.
854
853
  if pasteboard.changeCount() == saved_change + 1:
855
854
  restore_pasteboard(pasteboard, saved)
856
- else:
857
- # landed but OCR is blind to it (short/cropped text), or the
858
- # caller keeps the clipboard (restore=False): success, but the
859
- # clipboard keeps `text` — see the docstring's tradeoff.
860
- defer_restore()
855
+ # else: landed but OCR is blind to it (short/cropped text), a single
856
+ # character, or the caller keeps the clipboard (restore=False): success,
857
+ # but the clipboard keeps `text` — see the docstring's tradeoff.
861
858
  return True
862
859
  except BaseException:
863
860
  # Before Cmd+V the phone never got a paste command, so the
@@ -187,6 +187,40 @@ def text_probe(text: str) -> str | None:
187
187
  return probe if len(probe) >= 2 else None
188
188
 
189
189
 
190
+ # 0.2.5 (Andy's call, 2026-11-07): a typed text is confirmed only by a sighting where a field can be —
191
+ # a spot where the text's probe was not seen before the paste, below the strip at the top where the
192
+ # status bar and notification banners are drawn. A rise in the whole-screen count alone (a banner that
193
+ # carries the same words, a label somewhere else) no longer confirms a paste.
194
+ BANNER_STRIP_NY = 0.15
195
+ # Andy's call (2026-11-07, review R37): a text shorter than this (after the probe's compaction) is never
196
+ # confirmed by a sighting — "in" is part of "Sign in", "ok" of "Book" — so it never licenses a restore either
197
+ VERIFY_MIN_PROBE = 4
198
+
199
+
200
+ def probe_spots(text: str, hits) -> list[tuple[float, float]] | None:
201
+ """Where ``text``'s probe shows in ``hits`` (one spot per OCR line that holds it), leaving out the
202
+ paste-progress box (F44) and the banner strip at the top; None when the text is too short for a
203
+ probe. Hits without a position never count."""
204
+ probe = text_probe(text)
205
+ if probe is None:
206
+ return None
207
+ if len(probe) < VERIFY_MIN_PROBE:
208
+ return []
209
+ spots = []
210
+ for hit in hits:
211
+ nx, ny = getattr(hit, "nx", None), getattr(hit, "ny", None)
212
+ if nx is None or ny is None or ny < BANNER_STRIP_NY or _is_paste_hud(hit):
213
+ continue
214
+ if probe in _compact(getattr(hit, "text", hit)):
215
+ spots.append((nx, ny))
216
+ return spots
217
+
218
+
219
+ def has_new_spot(before, after, eps: float = 0.03) -> bool:
220
+ """True when some spot in ``after`` has no spot of ``before`` within ``eps`` in both axes."""
221
+ return any(all(abs(ax - bx) > eps or abs(ay - by) > eps for bx, by in before) for ax, ay in after)
222
+
223
+
190
224
  def probe_count(text: str, hits) -> int | None:
191
225
  """How many times ``text``'s probe occurs in the joined OCR ``hits``;
192
226
  None when the text is too short for a probe. The phone's "Pasting from …"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "noracu",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "mcpName": "io.github.sgInnora/noracu",
5
5
  "description": "Local MCP server: macOS apps and a browser by element index, plus iPhone Mirroring (experimental).",
6
6
  "type": "module",
package/src/mac-ax.js CHANGED
@@ -1250,14 +1250,71 @@ function opFrontmost(req) {
1250
1250
  }
1251
1251
  return out;
1252
1252
  }
1253
+ // The strips of each display that macOS keeps for the Dock: the display's frame minus its visible frame,
1254
+ // at the bottom, left and right (the top strip is the menu bar). screens: [{ f, v }] — frame and visible
1255
+ // frame in AppKit coordinates (origin bottom-left of the main screen); returns top-left [x, y, w, h].
1256
+ function dockStripsOf(screens) {
1257
+ const mainH = screens.length ? screens[0].f[3] : 0;
1258
+ const out = [];
1259
+ for (const { f, v } of screens) {
1260
+ const [fx, fy, fw] = f, [vx, vy, vw, vh] = v;
1261
+ const tl = (y, h) => mainH - y - h;
1262
+ if (vy > fy) out.push([fx, tl(fy, vy - fy), fw, vy - fy]);
1263
+ if (vx > fx) out.push([fx, tl(vy, vh), vx - fx, vh]);
1264
+ if (fx + fw > vx + vw) out.push([vx + vw, tl(vy, vh), fx + fw - vx - vw, vh]);
1265
+ }
1266
+ return out;
1267
+ }
1268
+ function dockStrips() {
1269
+ const s = $.NSScreen.screens;
1270
+ const screens = [];
1271
+ for (let i = 0; i < Number(s.count); i++) {
1272
+ const sc = s.objectAtIndex(i), f = sc.frame, v = sc.visibleFrame;
1273
+ screens.push({ f: [f.origin.x, f.origin.y, f.size.width, f.size.height].map(Number), v: [v.origin.x, v.origin.y, v.size.width, v.size.height].map(Number) });
1274
+ }
1275
+ return dockStripsOf(screens);
1276
+ }
1277
+ function inRect(x, y, r) { return x >= r[0] && y >= r[1] && x < r[0] + r[2] && y < r[1] + r[3]; }
1278
+ // While a banner or alert shows, Notification Center keeps one full-display window above everything (layer
1279
+ // 23) that lets clicks through except where a notification is drawn (E2 run 2026-11-07, macOS 27.2: a
1280
+ // memory-warning banner at the top right made a point in the middle of the screen read as covered). The
1281
+ // frames of the banners and alerts on screen, from accessibility; null — the whole overlay counts as
1282
+ // covering — when Notification Center's list is open, an element cannot be read, or none is found.
1283
+ function ncDrawnRects() {
1284
+ const a = ncApp();
1285
+ if (!a) return null;
1286
+ const rects = [];
1287
+ let doubt = false;
1288
+ const visit = (el, d) => {
1289
+ if (d > 14 || doubt) return;
1290
+ const v = readNode(el);
1291
+ if (v.__err) { doubt = true; return; }
1292
+ const sr = String(v.AXSubrole || '');
1293
+ if (sr.indexOf('AXNotificationCenter') === 0) {
1294
+ const fr = frameOf(v);
1295
+ if ((sr !== 'AXNotificationCenterBanner' && sr !== 'AXNotificationCenterAlert') || !fr) { doubt = true; return; }
1296
+ rects.push([fr[0] - 4, fr[1] - 4, fr[2] + 8, fr[3] + 8]); // a little margin for the shadow
1297
+ return;
1298
+ }
1299
+ for (const k of v.AXChildren || []) visit(k, d + 1);
1300
+ };
1301
+ for (const w of windowsOf(appElement(a))) visit(w, 0);
1302
+ return doubt || !rects.length ? null : rects;
1303
+ }
1304
+
1253
1305
  // The topmost on-screen window at a point, front to back, as the window server stacks them. Skipped:
1254
1306
  // invisible windows (alpha 0), desktop-level ones (negative layer), and the Dock's full-display overlay,
1255
- // which lets clicks through everywhere — only a Dock window as large as a whole display; the Dock itself
1256
- // (its platter) and other Dock-owned strips do cover what is under them.
1307
+ // which lets clicks through — except over the strip macOS keeps for the Dock, where the Dock is drawn:
1308
+ // there the overlay counts as covering (E2 run 2026-11-07: on macOS 27 the Dock has no window of its own
1309
+ // for its platter, so a point under the Dock read as the window behind it). The strip is the whole width
1310
+ // (or height) the Dock reserves, the gaps beside its platter included. Other Dock-owned windows cover
1311
+ // what is under them. Notification Center's full-display overlay (shown with a banner or alert) is
1312
+ // skipped the same way except over a banner or alert frame (ncDrawnRects), or everywhere when those
1313
+ // frames cannot be told.
1257
1314
  function cgTopAt(x, y) {
1258
1315
  const list = cast($.CGWindowListCopyWindowInfo((1 << 0) | (1 << 4), 0)); // on screen only, no desktop elements
1259
1316
  if (!list) return null;
1260
- let screens = null;
1317
+ let screens = null, strips = null, nc;
1261
1318
  for (let i = 0; i < Number(list.count); i++) {
1262
1319
  const d = list.objectAtIndex(i);
1263
1320
  const g = k => { const o = d.objectForKey(ks(k)); return o && !o.isNil() ? o.js : null; };
@@ -1268,9 +1325,17 @@ function cgTopAt(x, y) {
1268
1325
  if (!b || b.isNil()) continue;
1269
1326
  const [bx, by, bw, bh] = ['X', 'Y', 'Width', 'Height'].map(k => Number(b.objectForKey(ks(k)).js));
1270
1327
  if (bw * bh < 4 || x < bx || y < by || x >= bx + bw || y >= by + bh) continue;
1271
- if (owner === 'Dock') {
1328
+ if (owner === 'Dock' || owner === 'Notification Center') {
1272
1329
  if (!screens) screens = displays().map(s => s.frame);
1273
- if (screens.some(f => rectNear(f, [bx, by, bw, bh], 2))) continue;
1330
+ if (screens.some(f => rectNear(f, [bx, by, bw, bh], 2))) {
1331
+ if (owner === 'Dock') {
1332
+ if (!strips) strips = dockStrips();
1333
+ if (!strips.some(r => inRect(x, y, r))) continue;
1334
+ } else {
1335
+ if (nc === undefined) nc = ncDrawnRects();
1336
+ if (nc && !nc.some(r => inRect(x, y, r))) continue;
1337
+ }
1338
+ }
1274
1339
  }
1275
1340
  return { pid: Number(g('kCGWindowOwnerPID')), owner, layer, wid: Number(g('kCGWindowNumber')) };
1276
1341
  }
@@ -1998,7 +2063,7 @@ function opWindowOp(req) {
1998
2063
  // ── paste (mac_paste) ────────────────────────────────────────────────────────────────────────────
1999
2064
  // One engine call does the whole paste, so the user's clipboard never leaves this process and nothing
2000
2065
  // can slip in between the steps: focus guard → copy every item and type aside → write the text (marked
2001
- // transient, so clipboard managers skip it) → ⌘V through cliclick, only if the clipboard and the
2066
+ // transient, so clipboard managers skip it) → ⌘V as a key event, only if the clipboard and the
2002
2067
  // frontmost app are still as they were → wait for the paste to show in the focused element (else at
2003
2068
  // least 1 s, and only while the app answers) → put the user's items back, only if nobody else wrote
2004
2069
  // to the clipboard meanwhile. A password manager's concealed item is never copied or put back: the
@@ -2101,9 +2166,22 @@ function focusEvidence(appEl) {
2101
2166
  return { el: f.el, key: JSON.stringify([val, typeof n === 'number' ? n : null, sel || null]), raw, sel: sel || null };
2102
2167
  }
2103
2168
  const PASTE_MIN_HOLD_MS = 300;
2169
+ // The current keyboard layout's id (e.g. com.apple.keylayout.US), or null when it cannot be read.
2170
+ function keyboardLayoutId() {
2171
+ try {
2172
+ ObjC.import('Carbon');
2173
+ const s = $.TISCopyCurrentKeyboardLayoutInputSource();
2174
+ return String(ObjC.castRefToObject($.TISGetInputSourceProperty(s, $.kTISPropertyInputSourceID)).js);
2175
+ } catch (e) { return null; }
2176
+ }
2177
+ // Key code 9 is V on QWERTY, QWERTZ, AZERTY and Colemak layouts; a Dvorak layout puts K there, so ⌘ with
2178
+ // it would be ⌘K. The "Dvorak - QWERTY ⌘" layouts keep ⌘ shortcuts on QWERTY and are fine.
2179
+ function vKeyIsElsewhere(layout) { return typeof layout === 'string' && /dvorak/i.test(layout) && !/qwerty/i.test(layout); }
2104
2180
  function opPaste(req) {
2105
2181
  const text = String(req.text === undefined || req.text === null ? '' : req.text);
2106
2182
  if (!text) return invalid('text required');
2183
+ const layout = keyboardLayoutId();
2184
+ if (vKeyIsElsewhere(layout)) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `the keyboard layout ${layout} does not have V where ⌘V is sent from (key code 9) — nothing was pasted; mac_type types without the clipboard`, details: { kind: 'keyboard_layout' } }));
2107
2185
  const front = frontApp();
2108
2186
  if (!front) return fail(notDelivered({ code: 'FOCUS_UNKNOWN', message: 'could not read the frontmost app — nothing was pasted' }));
2109
2187
  let target = front;
@@ -2164,17 +2242,15 @@ function opPaste(req) {
2164
2242
  const restored = putBack(ours);
2165
2243
  return fail(notDelivered({ code: 'FOCUS_LOST', message: `the frontmost app changed to "${f2 ? f2.name : 'unknown'}" just before the paste — nothing was pasted (clipboard restored: ${restored})` }));
2166
2244
  }
2167
- const tool = req.cliclick || '/opt/homebrew/bin/cliclick';
2168
- const k = runTool(tool, ['kd:cmd', 't:v', 'ku:cmd'], 10000);
2169
- if (!k.started) {
2245
+ // ⌘V is the V key itself (key code 9) with the ⌘ flag, posted here. cliclick's `kd:cmd t:v ku:cmd`
2246
+ // types text, not that key: on macOS 27.2 TextEdit got a plain "v", or nothing, instead of a paste
2247
+ // (E2 run 2026-11-07, T7).
2248
+ const sent = postKey(KEY_V, [[MOD_KEYCODES.cmd, KEY_FLAGS.cmd]], 0);
2249
+ releaseStuckModifiers(['cmd']);
2250
+ if (!sent) {
2251
+ // the V key was never posted (postKey creates both events before posting either)
2170
2252
  const restored = putBack(ours);
2171
- return fail(notDelivered({ code: 'INTERNAL', message: `cliclick could not start: ${k.error} — nothing was pasted (clipboard restored: ${restored})` }));
2172
- }
2173
- if (k.timedOut || k.status !== 0) {
2174
- // ⌘V may or may not have gone out (and ⌘ may still be down): release ⌘, keep our text on the
2175
- // clipboard — a late paste must at worst repeat the text, never the user's clipboard
2176
- runTool(tool, ['ku:cmd'], 2000);
2177
- return fail({ code: 'ACTION_FAILED', message: `cliclick ${k.timedOut ? 'timed out' : `exited ${k.status}`} while sending ⌘V — the paste may or may not have happened (clipboard restored: false (paste_uncertain))`, delivery: 'unknown', retry: 'unsafe' });
2253
+ return fail(notDelivered({ code: 'ACTION_FAILED', message: `could not create the keyboard events for ⌘V — nothing was pasted (clipboard restored: ${restored})` }));
2178
2254
  }
2179
2255
  // the paste is done when the focused element shows it; without that evidence the clipboard stays
2180
2256
  // ours for at least hold_ms, so an app that reads it late does not get the user's clipboard instead
@@ -2509,6 +2585,7 @@ function opMenu(req) {
2509
2585
  // keypad flag, as hardware sends them. The server's focus guard runs before this op.
2510
2586
  const KEY_FLAGS = { cmd: 0x100000, shift: 0x20000, alt: 0x80000, ctrl: 0x40000, fn: 0x800000 };
2511
2587
  const MOD_KEYCODES = { cmd: 55, shift: 56, alt: 58, ctrl: 59 }; // left-hand keys; fn is a flag only (pressing Fn alone can switch input source)
2588
+ const KEY_V = 9; // the V key position (ANSI); mac_paste's ⌘V — see vKeyIsElsewhere for layouts that move it
2512
2589
  const FLAG_NUMPAD = 0x200000;
2513
2590
  const HELD_MASK = KEY_FLAGS.cmd | KEY_FLAGS.shift | KEY_FLAGS.alt | KEY_FLAGS.ctrl;
2514
2591
  const EV_FLAGS_CHANGED = 12;
package/src/server.mjs CHANGED
@@ -853,8 +853,22 @@ async function macScroll(args) {
853
853
  const dy = direction === "up" ? lines : direction === "down" ? -lines : 0;
854
854
  const dx = direction === "left" ? lines : direction === "right" ? -lines : 0;
855
855
  if (args.element_index === undefined) {
856
- const r = await sh("/usr/bin/osascript", ["-l", "JavaScript", "-e", WHEEL_SCRIPT, "--", String(dy), String(dx), "", ""], 8000);
857
- return r.ok ? { text: `scrolled ${direction} ${pages} page(s) (frontmost window; physical — delivery=delivered_unverified, retry=unsafe)` } : { error: "scroll failed: " + r.out.slice(0, 200) + (/not found/.test(r.out) ? " (delivery=not_delivered, retry=safe)" : " (delivery=unknown, retry=unsafe)") };
856
+ // 0.2.5: the frontmost app's front window on screen, scrolled at its center — and only when the window on
857
+ // top at that point is that app's (the same check as a raw x,y click). Before, the pointer went to
858
+ // whatever System Events called window 1, or stayed where it was when that read failed.
859
+ const fm = await frontmost();
860
+ const front = fm?.front;
861
+ if (!front) return { error: "focus_unknown: could not read the frontmost app — nothing was scrolled (delivery=not_delivered, retry=safe)" };
862
+ const wl = await axEngine({ op: "windows", app: front.name }, 15000);
863
+ const win = (wl?.ok ? wl.windows || [] : []).find((w) => w.pid === front.pid && (w.layer ?? 0) === 0 && w.onscreen !== false && Array.isArray(w.bounds) && w.bounds[2] > 0 && w.bounds[3] > 0);
864
+ if (!win) return { error: `no_window: "${front.name}" (the frontmost app) has no window on screen — nothing was scrolled (delivery=not_delivered, retry=safe); pass element_index to scroll something specific` };
865
+ const [px, py] = centerOf(win.bounds);
866
+ const g = await rawPointGuard(px, py, undefined);
867
+ if (g.error) return { error: g.error.replace(/; pass force:true to click without the check$/, "; pass element_index to scroll a specific element").replace("would not get the click", "would not get the scroll") };
868
+ const r = await sh("/usr/bin/osascript", ["-l", "JavaScript", "-e", WHEEL_SCRIPT, "--", String(dy), String(dx), String(px), String(py)], 8000);
869
+ return r.ok
870
+ ? { text: `scrolled ${direction} ${pages} page(s) at the center of ${win.title ? JSON.stringify(win.title) : "the front window"} of "${front.name}" (top window: ${g.owner}; physical — delivery=delivered_unverified, retry=unsafe)` }
871
+ : { error: "scroll failed: " + r.out.slice(0, 200) + " (delivery=unknown, retry=unsafe)" };
858
872
  }
859
873
  const l = lookupIndex(args.element_index, args.snapshot_id);
860
874
  if (l.error) return { error: l.error };
@@ -1041,7 +1055,7 @@ async function macType(args) {
1041
1055
  async function macPasteImpl(args) {
1042
1056
  const { text } = args;
1043
1057
  if (!text) return { error: "text required" };
1044
- const res = await axEngine({ op: "paste", text, app: args.app, force: args.force === true, cliclick: CLICLICK }, 25000);
1058
+ const res = await axEngine({ op: "paste", text, app: args.app, force: args.force === true }, 25000);
1045
1059
  if (!res.ok) return { error: axErrorText(res) };
1046
1060
  return { text: `pasted ${text.length} chars — delivery=${res.delivery}, retry=unsafe${res.reason ? ` (${res.reason})` : ""} (clipboard restored: ${res.restored}) (frontmost: ${res.front ?? "unknown"})` };
1047
1061
  }
@@ -2011,7 +2025,7 @@ const TOOLS = [
2011
2025
  { name: "mac_ax_state", desc: "Read an app's accessibility tree through the macOS Accessibility API (default: the frontmost app's focused window). Returns {app, snapshot_id, window, complete, elements:[{i, d, role, title, value, states, actions, frame}]}; i is the element_index for mac_click, mac_get, mac_set_value, mac_type, mac_scroll and mac_drag — unique across snapshots (an index never names an element of a later snapshot) and valid 30 s; an action first re-identifies the element and returns element_no_longer_valid if it is gone, moved or replaced. Options: interactive (only actionable elements), compact (default true: skip empty layout wrappers), skeleton (shallow map with children_count) then root (an element_index to drill into; adds new indexes to the same snapshot), surface (window|menubar|menu|sheet|alert|dialog|popover|focused|app), window (index or title) or window_id (from mac_windows), depth (logical depth, default 12, 1-40), max_nodes (default 400), web_accessibility (default true, false under NORACU_READ_ONLY=1: sets AXManualAccessibility on Electron/Chromium apps to expose web content, never AXEnhancedUserInterface which alters window behaviour; the result's web_accessibility is enabled / already_on, exposed when the app refused but its pages are in the tree anyway, or unsupported with a web_accessibility_hint — Google Chrome refuses it). window_identity unverifiable marks a window without a window ID: element_index actions in it are refused. ax_empty when the app has no readable window.", args: { app: "string?", interactive: "boolean?", compact: "boolean?", skeleton: "boolean?", root: "integer?", snapshot_id: "string?", surface: "string?", window: "string?", window_id: "integer?", depth: "number?", max_nodes: "integer?", web_accessibility: "boolean?" }, fn: macAxState },
2012
2026
  { name: "mac_click", desc: "Click a UI element by element_index (from mac_ax_state / mac_find; valid 30 s) or at raw {x,y}. With element_index the element is re-identified first (element_no_longer_valid if gone or changed). mechanism auto (default): its own accessibility action (press / show menu / select — no pointer, no focus change, works in background windows) when it has one, else a physical click that is sent only if a hit test shows the point reaches the element (occluded otherwise); semantic / physical force one path. count 2-3 and button middle are physical. A physical click is re-checked right before it is sent, and is delivered_verified only if the element is still there, changed, and its window is still on top at the point. A raw {x,y} click is sent only when the window on top at that point belongs to app (default: the frontmost app; the menu bar counts as the frontmost app's) — otherwise occluded names what covers it and nothing is sent; force:true skips that check. Results state delivery (delivered_verified / delivered_unverified / not_delivered / unknown) and whether a retry is safe, plus newly opened sheets, dialogs or menus.", args: { element_index: "integer?", snapshot_id: "string?", x: "number?", y: "number?", app: "string?", force: "boolean?", button: "string?", count: "number?", mechanism: "string?", timeout_ms: "integer?" }, fn: macClick },
2013
2027
  { name: "mac_drag", desc: "Drag from one UI element to another (sliders, selections, list items) with the physical pointer; from_index/to_index come from mac_ax_state or mac_find (valid 30 s). Both ends are re-identified and hit-tested first (either one gone or covered: nothing sent). Check the drop target afterwards.", args: { from_index: "integer", to_index: "integer", snapshot_id: "string?" }, required: ["from_index", "to_index"], fn: macDrag },
2014
- { name: "mac_scroll", desc: "Scroll up/down/left/right by a number of pages (default 1). Without element_index: the frontmost window (the pointer moves there). With element_index: a scroll area is scrolled at its own center (hit-tested; reports when the position did not change), any other element is scrolled into view (AXScrollToVisible).", args: { direction: "string?", pages: "number?", element_index: "integer?", snapshot_id: "string?" }, fn: macScroll },
2028
+ { name: "mac_scroll", desc: "Scroll up/down/left/right by a number of pages (default 1). Without element_index: the center of the frontmost app's front window (the pointer moves there), only when that app's window is on top at that point (else occluded, nothing scrolled). With element_index: a scroll area is scrolled at its own center (hit-tested; reports when the position did not change), any other element is scrolled into view (AXScrollToVisible).", args: { direction: "string?", pages: "number?", element_index: "integer?", snapshot_id: "string?" }, fn: macScroll },
2015
2029
  { name: "mac_key", desc: "Press a key or modifier chord, e.g. 'return', 'esc', 'cmd-c', 'cmd-shift-v', 'arrow-up'. Named keys (return, esc, tab, space, delete, arrows, home/end, page keys, F1-F16), with or without modifiers, go out as HID key events with each modifier pressed and released around the key; chords on a character key (cmd-c) go through cliclick. Pass app to refuse input unless that app is frontmost (focus guard). Chords that quit, log out, lock, force-quit, delete immediately or empty the Trash (cmd-q, alt-cmd-q, cmd-shift-q, cmd-alt-esc, ctrl-cmd-q, cmd-alt-delete, cmd-shift-delete…) are refused unless force:true.", args: { key: "string", app: "string?", force: "boolean?" }, fn: macKey },
2016
2030
  { name: "mac_type", desc: "Type text into element_index, or into the focused element (of app, if given). mechanism auto (default): inserted through accessibility at the caret (AXSelectedText) — IME-safe, clipboard untouched, works in a background app; delivered_verified only when the value reads back as exactly the old value with the text over the selection that was there (unreadable caret: delivered_unverified). replace:true sets the whole value instead (already that text: nothing sent). If the focused element takes no text through accessibility, auto falls back to physical keystrokes (not IME-safe; app is then a focus guard: refused unless that app is frontmost). mechanism physical forces keystrokes (clicking element_index first).", args: { text: "string", element_index: "integer?", snapshot_id: "string?", app: "string?", replace: "boolean?", mechanism: "string?", timeout_ms: "integer?" }, fn: macType },
2017
2031
  { name: "mac_paste", desc: "Paste text with Cmd+V through the clipboard, then put the user's clipboard back: every item and type is copied aside and restored within one call, only after the paste shows in the focused element (else after a 1 s hold) and only if nothing else wrote to the clipboard meanwhile — not while the app does not answer, so a late paste cannot insert the user's own clipboard; delivered_verified only when the focused field's value becomes exactly the text pasted over its selection; a password manager's concealed item is never copied — the clipboard is cleared after the paste instead. The pasted text is marked transient for clipboard managers. Pass app to refuse input unless that app is frontmost (focus guard). Refused when the clipboard holds Universal Clipboard content or more than 64 MB (force:true pastes anyway and leaves the pasted text on the clipboard). mac_type does not touch the clipboard.", args: { text: "string", app: "string?", force: "boolean?" }, fn: macPasteImpl },
@@ -2051,10 +2065,10 @@ const TOOLS = [
2051
2065
  { name: "phone_swipe", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Swipe (mouse drag) from [x,y] to [x,y] over an optional duration in ms; to move a list use phone_scroll. The mirror delivers a drag as pointer input, so a swipe that starts on an app icon picks the icon up and moves it (it can rearrange the Home Screen or make a folder): page the Home Screen from the empty strip just above the Dock (y about 0.80), never across the icon rows. Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed. Optional expect: text that must be on screen (OCR) first, else nothing is sent. Reports delivery and retry.", args: { from: "array", to: "array", ms: "number?", expect: "string?" }, fn: phoneSwipe },
2052
2066
  { name: "phone_home", desc: "EXPERIMENTAL. Send the Home Screen command via the iPhone Mirroring menu (works without python/pyobjc on English macOS while the mirror is live), falling back to an imctl swipe (needs python/pyobjc) only when that English menu item is absent (non-English macOS). Reports only that the command or gesture was sent — nothing on the iPhone screen is verified; refuses with mirror_not_live or mirror_state_unknown (or menu_unknown on timeout) when the mirror is not live or its state cannot be confirmed. Reports delivery and retry.", args: {}, fn: phoneHome },
2053
2067
  { name: "phone_app_switcher", desc: "EXPERIMENTAL. Send the App Switcher command via the iPhone Mirroring menu (works without python/pyobjc on English macOS while the mirror is live), falling back to an imctl gesture (needs python/pyobjc) only when that English menu item is absent (non-English macOS). Reports only that the command or gesture was sent — nothing on the iPhone screen is verified; refuses with mirror_not_live or mirror_state_unknown (or menu_unknown on timeout) when the mirror is not live or its state cannot be confirmed. Reports delivery and retry.", args: {}, fn: phoneAppSwitcher },
2054
- { name: "phone_scroll", desc: "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. Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed; 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. Reports delivery and retry.", args: { direction: "string?", distance: "number?", expect: "string?" }, fn: phoneScroll },
2055
- { name: "phone_type", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Type text via the clipboard (IME-safe; never echoes the typed text). Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed. Saves every clipboard item and type, clearing concealed or transient items instead of copying, and restores only after OCR sees the text appear within its 2.5 s check (Universal Clipboard or >64 MB items are not copied and leave the typed text on the clipboard; a paste confirmed late or type_not_confirmed also leaves the typed text on the clipboard). replace=true selects all and overwrites the field. Optional expect: on-screen text (OCR), else nothing is sent. Reports delivery and retry.", args: { text: "string", replace: "boolean?", expect: "string?" }, fn: phoneType },
2068
+ { name: "phone_scroll", desc: "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. Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed; reports scroll_no_effect when the screen did not change (list end, or the view does not scroll); a scroll that changed the screen is delivered_unverified, since a notification or an animation changes it too — take phone_screenshot to see where the list is. Optional expect: text that must be on screen (OCR) first, else nothing is sent. Reports delivery and retry.", args: { direction: "string?", distance: "number?", expect: "string?" }, fn: phoneScroll },
2069
+ { name: "phone_type", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Type text via the clipboard (IME-safe; never echoes the typed text). Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed. Saves every clipboard item and type, clearing concealed or transient items instead of copying, and restores only after OCR sees the text appear within its 2.5 s check at a spot where it was not before, below the status bar and notification strip — only that sighting makes the result delivered_verified (Universal Clipboard or >64 MB items are not copied and leave the typed text on the clipboard; a text under four characters, spaces and case aside, a paste seen only after the 2.5 s check, and type_not_confirmed are never verified and also leave the typed text on the clipboard). replace=true selects all and overwrites the field. Optional expect: on-screen text (OCR), else nothing is sent. Reports delivery and retry.", args: { text: "string", replace: "boolean?", expect: "string?" }, fn: phoneType },
2056
2070
  { name: "phone_key", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Press a key: return, delete, up, down, left, or right. Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed. Optional expect: text that must be on screen (OCR) first, else nothing is sent. Reports delivery and retry.", args: { key: "string", expect: "string?" }, fn: phoneKey },
2057
- { name: "phone_open", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed. Open an app: Home Screen, Spotlight via the menu, clear, type the name (the clipboard keeps it), then tap only an exact label inside the Spotlight Top Hit card (suggestion, website and Settings rows of the same name are ignored, so a name the Top Hit card does not show is app not found; reads the English \"Top Hit\" label unless NORACU_TOPHIT_LABELS names the phone's own; a pasted name that never shows up in Spotlight, even after up to 15 s, is open_not_confirmed — retry; a one- or two-letter name such as \"X\" that OCR cannot read in the Top Hit card is open_not_confirmed without the 15 s wait, nothing tapped — open it from its Home Screen icon); 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. Reports delivery and retry.", args: { app: "string" }, fn: phoneOpen },
2071
+ { name: "phone_open", desc: "EXPERIMENTAL. Needs iPhone Mirroring and a python3 with pyobjc. Refused with mirror_not_live or mirror_state_unknown when the mirror is not live or its state cannot be confirmed. Open an app: Home Screen, Spotlight via the menu, clear, type the name (the clipboard keeps it), then tap only an exact label inside the Spotlight Top Hit card (suggestion, website and Settings rows of the same name are ignored, so a name the Top Hit card does not show is app not found, and one it shows at two or more spots is open_not_confirmed with nothing tapped; reads the English \"Top Hit\" label unless NORACU_TOPHIT_LABELS names the phone's own; a pasted name that never shows up in Spotlight, even after up to 15 s, is open_not_confirmed — retry; a one- or two-letter name such as \"X\" that OCR cannot read in the Top Hit card is open_not_confirmed without the 15 s wait, nothing tapped — open it from its Home Screen icon); 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. Reports delivery and retry.", args: { app: "string" }, fn: phoneOpen },
2058
2072
  ];
2059
2073
 
2060
2074
  const AX_SURFACES = ["window", "menubar", "menu", "sheet", "alert", "dialog", "popover", "focused", "app"];
@@ -2468,15 +2482,17 @@ function traceCall(name, args, ms, isError, errText) {
2468
2482
  // phone_* results say what reached the phone, like the Mac tools: imctl's own lines name the outcome;
2469
2483
  // the delivery wording is added here, once for every phone tool (read-only phone tools get none).
2470
2484
  const PHONE_INPUTS = new Set(["phone_tap", "phone_longpress", "phone_swipe", "phone_scroll", "phone_type", "phone_key", "phone_open", "phone_home", "phone_app_switcher", "phone_launch"]);
2471
- // success that the phone screen confirmed (open: the app opened; scroll: the screen moved; type: the paste landed)
2472
- const PHONE_CONFIRMED = new Set(["phone_open", "phone_scroll", "phone_type"]);
2485
+ // success that the phone screen confirmed (open: the app opened; type: the paste landed). phone_scroll is not here
2486
+ // (0.2.5, Andy's call): "the screen changed" is all it sees, and a notification or an animation changes it too
2487
+ const PHONE_CONFIRMED = new Set(["phone_open", "phone_type"]);
2473
2488
  // "nothing was sent": refusals before the first event (expect_not_found, a capture that failed while checking --expect, invalid_args)
2474
2489
  const PHONE_NOTHING_SENT = /^(mirror_not_live|mirror_state_unknown|mirror_setup_required|expect_not_found|imctl unavailable|server_shutting_down)|server is shutting down|nothing was typed|nothing was sent/;
2475
2490
  function phoneDelivery(name, text, ok) {
2476
2491
  if (!PHONE_INPUTS.has(name) || /delivery=/.test(text)) return text;
2477
2492
  if (name === "phone_launch") return `${text} (delivery=${ok ? "delivered_unverified" : PHONE_NOTHING_SENT.test(text) ? "not_delivered" : "unknown"}, retry=safe)`;
2478
- // a paste only the frame diff saw (OCR cannot read the text back) is not verified (device run 2026-11-06)
2479
- if (ok && /OCR cannot read this text back/.test(text)) return `${text} (delivery=delivered_unverified, retry=unsafe)`;
2493
+ // a paste only the frame diff saw (OCR cannot read the text back) is not verified (device run 2026-11-06); neither is
2494
+ // one character OCR saw appear, nor a text seen late — OCR cannot tell the paste from a line repeating it (review R38; E2 T15)
2495
+ if (ok && /OCR cannot read this text back|no proof of where it landed|showed up late/.test(text)) return `${text} (delivery=delivered_unverified, retry=unsafe)`;
2480
2496
  if (ok) return `${text} (delivery=${PHONE_CONFIRMED.has(name) ? "delivered_verified" : "delivered_unverified"}, retry=unsafe)`;
2481
2497
  if (PHONE_NOTHING_SENT.test(text)) return `${text} (delivery=not_delivered, retry=safe)`;
2482
2498
  if (/^scroll_no_effect/.test(text)) return `${text} (delivery=delivered_unverified, retry=unsafe)`;