noracu 0.1.4 → 0.2.1

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.
@@ -23,6 +23,7 @@ methodology):
23
23
 
24
24
  from __future__ import annotations
25
25
 
26
+ import math
26
27
  import time
27
28
 
28
29
  from Quartz import (
@@ -112,12 +113,23 @@ def scroll_trackpad(total_px: float, nx: float = 0.5, ny: float = 0.6,
112
113
  deltas = scroll_steps(total_px)
113
114
  last = len(deltas) - 1
114
115
  sent = 1 # events posted so far (the mouse-moved above)
115
- for i, d in enumerate(deltas):
116
- if sent % 6 == 0:
117
- _require_focus() # F26: every 6 events; drop the rest on focus loss
118
- _scroll_event(src, d, x, y, 1 if i == 0 else (4 if i == last else 2))
119
- sent += 1
120
- time.sleep(0.016)
116
+ began = False
117
+ ended = False
118
+ try:
119
+ for i, d in enumerate(deltas):
120
+ if sent % 6 == 0:
121
+ _require_focus() # F26: every 6 events; drop the rest on focus loss
122
+ phase = 1 if i == 0 else (4 if i == last else 2)
123
+ _scroll_event(src, d, x, y, phase)
124
+ if phase == 1:
125
+ began = True
126
+ elif phase == 4:
127
+ ended = True
128
+ sent += 1
129
+ time.sleep(0.016)
130
+ finally:
131
+ if began and not ended:
132
+ _scroll_event(src, 0, x, y, 4)
121
133
 
122
134
 
123
135
  def _mouse_event(kind: int, x: float, y: float, source) -> None:
@@ -170,21 +182,37 @@ def tap(nx: float = 0.5, ny: float = 0.5, bounds: WindowBounds | None = None) ->
170
182
  src = _source()
171
183
  _require_focus() # F26: before the first event
172
184
  _mouse_event(kCGEventLeftMouseDown, x, y, src)
173
- time.sleep(TAP_INTERVAL_S)
174
- _mouse_event(kCGEventLeftMouseUp, x, y, src)
185
+ try:
186
+ time.sleep(TAP_INTERVAL_S)
187
+ finally:
188
+ _mouse_event(kCGEventLeftMouseUp, x, y, src)
189
+
190
+
191
+ SWIPE_MS_RANGE = (50, 5000)
192
+
193
+
194
+ def _check_duration(value: float, lo: float, hi: float, what: str) -> None:
195
+ # before any event: an invalid duration must not turn into a real press (math.isfinite: no nan/inf;
196
+ # bool is an int subclass in Python, so it is refused by name)
197
+ if not (isinstance(value, (int, float)) and not isinstance(value, bool)
198
+ and math.isfinite(value) and lo <= value <= hi):
199
+ raise ValueError(f"{what} must be between {lo} and {hi}")
175
200
 
176
201
 
177
202
  def long_press(nx: float = 0.5, ny: float = 0.5, duration_s: float = LONG_PRESS_S,
178
203
  bounds: WindowBounds | None = None) -> None:
179
204
  """Press and hold at normalized coordinates."""
205
+ _check_duration(duration_s, 0.01, 10, "long-press duration (s)")
180
206
  ensure_frontmost()
181
207
  b = bounds or get_bounds()
182
208
  x, y = b.denormalize(nx, ny)
183
209
  src = _source()
184
210
  _require_focus() # F26: before the press-down
185
211
  _mouse_event(kCGEventLeftMouseDown, x, y, src)
186
- time.sleep(duration_s)
187
- _mouse_event(kCGEventLeftMouseUp, x, y, src)
212
+ try:
213
+ time.sleep(duration_s)
214
+ finally:
215
+ _mouse_event(kCGEventLeftMouseUp, x, y, src)
188
216
 
189
217
 
190
218
  def _ease_in_out(t: float) -> float:
@@ -202,6 +230,7 @@ def swipe(from_x: float, from_y: float, to_x: float, to_y: float,
202
230
  The gesture is: mouse-down, 3px nudge, 20 eased drag steps,
203
231
  mouse-up. This is the shape iPhone Mirroring's recognizer accepts.
204
232
  """
233
+ _check_duration(duration_ms, *SWIPE_MS_RANGE, "swipe duration (ms)")
205
234
  ensure_frontmost()
206
235
  b = bounds or get_bounds()
207
236
  x0, y0 = b.denormalize(from_x, from_y)
@@ -211,25 +240,31 @@ def swipe(from_x: float, from_y: float, to_x: float, to_y: float,
211
240
  step_delay = (duration_ms / 1000.0) / SWIPE_STEPS
212
241
 
213
242
  _require_focus() # F26: before the first event
214
- _mouse_event(kCGEventLeftMouseDown, x0, y0, src)
215
- time.sleep(0.02)
216
-
217
- # Initial nudge: disambiguates swipe from long-press-drag.
218
- dx = 1 if x1 >= x0 else -1
219
- dy = 1 if y1 >= y0 else -1
220
- _mouse_event(kCGEventLeftMouseDragged, x0 + dx * SWIPE_NUDGE_PX,
221
- y0 + dy * SWIPE_NUDGE_PX, src)
222
- time.sleep(0.01)
223
-
224
- for i in range(1, SWIPE_STEPS + 1):
225
- t = i / SWIPE_STEPS
226
- e = _ease_in_out(t)
227
- cx = x0 + (x1 - x0) * e
228
- cy = y0 + (y1 - y0) * e
229
- _mouse_event(kCGEventLeftMouseDragged, cx, cy, src)
230
- time.sleep(step_delay)
231
-
232
- _mouse_event(kCGEventLeftMouseUp, x1, y1, src)
243
+ cx, cy = x0, y0
244
+ _mouse_event(kCGEventLeftMouseDown, cx, cy, src)
245
+ try:
246
+ time.sleep(0.02)
247
+
248
+ # Initial nudge: disambiguates swipe from long-press-drag.
249
+ dx = 1 if x1 >= x0 else -1
250
+ dy = 1 if y1 >= y0 else -1
251
+ nx, ny = x0 + dx * SWIPE_NUDGE_PX, y0 + dy * SWIPE_NUDGE_PX
252
+ _mouse_event(kCGEventLeftMouseDragged, nx, ny, src)
253
+ cx, cy = nx, ny
254
+ time.sleep(0.01)
255
+
256
+ for i in range(1, SWIPE_STEPS + 1):
257
+ if i % 5 == 0:
258
+ _require_focus() # R18: a long swipe stops (and releases) when the mirror loses focus
259
+ t = i / SWIPE_STEPS
260
+ e = _ease_in_out(t)
261
+ nx = x0 + (x1 - x0) * e
262
+ ny = y0 + (y1 - y0) * e
263
+ _mouse_event(kCGEventLeftMouseDragged, nx, ny, src)
264
+ cx, cy = nx, ny
265
+ time.sleep(step_delay)
266
+ finally:
267
+ _mouse_event(kCGEventLeftMouseUp, cx, cy, src)
233
268
 
234
269
 
235
270
  def scroll(dy_pixels: int, nx: float = 0.5, ny: float = 0.5,
@@ -303,12 +338,16 @@ def _cmd_chord(keycode: int, before_key=None) -> None:
303
338
  CGEventPost(kCGHIDEventTap, event)
304
339
 
305
340
  post(_VK_COMMAND, True, kCGEventFlagMaskCommand)
306
- time.sleep(0.03)
307
- post(keycode, True, kCGEventFlagMaskCommand)
308
- time.sleep(0.03)
309
- post(keycode, False, kCGEventFlagMaskCommand)
310
- time.sleep(0.03)
311
- post(_VK_COMMAND, False, 0)
341
+ try:
342
+ time.sleep(0.03)
343
+ post(keycode, True, kCGEventFlagMaskCommand)
344
+ try:
345
+ time.sleep(0.03)
346
+ finally:
347
+ post(keycode, False, kCGEventFlagMaskCommand)
348
+ time.sleep(0.03)
349
+ finally:
350
+ post(_VK_COMMAND, False, 0)
312
351
 
313
352
 
314
353
  def press_key(key: str) -> None:
@@ -320,8 +359,10 @@ def press_key(key: str) -> None:
320
359
  src = _source()
321
360
  _require_focus() # F26: before the key-down
322
361
  _key_event(keymap[key], True, src)
323
- time.sleep(0.02)
324
- _key_event(keymap[key], False, src)
362
+ try:
363
+ time.sleep(0.02)
364
+ finally:
365
+ _key_event(keymap[key], False, src)
325
366
 
326
367
 
327
368
  class ClipboardChanged(InputError):
@@ -332,6 +373,95 @@ class ClipboardChanged(InputError):
332
373
  """
333
374
 
334
375
 
376
+ # The user's clipboard is copied aside whole (every item, every type) and put back the same way. Items a
377
+ # password manager marks concealed (nspasteboard.org) or an app marks transient are never copied: putting
378
+ # the clipboard "back" means clearing it. Universal Clipboard content (reading it would fetch it from
379
+ # the other device), promised files and clipboards over the size limit are not copied either: the
380
+ # clipboard keeps the typed text. Our own write is not marked transient — iPhone Mirroring reads the
381
+ # Mac pasteboard, and the marker's effect on that path is unproven.
382
+ _CONCEALED = "org.nspasteboard.ConcealedType"
383
+ _TRANSIENT = "org.nspasteboard.TransientType"
384
+ _REMOTE = "com.apple.is-remote-clipboard"
385
+ _SAVE_LIMIT = 64 * 1024 * 1024
386
+
387
+
388
+ def _new_item():
389
+ from AppKit import NSPasteboardItem
390
+ return NSPasteboardItem.alloc().init()
391
+
392
+
393
+ def save_pasteboard(pasteboard, limit: int = _SAVE_LIMIT):
394
+ """Snapshot ``pasteboard`` for restore_pasteboard(): ``(kind, items)``.
395
+
396
+ kind "items": items is [[(type, data), ...], ...]; "concealed" /
397
+ "transient": not copied (restore clears); "empty"; "remote" /
398
+ "too_large": not copied (restore leaves the clipboard as it is).
399
+ A pasteboard object without ``types()`` (a text-only stand-in) is
400
+ saved as ("text", data of public.utf8-plain-text).
401
+ """
402
+ if getattr(pasteboard, "types", None) is None:
403
+ return ("text", pasteboard.dataForType_("public.utf8-plain-text"))
404
+ # types() lists only the first item's types: it tells a remote clipboard before any item is
405
+ # touched; every item's own types are then read (without data) for concealed / transient marks
406
+ types = [str(t) for t in (pasteboard.types() or [])]
407
+ if _REMOTE in types:
408
+ return ("remote", None)
409
+ items_ = list(pasteboard.pasteboardItems() or [])
410
+ for it in items_:
411
+ types += [str(t) for t in (it.types() or [])]
412
+ if _CONCEALED in types:
413
+ return ("concealed", None)
414
+ if _TRANSIENT in types:
415
+ return ("transient", None)
416
+ promised = any(t.startswith("com.apple.pasteboard.promised-file") for t in types)
417
+ if _REMOTE in types or (promised and "public.file-url" not in types):
418
+ return ("remote", None)
419
+ if not types:
420
+ return ("empty", None)
421
+ items, total = [], 0
422
+ for it in items_:
423
+ rec = []
424
+ for t in (it.types() or []):
425
+ d = it.dataForType_(t)
426
+ if d is None:
427
+ continue
428
+ total += int(d.length()) if hasattr(d, "length") else len(d)
429
+ if total > limit:
430
+ return ("too_large", None)
431
+ rec.append((str(t), d))
432
+ if rec:
433
+ items.append(rec)
434
+ if not items:
435
+ # a provider that answers only at the pasteboard level
436
+ return ("text", pasteboard.dataForType_("public.utf8-plain-text"))
437
+ return ("items", items)
438
+
439
+
440
+ def restore_pasteboard(pasteboard, saved) -> bool:
441
+ """Put a save_pasteboard() snapshot back (the caller checked the
442
+ changeCount). Returns False when it cannot be put back ("remote",
443
+ "too_large"): then the clipboard is left holding the typed text.
444
+ Raw text data (bytes or None, the older snapshot) is accepted too."""
445
+ if not isinstance(saved, tuple):
446
+ saved = ("text", saved)
447
+ kind, data = saved
448
+ if kind in ("remote", "too_large"):
449
+ return False
450
+ pasteboard.clearContents()
451
+ if kind == "text":
452
+ if data is not None:
453
+ pasteboard.setData_forType_(data, "public.utf8-plain-text")
454
+ elif kind == "items" and data:
455
+ objs = []
456
+ for rec in data:
457
+ it = _new_item()
458
+ for t, d in rec:
459
+ it.setData_forType_(d, t)
460
+ objs.append(it)
461
+ pasteboard.writeObjects_(objs)
462
+ return True
463
+
464
+
335
465
  class PendingRestore:
336
466
  """A clipboard restore type_text() could not license itself (F33).
337
467
 
@@ -368,10 +498,7 @@ class PendingRestore:
368
498
  self.done = True
369
499
  if self._pasteboard.changeCount() != self._saved_change + 1:
370
500
  return False # something else wrote the pasteboard: never restore
371
- self._pasteboard.clearContents()
372
- if self._saved is not None:
373
- self._pasteboard.setData_forType_(self._saved, "public.utf8-plain-text")
374
- return True
501
+ return restore_pasteboard(self._pasteboard, self._saved)
375
502
 
376
503
 
377
504
  def type_text(text: str, *, replace: bool = False, pasteboard=None,
@@ -630,8 +757,15 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
630
757
  if report is not None:
631
758
  report["count_before"] = count_before[0]
632
759
 
633
- saved = pasteboard.dataForType_("public.utf8-plain-text")
760
+ # the change count first: a copy that lands while the clipboard is being saved must not be
761
+ # overwritten by our write
634
762
  saved_change = pasteboard.changeCount()
763
+ saved = save_pasteboard(pasteboard)
764
+ if pasteboard.changeCount() != saved_change:
765
+ saved_change = None # nothing of ours to undo
766
+ raise ClipboardChanged(
767
+ "another app or device changed the clipboard while it was being saved; "
768
+ "nothing was typed and the clipboard was left as it is")
635
769
 
636
770
  pasteboard.clearContents()
637
771
  pasteboard.setString_forType_(text, "public.utf8-plain-text")
@@ -698,6 +832,11 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
698
832
  raise
699
833
  if not landed:
700
834
  landed = restore_ok
835
+ if report is not None:
836
+ # device run 2026-11-06: the frame diff alone (no OCR sighting) once
837
+ # confirmed a paste that never reached the field — the caller must
838
+ # not report such a paste as verified
839
+ report["seen"] = bool(restore_ok)
701
840
 
702
841
  if not landed:
703
842
  # F18 invariant: never restore unconfirmed — a late paste
@@ -713,9 +852,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
713
852
  sleep(min_hold_s - elapsed)
714
853
  # Restore the user's clipboard only if nothing else changed it.
715
854
  if pasteboard.changeCount() == saved_change + 1:
716
- pasteboard.clearContents()
717
- if saved is not None:
718
- pasteboard.setData_forType_(saved, "public.utf8-plain-text")
855
+ restore_pasteboard(pasteboard, saved)
719
856
  else:
720
857
  # landed but OCR is blind to it (short/cropped text), or the
721
858
  # caller keeps the clipboard (restore=False): success, but the
@@ -729,9 +866,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
729
866
  # restore then. Either way the original exception propagates.
730
867
  if not sent[0] and saved_change is not None:
731
868
  if pasteboard.changeCount() == saved_change + 1:
732
- pasteboard.clearContents()
733
- if saved is not None:
734
- pasteboard.setData_forType_(saved, "public.utf8-plain-text")
869
+ restore_pasteboard(pasteboard, saved)
735
870
  raise
736
871
 
737
872
 
@@ -743,5 +878,7 @@ def clear_text() -> None:
743
878
  src = _source()
744
879
  _require_focus() # F26: re-check between Cmd+A and Delete
745
880
  _key_event(_VK_DELETE, True, src)
746
- time.sleep(0.02)
747
- _key_event(_VK_DELETE, False, src)
881
+ try:
882
+ time.sleep(0.02)
883
+ finally:
884
+ _key_event(_VK_DELETE, False, src)
@@ -403,16 +403,23 @@ def parse_overlay(raw: str) -> dict:
403
403
  def overlay_snapshot() -> tuple[dict, bool]:
404
404
  """(overlay state, hover) from one probe; the state is what get_overlay() returns.
405
405
 
406
- Fail-open: any osascript failure (app not running, AX hiccup, timeout) returns
407
- live=None so callers can decide; this never raises.
406
+ Fail-open at the probe layer: any osascript failure (app not running, AX hiccup,
407
+ timeout) returns live=None so callers can decide; this never raises. When the app
408
+ is not running or has no window on any Space, ``reason`` is set ("not_running" or
409
+ "no_window") so _require_live() can report that without activating the app.
408
410
  """
409
411
  try:
410
412
  # strip=False: a trailing "<class>\t" line (nameless button) must keep its tab —
411
413
  # str.strip() would eat it and make the last line unparseable.
412
414
  raw = _run_osascript(_OVERLAY_SCRIPT, strip=False)
413
415
  except Exception:
416
+ if not is_running():
417
+ return {"live": None, "overlay": None, "buttons": 0, "reason": "not_running"}, False
414
418
  return {"live": None, "overlay": None, "buttons": 0}, False
415
- return parse_overlay_ex(raw)
419
+ state, hover = parse_overlay_ex(raw)
420
+ if raw.strip() == "NO_WINDOW" and get_window_info() is None:
421
+ state = {**state, "reason": "no_window"}
422
+ return state, hover
416
423
 
417
424
 
418
425
  def get_overlay() -> dict:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "noracu",
3
- "version": "0.1.4",
3
+ "version": "0.2.1",
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",
@@ -10,9 +10,10 @@
10
10
  },
11
11
  "scripts": {
12
12
  "start": "node src/server.mjs",
13
- "test": "node test/e2e.mjs",
14
- "test:ci": "NORACU_CI=1 node test/e2e.mjs",
15
- "prepublishOnly": "node --check src/server.mjs"
13
+ "test": "node test/engine-unit.mjs && node test/e2e.mjs",
14
+ "test:ci": "node test/engine-unit.mjs && NORACU_CI=1 node test/e2e.mjs",
15
+ "check": "node --check src/server.mjs && node --check src/mac-ax.js && node --check scripts/gen-tools.mjs && python3 -c \"import ast,sys; [ast.parse(open(f).read(), f) for f in sys.argv[1:]]\" imctl/src/imctl/*.py",
16
+ "prepublishOnly": "npm run check && node scripts/check-pack.mjs && node scripts/gen-tools.mjs && git diff --exit-code docs/tools.md"
16
17
  },
17
18
  "engines": {
18
19
  "node": ">=20"