noracu 0.2.6 → 0.2.7

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.
@@ -339,12 +339,13 @@ def open_spotlight_checked(settle_s=1.0, *, luma=None, sleep=time.sleep, opener=
339
339
  # a Top Hit card header near the top of the window (Spotlight's sits at ny ≈ 0.14; a
340
340
  # "Top Hit" line far down is no evidence), "none", or "unreadable"
341
341
  try:
342
- header = _tophit_header(read_screen())
342
+ hits = read_screen()
343
343
  except Exception as exc:
344
344
  if not verify.is_capture_error(exc):
345
345
  raise
346
346
  return "unreadable"
347
- return "card" if header is not None and header.ny < SPOTLIGHT_HEADER_MAX_NY else "none"
347
+ # 2026-11-08: or the top-field layout's field (a completion, or "Search or Ask")
348
+ return "card" if _spotlight_up(hits) else "none"
348
349
 
349
350
  before_home = card()
350
351
  if not home():
@@ -469,19 +470,36 @@ def choose_app_hit(hits: list, name: str, ambiguous: list | None = None) -> visi
469
470
  label inside the card → None: "not found" beats opening the
470
471
  wrong thing. Suggestion, website and Settings deep-link rows of
471
472
  the same name are never candidates.
473
+
474
+ 2026-11-08 (iOS 27 "Search or Ask"): Spotlight may put the search
475
+ field at the TOP and show no "Top Hit" header. Then the label band
476
+ under the field counts (more than TOP_FIELD_LABEL_MIN and at most
477
+ TOP_FIELD_CARD_SPAN below it: not the field line, not the Home Screen
478
+ showing through above the label, not the first section header) — but only when the field shows exactly ``name``
479
+ completed with "— Open" (OPEN_COMPLETION_ACTIONS): Spotlight's own
480
+ statement that its top result is something of that name that opens.
481
+ Any other completion, or none, → None.
472
482
  """
473
483
  want = _norm_label(name)
474
484
  header = _tophit_header(hits)
475
- if header is None:
476
- return None
485
+ if header is not None:
486
+ lo, hi = header.ny, header.ny + TOP_HIT_CARD_SPAN
487
+ else:
488
+ # 2026-11-08, top-field layout: no "Top Hit" header. Only when the field itself
489
+ # completes the exact name with "— Open" is the block right under it the top result;
490
+ # the field line (and any part of it OCR split off) is never a candidate.
491
+ field = _top_field_for(hits, name)
492
+ if field is None or field[1] not in OPEN_COMPLETION_ACTIONS:
493
+ return None
494
+ lo, hi = field[0] + TOP_FIELD_LABEL_MIN, field[0] + TOP_FIELD_CARD_SPAN
477
495
  found = []
478
496
  for hit in hits:
479
497
  if _norm_label(hit.text) != want:
480
498
  continue
481
499
  if hit.ny >= SEARCH_FIELD_NY:
482
500
  continue # the search field echoing the query
483
- if not header.ny < hit.ny <= header.ny + TOP_HIT_CARD_SPAN:
484
- continue # outside the Top Hit card (F35)
501
+ if not lo < hit.ny <= hi:
502
+ continue # outside the Top Hit card (F35) / the block under the top field
485
503
  found.append(hit)
486
504
  if not found:
487
505
  return None
@@ -609,6 +627,89 @@ def _field_echo(hits, name) -> bool:
609
627
  # the magnifier glyph may come back as "Q", "Q." or "Q:" in front of the text
610
628
  if _echo_matches(got, want) or _echo_matches(re.sub(r"^q[\s.,:;·•]*", "", got, count=1), want):
611
629
  return True
630
+ # 2026-11-08: the top-field layout echoes the query at the top, often with a completion
631
+ # ("Calculator — Open"); the query part alone is compared, with the same OCR-slip tolerance
632
+ return any(_echo_matches(query, want) for _, query, _a in _top_field_lines(hits))
633
+
634
+
635
+ # 2026-11-08 device run (iOS 27, the "Search or Ask" Spotlight): the search field can sit at the
636
+ # TOP of the window (ny ≈ 0.12). Typing an app's exact name then shows the query with an inline
637
+ # completion in the field — read as "Calculator -Open" — and the results start right under it with
638
+ # that app's icon and label (label at ny ≈ 0.28) under NO "Top Hit" header; the first section
639
+ # header ("Chrome", "Settings", …) follows at ny ≈ 0.32, and a Settings row of the same name lower
640
+ # down (ny ≈ 0.49). phone_open's every read failed there: no header, and the bottom-field echo
641
+ # never matched (0.2.6 failed the same way). The field's own completion is the evidence this layout
642
+ # offers: "<name> — Open" says Spotlight's top result is something named <name> that opens.
643
+ TOP_FIELD_MAX_NY = 0.16 # the top search field line (measured 0.12)
644
+ TOP_FIELD_LINE_EPS = 0.02 # hits this close to the field line are parts of it (OCR may split it)
645
+ # the top result's label band under the field: label measured at +0.16, the first section header at
646
+ # +0.20, and the dimmed Home Screen behind the panel shows through above the label (a widget's
647
+ # "SUNDAY" at +0.06). Only (field + TOP_FIELD_LABEL_MIN, field + TOP_FIELD_CARD_SPAN] counts, so
648
+ # neither that background text nor a section header that carries the app's name ("Chrome" over
649
+ # Chrome's own results) is ever a candidate.
650
+ TOP_FIELD_LABEL_MIN = 0.10
651
+ TOP_FIELD_CARD_SPAN = 0.18
652
+ OPEN_COMPLETION_ACTIONS = ("open",) # the completion word that marks something that opens (English)
653
+ # completion words that also show Spotlight is up (a previous query that was no app: "— Ask Siri")
654
+ SPOTLIGHT_UP_ACTIONS = OPEN_COMPLETION_ACTIONS + ("ask siri",)
655
+ # the dash needs whitespace on at least one side: OCR reads the completion as "Calculator -Open" or
656
+ # "zq7pdcan- Ask Siri" (both seen on the device); a hyphen inside a name ("Wi-Fi") has none
657
+ _COMPLETION = re.compile(r"^(?P<q>.*\S)(?:\s+[—–-]\s*|[—–-]\s+)(?P<a>\S.*)$")
658
+
659
+
660
+ def _top_field_lines(hits):
661
+ """(ny, query, action) for each line in the top search-field zone: the hits within
662
+ TOP_FIELD_LINE_EPS of each other joined left to right, split at a " — <action>" completion
663
+ (action None without one). Query and action are _norm_label'ed."""
664
+ top = sorted((h for h in hits if h.ny < TOP_FIELD_MAX_NY), key=lambda h: (h.ny, h.nx))
665
+ lines, used = [], set()
666
+ for i, h in enumerate(top):
667
+ if i in used:
668
+ continue
669
+ group = [j for j in range(i, len(top)) if j not in used and abs(top[j].ny - h.ny) <= TOP_FIELD_LINE_EPS]
670
+ used.update(group)
671
+ text = " ".join(top[j].text for j in sorted(group, key=lambda j: top[j].nx))
672
+ m = _COMPLETION.match(unicodedata.normalize("NFKC", text).strip())
673
+ if m:
674
+ lines.append((h.ny, _norm_label(m.group("q")), _norm_label(m.group("a"))))
675
+ else:
676
+ lines.append((h.ny, _norm_label(text), None))
677
+ return lines
678
+
679
+
680
+ def _top_field_for(hits, name):
681
+ """(ny, action) of the top search field when it shows ``name`` (exactly, after _norm_label),
682
+ with or without a completion; None otherwise."""
683
+ want = _norm_label(name)
684
+ for ny, query, action in _top_field_lines(hits):
685
+ if query == want:
686
+ return ny, action
687
+ return None
688
+
689
+
690
+ def _spotlight_up(hits, name=None) -> bool:
691
+ """Spotlight is on screen: a "Top Hit" header near the top, or (top-field layout) the empty
692
+ field's "Search or Ask", or a field line completed with a SPOTLIGHT_UP_ACTIONS word whose
693
+ query is exactly ``name`` — or, without a name (the F43 check), completed with "Open" AND
694
+ with that query's label in the label band under it. Any other line in that zone (the
695
+ notification strip: a banner can read "X - Y" or even "X - Open") is no evidence."""
696
+ header = _tophit_header(hits)
697
+ if header is not None and header.ny < SPOTLIGHT_HEADER_MAX_NY:
698
+ return True
699
+ want = None if name is None else _norm_label(name)
700
+ for ny, query, action in _top_field_lines(hits):
701
+ if query == "search or ask":
702
+ return True
703
+ if want is not None:
704
+ if action in SPOTLIGHT_UP_ACTIONS and query == want:
705
+ return True
706
+ elif action in OPEN_COMPLETION_ACTIONS and any(
707
+ _norm_label(h.text) == query and ny + TOP_FIELD_LABEL_MIN < h.ny <= ny + TOP_FIELD_CARD_SPAN
708
+ for h in hits):
709
+ # without a name to match (the F43 check after Home), an "Open" completion counts
710
+ # only with Spotlight's own structure under it — that query's label in the label band;
711
+ # a banner that happens to read "Calendar - Open" has none
712
+ return True
612
713
  return False
613
714
 
614
715
 
@@ -636,7 +737,7 @@ def home_via_menu(timeout: float = TIDY_OSASCRIPT_TIMEOUT_S) -> bool:
636
737
  return _run_view_menu_command("Home Screen", timeout=timeout)
637
738
 
638
739
 
639
- def _tap_and_confirm_open(nx, ny, *, luma, sleep, tap, read_screen):
740
+ def _tap_and_confirm_open(nx, ny, *, luma, sleep, tap, read_screen, name=None):
640
741
  """Tap (nx, ny) and confirm the app actually opened (F24 ②).
641
742
 
642
743
  One luma frame before the tap, one after a 1.0s settle, then one
@@ -654,8 +755,10 @@ def _tap_and_confirm_open(nx, ny, *, luma, sleep, tap, read_screen):
654
755
  sleep(1.0)
655
756
  after = luma()
656
757
  hits = read_screen()
758
+ # 2026-11-08: Spotlight still up in either layout (a Top Hit header near the top, or the top
759
+ # field with its completion / "Search or Ask") means the tap did not open anything
657
760
  opened = (verify.mean_abs_diff(before, after) >= OPEN_MIN_DIFF
658
- and _tophit_header(hits) is None)
761
+ and _tophit_header(hits) is None and not _spotlight_up(hits, name))
659
762
  return opened, hits
660
763
 
661
764
 
@@ -731,8 +834,14 @@ def open_app(name: str, *, spotlight_open: bool = False,
731
834
  "deadline" (the OPEN_DEADLINE_S budget ran out before a tap; back on
732
835
  the Home Screen); "ambiguous" (Y6: the Top Hit card showed the name at
733
836
  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).
837
+ back on the Home Screen); "focus_lost" (another app came to the front
838
+ during type_text's wait after the clipboard write: the paste was called
839
+ off and nothing was tapped; Spotlight is left as it is — going Home
840
+ would pull the mirror forward again); "clipboard_changed" (another app or
841
+ device wrote the clipboard before ⌘V: nothing was pasted or tapped, the
842
+ new clipboard is left alone; back on the Home Screen); or
843
+ "spotlight_unavailable" (Spotlight could not be opened; nothing was
844
+ typed or tapped).
736
845
 
737
846
  ``read_screen`` (default vision.read_screen), ``luma`` (default
738
847
  verify.window_luma), ``sleep``, ``tap`` (default inp.tap),
@@ -809,7 +918,21 @@ def open_app(name: str, *, spotlight_open: bool = False,
809
918
  return "deadline"
810
919
  clear_text() # iOS kept the last query; new input would append (F17)
811
920
  sleep(0.3)
812
- typed = type_text(name)
921
+ try:
922
+ typed = type_text(name)
923
+ except inp.PasteFocusLost:
924
+ # 0.2.7: another app came to the front during the wait after the clipboard write;
925
+ # the paste was called off. No trip Home: that would pull the mirror forward again, the
926
+ # very thing the paste refused to do (Spotlight closes by itself when left idle).
927
+ return "focus_lost"
928
+ except inp.ClipboardChanged:
929
+ # another app or device wrote the clipboard before ⌘V: nothing was pasted and their
930
+ # clipboard is left alone. Tidy up only while the mirror is still in front — if the
931
+ # user also moved away, going Home would pull it forward: report focus_lost instead
932
+ if not inp._focus_check():
933
+ return "focus_lost"
934
+ tidy()
935
+ return "clipboard_changed"
813
936
  sleep(1.5) # wait for Spotlight results
814
937
  hit = None
815
938
  if typed is not False:
@@ -894,7 +1017,7 @@ def open_app(name: str, *, spotlight_open: bool = False,
894
1017
  # so ③ can find the label again (F32/F35).
895
1018
  opened, hits = _tap_and_confirm_open(
896
1019
  hit.nx, hit.ny, luma=luma, sleep=sleep, tap=tap,
897
- read_screen=reread)
1020
+ read_screen=reread, name=name)
898
1021
  if opened:
899
1022
  return "opened"
900
1023
 
@@ -906,7 +1029,7 @@ def open_app(name: str, *, spotlight_open: bool = False,
906
1029
  if again is not None and not out_of_time():
907
1030
  opened, _ = _tap_and_confirm_open(
908
1031
  again.nx, again.ny - SPOTLIGHT_ICON_ABOVE_LABEL,
909
- luma=luma, sleep=sleep, tap=tap, read_screen=reread)
1032
+ luma=luma, sleep=sleep, tap=tap, read_screen=reread, name=name)
910
1033
  if opened:
911
1034
  return "opened"
912
1035
  except Exception as exc:
@@ -43,11 +43,20 @@ from Quartz import (
43
43
  CGEventSetFlags,
44
44
  )
45
45
 
46
- from . import window
46
+ from . import pointer, window
47
47
  from .window import WindowBounds, ensure_frontmost, get_bounds
48
48
 
49
49
  TAP_INTERVAL_S = 0.05
50
50
  LONG_PRESS_S = 0.8
51
+ # Device run 2026-11-07/08 (macOS 27.2): iPhone Mirroring pastes
52
+ # through Universal Clipboard, which tells the phone about new Mac clipboard content
53
+ # asynchronously. Once in about 30 pastes (23:33, Cmd+V ~0.5 s after the write) the phone pasted
54
+ # the text the Mac clipboard held BEFORE the write; shell pastes 0.4-3.4 s after the write landed
55
+ # 23/23 the same night, so the race is rare. type_text waits this long between its write and
56
+ # Cmd+V to narrow it. The value is a judgement, not a measured threshold, and it does not close
57
+ # the race. It does not address the other failure seen (the phone shows "Pasting from ..." and
58
+ # then pastes nothing), whose cause is not established.
59
+ PASTE_SETTLE_S = 1.5
51
60
  SWIPE_STEPS = 20
52
61
  SWIPE_NUDGE_PX = 3
53
62
  SWIPE_DEFAULT_MS = 300
@@ -67,6 +76,13 @@ class FocusLost(InputError):
67
76
  """
68
77
 
69
78
 
79
+ class PasteFocusLost(FocusLost):
80
+ """type_text's Cmd+V was called off: another app came to the front during
81
+ the wait after the clipboard write. Nothing was pasted (a replace's Cmd+A
82
+ had already been sent), and the clipboard went back under the changeCount
83
+ rule. Raised instead of bringing iPhone Mirroring forward again."""
84
+
85
+
70
86
  # F26: consulted right before every synthesized event. Module-level so
71
87
  # tests can swap it; window.is_frontmost asks System Events afresh on
72
88
  # every call (F30: an in-process NSWorkspace answer is a stale snapshot).
@@ -139,6 +155,7 @@ def _mouse_event(kind: int, x: float, y: float, source) -> None:
139
155
  if event is None:
140
156
  raise InputError(f"CGEventCreateMouseEvent returned None for {kind}")
141
157
  CGEventPost(kCGHIDEventTap, event)
158
+ pointer.moved_to(x, y) # 0.2.7: the CLI puts the pointer back after the command
142
159
 
143
160
 
144
161
  def _key_event(keycode: int, down: bool, source) -> None:
@@ -361,7 +378,7 @@ def check_chord_layout(keycode: int) -> None:
361
378
  "switch the Mac to a QWERTY-style input source (U.S., ABC, Pinyin) and retry")
362
379
 
363
380
 
364
- def _cmd_chord(keycode: int, before_key=None) -> None:
381
+ def _cmd_chord(keycode: int, before_key=None, activate: bool = True) -> None:
365
382
  """Send a real Command chord: ⌘ down → key down → key up → ⌘ up.
366
383
 
367
384
  iPhone Mirroring forwards the *state* of the physical modifier
@@ -375,9 +392,16 @@ def _cmd_chord(keycode: int, before_key=None) -> None:
375
392
  ``before_key`` runs after the focus checks, right before the first
376
393
  event: the caller's last chance to call the chord off by raising —
377
394
  nothing is posted then (F35).
395
+
396
+ ``activate=False``: never bring iPhone Mirroring forward — when another
397
+ app is frontmost, raise FocusLost before anything is posted. type_text's
398
+ ⌘V uses it: by then the user may have moved to another app during the
399
+ wait after the clipboard write, and pulling the mirror back would send
400
+ the paste (and their next keystrokes) to the phone.
378
401
  """
379
402
  check_chord_layout(keycode) # review 0.2.6 #5: before anything is sent
380
- ensure_frontmost()
403
+ if activate:
404
+ ensure_frontmost()
381
405
  _require_focus() # F26: before the chord's first event
382
406
  if before_key is not None:
383
407
  before_key()
@@ -564,7 +588,8 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
564
588
  sleep=time.sleep, clock=time.monotonic,
565
589
  timeout_s: float = 2.5, poll_s: float = 0.15,
566
590
  min_hold_s: float = 0.3, pending: list | None = None,
567
- report: dict | None = None, restore: bool = True) -> bool:
591
+ report: dict | None = None, restore: bool = True,
592
+ settle_s: float = PASTE_SETTLE_S) -> bool:
568
593
  """Type text via clipboard paste (IME-safe), confirmed on screen.
569
594
 
570
595
  Direct CGEvent keystroke synthesis breaks under CJK IMEs and is
@@ -635,7 +660,8 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
635
660
  search-history chip with the same query, an older message) licensed a
636
661
  restore at once, and a paste that the phone read late could then paste
637
662
  the user's ORIGINAL clipboard. The default checks now count the text's
638
- probe before the pasteboard write — the higher of two reads 0.3 s
663
+ probe right before Cmd+V (after the pasteboard write and the
664
+ ``settle_s`` wait) — the higher of two reads 0.3 s
639
665
  apart, so a read that misses an occurrence cannot fake a rise — and
640
666
  license a restore only when the count RISES over it, in two reads 0.3 s
641
667
  apart. Without a pre-paste count (a read failed) OCR never licenses a
@@ -644,6 +670,18 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
644
670
  count as ``count_before`` (None: unknown), for a caller that keeps
645
671
  watching after a False result.
646
672
 
673
+ ``settle_s`` (device run 2026-11-07/08): the wait between writing the
674
+ pasteboard and Cmd+V. The phone reads the Mac clipboard through Universal
675
+ Clipboard, which announces new content asynchronously; a Cmd+V that
676
+ arrives first pastes the phone's OWN clipboard (an older paste, or
677
+ something copied on the phone) instead of ``text``. The wait lowers that
678
+ chance; it cannot rule it out, so an unconfirmed paste is still reported
679
+ as unconfirmed and the caller reads the field. The pre-paste reads come
680
+ after the wait, so the write-to-Cmd+V time is ``settle_s`` plus those
681
+ reads. Cmd+V never brings iPhone Mirroring back to the front: when
682
+ another app took it during the wait, FocusLost (nothing pasted; the
683
+ clipboard goes back under the changeCount rule).
684
+
647
685
  ``restore=False``: once Cmd+V may be on its way the user's clipboard is
648
686
  never put back — no restore here and no PendingRestore — and it keeps
649
687
  ``text``; only an error before Cmd+V still restores it. open_app uses
@@ -683,8 +721,21 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
683
721
  check_chord_layout(_VK_A)
684
722
  check_chord_layout(_VK_V)
685
723
  ensure_frontmost()
724
+ default_chord = chord is None
686
725
  if chord is None:
687
726
  chord = _cmd_chord
727
+
728
+ def paste_chord(keycode, before_key=None):
729
+ # the ⌘V after the wait never re-activates the mirror: PasteFocusLost instead
730
+ # (_cmd_chord raises FocusLost only before its first event)
731
+ try:
732
+ return _cmd_chord(keycode, before_key=before_key, activate=False)
733
+ except PasteFocusLost:
734
+ raise
735
+ except FocusLost as exc:
736
+ raise PasteFocusLost(str(exc)) from exc
737
+ else:
738
+ paste_chord = chord # injected (tests): one chord for both keys
688
739
  if pasteboard is None:
689
740
  pasteboard = NSPasteboard.generalPasteboard()
690
741
  # F27: a single character is invisible to the default OCR probe
@@ -788,12 +839,40 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
788
839
  chord(_VK_A) # select the focused field's content first (see docstring)
789
840
  sleep(0.05)
790
841
 
842
+ # the change count first: a copy that lands while the clipboard is being saved must not be
843
+ # overwritten by our write
844
+ saved_change = pasteboard.changeCount()
845
+ saved = save_pasteboard(pasteboard)
846
+ if pasteboard.changeCount() != saved_change:
847
+ saved_change = None # nothing of ours to undo
848
+ raise ClipboardChanged(
849
+ "another app or device changed the clipboard while it was being saved; "
850
+ "nothing was typed and the clipboard was left as it is")
851
+
852
+ pasteboard.clearContents()
853
+ pasteboard.setString_forType_(text, "public.utf8-plain-text")
854
+ # Device run 2026-11-07/08: let Universal Clipboard tell the phone about the new content
855
+ # before Cmd+V (PASTE_SETTLE_S). The pre-paste reads, the "before" frame, the chord's
856
+ # focus check and last_check (the changeCount guard) all come after the wait, so each
857
+ # describes the moment right before Cmd+V.
858
+ sleep(max(0.05, settle_s))
859
+ # 0.2.7: the wait is when someone copies something or moves to another app (or Space):
860
+ # say so now, before any screen read — the same checks run again right before Cmd+V
861
+ # focus first: when both happened, the user moved away — a caller must not take the
862
+ # clipboard change for a reason to bring the mirror forward again (open_app tidies on it)
863
+ if default_chord and not _focus_check():
864
+ raise PasteFocusLost("iPhone Mirroring is not the frontmost app")
865
+ if pasteboard.changeCount() != saved_change + 1:
866
+ raise ClipboardChanged(
867
+ "another app or device changed the clipboard during the wait before the paste; "
868
+ "nothing was typed and the clipboard was left as it is")
869
+
791
870
  if pre_read:
792
871
  # F27: the pre-paste sweep for a single character, taken on a
793
872
  # still screen only (a mid-transition read could miss a label
794
873
  # that is already there and later pass it off as the paste).
795
- # It runs before the pasteboard write so the stretch between our
796
- # write and Cmd+V (F35) stays short.
874
+ # Taken after the clipboard write and the wait (0.2.7), so
875
+ # the baseline is the screen right before Cmd+V.
797
876
  try:
798
877
  if verify.wait_still(sleep=sleep, clock=clock):
799
878
  sweep_before[0] = sweep_read()
@@ -807,6 +886,9 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
807
886
  # 0.3 s apart (a redraw or the select-all highlight can hide an
808
887
  # occurrence from one read). A capture failure in either leaves it
809
888
  # unknown: then OCR can never license a restore for this paste.
889
+ # 0.2.7: read after the clipboard write and the wait, so
890
+ # text that appears during the wait is part of the baseline and
891
+ # can never pass for the paste (a restore license).
810
892
  try:
811
893
  r1 = vision.read_screen()
812
894
  first = verify.probe_count(text, r1)
@@ -824,21 +906,14 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
824
906
  if report is not None:
825
907
  report["count_before"] = count_before[0]
826
908
 
827
- # the change count first: a copy that lands while the clipboard is being saved must not be
828
- # overwritten by our write
829
- saved_change = pasteboard.changeCount()
830
- saved = save_pasteboard(pasteboard)
831
- if pasteboard.changeCount() != saved_change:
832
- saved_change = None # nothing of ours to undo
833
- raise ClipboardChanged(
834
- "another app or device changed the clipboard while it was being saved; "
835
- "nothing was typed and the clipboard was left as it is")
836
-
837
- pasteboard.clearContents()
838
- pasteboard.setString_forType_(text, "public.utf8-plain-text")
839
- sleep(0.05)
840
-
841
- changed = before_check()
909
+ try:
910
+ changed = before_check()
911
+ except Exception as exc:
912
+ # the mirror window left the screen during the reads (another Space came to the
913
+ # front): that is the user moving away, not a broken capture — call the paste off
914
+ if default_chord and verify.is_capture_error(exc) and not _focus_check():
915
+ raise PasteFocusLost("iPhone Mirroring is not the frontmost app") from exc
916
+ raise
842
917
 
843
918
  def last_check():
844
919
  # F35: the last look at the pasteboard, after the chord's focus
@@ -853,7 +928,7 @@ def type_text(text: str, *, replace: bool = False, pasteboard=None,
853
928
  sent[0] = True
854
929
 
855
930
  # real ⌘ chord — flags alone reach the phone as "v" (F14)
856
- chord(_VK_V, before_key=last_check)
931
+ paste_chord(_VK_V, before_key=last_check) # never re-activates the mirror after the wait
857
932
  t0 = clock()
858
933
 
859
934
  # landed: did the paste show up on screen? (decides the return
@@ -0,0 +1,81 @@
1
+ """Put the Mac pointer back after a phone gesture (0.2.7, a Mac shared with a person).
2
+
3
+ A tap, swipe, long press or scroll moves the real pointer onto the mirror
4
+ window (a mouse event with a location moves it). When the Mac is shared
5
+ (NORACU_USER_IDLE_S is not 0 — the same variable and rule as the noracu
6
+ server), the CLI remembers where the pointer was before a command and, after
7
+ it, warps it back — only when the pointer is still where noracu's own last
8
+ event left it: if someone moved it meanwhile, it stays where they put it.
9
+ A warp posts no event (the person's idle time is not reset by it).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import re
16
+ import time
17
+
18
+ _home = None # where the pointer was before the command (None: not tracking)
19
+ _last = None # where noracu's last mouse event put it (None: no mouse event yet)
20
+
21
+
22
+ def enabled() -> bool:
23
+ """Off only for a plain zero ("0", "0.0"), like the server; unset or unreadable means on."""
24
+ raw = os.environ.get("NORACU_USER_IDLE_S", "").strip()
25
+ return not re.fullmatch(r"0+(\.0+)?", raw)
26
+
27
+
28
+ def _where():
29
+ try:
30
+ import Quartz # type: ignore
31
+
32
+ ev = Quartz.CGEventCreate(None)
33
+ if ev is None:
34
+ return None
35
+ p = Quartz.CGEventGetLocation(ev)
36
+ return (float(p.x), float(p.y))
37
+ except Exception:
38
+ return None
39
+
40
+
41
+ def _warp(p) -> None:
42
+ import Quartz # type: ignore
43
+
44
+ Quartz.CGWarpMouseCursorPosition(p)
45
+ Quartz.CGAssociateMouseAndMouseCursorPosition(True)
46
+
47
+
48
+ def remember() -> None:
49
+ """Called once before a command runs."""
50
+ global _home, _last
51
+ _last = None
52
+ _home = _where() if enabled() else None
53
+
54
+
55
+ def moved_to(x: float, y: float) -> None:
56
+ """Called after every mouse event noracu posts."""
57
+ global _last
58
+ _last = (float(x), float(y))
59
+
60
+
61
+ def restore() -> bool:
62
+ """Called once after a command (also after an error). True when the pointer was put back."""
63
+ global _home, _last
64
+ home, last = _home, _last
65
+ _home = _last = None
66
+ if home is None or last is None:
67
+ return False
68
+ def still_ours() -> bool:
69
+ now = _where()
70
+ return now is not None and abs(now[0] - last[0]) <= 2 and abs(now[1] - last[1]) <= 2
71
+
72
+ if not still_ours():
73
+ return False # someone moved it: leave it where they put it
74
+ try:
75
+ time.sleep(0.1) # let the last posted events reach the mirror before the pointer leaves it
76
+ if not still_ours():
77
+ return False # moved during that wait
78
+ _warp(home)
79
+ return True
80
+ except Exception:
81
+ return False
@@ -263,10 +263,18 @@ def _is_paste_hud(hit) -> bool:
263
263
 
264
264
 
265
265
  def shows_paste_hud(hits) -> bool:
266
- """True when one OCR hit reads like the phone's "Pasting from …" progress
267
- box (compared like probes: NFKC, lowercase, whitespace removed). While it
268
- shows, a paste is still on its way to the phone."""
269
- return any(_is_paste_hud(hit) for hit in hits)
266
+ """True when the OCR read shows the phone's "Pasting from …" progress box
267
+ (compared like probes: NFKC, lowercase, whitespace removed). While it
268
+ shows, a paste is still on its way to the phone.
269
+
270
+ 0.2.7: one hit, or two consecutive hits read together — OCR can
271
+ split "Pasting" and "from" into two hits. Only neighbours are joined
272
+ (not the whole screen), and a false match can only block a restore or a
273
+ confirmation (fail-closed), never license one."""
274
+ texts = [str(getattr(hit, "text", hit)) for hit in hits]
275
+ if any(PASTE_HUD_PROBE in _compact(t) for t in texts):
276
+ return True
277
+ return any(PASTE_HUD_PROBE in _compact(a + b) for a, b in zip(texts, texts[1:]))
270
278
 
271
279
 
272
280
  def screen_shows_text(text: str, read_screen) -> bool:
@@ -43,13 +43,34 @@ class WindowBounds:
43
43
  )
44
44
 
45
45
 
46
+ # Device run 2026-11-07: while the phone's keyboard is composing (a Pinyin "x" with its underline),
47
+ # iPhone Mirroring adds a 397x28 AXDialog window — the candidate bar — and System Events lists it as
48
+ # window 1, ahead of the phone (AXStandardWindow). Every script that reads the mirror window starts
49
+ # with this static block: mi is the index of the first AXStandardWindow, else 1 as before. Fixed text
50
+ # joined into the scripts below — no runtime value is interpolated (invariant 1).
51
+ # Device run 2026-11-08 03:44: the first version kept `contents of cand`, which System Events turns
52
+ # into a reference BY NAME (window "iPhone Mirroring"); during a connection blip that name did not
53
+ # resolve and `position of` failed with -1728. The index is re-read on every call, like window 1 was.
54
+ _PICK_WINDOW = '''
55
+ set mi to 1
56
+ repeat with i from 1 to (count of windows)
57
+ try
58
+ if ((subrole of window i) as text) is "AXStandardWindow" then
59
+ set mi to i
60
+ exit repeat
61
+ end if
62
+ end try
63
+ end repeat
64
+ '''
65
+
46
66
  _GET_BOUNDS_SCRIPT = '''
47
67
  tell application "System Events"
48
68
  tell process "iPhone Mirroring"
49
69
  set winCount to count of windows
50
70
  if winCount is 0 then return "NO_WINDOW"
51
- set {x, y} to position of window 1
52
- set {w, h} to size of window 1
71
+ ''' + _PICK_WINDOW + '''
72
+ set {x, y} to position of window mi
73
+ set {w, h} to size of window mi
53
74
  return (x as text) & "," & (y as text) & "," & (w as text) & "," & (h as text)
54
75
  end tell
55
76
  end tell
@@ -155,7 +176,15 @@ def get_bounds() -> WindowBounds:
155
176
  Raises WindowError if the app is not running or has no window
156
177
  (e.g. the window was closed but the process lives on).
157
178
  """
158
- out = _run_osascript(_GET_BOUNDS_SCRIPT)
179
+ try:
180
+ out = _run_osascript(_GET_BOUNDS_SCRIPT)
181
+ except WindowError:
182
+ # device run 2026-11-08 03:44: System Events lost the window for a moment during a
183
+ # connection blip (-1728). A read sends nothing to the phone, so one retry is safe.
184
+ import time
185
+
186
+ time.sleep(0.3)
187
+ out = _run_osascript(_GET_BOUNDS_SCRIPT)
159
188
  if out == "NO_WINDOW":
160
189
  # Window closed but process alive: re-activate to restore it.
161
190
  subprocess.run(
@@ -180,7 +209,7 @@ def get_bounds() -> WindowBounds:
180
209
  return WindowBounds(x=x, y=y, width=w, height=h)
181
210
 
182
211
 
183
- # Language-independent mirror-state probe. When the mirroring session is live, window 1 contains a
212
+ # Language-independent mirror-state probe. When the mirroring session is live, the mirror window (window mi, see _PICK_WINDOW) contains a
184
213
  # single group (the AXHostingView) with no children; when an overlay is shown (paused, connecting,
185
214
  # "iPhone in use", …) that group gains child elements (image / static text / button). Overlay text
186
215
  # is localized, so the decision never matches on text — only on structure (child count, classes).
@@ -212,7 +241,8 @@ tell application "System Events"
212
241
  tell process "iPhone Mirroring"
213
242
  set winCount to count of windows
214
243
  if winCount is 0 then return "NO_WINDOW"
215
- tell window 1
244
+ ''' + _PICK_WINDOW + '''
245
+ tell window mi
216
246
  if not (exists group 1) then return "NO_GROUP"
217
247
  set els to UI elements of group 1
218
248
  if (count of els) is 0 then return ""
@@ -259,7 +289,8 @@ end tell
259
289
  _CLICK_RESUME_SCRIPT = '''
260
290
  tell application "System Events"
261
291
  tell process "iPhone Mirroring"
262
- tell window 1
292
+ ''' + _PICK_WINDOW + '''
293
+ tell window mi
263
294
  set target to missing value
264
295
  set n to 0
265
296
  repeat with b in (buttons of group 1)
@@ -513,6 +544,8 @@ def _move_pointer_off_window() -> bool:
513
544
  None, Quartz.kCGEventMouseMoved, (x, y), Quartz.kCGMouseButtonLeft
514
545
  )
515
546
  Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev)
547
+ from . import pointer
548
+ pointer.moved_to(x, y) # 0.2.7: the CLI puts the pointer back after the command
516
549
  return True
517
550
  except Exception:
518
551
  return False
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "noracu",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
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",
@@ -13,8 +13,8 @@
13
13
  "test": "node test/engine-unit.mjs && node test/e2e.mjs",
14
14
  "test:ci": "node test/engine-unit.mjs && NORACU_CI=1 node test/e2e.mjs",
15
15
  "test:imctl": "cd imctl && ${NORACU_PYTHON:-python3} tests/test_smoke.py",
16
- "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",
17
- "prepublishOnly": "npm run check && node scripts/check-pack.mjs && node scripts/gen-tools.mjs && git diff --exit-code docs/tools.md"
16
+ "check": "node --check src/server.mjs && node --check src/mac-ax.js && node --check scripts/gen-tools.mjs && node --check scripts/release-gate.mjs && python3 -c \"import ast,sys; [ast.parse(open(f).read(), f) for f in sys.argv[1:]]\" imctl/src/imctl/*.py",
17
+ "prepublishOnly": "npm run check && node scripts/release-gate.mjs && node scripts/check-pack.mjs && node scripts/gen-tools.mjs && git diff --exit-code docs/tools.md"
18
18
  },
19
19
  "engines": {
20
20
  "node": ">=20"