noracu 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,20 +21,34 @@ from __future__ import annotations
21
21
 
22
22
  import argparse
23
23
  import json
24
+ import math
24
25
  import os
25
26
  import signal
26
27
  import sys
27
28
  import tempfile
29
+ import time
28
30
 
29
31
  from . import gestures, input, verify, vision
30
32
  from .vision import CaptureError
31
- from .window import WindowError, ensure_frontmost, get_overlay
33
+ import subprocess
32
34
 
33
- # F31: every phone input command starts in _require_live(), which first brings
34
- # the mirror to the front — switching Spaces if needed and waiting for a real
35
- # frame — so the expect OCR and scroll baseline that follow read the phone, not
36
- # another Space or a transition frame. Module-level so tests can swap it.
35
+ from .window import WindowError, ensure_frontmost, get_overlay, is_frontmost
36
+
37
+ # F31 / R13 §3: every phone input command starts in _require_live(), which probes
38
+ # get_overlay() first so a paused or stopped mirror refuses without stealing focus,
39
+ # then brings the mirror to the front (switching Spaces if needed and waiting for a
40
+ # real frame) before any capture or input. Module-level callables so tests can swap them.
37
41
  _bring_front = ensure_frontmost
42
+ _is_front = is_frontmost
43
+ sleep = time.sleep
44
+
45
+ _MIRROR_NOT_RUNNING_LINE = (
46
+ "mirror_not_live: iPhone Mirroring is not running — call phone_launch first"
47
+ )
48
+ _MIRROR_STATE_UNKNOWN_LINE = (
49
+ "mirror_state_unknown: could not tell whether iPhone Mirroring is live — "
50
+ "nothing was sent; retry, or call phone_status"
51
+ )
38
52
 
39
53
  # F25: one line, one exit code for every capture failure. The pixels a check
40
54
  # needed are not the phone's — report that, never guess from whatever
@@ -45,29 +59,85 @@ _CAPTURE_FAILED_LINE = (
45
59
  )
46
60
 
47
61
 
62
+ # R19: the same failure while checking --expect, before the first event
63
+ _CAPTURE_FAILED_EXPECT_LINE = (
64
+ "capture_failed: could not capture the iPhone Mirroring window to check --expect "
65
+ "(it may be hidden, minimized or on another Space); no image was returned, so nothing was sent"
66
+ )
67
+
68
+
48
69
  def _capture_failed() -> int:
49
70
  """Print the F25 capture-failure line; exit code 7."""
50
71
  print(_CAPTURE_FAILED_LINE, file=sys.stderr)
51
72
  return 7
52
73
 
53
74
 
54
- def _require_live() -> int | None:
55
- """Refuse phone input while the mirror shows an overlay instead of the phone stream.
75
+ def _mirror_not_live(overlay: dict) -> int:
76
+ label = overlay.get("overlay") or "overlay shown"
77
+ print(
78
+ f"mirror_not_live: {label} — call phone_launch (or imctl resume) first",
79
+ file=sys.stderr,
80
+ )
81
+ return 3
56
82
 
57
- Returns exit code 3 after printing a `mirror_not_live:` line when the mirror is
58
- verifiably not live; returns None (allow) when live or unknown (fail-open).
59
- F31: brings the mirror to the front first (see _bring_front).
83
+
84
+ def _require_live() -> int | None:
85
+ """Refuse phone input unless iPhone Mirroring is verifiably live (fail-closed).
86
+
87
+ Probes get_overlay() first to avoid stealing focus when the mirror is paused or off:
88
+ - reason in ("not_running", "no_window") -> mirror_not_live (exit 3), no _bring_front
89
+ - live is False -> mirror_not_live (exit 3), no _bring_front
90
+ - live is True -> _bring_front() (F31), then allow (None)
91
+ - live is None -> _bring_front(), sleep(0.4), probe again:
92
+ True -> allow; False -> mirror_not_live; still None -> mirror_state_unknown (exit 3).
60
93
  """
61
- _bring_front()
62
94
  overlay = get_overlay()
95
+ if overlay.get("reason") in ("not_running", "no_window"):
96
+ print(_MIRROR_NOT_RUNNING_LINE, file=sys.stderr)
97
+ return 3
63
98
  if overlay["live"] is False:
64
- label = overlay["overlay"] or "overlay shown"
65
- print(
66
- f"mirror_not_live: {label} — call phone_launch (or imctl resume) first",
67
- file=sys.stderr,
68
- )
99
+ return _mirror_not_live(overlay)
100
+ if overlay["live"] is True:
101
+ # R18: bringing it forward can take a Space switch; the mirror may stop being live meanwhile
102
+ # (the iPhone was picked up) — so when it was not in front, look again afterwards
103
+ try:
104
+ was_front = _is_front()
105
+ except Exception:
106
+ was_front = False
107
+ try:
108
+ _bring_front()
109
+ except (WindowError, subprocess.TimeoutExpired):
110
+ print(_MIRROR_STATE_UNKNOWN_LINE, file=sys.stderr)
111
+ return 3
112
+ if was_front:
113
+ return None
114
+ overlay = get_overlay()
115
+ if overlay["live"] is True:
116
+ return None
117
+ if overlay["live"] is False:
118
+ return _mirror_not_live(overlay)
119
+ print(_MIRROR_STATE_UNKNOWN_LINE, file=sys.stderr)
69
120
  return 3
70
- return None
121
+ try:
122
+ _bring_front()
123
+ except (WindowError, subprocess.TimeoutExpired):
124
+ again = get_overlay()
125
+ if again.get("reason") in ("not_running", "no_window"):
126
+ print(_MIRROR_NOT_RUNNING_LINE, file=sys.stderr)
127
+ return 3
128
+ print(_MIRROR_STATE_UNKNOWN_LINE, file=sys.stderr)
129
+ return 3
130
+ sleep(0.4)
131
+ overlay = get_overlay()
132
+ if overlay.get("reason") in ("not_running", "no_window"):
133
+ print(_MIRROR_NOT_RUNNING_LINE, file=sys.stderr)
134
+ return 3
135
+ if overlay["live"] is True:
136
+ return None
137
+ if overlay["live"] is False:
138
+ return _mirror_not_live(overlay)
139
+ print(_MIRROR_STATE_UNKNOWN_LINE, file=sys.stderr)
140
+ return 3
71
141
 
72
142
 
73
143
  def _require_expect(args, read_screen=None, read_sweep=None) -> int | None:
@@ -100,8 +170,9 @@ def _require_expect(args, read_screen=None, read_sweep=None) -> int | None:
100
170
  hits = read_sweep()
101
171
  except (WindowError, CaptureError):
102
172
  # F25: an unreadable screen is not a match — refuse exactly like
103
- # expect_not_found; nothing is sent.
104
- return _capture_failed()
173
+ # expect_not_found; nothing is sent (R19: and the line says so).
174
+ print(_CAPTURE_FAILED_EXPECT_LINE, file=sys.stderr)
175
+ return 7
105
176
  if verify.screen_contains(expect, hits):
106
177
  return None
107
178
  print(
@@ -141,19 +212,40 @@ def _cmd_tap(args) -> int:
141
212
  return 0
142
213
 
143
214
 
215
+ def _invalid_duration(exc: ValueError) -> int:
216
+ print(f"invalid_args: {exc}; nothing was sent", file=sys.stderr)
217
+ return 2
218
+
219
+
144
220
  def _cmd_longpress(args) -> int:
221
+ # R19: a bad duration is refused before the mirror is brought forward
222
+ try:
223
+ input._check_duration(_longpress_duration(args), 0.01, 10, "long-press duration (s)")
224
+ except ValueError as exc:
225
+ return _invalid_duration(exc)
145
226
  guard = _require_live()
146
227
  if guard is not None:
147
228
  return guard
148
229
  guard = _require_expect(args)
149
230
  if guard is not None:
150
231
  return guard
151
- input.long_press(args.x, args.y, args.duration)
152
- print(f"long-pressed ({args.x}, {args.y}) for {args.duration}s")
232
+ duration = _longpress_duration(args)
233
+ input.long_press(args.x, args.y, duration)
234
+ print(f"long-pressed ({args.x}, {args.y}) for {duration}s")
153
235
  return 0
154
236
 
155
237
 
238
+ def _longpress_duration(args) -> float:
239
+ opt = getattr(args, "duration_opt", None)
240
+ pos = getattr(args, "duration", None)
241
+ return opt if opt is not None else pos if pos is not None else 0.8
242
+
243
+
156
244
  def _cmd_swipe(args) -> int:
245
+ try:
246
+ input._check_duration(args.ms, *input.SWIPE_MS_RANGE, "swipe duration (ms)")
247
+ except ValueError as exc:
248
+ return _invalid_duration(exc)
157
249
  guard = _require_live()
158
250
  if guard is not None:
159
251
  return guard
@@ -166,14 +258,20 @@ def _cmd_swipe(args) -> int:
166
258
 
167
259
 
168
260
  def _cmd_home(_args) -> int:
261
+ guard = _require_live()
262
+ if guard is not None:
263
+ return guard
169
264
  gestures.home()
170
265
  print("home gesture sent")
171
266
  return 0
172
267
 
173
268
 
174
269
  def _cmd_app_switcher(_args) -> int:
270
+ guard = _require_live()
271
+ if guard is not None:
272
+ return guard
175
273
  gestures.app_switcher()
176
- print("app switcher opened")
274
+ print("app switcher gesture sent")
177
275
  return 0
178
276
 
179
277
 
@@ -225,18 +323,120 @@ def _cmd_type(args) -> int:
225
323
  guard = _require_expect(args)
226
324
  if guard is not None:
227
325
  return guard
228
- if input.type_text(args.text, replace=args.replace):
229
- print(f"typed {args.text!r}")
326
+ report = {}
327
+ if input.type_text(args.text, replace=args.replace, report=report):
328
+ if report.get("seen", True):
329
+ print(f"typed {len(args.text)} chars")
330
+ return 0
331
+ if _late_paste_probe(args.text) is None:
332
+ # one character: OCR cannot read it back, only the picture changed
333
+ print(f"typed {len(args.text)} chars (the screen changed after the paste, but "
334
+ "OCR cannot read this text back — check the field; the clipboard still "
335
+ "holds the typed text)")
336
+ return 0
337
+ # device run 2026-11-06: only the picture changed (a selection highlight, a
338
+ # results list redraw) and OCR never saw the text — watch for it like an
339
+ # unconfirmed paste instead of reporting it typed
340
+ count_before = report.get("count_before")
341
+ late = _watch_late_paste(args.text, baseline=count_before)
342
+ 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()
345
+ # restores only under its own checks (a rise seen inside its window, the
346
+ # minimum hold, an untouched changeCount); after the fact, leaving the
347
+ # typed text on the clipboard is the choice that can never hand the phone
348
+ # 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)")
230
352
  return 0
353
+ watched = (f" or a further {LATE_PASTE_WATCH_S:.0f}s check"
354
+ if _late_paste_probe(args.text) else
355
+ " (one-character text cannot be confirmed by OCR afterwards)")
356
+ if args.replace and count_before:
357
+ # F41: the text was on screen before the paste, and a field replaced with
358
+ # the same text shows no change at all
359
+ advice = ("the text was already on screen before this paste, and replacing a "
360
+ "field with the same text shows no change — read the screen "
361
+ "(phone_ocr / phone_screenshot): if the field shows the text, it "
362
+ "holds it")
363
+ else:
364
+ advice = ("it may still land: read the screen (phone_ocr / phone_screenshot) "
365
+ "before typing again, or retype with replace=true")
231
366
  print(
232
- "type_not_confirmed: the paste did not show on screen within 2.5s; "
233
- "the clipboard still holds the typed text and your previous clipboard "
234
- "was not restored",
367
+ "type_not_confirmed: the paste did not show on screen within the 2.5s "
368
+ f"confirmation window{watched} — {advice}; the clipboard still holds the "
369
+ "typed text and your previous clipboard was not restored",
235
370
  file=sys.stderr,
236
371
  )
237
372
  return 4
238
373
 
239
374
 
375
+ # F38 (2026-11-05 real-device): a paste reported unconfirmed after 2.5 s showed up a
376
+ # few seconds later, and the caller's retry typed the text twice ("… case … case").
377
+ # Before type_not_confirmed, keep watching — read-only, no second Cmd+V — for up to
378
+ # this long.
379
+ # F42: on the device a paste reached the phone up to more than 10 s after Cmd+V.
380
+ LATE_PASTE_WATCH_S = 15.0 # needs two consecutive sightings ~1 s apart
381
+
382
+
383
+ def _late_paste_probe(text):
384
+ """The OCR probe for ``text``, or None when OCR cannot confirm it (< 2 chars)."""
385
+ return verify.text_probe(text)
386
+
387
+
388
+ def _watch_late_paste(text, *, baseline=None, read_screen=None, sleep=time.sleep,
389
+ clock=time.monotonic, watch_s=LATE_PASTE_WATCH_S):
390
+ """Seconds into the watch until ``text`` showed up on screen, or None.
391
+
392
+ Read-only: it never pastes again. ``baseline`` is type_text()'s pre-paste
393
+ count of the text's probe (F41); the paste counts as arrived once the count
394
+ is above it in TWO consecutive readable frames (one OCR misread is not
395
+ enough). Without a baseline (type_text() could not read the screen before
396
+ the paste) the watch's own first two readable frames set it — the higher
397
+ count, as in type_text(): text already on screen elsewhere is then never
398
+ taken for the paste, at the price of missing a paste that landed before
399
+ those frames (reported unconfirmed — the caller is told to read the
400
+ screen before typing again). Text too short for a probe is
401
+ not watched at all (None at once). A capture failure breaks the run of
402
+ sightings (F25), never counts as one. ``read_screen``, ``sleep`` and
403
+ ``clock`` are injectable for tests.
404
+ """
405
+ if _late_paste_probe(text) is None:
406
+ return None
407
+ if read_screen is None:
408
+ read_screen = vision.read_screen
409
+ floor = baseline
410
+ floor_reads = [] # without a baseline: the counts of the first two readable frames
411
+ t0 = clock()
412
+ run = 0
413
+ # a first sighting always gets its confirming read, even past the window,
414
+ # and that read follows after a short pause rather than the usual second
415
+ while clock() - t0 < watch_s or run == 1:
416
+ try:
417
+ hits = read_screen()
418
+ except Exception as exc:
419
+ if not verify.is_capture_error(exc):
420
+ raise
421
+ hits = None
422
+ if hits is None:
423
+ run = 0
424
+ else:
425
+ seen = verify.probe_count(text, hits)
426
+ if floor is None:
427
+ floor_reads.append(seen) # no pre-paste count: these frames set the floor
428
+ if len(floor_reads) == 2:
429
+ floor = max(floor_reads)
430
+ elif seen > floor:
431
+ run += 1
432
+ if run >= 2:
433
+ return clock() - t0
434
+ else:
435
+ run = 0
436
+ sleep(0.4 if run == 1 else 1.0)
437
+ return None
438
+
439
+
240
440
  def _cmd_key(args) -> int:
241
441
  guard = _require_live()
242
442
  if guard is not None:
@@ -274,21 +474,46 @@ def _cmd_find(args) -> int:
274
474
  return 0
275
475
 
276
476
 
477
+ def _open_deadline_kwargs(now=time.time) -> dict:
478
+ """open_app's time budget from NORACU_OPEN_DEADLINE_EPOCH, an absolute time the
479
+ server sets well before its own timeout (counted from the spawn, so start-up
480
+ and opening Spotlight are inside it). {} → open_app's default."""
481
+ try:
482
+ epoch = float(os.environ.get("NORACU_OPEN_DEADLINE_EPOCH", ""))
483
+ except ValueError:
484
+ return {}
485
+ if not math.isfinite(epoch) or epoch <= 0: # NaN, inf or nonsense
486
+ return {}
487
+ # already past → 0: open_app goes back to the Home Screen without clearing or typing
488
+ return {"deadline_s": max(0.0, epoch - now())}
489
+
490
+
277
491
  def _cmd_open(args) -> int:
278
492
  guard = _require_live()
279
493
  if guard is not None:
280
494
  return guard
281
495
  # Open Spotlight here (not inside open_app) so a failure can be
282
496
  # reported as its own condition instead of a bogus "app not found".
497
+ # Stopped from outside (SIGTERM → SystemExit): no tidy-up trip of its own. Going Home from here
498
+ # would bring the mirror forward and send a Cmd chord while the server may be stopping (and a
499
+ # SIGKILL 1.5 s later could leave Cmd held); after a timeout the server returns the phone to the
500
+ # Home Screen itself through the mirror's menu (no focus change, no chord).
501
+ return _open_and_report(args)
502
+
503
+
504
+ def _open_and_report(args) -> int:
505
+ tidy = {} # open_app records whether its trip back to the Home Screen worked
283
506
  try:
284
507
  # F34: one retry — on the device the Spotlight command was once
285
- # ignored right after an app closed. Each try starts from the Home
286
- # Screen, so a second try cannot toggle an open Spotlight shut.
508
+ # ignored right after an app closed. Each try goes Home first; when Home
509
+ # lands back in Spotlight (iOS 27, F43) the gate reports it open instead
510
+ # of toggling it shut.
287
511
  if not (gestures.open_spotlight_checked()
288
512
  or gestures.open_spotlight_checked()):
289
513
  result = "spotlight_unavailable"
290
514
  else:
291
- result = gestures.open_app(args.app, spotlight_open=True)
515
+ result = gestures.open_app(args.app, spotlight_open=True, report=tidy,
516
+ **_open_deadline_kwargs())
292
517
  except (WindowError, CaptureError):
293
518
  # F25: the Spotlight gate and the result matching both read the
294
519
  # mirroring window's pixels; without them nothing about the
@@ -297,16 +522,43 @@ def _cmd_open(args) -> int:
297
522
  if result == "opened":
298
523
  print(f"opened {args.app!r}")
299
524
  return 0
525
+ # every unsuccessful path ends with a trip back to the Home Screen; say so only
526
+ # when it worked
527
+ home_note = ("back on the Home Screen" if tidy.get("home") else
528
+ "could not go back to the Home Screen — Spotlight may still be open")
529
+ # the app-not-found lines mention the Home Screen only when the trip back failed
530
+ stuck = "" if tidy.get("home") else f"; {home_note}"
300
531
  if result == "not_found":
301
- print(f"app not found: {args.app!r}")
532
+ print(f"app not found: {args.app!r} (Spotlight's Top Hit did not show exactly "
533
+ f"this name — use the name the phone shows under the app icon){stuck}")
534
+ return 1
535
+ if result == "no_top_hit":
536
+ if os.environ.get("NORACU_TOPHIT_LABELS", "").strip():
537
+ print(f"app not found: {args.app!r} (Spotlight showed no Top Hit labelled "
538
+ f"{', '.join(repr(x) for x in gestures.TOP_HIT_LABELS)} — no app by that "
539
+ f"name, or NORACU_TOPHIT_LABELS does not match your iPhone's label){stuck}")
540
+ else:
541
+ print(f"app not found: {args.app!r} (Spotlight showed no Top Hit — no app by that "
542
+ "name, or the iPhone is not set to English: phone_open reads Spotlight's "
543
+ f"\"Top Hit\" label; set NORACU_TOPHIT_LABELS to the label your iPhone shows){stuck}")
302
544
  return 1
545
+ if result == "deadline":
546
+ print(f"open_not_confirmed: ran out of time opening {args.app!r} (the Mac may be "
547
+ f"under heavy load); {home_note}", file=sys.stderr)
548
+ return 4
549
+ if result == "not_typed":
550
+ print(f"open_not_confirmed: the name {args.app!r} was pasted into Spotlight but never "
551
+ "showed up on the phone (a paste can take several seconds to reach the iPhone, "
552
+ "or be lost; an iPhone not set to English also needs NORACU_TOPHIT_LABELS) — "
553
+ f"nothing was tapped; {home_note}; retry phone_open", file=sys.stderr)
554
+ return 4
303
555
  if result == "spotlight_unavailable":
304
556
  print("spotlight unavailable (could not reach the Home Screen, the menu command failed, or the screen did not change)")
305
557
  return 1
306
558
  # "not_confirmed" (F24): the row — and possibly the Top Hit icon —
307
559
  # was tapped but the app never verifiably opened; the phone is
308
560
  # back on the Home Screen.
309
- print(f"open_not_confirmed: tapped {args.app!r} in Spotlight but the app did not open; back on the Home Screen", file=sys.stderr)
561
+ print(f"open_not_confirmed: tapped {args.app!r} in Spotlight but the app did not open; {home_note}", file=sys.stderr)
310
562
  return 4
311
563
 
312
564
 
@@ -320,6 +572,9 @@ def _cmd_verify(args) -> int:
320
572
  if args.action not in actions:
321
573
  print(f"unknown action: {args.action}", file=sys.stderr)
322
574
  return 2
575
+ guard = _require_live()
576
+ if guard is not None:
577
+ return guard
323
578
  ok = verify.verify_action(actions[args.action])
324
579
  print("screen changed: yes" if ok else "screen changed: NO (action may have been dropped)")
325
580
  return 0 if ok else 1
@@ -329,9 +584,22 @@ def _cmd_launch(_args) -> int:
329
584
  live = gestures.launch()
330
585
  if live is False:
331
586
  # F29: never report "ready" while the overlay is still up.
587
+ from .window import is_setup_screen
588
+
589
+ if is_setup_screen():
590
+ # F37: a welcome / setup screen is the user's to finish; nothing was clicked.
591
+ print(
592
+ "mirror_setup_required: iPhone Mirroring is showing a setup or welcome "
593
+ "screen (its window is not phone-shaped) — finish it in the iPhone "
594
+ "Mirroring window yourself (noracu never clicks through setup screens), "
595
+ "then call phone_launch again",
596
+ file=sys.stderr,
597
+ )
598
+ return 3
332
599
  print(
333
- "mirror_not_live: iPhone Mirroring is still paused — lock the iPhone, keep it "
334
- "near the Mac, then call phone_launch again",
600
+ "mirror_not_live: iPhone Mirroring is not live yet — if it shows a paused "
601
+ "notice, lock the iPhone and keep it near the Mac; if it is reconnecting, wait "
602
+ "a few seconds and check phone_status; then call phone_launch again",
335
603
  file=sys.stderr,
336
604
  )
337
605
  return 3
@@ -389,7 +657,10 @@ def build_parser() -> argparse.ArgumentParser:
389
657
  sp = sub.add_parser("longpress", help="long-press at normalized coords")
390
658
  sp.add_argument("x", type=float)
391
659
  sp.add_argument("y", type=float)
392
- sp.add_argument("--duration", type=float, default=0.8)
660
+ # positional (older callers) or --duration; argparse would let the positional's default overwrite
661
+ # the option, so they land in separate fields and _cmd_longpress picks one
662
+ sp.add_argument("duration", nargs="?", type=float, default=None)
663
+ sp.add_argument("--duration", dest="duration_opt", type=float, default=None)
393
664
  sp.add_argument("--expect", help="refuse to act unless this text is on screen (OCR)")
394
665
  sp.set_defaults(func=_cmd_longpress)
395
666
 
@@ -452,10 +723,19 @@ def _on_sigterm(signum, _frame):
452
723
  raise SystemExit(128 + signum)
453
724
 
454
725
 
726
+ def _stdin_values(args) -> None:
727
+ # type / find / open take their text as "-" to read it from stdin: text in argv is visible to every
728
+ # local user in the process list while imctl runs
729
+ for field in ("text", "app"):
730
+ if getattr(args, field, None) == "-" and getattr(args, "command", None) in ("type", "find", "open"):
731
+ setattr(args, field, sys.stdin.read())
732
+
733
+
455
734
  def main(argv: list[str] | None = None) -> int:
456
735
  signal.signal(signal.SIGTERM, _on_sigterm)
457
736
  parser = build_parser()
458
737
  args = parser.parse_args(argv)
738
+ _stdin_values(args)
459
739
  try:
460
740
  return args.func(args)
461
741
  except input.FocusLost: