noracu 0.1.1 → 0.1.3

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.
@@ -3,13 +3,23 @@
3
3
  These map to standard iOS interactions. Coordinates are normalized
4
4
  (0-1) within the mirroring window. Gesture start points were chosen to
5
5
  match iOS conventions (e.g. home swipe starts at the very bottom edge).
6
+
7
+ Phone-level actions that the mirroring app exposes as menu commands
8
+ (Spotlight, Home Screen) are triggered through those menus rather than
9
+ synthesized touch gestures — see the menu-command section below.
6
10
  """
7
11
 
8
12
  from __future__ import annotations
9
13
 
14
+ import math
15
+ import subprocess
16
+ import time
17
+ import unicodedata
18
+
10
19
  from . import input as inp
20
+ from . import verify
11
21
  from . import vision
12
- from .window import ensure_running, get_bounds
22
+ from .window import WindowError, ensure_frontmost, ensure_running, get_bounds
13
23
 
14
24
 
15
25
  class GestureError(RuntimeError):
@@ -58,16 +68,75 @@ def app_switcher() -> None:
58
68
  ev(kCGEventLeftMouseUp, x1, y1)
59
69
 
60
70
 
71
+ # Wheel pixels per window point of list movement, measured on iPhone Mirroring
72
+ # (Settings list, 524 pt window: between 1.1 and 1.6 px/pt across runs).
73
+ _SCROLL_PX_PER_PT = 1.3
74
+
75
+
61
76
  def scroll_down(distance: float = 0.5) -> None:
62
- """Scroll content down (swipe up) by a normalized distance."""
63
- start = min(0.9, 0.4 + distance / 2)
64
- inp.swipe(0.5, start, 0.5, start - distance, duration_ms=300)
77
+ """Reveal content further down a list by about `distance` window heights.
78
+
79
+ Uses trackpad-style scroll events; a vertical mouse drag does not scroll
80
+ lists in iPhone Mirroring (F16). Swipes stay for gestures such as paging.
81
+ """
82
+ b = get_bounds()
83
+ inp.scroll_trackpad(-distance * b.height * _SCROLL_PX_PER_PT, bounds=b)
65
84
 
66
85
 
67
86
  def scroll_up(distance: float = 0.5) -> None:
68
- """Scroll content up (swipe down) by a normalized distance."""
69
- start = max(0.1, 0.6 - distance / 2)
70
- inp.swipe(0.5, start, 0.5, start + distance, duration_ms=300)
87
+ """Reveal content further up a list by about `distance` window heights."""
88
+ b = get_bounds()
89
+ inp.scroll_trackpad(distance * b.height * _SCROLL_PX_PER_PT, bounds=b)
90
+
91
+
92
+ # 待真机标定:一次 0.5 窗口高度滚动的整窗 luma 帧差下限。
93
+ SCROLL_MIN_DIFF = 2.0
94
+
95
+
96
+ def scroll_checked(direction, distance=0.5, *, luma=None, scroller=None,
97
+ sleep=time.sleep, settle_s=0.6) -> bool:
98
+ """Scroll by `distance` window heights and confirm the screen moved (F20).
99
+
100
+ `direction` is "up" or "down"; `distance` is in window heights and
101
+ must satisfy 0 < distance <= 3. Both are validated before anything
102
+ is captured or sent: the 0.1.1 tool description named no unit, so
103
+ callers passed pixels (150-600) and a 600-window-height scroll was
104
+ silently accepted as success.
105
+
106
+ The scroll itself is the existing scroll_down/scroll_up trackpad
107
+ events. A list already at its end, or a view that does not scroll,
108
+ leaves the screen unchanged — this gate compares the mirroring
109
+ window's luma before/after and reports that as False instead of
110
+ success.
111
+
112
+ `luma` (default verify.window_luma), `scroller` (default:
113
+ scroll_down/scroll_up by direction) and `sleep` are injectable so
114
+ tests can drive this without a phone.
115
+
116
+ Returns True when the screen changed by at least SCROLL_MIN_DIFF.
117
+
118
+ Capture failures are never swallowed (F25): a WindowError or
119
+ CaptureError from the luma captures propagates to the caller (the
120
+ CLI reports capture_failed) — an unreadable screen is not evidence
121
+ that the scroll had no effect.
122
+ """
123
+ if direction not in ("up", "down"):
124
+ raise ValueError(f"direction must be 'up' or 'down', got {direction!r}")
125
+ if (not isinstance(distance, (int, float)) or isinstance(distance, bool)
126
+ or not 0 < distance <= 3 or not math.isfinite(distance)):
127
+ raise ValueError(
128
+ "distance is in window heights, 0 < distance <= 3 (default 0.5); "
129
+ f"got {distance!r}"
130
+ )
131
+ if luma is None:
132
+ luma = verify.window_luma
133
+ if scroller is None:
134
+ scroller = lambda d, dist: (scroll_down if d == "down" else scroll_up)(dist)
135
+ before = luma()
136
+ scroller(direction, distance)
137
+ sleep(settle_s)
138
+ after = luma()
139
+ return verify.mean_abs_diff(before, after) >= SCROLL_MIN_DIFF
71
140
 
72
141
 
73
142
  def page_left() -> None:
@@ -81,28 +150,473 @@ def page_right() -> None:
81
150
 
82
151
 
83
152
  def pull_down_search() -> None:
84
- """Swipe down from mid-screen: open Spotlight search."""
153
+ """Swipe down from mid-screen (DEPRECATED — never use for Spotlight).
154
+
155
+ F13: iOS sometimes reads this swipe as an icon long-press-drag, which
156
+ drops the home screen into edit (jiggle) mode — a stray tap on a "−"
157
+ badge there offers to DELETE apps. open_spotlight() replaces it.
158
+ Kept only as a raw gesture primitive; nothing in imctl calls it.
159
+ """
85
160
  inp.swipe(0.5, 0.25, 0.5, 0.75, duration_ms=280)
86
161
 
87
162
 
88
- def open_app(name: str) -> bool:
89
- """Open an app by name via Spotlight + OCR + tap.
163
+ # --- iPhone Mirroring menu commands -----------------------------------------
164
+ #
165
+ # The View menu of iPhone Mirroring exposes phone-level actions (Home
166
+ # Screen, App Switcher, Spotlight) as real menu commands, which iOS
167
+ # cannot misread as touch gestures. We trigger them by keyboard shortcut
168
+ # when one is readable — language-independent, because the shortcut
169
+ # character (AXMenuItemCmdChar), not the localized menu title, drives
170
+ # it — and fall back to clicking the English menu item.
171
+
172
+ # Static AppleScript only (invariant 1): script text is fixed; the menu
173
+ # item name travels as an osascript argument, never interpolated.
174
+ _MENU_SHORTCUT_SCRIPT = '''
175
+ on run(argv)
176
+ tell application "System Events"
177
+ tell process "iPhone Mirroring"
178
+ set cc to ""
179
+ set cm to ""
180
+ try
181
+ set cc to (value of attribute "AXMenuItemCmdChar" of menu item (item 1 of argv) of menu 1 of menu bar item "View" of menu bar 1) as text
182
+ end try
183
+ try
184
+ set cm to (value of attribute "AXMenuItemCmdModifiers" of menu item (item 1 of argv) of menu 1 of menu bar item "View" of menu bar 1) as text
185
+ end try
186
+ return cc & "," & cm
187
+ end tell
188
+ end tell
189
+ end run
190
+ '''
191
+
192
+ _CLICK_MENU_ITEM_SCRIPT = '''
193
+ on run(argv)
194
+ tell application "System Events"
195
+ tell process "iPhone Mirroring"
196
+ click menu item (item 1 of argv) of menu 1 of menu bar item "View" of menu bar 1
197
+ end tell
198
+ end tell
199
+ end run
200
+ '''
201
+
202
+
203
+ def _run_osascript(script: str, args: list[str] | None = None) -> str:
204
+ """Run a static AppleScript; runtime values go through argv only."""
205
+ cmd = ["osascript", "-e", script]
206
+ if args:
207
+ cmd += ["--"] + args
208
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
209
+ if result.returncode != 0:
210
+ raise GestureError(f"osascript failed: {result.stderr.strip()}")
211
+ return result.stdout.strip()
212
+
213
+
214
+ def _view_menu_shortcut(item: str) -> tuple[str, int] | None:
215
+ """Read a View menu item's shortcut — read-only, never clicks.
216
+
217
+ Returns (cmdChar, cmdModifiers), or None when unreadable.
218
+ AXMenuItemCmdModifiers uses the Carbon menu-modifier bits: 0 means
219
+ the Command key alone (Spotlight is Cmd+3 here), 1 adds Shift,
220
+ 8 means no key equivalent at all.
221
+ """
222
+ try:
223
+ raw = _run_osascript(_MENU_SHORTCUT_SCRIPT, [item])
224
+ except (GestureError, OSError, subprocess.TimeoutExpired):
225
+ return None
226
+ char, sep, mods = raw.partition(",")
227
+ if not sep:
228
+ return None
229
+ try:
230
+ return char, int(mods.strip())
231
+ except ValueError: # "missing value" / empty — no usable shortcut
232
+ return None
233
+
234
+
235
+ def _run_view_menu_command(item: str) -> bool:
236
+ """Trigger a View menu command of iPhone Mirroring.
237
+
238
+ Primary: the item's shortcut as a real Command chord (works on any
239
+ UI language). Fallback: clicking the English menu item. Returns
240
+ False when neither path works (app not running, localized menus…).
241
+ """
242
+ shortcut = _view_menu_shortcut(item)
243
+ if shortcut is not None:
244
+ char, mods = shortcut
245
+ keycode = inp.keycode_for_char(char) if mods == 0 else None
246
+ if keycode is not None:
247
+ try:
248
+ ensure_frontmost()
249
+ inp._cmd_chord(keycode)
250
+ return True
251
+ except (inp.InputError, WindowError):
252
+ pass # fall through to clicking the menu item
253
+ try:
254
+ ensure_frontmost()
255
+ _run_osascript(_CLICK_MENU_ITEM_SCRIPT, [item])
256
+ return True
257
+ except (GestureError, OSError, subprocess.TimeoutExpired, WindowError):
258
+ return False
90
259
 
91
- Returns True if the app name was found on screen after typing.
260
+
261
+ def open_spotlight() -> bool:
262
+ """Open the phone's Spotlight search (View ▸ Spotlight).
263
+
264
+ Never a swipe: the old pull-down could be misread by iOS as a
265
+ long-press-drag that triggers home-screen edit mode (F13).
92
266
  """
93
- pull_down_search()
94
- import time
267
+ return _run_view_menu_command("Spotlight")
95
268
 
96
- time.sleep(1.0)
97
- inp.type_text(name)
98
- time.sleep(1.5) # wait for Spotlight results
99
269
 
100
- hit = vision.find(name)
101
- if hit is None:
270
+ # Minimum mean-abs-luma diff (0-255 scale, verify.mean_abs_diff) for
271
+ # "Spotlight actually opened". Pending on-device calibration of the
272
+ # single "Home Screen → Spotlight" frame diff — the gate below always
273
+ # starts from the home screen, so that is the only scenario to
274
+ # calibrate.
275
+ SPOTLIGHT_MIN_DIFF = 6.0
276
+
277
+
278
+ def open_spotlight_checked(settle_s=1.0, *, luma=None, sleep=time.sleep, opener=None, home=None, home_settle_s=0.8) -> bool:
279
+ """Go to the Home Screen, open Spotlight, and confirm it (F17 guard).
280
+
281
+ Two layers of protection, in order:
282
+
283
+ ① Home Screen first (View ▸ Home Screen). The home screen has no
284
+ app input field, so even if every later step fails, the caller's
285
+ clear_text() (Cmd+A + Delete) cannot delete user content. It also
286
+ avoids re-sending the Spotlight command when Spotlight is already
287
+ open: if that command is a toggle, it would close Spotlight, and
288
+ the large screen change would fool layer ② into reporting success
289
+ while the keystrokes land in the app underneath.
290
+
291
+ ② A visible-change gate. open_spotlight() returning True only
292
+ means the View ▸ Spotlight menu command was dispatched — not that
293
+ Spotlight appeared on the phone. This gate compares the mirroring
294
+ window's luma before and after the menu command and reports
295
+ success only when the screen changed by at least
296
+ SPOTLIGHT_MIN_DIFF (calibrated for the single home-screen →
297
+ Spotlight transition).
298
+
299
+ ``luma`` (default verify.window_luma), ``sleep``, ``opener``
300
+ (default open_spotlight) and ``home`` (default: View ▸ Home
301
+ Screen) are injectable so tests can drive this without a phone.
302
+ """
303
+ if luma is None:
304
+ luma = verify.window_luma
305
+ if opener is None:
306
+ opener = open_spotlight
307
+ if home is None:
308
+ home = lambda: _run_view_menu_command("Home Screen")
309
+ if not home():
102
310
  return False
103
- inp.tap(hit.nx, hit.ny)
104
- time.sleep(1.0)
105
- return True
311
+ sleep(home_settle_s)
312
+ before = luma()
313
+ if not opener():
314
+ return False
315
+ sleep(settle_s)
316
+ after = luma()
317
+ return verify.mean_abs_diff(before, after) >= SPOTLIGHT_MIN_DIFF
318
+
319
+
320
+ # OCR look-alikes: characters Vision misreads a Latin letter as (the
321
+ # one-letter app "X" comes back as a multiplication sign, a Cyrillic
322
+ # ha, …). Only characters that get misread AS a Latin letter belong
323
+ # here — this is deliberately NOT a general transliteration table.
324
+ _LABEL_LOOKALIKES = {
325
+ "×": "x", # multiplication sign
326
+ "х": "x", # Cyrillic small letter ha (U+0445)
327
+ "Х": "x", # Cyrillic capital letter ha (U+0425)
328
+ }
329
+
330
+
331
+ def _norm_label(s: str) -> str:
332
+ """Normalize an app label (or query) for exact comparison.
333
+
334
+ NFKC (folds full-width "X" to "X") → strip → drop trailing
335
+ punctuation OCR appends to labels ("X.") → lowercase → map the
336
+ look-alike characters above to the Latin letter they get
337
+ misread as. Lets very short names like "X" match what Vision
338
+ actually returns without ever falling back to substring
339
+ matching.
340
+ """
341
+ s = unicodedata.normalize("NFKC", s).strip()
342
+ s = s.rstrip(".:·•,")
343
+ s = s.lower()
344
+ return "".join(_LABEL_LOOKALIKES.get(ch, ch) for ch in s)
345
+
346
+
347
+ def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
348
+ """Pick the Spotlight result row for ``name`` from OCR hits.
349
+
350
+ iOS 26 draws the Spotlight search field at the BOTTOM of the screen
351
+ (ny ≈ 0.95) and echoes the typed query inside it, so a plain text
352
+ match finds the field itself. A result row must:
353
+ - equal ``name`` after _norm_label() on BOTH sides (NFKC, strip,
354
+ trailing-punctuation drop, lowercase, OCR look-alike folding —
355
+ so the one-letter app "X" still matches labels Vision reads as
356
+ "x", "×", "X." or full-width "X"), and
357
+ - lie above the bottom search-field zone (ny < 0.88).
358
+ The comparison stays EXACT — substring/prefix matching is
359
+ forbidden: "X" must never hit "Xcode" or "X Corp". When several
360
+ rows match, the topmost (smallest ny) wins. Returns None when
361
+ nothing qualifies.
362
+ """
363
+ want = _norm_label(name)
364
+ best = None
365
+ for hit in hits:
366
+ if _norm_label(hit.text) != want:
367
+ continue
368
+ if hit.ny >= 0.88:
369
+ continue # the search field echoing the query
370
+ if best is None or hit.ny < best.ny:
371
+ best = hit
372
+ return best
373
+
374
+
375
+ def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep):
376
+ """Read the screen up to ``attempts`` times for a Spotlight result row.
377
+
378
+ Each pass calls ``read_screen()`` for OCR hits and hands them to
379
+ choose_app_hit(); a match returns immediately. Between passes we
380
+ wait ``delay_s`` — Spotlight results can lag the keystrokes, so a
381
+ single read races them (F17). No sleep after the last pass. Returns
382
+ None when no pass matches. ``read_screen`` and ``sleep`` are
383
+ injectable so tests can drive this without a phone.
384
+
385
+ Very short names (``_norm_label(name)`` ≤ 2 chars, e.g. "X") get one
386
+ extra read per pass, with ``read_screen(language_correction=False)``:
387
+ Vision's language correction tends to drop or rewrite
388
+ single-character labels, and they are recognized more reliably
389
+ without it. F27: Vision's full-frame pass can also skip such a label
390
+ entirely (the app "X" on 2026-11-04), so a short name that both
391
+ reads miss gets a third read with the minimumTextHeight sweep —
392
+ ``read_screen(language_correction=False, sweep=True)``. The match
393
+ stays exact either way. Long names keep the exact original
394
+ read/sleep sequence.
395
+ """
396
+ short = len(_norm_label(name)) <= 2
397
+ for i in range(attempts):
398
+ hit = choose_app_hit(read_screen(), name)
399
+ if hit is not None:
400
+ return hit
401
+ if short:
402
+ hit = choose_app_hit(read_screen(language_correction=False), name)
403
+ if hit is not None:
404
+ return hit
405
+ hit = choose_app_hit(
406
+ read_screen(language_correction=False, sweep=True), name)
407
+ if hit is not None:
408
+ return hit
409
+ if i + 1 < attempts:
410
+ sleep(delay_s)
411
+ return None
412
+
413
+
414
+ # 2026-11-03 在 iPhone 17 Pro Max 镜像上实测:Spotlight「Top Hit」卡片里
415
+ # App 图标中心在文字标签中心上方 0.052(标签中心 0.27 → 图标中心
416
+ # 0.218,单位为窗口高度比例)。
417
+ SPOTLIGHT_ICON_ABOVE_LABEL = 0.052
418
+
419
+ # 待真机标定:打开 App 前后整窗 luma 帧差下限。
420
+ OPEN_MIN_DIFF = 12.0
421
+
422
+
423
+ def _tophit_header(hits):
424
+ """The OCR hit for the Spotlight "Top Hit" card header, or None.
425
+
426
+ Matched exactly after _norm_label (case-folding, trailing
427
+ punctuation), so a list row that merely contains the words can
428
+ never pose as the card header.
429
+ """
430
+ want = _norm_label("Top Hit")
431
+ for hit in hits:
432
+ if _norm_label(hit.text) == want:
433
+ return hit
434
+ return None
435
+
436
+
437
+ def _tap_and_confirm_open(nx, ny, *, luma, sleep, tap, read_screen):
438
+ """Tap (nx, ny) and confirm the app actually opened (F24 ②).
439
+
440
+ One luma frame before the tap, one after a 1.0s settle, then one
441
+ OCR read. The tap counts as opened only when BOTH hold: the
442
+ whole-window frame diff reached OPEN_MIN_DIFF (the screen
443
+ visibly left Spotlight — a dead tap leaves it nearly identical)
444
+ and the "Top Hit" header is gone from the OCR read (a large
445
+ diff alone can be the results list reflowing under a dead tap).
446
+ Returns (opened, hits); ``hits`` is the post-tap OCR read, handed
447
+ back so the caller can search it for the Top Hit header without
448
+ reading the screen a second time.
449
+ """
450
+ before = luma()
451
+ tap(nx, ny)
452
+ sleep(1.0)
453
+ after = luma()
454
+ hits = read_screen()
455
+ opened = (verify.mean_abs_diff(before, after) >= OPEN_MIN_DIFF
456
+ and _tophit_header(hits) is None)
457
+ return opened, hits
458
+
459
+
460
+ def open_app(name: str, *, spotlight_open: bool = False,
461
+ read_screen=None, luma=None, sleep=time.sleep, tap=None,
462
+ home=None, clear_text=None, type_text=None) -> str:
463
+ """Open an app by name: Spotlight → clear → type → OCR → tap → CONFIRM.
464
+
465
+ ``spotlight_open`` lets a caller that already ran
466
+ open_spotlight_checked() itself (to tell "spotlight unavailable"
467
+ apart from "app not found") skip the internal call and go
468
+ straight to clear → type.
469
+
470
+ Spotlight is opened through open_spotlight_checked(), which
471
+ first returns to the Home Screen and only then opens Spotlight,
472
+ and reports success only when the screen visibly changed: if the
473
+ menu command silently failed, clear_text() (Cmd+A + Delete) would
474
+ land in whatever focused text field the frontmost app shows (a
475
+ note body, a message draft…) and wipe it — so on a failed gate
476
+ this does nothing at all: no clearing, no typing, no taps (F17
477
+ safety gate).
478
+
479
+ The search field is cleared (Cmd+A + Delete) before typing: iOS
480
+ keeps the previous Spotlight query, so the new name would be
481
+ appended to it and no result row would match (F17). Results are
482
+ then read up to twice (find_app_hit) because they can lag the
483
+ keystrokes.
484
+
485
+ The top hit is never opened with Return — it may belong to a
486
+ different app than the requested one.
487
+
488
+ F24 (2026-11-03 real-device retest): a tapped row is not an
489
+ opened app. On iOS 27 Spotlight the OCR hit can be the Top Hit
490
+ card's label UNDER the app icon, and tapping that label text
491
+ does nothing — the screen stays on Spotlight while the caller
492
+ was told "opened". So after find_app_hit matches a row:
493
+
494
+ ① stability — wait 0.5s, re-read, re-pick with choose_app_hit.
495
+ When the row moved by more than 0.02 the results were still
496
+ reflowing: the second read wins, with at most one more read
497
+ (still moving → the last read is authoritative).
498
+ ② tap the row, then confirm via _tap_and_confirm_open (frame
499
+ diff ≥ OPEN_MIN_DIFF and the "Top Hit" header gone).
500
+ ③ when that tap did nothing and the hit sits inside the Top Hit
501
+ card — the "Top Hit" header above the hit, less than 0.15 away —
502
+ tap the icon SPOTLIGHT_ICON_ABOVE_LABEL above the label and
503
+ confirm the same way. Any other hit gets NO second tap: an
504
+ upward offset there could land on a different app's row.
505
+ ④ still nothing confirmed → back to the Home Screen (View ▸
506
+ Home Screen), reported as not_confirmed.
507
+
508
+ A capture failure after the hit is found (WindowError /
509
+ CaptureError, F25) counts as unconfirmed — no further taps.
510
+
511
+ Returns "opened"; "not_found" (no row matched; back on the Home
512
+ Screen); "not_confirmed" (row — and possibly the Top Hit icon —
513
+ tapped but the app never verifiably opened; back on the Home
514
+ Screen); or "spotlight_unavailable" (Spotlight could not be
515
+ opened; nothing was typed or tapped).
516
+
517
+ ``read_screen`` (default vision.read_screen), ``luma`` (default
518
+ verify.window_luma), ``sleep``, ``tap`` (default inp.tap),
519
+ ``home`` (default View ▸ Home Screen), ``clear_text`` and
520
+ ``type_text`` are injectable so tests can drive this without a
521
+ phone.
522
+ """
523
+ if read_screen is None:
524
+ read_screen = vision.read_screen
525
+ if luma is None:
526
+ luma = verify.window_luma
527
+ if tap is None:
528
+ tap = inp.tap
529
+ if home is None:
530
+ home = lambda: _run_view_menu_command("Home Screen")
531
+ if clear_text is None:
532
+ clear_text = inp.clear_text
533
+ pending: list = []
534
+ if type_text is None:
535
+ def type_text(text):
536
+ return inp.type_text(text, pending=pending)
537
+ raw_read = read_screen
538
+
539
+ def read_screen(**kwargs):
540
+ # F33: every later read is also evidence for a clipboard restore
541
+ # type_text could not license in time (a paste that landed late).
542
+ hits = raw_read(**kwargs)
543
+ for restore in pending:
544
+ restore.offer(hits)
545
+ return hits
546
+
547
+ short = len(_norm_label(name)) <= 2
548
+
549
+ def reread():
550
+ # F32: the default pass alone keeps missing a one-letter label, and
551
+ # a missed row looked like a moved row — the tap then went to a
552
+ # different row ("X" opened a Chrome search). Short names read the
553
+ # same frame with the sweep too.
554
+ return read_screen(also_sweep=True) if short else read_screen()
555
+
556
+ # F34: one retry — on the device the Spotlight command was once ignored
557
+ # right after an app closed. Each try starts from the Home Screen, so a
558
+ # second try cannot toggle an open Spotlight shut.
559
+ if not spotlight_open and not (open_spotlight_checked()
560
+ or open_spotlight_checked()):
561
+ return "spotlight_unavailable"
562
+ clear_text() # iOS kept the last query; new input would append (F17)
563
+ sleep(0.3)
564
+ typed = type_text(name)
565
+ sleep(1.5) # wait for Spotlight results
566
+
567
+ # F33: a paste type_text did not see arrive may still be on its way (on
568
+ # the device it once showed up 8-10 s after Cmd+V): one more read pass.
569
+ hit = find_app_hit(read_screen, name, attempts=3 if typed is False else 2,
570
+ sleep=sleep)
571
+ if hit is None:
572
+ # Leave the phone tidy: back to the home screen (View ▸ Home Screen).
573
+ home()
574
+ return "not_found"
575
+
576
+ try:
577
+ # ① the Spotlight results can still be reflowing when
578
+ # find_app_hit returns; re-read after 0.5s and re-pick.
579
+ sleep(0.5)
580
+ again = choose_app_hit(reread(), name)
581
+ if again is not None:
582
+ if math.hypot(again.nx - hit.nx, again.ny - hit.ny) > 0.02:
583
+ # the row moved: the second read wins, with at most
584
+ # one more read — still moving → the last one wins
585
+ hit = again
586
+ once_more = choose_app_hit(reread(), name)
587
+ if (once_more is not None
588
+ and math.hypot(once_more.nx - hit.nx,
589
+ once_more.ny - hit.ny) > 0.02):
590
+ hit = once_more
591
+ # else: the two reads agree — the first hit stands
592
+
593
+ # ② tap the row (the label inside the Top Hit card) and confirm
594
+ opened, hits = _tap_and_confirm_open(
595
+ hit.nx, hit.ny, luma=luma, sleep=sleep, tap=tap,
596
+ read_screen=read_screen)
597
+ if opened:
598
+ return "opened"
599
+
600
+ # ③ the label tap did nothing and the hit sits inside the Top
601
+ # Hit card → tap the icon above the label. Anywhere else, no
602
+ # second tap: an upward offset could hit another app's row.
603
+ header = _tophit_header(hits)
604
+ if (header is not None and header.ny < hit.ny
605
+ and hit.ny - header.ny < 0.15):
606
+ opened, _ = _tap_and_confirm_open(
607
+ hit.nx, hit.ny - SPOTLIGHT_ICON_ABOVE_LABEL,
608
+ luma=luma, sleep=sleep, tap=tap, read_screen=read_screen)
609
+ if opened:
610
+ return "opened"
611
+ except Exception as exc:
612
+ if not verify.is_capture_error(exc):
613
+ raise
614
+ # F25: an unreadable screen is not evidence the app opened —
615
+ # no further taps; wrap up unconfirmed below.
616
+
617
+ # ④ leave the phone tidy and say the taps were not confirmed
618
+ home()
619
+ return "not_confirmed"
106
620
 
107
621
 
108
622
  def read_text() -> list:
@@ -114,9 +628,12 @@ def status() -> dict:
114
628
  """Return a status dict for the mirroring session.
115
629
 
116
630
  Keys: running; and when running: window {x,y,w,h} (AX bounds), window_id, onscreen, frontmost,
117
- paused (True/False, or null when the "Connection Paused" text cannot be read).
631
+ live (True/False/null — is the phone stream up), overlay (text shown over the stream when not
632
+ live, e.g. a paused/connecting notice), paused (True/False, or null when the state is unknown).
118
633
  """
119
- from .window import get_window_info, is_frontmost, is_paused, is_running
634
+ from .window import (
635
+ get_overlay, get_window_info, is_frontmost, is_paused, is_running,
636
+ )
120
637
 
121
638
  running = is_running()
122
639
  info = {"running": running}
@@ -131,7 +648,10 @@ def status() -> dict:
131
648
  info["window_id"] = wi["id"]
132
649
  info["onscreen"] = wi["onscreen"]
133
650
  info["frontmost"] = is_frontmost()
134
- info["paused"] = is_paused()
651
+ overlay = get_overlay()
652
+ info["live"] = overlay["live"]
653
+ info["overlay"] = overlay["overlay"]
654
+ info["paused"] = is_paused(overlay)
135
655
  return info
136
656
 
137
657
 
@@ -142,10 +662,17 @@ def resume() -> bool:
142
662
  return _resume()
143
663
 
144
664
 
145
- def launch() -> None:
146
- """Ensure iPhone Mirroring is running, frontmost, and not paused."""
665
+ def launch() -> bool | None:
666
+ """Ensure iPhone Mirroring is running, frontmost, and not paused.
667
+
668
+ Returns the stream state afterwards: True live, False still paused or connecting,
669
+ None unknown. F29: resume()'s result used to be dropped, so phone_launch reported
670
+ "ready" while the overlay was still up.
671
+ """
147
672
  ensure_running()
148
- from .window import ensure_frontmost, resume as _resume
673
+ from .window import ensure_frontmost, get_overlay, resume as _resume
149
674
 
150
675
  ensure_frontmost()
151
- _resume()
676
+ if _resume():
677
+ return True
678
+ return get_overlay()["live"]