noracu 0.2.3 → 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/docs/usage.md CHANGED
@@ -285,7 +285,7 @@ model — don't let it override the task.
285
285
  | `mirror_setup_required: …` | iPhone Mirroring shows a setup or welcome screen — finish it yourself in its window, then call `phone_launch` |
286
286
  | `menu_unknown: …` | `phone_home` or `phone_app_switcher` menu command timed out (`delivery=unknown, retry=unsafe`) — inspect `phone_screenshot` before retrying |
287
287
  | `imctl_timeout: …` | a phone step ran past its time limit and was stopped — check `phone_status` / `phone_screenshot` before retrying (after `phone_open`, noracu goes back to the Home Screen); raise `NORACU_PHONE_TIMEOUT_MS` on a slow Mac |
288
- | `imctl unavailable: no python3 with pyobjc found …` | install pyobjc for a python3 (`python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit`) or set `NORACU_PYTHON` |
288
+ | `imctl unavailable: no python3 with pyobjc found …` | install pyobjc for a python3 (`python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-Cocoa`) or set `NORACU_PYTHON` |
289
289
 
290
290
  ## 9. iPhone layer
291
291
 
@@ -336,16 +336,25 @@ when the state cannot be read), and `phone_ocr` / `phone_find` start with a
336
336
  `phone_scroll {"direction": "down", "distance": 0.5}` moves the list under the
337
337
  mirror by about half a window, with trackpad-style scroll events; a vertical
338
338
  `phone_swipe` drag does not scroll lists in iPhone Mirroring, so keep swipes
339
- for gestures such as Home Screen paging.
339
+ for gestures such as Home Screen paging. Start a page swipe in the empty strip
340
+ just above the Dock (y about 0.80): the mirror delivers a drag as pointer
341
+ input, and one that starts on an app icon picks the icon up and moves it — it
342
+ can rearrange the Home Screen or drop the icon on another one and make a folder.
340
343
 
341
344
  `phone_type` pastes through the clipboard with a real Command-V chord (never
342
345
  echoing the typed text), saving every clipboard item and type, clearing
343
346
  concealed or transient items instead of copying, and restoring the clipboard
344
- once OCR sees the pasted text appear on the phone (more often than before the
345
- paste — text already on screen does not count). Universal Clipboard or >64 MB
346
- items are not copied and leave the typed text on the clipboard; if the paste
347
- only shows up a few seconds late (still reported as typed — do not type it
348
- 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.
349
358
  `phone_open {"app": "Calculator"}` opens Spotlight through iPhone Mirroring's
350
359
  own shortcut, pastes the name, and taps it only when Spotlight's Top Hit card
351
360
  shows exactly that name (a web suggestion or Settings row with the same name
@@ -353,7 +362,11 @@ is never tapped); otherwise it returns to the Home Screen and reports
353
362
  `app not found` (`delivery=delivered_unverified, retry=safe`). A paste can take
354
363
  several seconds to reach the iPhone: when the
355
364
  name never shows up, `phone_open` waits up to 15 s and then reports
356
- `open_not_confirmed` (retry) rather than `app not found`. Use the name the phone shows under the icon (`拼多多`, not
365
+ `open_not_confirmed` (retry) rather than `app not found`. OCR rarely reads a
366
+ one- or two-letter name such as `X`, in the Top Hit card or the search field,
367
+ so for those `phone_open` does not wait the 15 s: it reports `open_not_confirmed`
368
+ and taps nothing — open such an app from its Home Screen icon
369
+ (`phone_screenshot`, then `phone_tap`). Use the name the phone shows under the icon (`拼多多`, not
357
370
  `Pinduoduo`); it reads Spotlight's English "Top Hit" label, so on an iPhone
358
371
  set to another language set `NORACU_TOPHIT_LABELS` to the label the phone shows.
359
372
 
package/imctl/README.md CHANGED
@@ -63,7 +63,7 @@ the mirroring gesture recognizer:
63
63
 
64
64
  - macOS 15 (Sequoia) or later with **iPhone Mirroring** configured
65
65
  (iPhone signed into the same Apple Account, Bluetooth + Wi-Fi on)
66
- - Python 3.10+ with pyobjc: `python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit`
66
+ - Python 3.10+ with pyobjc: `python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-Cocoa`
67
67
  (Apple's `/usr/bin/python3` usually lacks it; Homebrew's `python3` is the common working choice)
68
68
  - **Accessibility** and **Screen Recording** permissions granted to
69
69
  your terminal app (System Settings → Privacy & Security)
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "imctl"
7
- version = "0.2.3"
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,7 +27,7 @@ dependencies = []
27
27
  pyobjc = [
28
28
  "pyobjc-framework-Quartz>=10.0",
29
29
  "pyobjc-framework-Vision>=10.0",
30
- "pyobjc-framework-AppKit>=10.0",
30
+ "pyobjc-framework-Cocoa>=10.0",
31
31
  ]
32
32
 
33
33
  [project.scripts]
@@ -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.3"
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,17 @@ 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
566
+ if result == "short_unreadable":
567
+ print(f"open_not_confirmed: could not read {args.app!r} in Spotlight — OCR often misses a "
568
+ "one- or two-letter name, in the Top Hit card and in the search field alike, so "
569
+ f"nothing was tapped and the app may well be installed; {home_note} — open it from "
570
+ "its Home Screen icon instead (phone_screenshot, then phone_tap)", file=sys.stderr)
571
+ return 4
549
572
  if result == "not_typed":
550
573
  print(f"open_not_confirmed: the name {args.app!r} was pasted into Spotlight but never "
551
574
  "showed up on the phone (a paste can take several seconds to reach the iPhone, "
@@ -137,14 +137,25 @@ def scroll_checked(direction, distance=0.5, *, luma=None, scroller=None,
137
137
  return verify.mean_abs_diff(before, after) >= SCROLL_MIN_DIFF
138
138
 
139
139
 
140
+ # F45 (device run 2026-11-07): iPhone Mirroring turns a mouse drag into pointer input, and a
141
+ # pointer drag that starts on an app icon picks the icon up at once. A page swipe at mid-height
142
+ # starts on an icon row: twice it carried an icon onto another one and made a folder (and left the
143
+ # Home Screen in edit mode, where every icon shows a "−" delete badge). Page swipes start in the
144
+ # empty strip between the last icon row and the Dock, where the page dots are; five swipes there
145
+ # paged without picking anything up.
146
+ PAGE_SWIPE_NY = 0.80
147
+ PAGE_SWIPE_FROM_NX = 0.9
148
+ PAGE_SWIPE_TO_NX = 0.1
149
+
150
+
140
151
  def page_left() -> None:
141
- """Swipe right-to-left: go to the next home-screen page."""
142
- inp.swipe(0.8, 0.5, 0.2, 0.5, duration_ms=280)
152
+ """Swipe right-to-left: go to the next home-screen page (from the strip above the Dock, F45)."""
153
+ inp.swipe(PAGE_SWIPE_FROM_NX, PAGE_SWIPE_NY, PAGE_SWIPE_TO_NX, PAGE_SWIPE_NY, duration_ms=280)
143
154
 
144
155
 
145
156
  def page_right() -> None:
146
- """Swipe left-to-right: go to the previous home-screen page."""
147
- inp.swipe(0.2, 0.5, 0.8, 0.5, duration_ms=280)
157
+ """Swipe left-to-right: go to the previous home-screen page (from the strip above the Dock, F45)."""
158
+ inp.swipe(PAGE_SWIPE_TO_NX, PAGE_SWIPE_NY, PAGE_SWIPE_FROM_NX, PAGE_SWIPE_NY, duration_ms=280)
148
159
 
149
160
 
150
161
  def pull_down_search() -> None:
@@ -367,10 +378,43 @@ _LABEL_LOOKALIKES = {
367
378
  # Spotlight is open (the header measured at ny ≈ 0.14).
368
379
  SPOTLIGHT_HEADER_MAX_NY = 0.3
369
380
 
370
- # Spotlight's search field is at the bottom of the window (ny >= SEARCH_FIELD_NY) and echoes the
371
- # typed query. choose_app_hit never takes a label there; open_app reads that echo as the proof
372
- # that a late paste has reached the phone (F42).
373
- SEARCH_FIELD_NY = 0.88
381
+ # Spotlight's search field is in the bottom part of the window (ny >= SEARCH_FIELD_NY) and echoes
382
+ # the typed query. choose_app_hit never takes a label there; open_app reads that echo as the proof
383
+ # that a late paste has reached the phone (F42). 2026-11-06 device run (macOS 27.2 / iOS 27): the
384
+ # field is not always at the very bottom — it sat at ny ≈ 0.93 on one screen and floated at
385
+ # ny ≈ 0.82 on others ("Q Search" read at 0.821 before typing, the query at 0.821–0.823 after),
386
+ # where the old 0.88 bound never saw it: every unmatched name waited out the late-paste reads and
387
+ # was reported as never typed, and "X" ran out of time. The Top Hit card stays above 0.3.
388
+ SEARCH_FIELD_NY = 0.78
389
+
390
+ # The field echo is only evidence that the paste arrived — it never picks what is tapped — so a
391
+ # long name may differ from it by an OCR slip or two (seen on the device: "Zaxwv" and "Zqxw" for
392
+ # "Zqxwv"). Short names stay exact.
393
+ ECHO_FUZZY_MIN_LEN = 6 # names this long tolerate one edit …
394
+ ECHO_FUZZY_TWO_LEN = 14 # … and this long, two
395
+
396
+
397
+ def _edit_distance(a: str, b: str, limit: int) -> int:
398
+ """Levenshtein distance between a and b, or limit + 1 once it is certain to exceed limit."""
399
+ if abs(len(a) - len(b)) > limit:
400
+ return limit + 1
401
+ prev = list(range(len(b) + 1))
402
+ for i, ca in enumerate(a, 1):
403
+ cur = [i]
404
+ for j, cb in enumerate(b, 1):
405
+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
406
+ if min(cur) > limit:
407
+ return limit + 1
408
+ prev = cur
409
+ return prev[-1]
410
+
411
+
412
+ def _echo_matches(got: str, want: str) -> bool:
413
+ """The field text ``got`` shows the query ``want`` (both _norm_label'ed)."""
414
+ if got == want:
415
+ return True
416
+ edits = (1 if len(want) >= ECHO_FUZZY_MIN_LEN else 0) + (1 if len(want) >= ECHO_FUZZY_TWO_LEN else 0)
417
+ return edits > 0 and _edit_distance(got, want, edits) <= edits
374
418
 
375
419
 
376
420
  def _norm_label(s: str) -> str:
@@ -389,7 +433,11 @@ def _norm_label(s: str) -> str:
389
433
  return "".join(_LABEL_LOOKALIKES.get(ch, ch) for ch in s)
390
434
 
391
435
 
392
- 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:
393
441
  """Pick the Spotlight result row for ``name`` from OCR hits.
394
442
 
395
443
  iOS 26 draws the Spotlight search field at the BOTTOM of the screen
@@ -401,9 +449,15 @@ def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
401
449
  "x", "×", "X." or full-width "X"), and
402
450
  - lie above the bottom search-field zone (ny < 0.88).
403
451
  The comparison stays EXACT — substring/prefix matching is
404
- forbidden: "X" must never hit "Xcode" or "X Corp". When several
405
- rows match, the topmost (smallest ny) wins. Returns None when
406
- 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.
407
461
 
408
462
  F35 (2026-11-05 real-device): an exact label is not an app. The
409
463
  query "Pinduoduo" matched a Chrome *suggestion* row of that name
@@ -420,7 +474,7 @@ def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
420
474
  header = _tophit_header(hits)
421
475
  if header is None:
422
476
  return None
423
- best = None
477
+ found = []
424
478
  for hit in hits:
425
479
  if _norm_label(hit.text) != want:
426
480
  continue
@@ -428,13 +482,19 @@ def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
428
482
  continue # the search field echoing the query
429
483
  if not header.ny < hit.ny <= header.ny + TOP_HIT_CARD_SPAN:
430
484
  continue # outside the Top Hit card (F35)
431
- if best is None or hit.ny < best.ny:
432
- 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
433
493
  return best
434
494
 
435
495
 
436
496
  def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep,
437
- deadline=None, clock=time.monotonic):
497
+ deadline=None, clock=time.monotonic, ambiguous=None):
438
498
  """Read the screen up to ``attempts`` times for a Spotlight result row.
439
499
 
440
500
  Each pass calls ``read_screen()`` for OCR hits and hands them to
@@ -457,6 +517,7 @@ def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep,
457
517
  stays exact either way. Long names keep the exact original
458
518
  read/sleep sequence. ``deadline`` (a ``clock()`` value) is checked
459
519
  before every read; once reached, no further read happens.
520
+ ``ambiguous`` is handed to every choose_app_hit() call (Y6).
460
521
  """
461
522
  short = len(_norm_label(name)) <= 2
462
523
 
@@ -478,7 +539,7 @@ def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep,
478
539
  for kwargs in reads:
479
540
  if expired():
480
541
  return None # out of time before this read (open_app reports it)
481
- hit = choose_app_hit(read_screen(**kwargs), name)
542
+ hit = choose_app_hit(read_screen(**kwargs), name, ambiguous)
482
543
  if hit is not None:
483
544
  return hit
484
545
  return None
@@ -511,6 +572,11 @@ OPEN_DEADLINE_S = 38.0
511
572
  # is enough — a Top Hit card alone may still be the previous query's.
512
573
  OPEN_LATE_PASTE_S = 15.0 # a later device run under load saw ~15 s from Cmd+V to the echo
513
574
  OPEN_LATE_PASTE_PASSES = 30 # a cap for injected clocks; the time limit normally ends it first
575
+ # A one- or two-letter name almost never shows as an echo (2026-11-06 device run: "X" in the
576
+ # field in 2 of 24 reads, its Top Hit label in none), so waiting for one only ran phone_open into
577
+ # its time limit. Short names get this much late reading — at least one full pass — and then
578
+ # open_app reports "short_unreadable" instead of not_found / not_typed, which it cannot tell apart.
579
+ OPEN_LATE_SHORT_S = 4.0
514
580
 
515
581
 
516
582
  # The Spotlight "Top Hit" section label phone_open looks for. English by default;
@@ -527,11 +593,13 @@ TOP_HIT_LABELS = _tophit_labels(os.environ.get("NORACU_TOPHIT_LABELS"))
527
593
 
528
594
 
529
595
  def _field_echo(hits, name) -> bool:
530
- """True when the search field shows exactly ``name`` (F42).
596
+ """True when the search field shows ``name`` (F42).
531
597
 
532
598
  The field is the bottom zone (ny >= SEARCH_FIELD_NY); OCR may read the
533
- magnifier glyph in front of the text as a "Q". Exact after _norm_label,
534
- like every other label comparison here.
599
+ magnifier glyph in front of the text as a "Q". Compared after
600
+ _norm_label; a name of ECHO_FUZZY_MIN_LEN characters or more tolerates
601
+ one OCR slip (two from ECHO_FUZZY_TWO_LEN) — this only says the paste
602
+ arrived, it never decides a tap.
535
603
  """
536
604
  want = _norm_label(name)
537
605
  for hit in hits:
@@ -539,7 +607,7 @@ def _field_echo(hits, name) -> bool:
539
607
  continue
540
608
  got = _norm_label(hit.text)
541
609
  # the magnifier glyph may come back as "Q", "Q." or "Q:" in front of the text
542
- if got == want or re.sub(r"^q[\s.,:;·•]*", "", got, count=1) == want:
610
+ if _echo_matches(got, want) or _echo_matches(re.sub(r"^q[\s.,:;·•]*", "", got, count=1), want):
543
611
  return True
544
612
  return False
545
613
 
@@ -656,9 +724,15 @@ def open_app(name: str, *, spotlight_open: bool = False,
656
724
  name during the late-paste reads either — the name may never have
657
725
  reached the phone, so this is no evidence the app is missing; back on
658
726
  the Home Screen);
727
+ "short_unreadable" (a one- or two-letter name that no read matched
728
+ within OPEN_LATE_SHORT_S of late reading: OCR misses such text in the
729
+ Top Hit card and the search field alike, so whether it was typed or
730
+ the app exists is unknown — nothing was tapped; back on the Home Screen);
659
731
  "deadline" (the OPEN_DEADLINE_S budget ran out before a tap; back on
660
- the Home Screen); or "spotlight_unavailable" (Spotlight could not be
661
- 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).
662
736
 
663
737
  ``read_screen`` (default vision.read_screen), ``luma`` (default
664
738
  verify.window_luma), ``sleep``, ``tap`` (default inp.tap),
@@ -696,6 +770,7 @@ def open_app(name: str, *, spotlight_open: bool = False,
696
770
  deadline = None if deadline_s is None else clock() + deadline_s
697
771
  saw_top_hit = [False]
698
772
  saw_echo = [False]
773
+ ambiguous: list = [] # Y6: a read showed the name at two or more spots in the card
699
774
 
700
775
  def read_screen(**kwargs):
701
776
  # F33: every later read is also evidence for a clipboard restore an
@@ -739,12 +814,12 @@ def open_app(name: str, *, spotlight_open: bool = False,
739
814
  hit = None
740
815
  if typed is not False:
741
816
  hit = find_app_hit(read_screen, name, attempts=2, sleep=sleep,
742
- deadline=deadline, clock=clock)
817
+ deadline=deadline, clock=clock, ambiguous=ambiguous)
743
818
  if hit is None and not saw_echo[0]:
744
819
  # F33/F42: the name is not in the search field yet — the paste may still be on its
745
820
  # way, whether type_text missed it or took another change for it (a clear that
746
821
  # landed late redraws the results: seen on the device after a back-to-back open)
747
- limit = clock() + OPEN_LATE_PASTE_S
822
+ limit = clock() + (OPEN_LATE_SHORT_S if short else OPEN_LATE_PASTE_S)
748
823
  if deadline is not None:
749
824
  limit = min(limit, deadline)
750
825
  echo_passes = 0
@@ -758,7 +833,8 @@ def open_app(name: str, *, spotlight_open: bool = False,
758
833
  break
759
834
  sleep(1.0)
760
835
  hit = find_app_hit(read_screen, name, attempts=1, sleep=sleep,
761
- deadline=deadline if confirming else limit, clock=clock)
836
+ deadline=deadline if confirming else limit, clock=clock,
837
+ ambiguous=ambiguous)
762
838
  if hit is not None:
763
839
  break
764
840
  # only the search field showing the name proves the paste arrived — a Top Hit
@@ -772,6 +848,12 @@ def open_app(name: str, *, spotlight_open: bool = False,
772
848
  tidy()
773
849
  if out_of_time():
774
850
  return "deadline"
851
+ if ambiguous:
852
+ return "ambiguous" # Y6: the card showed the name at more than one spot
853
+ if short:
854
+ # OCR misses one- and two-letter text in the card and in the field alike: neither
855
+ # "not typed" nor "not found" is known — say that instead (2026-11-06 device run)
856
+ return "short_unreadable"
775
857
  if not saw_echo[0]:
776
858
  return "not_typed" # F42: the name never showed up in the search field
777
859
  return "not_found" if saw_top_hit[0] else "no_top_hit"
@@ -783,13 +865,21 @@ def open_app(name: str, *, spotlight_open: bool = False,
783
865
  # ① the Spotlight results can still be reflowing when
784
866
  # find_app_hit returns; re-read after 0.5s and re-pick.
785
867
  sleep(0.5)
786
- 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"
787
874
  if again is not None:
788
875
  if math.hypot(again.nx - hit.nx, again.ny - hit.ny) > 0.02:
789
876
  # the row moved: the second read wins, with at most
790
877
  # one more read — still moving → the last one wins
791
878
  hit = again
792
- once_more = choose_app_hit(reread(), name)
879
+ once_more = choose_app_hit(reread(), name, split)
880
+ if split:
881
+ tidy()
882
+ return "ambiguous"
793
883
  if (once_more is not None
794
884
  and math.hypot(once_more.nx - hit.nx,
795
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.3",
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",
@@ -12,6 +12,7 @@
12
12
  "start": "node src/server.mjs",
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
+ "test:imctl": "cd imctl && ${NORACU_PYTHON:-python3} tests/test_smoke.py",
15
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",
16
17
  "prepublishOnly": "npm run check && node scripts/check-pack.mjs && node scripts/gen-tools.mjs && git diff --exit-code docs/tools.md"
17
18
  },