noracu 0.1.2 → 0.1.4

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.
@@ -11,10 +11,15 @@ synthesized touch gestures — see the menu-command section below.
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
+ import math
15
+ import os
16
+ import re
14
17
  import subprocess
15
18
  import time
19
+ import unicodedata
16
20
 
17
21
  from . import input as inp
22
+ from . import verify
18
23
  from . import vision
19
24
  from .window import WindowError, ensure_frontmost, ensure_running, get_bounds
20
25
 
@@ -86,6 +91,56 @@ def scroll_up(distance: float = 0.5) -> None:
86
91
  inp.scroll_trackpad(distance * b.height * _SCROLL_PX_PER_PT, bounds=b)
87
92
 
88
93
 
94
+ # 待真机标定:一次 0.5 窗口高度滚动的整窗 luma 帧差下限。
95
+ SCROLL_MIN_DIFF = 2.0
96
+
97
+
98
+ def scroll_checked(direction, distance=0.5, *, luma=None, scroller=None,
99
+ sleep=time.sleep, settle_s=0.6) -> bool:
100
+ """Scroll by `distance` window heights and confirm the screen moved (F20).
101
+
102
+ `direction` is "up" or "down"; `distance` is in window heights and
103
+ must satisfy 0 < distance <= 3. Both are validated before anything
104
+ is captured or sent: the 0.1.1 tool description named no unit, so
105
+ callers passed pixels (150-600) and a 600-window-height scroll was
106
+ silently accepted as success.
107
+
108
+ The scroll itself is the existing scroll_down/scroll_up trackpad
109
+ events. A list already at its end, or a view that does not scroll,
110
+ leaves the screen unchanged — this gate compares the mirroring
111
+ window's luma before/after and reports that as False instead of
112
+ success.
113
+
114
+ `luma` (default verify.window_luma), `scroller` (default:
115
+ scroll_down/scroll_up by direction) and `sleep` are injectable so
116
+ tests can drive this without a phone.
117
+
118
+ Returns True when the screen changed by at least SCROLL_MIN_DIFF.
119
+
120
+ Capture failures are never swallowed (F25): a WindowError or
121
+ CaptureError from the luma captures propagates to the caller (the
122
+ CLI reports capture_failed) — an unreadable screen is not evidence
123
+ that the scroll had no effect.
124
+ """
125
+ if direction not in ("up", "down"):
126
+ raise ValueError(f"direction must be 'up' or 'down', got {direction!r}")
127
+ if (not isinstance(distance, (int, float)) or isinstance(distance, bool)
128
+ or not 0 < distance <= 3 or not math.isfinite(distance)):
129
+ raise ValueError(
130
+ "distance is in window heights, 0 < distance <= 3 (default 0.5); "
131
+ f"got {distance!r}"
132
+ )
133
+ if luma is None:
134
+ luma = verify.window_luma
135
+ if scroller is None:
136
+ scroller = lambda d, dist: (scroll_down if d == "down" else scroll_up)(dist)
137
+ before = luma()
138
+ scroller(direction, distance)
139
+ sleep(settle_s)
140
+ after = luma()
141
+ return verify.mean_abs_diff(before, after) >= SCROLL_MIN_DIFF
142
+
143
+
89
144
  def page_left() -> None:
90
145
  """Swipe right-to-left: go to the next home-screen page."""
91
146
  inp.swipe(0.8, 0.5, 0.2, 0.5, duration_ms=280)
@@ -147,18 +202,18 @@ end run
147
202
  '''
148
203
 
149
204
 
150
- def _run_osascript(script: str, args: list[str] | None = None) -> str:
205
+ def _run_osascript(script: str, args: list[str] | None = None, timeout: float = 10) -> str:
151
206
  """Run a static AppleScript; runtime values go through argv only."""
152
207
  cmd = ["osascript", "-e", script]
153
208
  if args:
154
209
  cmd += ["--"] + args
155
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
210
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
156
211
  if result.returncode != 0:
157
212
  raise GestureError(f"osascript failed: {result.stderr.strip()}")
158
213
  return result.stdout.strip()
159
214
 
160
215
 
161
- def _view_menu_shortcut(item: str) -> tuple[str, int] | None:
216
+ def _view_menu_shortcut(item: str, timeout: float = 10) -> tuple[str, int] | None:
162
217
  """Read a View menu item's shortcut — read-only, never clicks.
163
218
 
164
219
  Returns (cmdChar, cmdModifiers), or None when unreadable.
@@ -167,7 +222,7 @@ def _view_menu_shortcut(item: str) -> tuple[str, int] | None:
167
222
  8 means no key equivalent at all.
168
223
  """
169
224
  try:
170
- raw = _run_osascript(_MENU_SHORTCUT_SCRIPT, [item])
225
+ raw = _run_osascript(_MENU_SHORTCUT_SCRIPT, [item], timeout=timeout)
171
226
  except (GestureError, OSError, subprocess.TimeoutExpired):
172
227
  return None
173
228
  char, sep, mods = raw.partition(",")
@@ -179,27 +234,29 @@ def _view_menu_shortcut(item: str) -> tuple[str, int] | None:
179
234
  return None
180
235
 
181
236
 
182
- def _run_view_menu_command(item: str) -> bool:
237
+ def _run_view_menu_command(item: str, timeout: float = 10) -> bool:
183
238
  """Trigger a View menu command of iPhone Mirroring.
184
239
 
185
240
  Primary: the item's shortcut as a real Command chord (works on any
186
241
  UI language). Fallback: clicking the English menu item. Returns
187
242
  False when neither path works (app not running, localized menus…).
243
+ ``timeout`` bounds each osascript run it makes, including those that
244
+ bring the mirror to the front.
188
245
  """
189
- shortcut = _view_menu_shortcut(item)
246
+ shortcut = _view_menu_shortcut(item, timeout=timeout)
190
247
  if shortcut is not None:
191
248
  char, mods = shortcut
192
249
  keycode = inp.keycode_for_char(char) if mods == 0 else None
193
250
  if keycode is not None:
194
251
  try:
195
- ensure_frontmost()
252
+ ensure_frontmost(timeout=timeout)
196
253
  inp._cmd_chord(keycode)
197
254
  return True
198
- except (inp.InputError, WindowError):
255
+ except (inp.InputError, WindowError, OSError, subprocess.TimeoutExpired):
199
256
  pass # fall through to clicking the menu item
200
257
  try:
201
- ensure_frontmost()
202
- _run_osascript(_CLICK_MENU_ITEM_SCRIPT, [item])
258
+ ensure_frontmost(timeout=timeout)
259
+ _run_osascript(_CLICK_MENU_ITEM_SCRIPT, [item], timeout=timeout)
203
260
  return True
204
261
  except (GestureError, OSError, subprocess.TimeoutExpired, WindowError):
205
262
  return False
@@ -214,55 +271,567 @@ def open_spotlight() -> bool:
214
271
  return _run_view_menu_command("Spotlight")
215
272
 
216
273
 
274
+ # Minimum mean-abs-luma diff (0-255 scale, verify.mean_abs_diff) for
275
+ # "Spotlight actually opened". Pending on-device calibration of the
276
+ # single "Home Screen → Spotlight" frame diff — the gate below always
277
+ # starts from the home screen, so that is the only scenario to
278
+ # calibrate.
279
+ SPOTLIGHT_MIN_DIFF = 6.0
280
+
281
+
282
+ def open_spotlight_checked(settle_s=1.0, *, luma=None, sleep=time.sleep, opener=None, home=None,
283
+ home_settle_s=0.8, read_screen=None) -> bool:
284
+ """Go to the Home Screen, open Spotlight, and confirm it (F17 guard).
285
+
286
+ Two layers of protection, in order:
287
+
288
+ ① Home Screen first (View ▸ Home Screen). The home screen has no
289
+ app input field, so even if every later step fails, the caller's
290
+ clear_text() (Cmd+A + Delete) cannot delete user content. It also
291
+ avoids re-sending the Spotlight command when Spotlight is already
292
+ open: if that command is a toggle, it would close Spotlight, and
293
+ the large screen change would fool layer ② into reporting success
294
+ while the keystrokes land in the app underneath.
295
+
296
+ ② A visible-change gate. open_spotlight() returning True only
297
+ means the View ▸ Spotlight menu command was dispatched — not that
298
+ Spotlight appeared on the phone. This gate compares the mirroring
299
+ window's luma before and after the menu command and reports
300
+ success only when the screen changed by at least
301
+ SPOTLIGHT_MIN_DIFF (calibrated for the single home-screen →
302
+ Spotlight transition).
303
+
304
+ ③ F43 (2026-11-05 real-device, iOS 27): going Home from an app that
305
+ was opened from Spotlight lands back IN Spotlight, with the previous
306
+ query and its Top Hit card. The Spotlight command then closed it, and
307
+ that big change fooled layer ② into "opened" while the paste went to
308
+ the Home Screen (every phone_open right after a successful one
309
+ failed). When Home itself brought up a Top Hit card (none was on
310
+ screen before it), Spotlight is already open: it is reported as open
311
+ and no toggle is sent (the caller clears the old query first). A card
312
+ that was there before Home may be another app's (Safari shows one) with
313
+ Home ignored, so then — and when a read fails — layer ② decides. Known limit: a previous query
314
+ without a Top Hit card (no results) is not recognized, and the toggle
315
+ still closes that Spotlight.
316
+
317
+ ``luma`` (default verify.window_luma), ``sleep``, ``opener``
318
+ (default open_spotlight), ``home`` (default: View ▸ Home Screen)
319
+ and ``read_screen`` (default vision.read_screen) are injectable so
320
+ tests can drive this without a phone.
321
+ """
322
+ if luma is None:
323
+ luma = verify.window_luma
324
+ if read_screen is None:
325
+ read_screen = vision.read_screen
326
+ if opener is None:
327
+ opener = open_spotlight
328
+ if home is None:
329
+ home = lambda: _run_view_menu_command("Home Screen")
330
+
331
+ def card():
332
+ # a Top Hit card header near the top of the window (Spotlight's sits at ny ≈ 0.14; a
333
+ # "Top Hit" line far down is no evidence), "none", or "unreadable"
334
+ try:
335
+ header = _tophit_header(read_screen())
336
+ except Exception as exc:
337
+ if not verify.is_capture_error(exc):
338
+ raise
339
+ return "unreadable"
340
+ return "card" if header is not None and header.ny < SPOTLIGHT_HEADER_MAX_NY else "none"
341
+
342
+ before_home = card()
343
+ if not home():
344
+ return False
345
+ sleep(home_settle_s)
346
+ # F43: Home itself brought up a Top Hit card — Spotlight with the previous query: do not
347
+ # toggle it shut. A card that was already there before Home may be another app's own
348
+ # (Safari shows one too) with Home ignored; then, and when unsure, the gate below decides.
349
+ if before_home == "none" and card() == "card":
350
+ return True
351
+ before = luma()
352
+ if not opener():
353
+ return False
354
+ sleep(settle_s)
355
+ after = luma()
356
+ return verify.mean_abs_diff(before, after) >= SPOTLIGHT_MIN_DIFF
357
+
358
+
359
+ # OCR look-alikes: characters Vision misreads a Latin letter as (the
360
+ # one-letter app "X" comes back as a multiplication sign, a Cyrillic
361
+ # ha, …). Only characters that get misread AS a Latin letter belong
362
+ # here — this is deliberately NOT a general transliteration table.
363
+ _LABEL_LOOKALIKES = {
364
+ "×": "x", # multiplication sign
365
+ "х": "x", # Cyrillic small letter ha (U+0445)
366
+ "Х": "x", # Cyrillic capital letter ha (U+0425)
367
+ }
368
+
369
+
370
+ # open_spotlight_checked() takes a Top Hit header only this high up the window as proof that
371
+ # Spotlight is open (the header measured at ny ≈ 0.14).
372
+ SPOTLIGHT_HEADER_MAX_NY = 0.3
373
+
374
+ # Spotlight's search field is at the bottom of the window (ny >= SEARCH_FIELD_NY) and echoes the
375
+ # typed query. choose_app_hit never takes a label there; open_app reads that echo as the proof
376
+ # that a late paste has reached the phone (F42).
377
+ SEARCH_FIELD_NY = 0.88
378
+
379
+
380
+ def _norm_label(s: str) -> str:
381
+ """Normalize an app label (or query) for exact comparison.
382
+
383
+ NFKC (folds full-width "X" to "X") → strip → drop trailing
384
+ punctuation OCR appends to labels ("X.") → lowercase → map the
385
+ look-alike characters above to the Latin letter they get
386
+ misread as. Lets very short names like "X" match what Vision
387
+ actually returns without ever falling back to substring
388
+ matching.
389
+ """
390
+ s = unicodedata.normalize("NFKC", s).strip()
391
+ s = s.rstrip(".:·•,")
392
+ s = s.lower()
393
+ return "".join(_LABEL_LOOKALIKES.get(ch, ch) for ch in s)
394
+
395
+
217
396
  def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
218
397
  """Pick the Spotlight result row for ``name`` from OCR hits.
219
398
 
220
399
  iOS 26 draws the Spotlight search field at the BOTTOM of the screen
221
400
  (ny ≈ 0.95) and echoes the typed query inside it, so a plain text
222
401
  match finds the field itself. A result row must:
223
- - equal ``name`` case-insensitively after stripping whitespace, and
402
+ - equal ``name`` after _norm_label() on BOTH sides (NFKC, strip,
403
+ trailing-punctuation drop, lowercase, OCR look-alike folding —
404
+ so the one-letter app "X" still matches labels Vision reads as
405
+ "x", "×", "X." or full-width "X"), and
224
406
  - lie above the bottom search-field zone (ny < 0.88).
225
- When several rows match, the topmost (smallest ny) wins. Returns
226
- None when nothing qualifies.
407
+ The comparison stays EXACT — substring/prefix matching is
408
+ forbidden: "X" must never hit "Xcode" or "X Corp". When several
409
+ rows match, the topmost (smallest ny) wins. Returns None when
410
+ nothing qualifies.
411
+
412
+ F35 (2026-11-05 real-device): an exact label is not an app. The
413
+ query "Pinduoduo" matched a Chrome *suggestion* row of that name
414
+ (the app's own Top Hit label reads 拼多多), the tap opened a web
415
+ search, and the open was reported as confirmed. Only a row INSIDE
416
+ the Top Hit card counts now: below the "Top Hit" header and at
417
+ most TOP_HIT_CARD_SPAN under it — the same geometry the icon
418
+ fallback in open_app() already relies on. No header, or no exact
419
+ label inside the card → None: "not found" beats opening the
420
+ wrong thing. Suggestion, website and Settings deep-link rows of
421
+ the same name are never candidates.
227
422
  """
228
- want = name.strip().lower()
423
+ want = _norm_label(name)
424
+ header = _tophit_header(hits)
425
+ if header is None:
426
+ return None
229
427
  best = None
230
428
  for hit in hits:
231
- if hit.text.strip().lower() != want:
429
+ if _norm_label(hit.text) != want:
232
430
  continue
233
- if hit.ny >= 0.88:
431
+ if hit.ny >= SEARCH_FIELD_NY:
234
432
  continue # the search field echoing the query
433
+ if not header.ny < hit.ny <= header.ny + TOP_HIT_CARD_SPAN:
434
+ continue # outside the Top Hit card (F35)
235
435
  if best is None or hit.ny < best.ny:
236
436
  best = hit
237
437
  return best
238
438
 
239
439
 
240
- def open_app(name: str, *, spotlight_open: bool = False) -> bool:
241
- """Open an app by name: Spotlight → type → OCR → tap the result row.
440
+ def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep,
441
+ deadline=None, clock=time.monotonic):
442
+ """Read the screen up to ``attempts`` times for a Spotlight result row.
443
+
444
+ Each pass calls ``read_screen()`` for OCR hits and hands them to
445
+ choose_app_hit(); a match returns immediately. Between passes we
446
+ wait ``delay_s`` — Spotlight results can lag the keystrokes, so a
447
+ single read races them (F17). No sleep after the last pass. Returns
448
+ None when no pass matches. ``read_screen`` and ``sleep`` are
449
+ injectable so tests can drive this without a phone.
450
+
451
+ Very short names (``_norm_label(name)`` ≤ 2 chars, e.g. "X") get one
452
+ extra read per pass, with ``read_screen(language_correction=False)``:
453
+ Vision's language correction tends to drop or rewrite
454
+ single-character labels, and they are recognized more reliably
455
+ without it. F27: Vision's full-frame pass can also skip such a label
456
+ entirely (the app "X" on 2026-11-04), so a short name that both
457
+ reads miss gets a third read that adds the minimumTextHeight sweep
458
+ to the default pass on the same frame —
459
+ ``read_screen(language_correction=False, also_sweep=True)`` (F35:
460
+ the Top Hit header must be in the same read as the label). The match
461
+ stays exact either way. Long names keep the exact original
462
+ read/sleep sequence. ``deadline`` (a ``clock()`` value) is checked
463
+ before every read; once reached, no further read happens.
464
+ """
465
+ short = len(_norm_label(name)) <= 2
466
+
467
+ def expired():
468
+ return deadline is not None and clock() >= deadline
469
+
470
+ reads = [{}]
471
+ if short:
472
+ # F35: the sweep finds the one-letter label, but choose_app_hit also
473
+ # needs the "Top Hit" header from the SAME frame — the last read uses
474
+ # both the default pass and the sweep (also_sweep), not the sweep alone.
475
+ reads += [{"language_correction": False},
476
+ {"language_correction": False, "also_sweep": True}]
477
+ for i in range(attempts):
478
+ if i:
479
+ if expired():
480
+ return None
481
+ sleep(delay_s)
482
+ for kwargs in reads:
483
+ if expired():
484
+ return None # out of time before this read (open_app reports it)
485
+ hit = choose_app_hit(read_screen(**kwargs), name)
486
+ if hit is not None:
487
+ return hit
488
+ return None
489
+
490
+
491
+ # 2026-11-03 在 iPhone 17 Pro Max 镜像上实测:Spotlight「Top Hit」卡片里
492
+ # App 图标中心在文字标签中心上方 0.052(标签中心 0.27 → 图标中心
493
+ # 0.218,单位为窗口高度比例)。
494
+ SPOTLIGHT_ICON_ABOVE_LABEL = 0.052
495
+
496
+ # Top Hit 卡片的纵向范围:卡片内的行在 "Top Hit" 标题下方、且距标题不超过这个
497
+ # 窗高比例。2026-11-05(macOS 27.2 / iOS 27)实测:标题 0.136,卡片内标签 0.24,
498
+ # 下一个分区标题 "Suggestions" 0.294,第一条建议行 0.336 —— 0.15 落在卡片与
499
+ # 建议区之间。choose_app_hit()(F35)与 open_app() 的图标兜底共用这一个值。
500
+ TOP_HIT_CARD_SPAN = 0.15
501
+
502
+ # 待真机标定:打开 App 前后整窗 luma 帧差下限。
503
+ OPEN_MIN_DIFF = 12.0
504
+
505
+ # open_app's own time budget (seconds). The server stops `open` at 45 s from outside; a run
506
+ # that is killed there can leave Spotlight open with the name typed in. open_app checks this
507
+ # budget before every read pass and tap and, once it is spent, goes back to the Home Screen
508
+ # and reports "deadline" instead (F39).
509
+ OPEN_DEADLINE_S = 38.0
510
+
511
+ # F42 (2026-11-05 real-device): a paste reached the phone anywhere from 1.5 s to more than 10 s
512
+ # after Cmd+V — the text travels to the iPhone only when it pastes. When type_text did not see
513
+ # the paste arrive, open_app keeps reading Spotlight, one pass a second, for up to this long
514
+ # (within its budget). Once the search field shows the name, the query is in, and one more pass
515
+ # is enough — a Top Hit card alone may still be the previous query's.
516
+ OPEN_LATE_PASTE_S = 15.0 # a later device run under load saw ~15 s from Cmd+V to the echo
517
+ OPEN_LATE_PASTE_PASSES = 30 # a cap for injected clocks; the time limit normally ends it first
518
+
519
+
520
+ # The Spotlight "Top Hit" section label phone_open looks for. English by default;
521
+ # NORACU_TOPHIT_LABELS (comma-separated) supplies the label of an iPhone set to another
522
+ # language, exactly as the phone shows it (no unverified translations built in).
523
+ def _tophit_labels(raw):
524
+ # ASCII and full-width commas, and the ideographic enumeration comma
525
+ parts = re.split(r"[,,、]", raw or "")
526
+ labels = tuple(_norm_label(x) for x in parts if x.strip())
527
+ return labels or (_norm_label("Top Hit"),)
528
+
529
+
530
+ TOP_HIT_LABELS = _tophit_labels(os.environ.get("NORACU_TOPHIT_LABELS"))
531
+
532
+
533
+ def _field_echo(hits, name) -> bool:
534
+ """True when the search field shows exactly ``name`` (F42).
535
+
536
+ The field is the bottom zone (ny >= SEARCH_FIELD_NY); OCR may read the
537
+ magnifier glyph in front of the text as a "Q". Exact after _norm_label,
538
+ like every other label comparison here.
539
+ """
540
+ want = _norm_label(name)
541
+ for hit in hits:
542
+ if hit.ny < SEARCH_FIELD_NY:
543
+ continue
544
+ got = _norm_label(hit.text)
545
+ # the magnifier glyph may come back as "Q", "Q." or "Q:" in front of the text
546
+ if got == want or re.sub(r"^q[\s.,:;·•]*", "", got, count=1) == want:
547
+ return True
548
+ return False
549
+
550
+
551
+ def _tophit_header(hits):
552
+ """The OCR hit for the Spotlight "Top Hit" card header, or None.
553
+
554
+ Matched exactly after _norm_label (case-folding, trailing
555
+ punctuation) against TOP_HIT_LABELS, so a list row that merely
556
+ contains the words can never pose as the card header. Several
557
+ matches → the first in reading order (the topmost).
558
+ """
559
+ for hit in hits:
560
+ if _norm_label(hit.text) in TOP_HIT_LABELS:
561
+ return hit
562
+ return None
563
+
564
+
565
+ # open_app's tidy-up trip to the Home Screen must fit inside the time the server leaves after
566
+ # its deadline (two 10 s osascript runs did not), so it uses shorter ones.
567
+ TIDY_OSASCRIPT_TIMEOUT_S = 4.0
568
+
242
569
 
243
- ``spotlight_open`` lets a caller that already ran open_spotlight()
244
- itself (to tell "spotlight unavailable" apart from "app not found")
245
- skip the internal call. Returns True when a row matching ``name``
246
- was tapped; False when Spotlight could not be opened or no row
247
- matched (after returning to the home screen).
570
+ def home_via_menu(timeout: float = TIDY_OSASCRIPT_TIMEOUT_S) -> bool:
571
+ """View ▸ Home Screen in iPhone Mirroring (what open_app uses to tidy up)."""
572
+ return _run_view_menu_command("Home Screen", timeout=timeout)
573
+
574
+
575
+ def _tap_and_confirm_open(nx, ny, *, luma, sleep, tap, read_screen):
576
+ """Tap (nx, ny) and confirm the app actually opened (F24 ②).
577
+
578
+ One luma frame before the tap, one after a 1.0s settle, then one
579
+ OCR read. The tap counts as opened only when BOTH hold: the
580
+ whole-window frame diff reached OPEN_MIN_DIFF (the screen
581
+ visibly left Spotlight — a dead tap leaves it nearly identical)
582
+ and the "Top Hit" header is gone from the OCR read (a large
583
+ diff alone can be the results list reflowing under a dead tap).
584
+ Returns (opened, hits); ``hits`` is the post-tap OCR read, handed
585
+ back so the caller can search it for the Top Hit header without
586
+ reading the screen a second time.
587
+ """
588
+ before = luma()
589
+ tap(nx, ny)
590
+ sleep(1.0)
591
+ after = luma()
592
+ hits = read_screen()
593
+ opened = (verify.mean_abs_diff(before, after) >= OPEN_MIN_DIFF
594
+ and _tophit_header(hits) is None)
595
+ return opened, hits
596
+
597
+
598
+ def open_app(name: str, *, spotlight_open: bool = False,
599
+ read_screen=None, luma=None, sleep=time.sleep, tap=None,
600
+ home=None, clear_text=None, type_text=None,
601
+ clock=time.monotonic, deadline_s: float | None = OPEN_DEADLINE_S,
602
+ report: dict | None = None) -> str:
603
+ """Open an app by name: Spotlight → clear → type → OCR → tap → CONFIRM.
604
+
605
+ ``spotlight_open`` lets a caller that already ran
606
+ open_spotlight_checked() itself (to tell "spotlight unavailable"
607
+ apart from "app not found") skip the internal call and go
608
+ straight to clear → type.
609
+
610
+ Spotlight is opened through open_spotlight_checked(), which
611
+ first returns to the Home Screen and only then opens Spotlight,
612
+ and reports success only when the screen visibly changed: if the
613
+ menu command silently failed, clear_text() (Cmd+A + Delete) would
614
+ land in whatever focused text field the frontmost app shows (a
615
+ note body, a message draft…) and wipe it — so on a failed gate
616
+ this does nothing at all: no clearing, no typing, no taps (F17
617
+ safety gate).
618
+
619
+ The search field is cleared (Cmd+A + Delete) before typing: iOS
620
+ keeps the previous Spotlight query, so the new name would be
621
+ appended to it and no result row would match (F17). Results are
622
+ then read up to twice (find_app_hit) because they can lag the
623
+ keystrokes — or, when type_text did not see the paste arrive, once a
624
+ second for up to OPEN_LATE_PASTE_S (F42): once the search field shows
625
+ the name, one more pass.
248
626
 
249
627
  The top hit is never opened with Return — it may belong to a
250
628
  different app than the requested one.
251
- """
252
- if not spotlight_open and not open_spotlight():
253
- return False
254
- time.sleep(1.0)
255
- inp.type_text(name)
256
- time.sleep(1.5) # wait for Spotlight results
257
629
 
258
- hit = choose_app_hit(vision.read_screen(), name)
630
+ F24 (2026-11-03 real-device retest): a tapped row is not an
631
+ opened app. On iOS 27 Spotlight the OCR hit can be the Top Hit
632
+ card's label UNDER the app icon, and tapping that label text
633
+ does nothing — the screen stays on Spotlight while the caller
634
+ was told "opened". So after find_app_hit matches a row:
635
+
636
+ ① stability — wait 0.5s, re-read, re-pick with choose_app_hit.
637
+ When the row moved by more than 0.02 the results were still
638
+ reflowing: the second read wins, with at most one more read
639
+ (still moving → the last read is authoritative).
640
+ ② tap the row, then confirm via _tap_and_confirm_open (frame
641
+ diff ≥ OPEN_MIN_DIFF and the "Top Hit" header gone).
642
+ ③ when that tap did nothing and the post-tap read still shows the
643
+ exact label inside the Top Hit card (choose_app_hit, F35), tap the
644
+ icon SPOTLIGHT_ICON_ABOVE_LABEL above THAT label and confirm the
645
+ same way. Otherwise NO second tap: an upward offset from a stale
646
+ position could land on a different app's row.
647
+ ④ still nothing confirmed → back to the Home Screen (View ▸
648
+ Home Screen), reported as not_confirmed.
649
+
650
+ A capture failure after the hit is found (WindowError /
651
+ CaptureError, F25) counts as unconfirmed — no further taps.
652
+
653
+ Returns "opened"; "not_found" (a Top Hit card was seen, but never
654
+ with exactly this name; back on the Home Screen); "no_top_hit" (no
655
+ read showed Spotlight's "Top Hit" header at all — no such app, or a
656
+ non-English iPhone; back on the Home Screen); "not_confirmed" (row
657
+ — and possibly the Top Hit icon — tapped but the app never
658
+ verifiably opened; back on the Home Screen); "not_typed" (type_text
659
+ did not see the paste arrive and the search field never showed the
660
+ name during the late-paste reads either — the name may never have
661
+ reached the phone, so this is no evidence the app is missing; back on
662
+ the Home Screen);
663
+ "deadline" (the OPEN_DEADLINE_S budget ran out before a tap; back on
664
+ the Home Screen); or "spotlight_unavailable" (Spotlight could not be
665
+ opened; nothing was typed or tapped).
666
+
667
+ ``read_screen`` (default vision.read_screen), ``luma`` (default
668
+ verify.window_luma), ``sleep``, ``tap`` (default inp.tap),
669
+ ``home`` (default View ▸ Home Screen), ``clear_text`` and
670
+ ``type_text`` are injectable so tests can drive this without a
671
+ phone. ``report`` (a dict), when given, receives ``home``: whether
672
+ the last trip back to the Home Screen worked.
673
+ """
674
+ if read_screen is None:
675
+ read_screen = vision.read_screen
676
+ if luma is None:
677
+ luma = verify.window_luma
678
+ if tap is None:
679
+ tap = inp.tap
680
+ if home is None:
681
+ home = home_via_menu
682
+
683
+ def tidy():
684
+ # back to the Home Screen; the caller learns whether that worked
685
+ ok = bool(home())
686
+ if report is not None:
687
+ report["home"] = ok
688
+ return ok
689
+
690
+ if clear_text is None:
691
+ clear_text = inp.clear_text
692
+ pending: list = []
693
+ if type_text is None:
694
+ def type_text(text):
695
+ # F42: never give the clipboard back here — the name can reach the phone more
696
+ # than 10 s after Cmd+V, and Spotlight can show it in its own suggestions before
697
+ # that; a restore in between would paste the user's clipboard into the search
698
+ return inp.type_text(text, pending=pending, restore=False)
699
+ raw_read = read_screen
700
+ deadline = None if deadline_s is None else clock() + deadline_s
701
+ saw_top_hit = [False]
702
+ saw_echo = [False]
703
+
704
+ def read_screen(**kwargs):
705
+ # F33: every later read is also evidence for a clipboard restore an
706
+ # injected type_text may have handed over (the default never does: F42).
707
+ hits = raw_read(**kwargs)
708
+ for restore in pending:
709
+ restore.offer(hits)
710
+ if _tophit_header(hits) is not None:
711
+ saw_top_hit[0] = True # tells "not_found" apart from "no_top_hit"
712
+ if _field_echo(hits, name):
713
+ saw_echo[0] = True # F42: the name is in the search field — the paste arrived
714
+ return hits
715
+
716
+ def out_of_time():
717
+ return deadline is not None and clock() >= deadline
718
+
719
+ short = len(_norm_label(name)) <= 2
720
+
721
+ def reread():
722
+ # F32: the default pass alone keeps missing a one-letter label, and
723
+ # a missed row looked like a moved row — the tap then went to a
724
+ # different row ("X" opened a Chrome search). Short names read the
725
+ # same frame with the sweep too.
726
+ return read_screen(also_sweep=True) if short else read_screen()
727
+
728
+ # F34: one retry — on the device the Spotlight command was once ignored
729
+ # right after an app closed. Each try goes Home first; when Home lands back in
730
+ # Spotlight (iOS 27, F43) the gate reports it open instead of toggling it shut.
731
+ if not spotlight_open and not (open_spotlight_checked()
732
+ or open_spotlight_checked()):
733
+ return "spotlight_unavailable"
734
+ if out_of_time():
735
+ # the budget was spent before anything was typed (a tiny
736
+ # NORACU_PHONE_TIMEOUT_MS, or a slow start) — do not clear or type at all
737
+ tidy()
738
+ return "deadline"
739
+ clear_text() # iOS kept the last query; new input would append (F17)
740
+ sleep(0.3)
741
+ typed = type_text(name)
742
+ sleep(1.5) # wait for Spotlight results
743
+ hit = None
744
+ if typed is not False:
745
+ hit = find_app_hit(read_screen, name, attempts=2, sleep=sleep,
746
+ deadline=deadline, clock=clock)
747
+ if hit is None and not saw_echo[0]:
748
+ # F33/F42: the name is not in the search field yet — the paste may still be on its
749
+ # way, whether type_text missed it or took another change for it (a clear that
750
+ # landed late redraws the results: seen on the device after a back-to-back open)
751
+ limit = clock() + OPEN_LATE_PASTE_S
752
+ if deadline is not None:
753
+ limit = min(limit, deadline)
754
+ echo_passes = 0
755
+ for i in range(OPEN_LATE_PASTE_PASSES):
756
+ # the pass right after the first echo still runs past the limit (the results
757
+ # trail the query by a moment), but never past the open budget
758
+ confirming = echo_passes == 1
759
+ if i:
760
+ stop_at = deadline if confirming else limit
761
+ if stop_at is not None and clock() >= stop_at:
762
+ break
763
+ sleep(1.0)
764
+ hit = find_app_hit(read_screen, name, attempts=1, sleep=sleep,
765
+ deadline=deadline if confirming else limit, clock=clock)
766
+ if hit is not None:
767
+ break
768
+ # only the search field showing the name proves the paste arrived — a Top Hit
769
+ # card may still be the previous query's; once it is in, one more pass
770
+ if saw_echo[0]:
771
+ echo_passes += 1
772
+ if echo_passes >= 2:
773
+ break
259
774
  if hit is None:
260
775
  # Leave the phone tidy: back to the home screen (View ▸ Home Screen).
261
- _run_view_menu_command("Home Screen")
262
- return False
263
- inp.tap(hit.nx, hit.ny)
264
- time.sleep(1.0)
265
- return True
776
+ tidy()
777
+ if out_of_time():
778
+ return "deadline"
779
+ if not saw_echo[0]:
780
+ return "not_typed" # F42: the name never showed up in the search field
781
+ return "not_found" if saw_top_hit[0] else "no_top_hit"
782
+
783
+ try:
784
+ if out_of_time():
785
+ tidy()
786
+ return "deadline"
787
+ # ① the Spotlight results can still be reflowing when
788
+ # find_app_hit returns; re-read after 0.5s and re-pick.
789
+ sleep(0.5)
790
+ again = choose_app_hit(reread(), name)
791
+ if again is not None:
792
+ if math.hypot(again.nx - hit.nx, again.ny - hit.ny) > 0.02:
793
+ # the row moved: the second read wins, with at most
794
+ # one more read — still moving → the last one wins
795
+ hit = again
796
+ once_more = choose_app_hit(reread(), name)
797
+ if (once_more is not None
798
+ and math.hypot(once_more.nx - hit.nx,
799
+ once_more.ny - hit.ny) > 0.02):
800
+ hit = once_more
801
+ # else: the two reads agree — the first hit stands
802
+
803
+ if out_of_time():
804
+ tidy()
805
+ return "deadline"
806
+ # ② tap the row (the label inside the Top Hit card) and confirm.
807
+ # The post-tap read uses reread(): for a short name it also sweeps,
808
+ # so ③ can find the label again (F32/F35).
809
+ opened, hits = _tap_and_confirm_open(
810
+ hit.nx, hit.ny, luma=luma, sleep=sleep, tap=tap,
811
+ read_screen=reread)
812
+ if opened:
813
+ return "opened"
814
+
815
+ # ③ the label tap did nothing → tap the icon above the label, but
816
+ # only where the post-tap read shows that label inside the Top Hit
817
+ # card NOW (choose_app_hit, F35) — never the first read's position:
818
+ # the results may have changed. No such label → no second tap.
819
+ again = choose_app_hit(hits, name)
820
+ if again is not None and not out_of_time():
821
+ opened, _ = _tap_and_confirm_open(
822
+ again.nx, again.ny - SPOTLIGHT_ICON_ABOVE_LABEL,
823
+ luma=luma, sleep=sleep, tap=tap, read_screen=reread)
824
+ if opened:
825
+ return "opened"
826
+ except Exception as exc:
827
+ if not verify.is_capture_error(exc):
828
+ raise
829
+ # F25: an unreadable screen is not evidence the app opened —
830
+ # no further taps; wrap up unconfirmed below.
831
+
832
+ # ④ leave the phone tidy and say the taps were not confirmed
833
+ tidy()
834
+ return "not_confirmed"
266
835
 
267
836
 
268
837
  def read_text() -> list:
@@ -275,15 +844,19 @@ def status() -> dict:
275
844
 
276
845
  Keys: running; and when running: window {x,y,w,h} (AX bounds), window_id, onscreen, frontmost,
277
846
  live (True/False/null — is the phone stream up), overlay (text shown over the stream when not
278
- live, e.g. a paused/connecting notice), paused (True/False, or null when the state is unknown).
847
+ live, e.g. a paused/connecting notice), paused (True/False, or null when the state is unknown),
848
+ setup (True when the overlay is a setup / welcome screen the user must finish — F37; then
849
+ paused is False: there is no Resume control to press).
279
850
  """
280
851
  from .window import (
281
852
  get_overlay, get_window_info, is_frontmost, is_paused, is_running,
853
+ is_setup_screen,
282
854
  )
283
855
 
284
856
  running = is_running()
285
857
  info = {"running": running}
286
858
  if running:
859
+ b = None
287
860
  try:
288
861
  b = get_bounds()
289
862
  info["window"] = {"x": b.x, "y": b.y, "w": b.width, "h": b.height}
@@ -297,7 +870,9 @@ def status() -> dict:
297
870
  overlay = get_overlay()
298
871
  info["live"] = overlay["live"]
299
872
  info["overlay"] = overlay["overlay"]
300
- info["paused"] = is_paused(overlay)
873
+ setup = b is not None and is_setup_screen(overlay, b)
874
+ info["paused"] = False if setup else is_paused(overlay)
875
+ info["setup"] = setup
301
876
  return info
302
877
 
303
878
 
@@ -308,10 +883,17 @@ def resume() -> bool:
308
883
  return _resume()
309
884
 
310
885
 
311
- def launch() -> None:
312
- """Ensure iPhone Mirroring is running, frontmost, and not paused."""
886
+ def launch() -> bool | None:
887
+ """Ensure iPhone Mirroring is running, frontmost, and not paused.
888
+
889
+ Returns the stream state afterwards: True live, False still paused or connecting,
890
+ None unknown. F29: resume()'s result used to be dropped, so phone_launch reported
891
+ "ready" while the overlay was still up.
892
+ """
313
893
  ensure_running()
314
- from .window import ensure_frontmost, resume as _resume
894
+ from .window import ensure_frontmost, get_overlay, resume as _resume
315
895
 
316
896
  ensure_frontmost()
317
- _resume()
897
+ if _resume():
898
+ return True
899
+ return get_overlay()["live"]