noracu 0.1.3 → 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.
@@ -12,6 +12,8 @@ synthesized touch gestures — see the menu-command section below.
12
12
  from __future__ import annotations
13
13
 
14
14
  import math
15
+ import os
16
+ import re
15
17
  import subprocess
16
18
  import time
17
19
  import unicodedata
@@ -200,18 +202,18 @@ end run
200
202
  '''
201
203
 
202
204
 
203
- 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:
204
206
  """Run a static AppleScript; runtime values go through argv only."""
205
207
  cmd = ["osascript", "-e", script]
206
208
  if args:
207
209
  cmd += ["--"] + args
208
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
210
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
209
211
  if result.returncode != 0:
210
212
  raise GestureError(f"osascript failed: {result.stderr.strip()}")
211
213
  return result.stdout.strip()
212
214
 
213
215
 
214
- def _view_menu_shortcut(item: str) -> tuple[str, int] | None:
216
+ def _view_menu_shortcut(item: str, timeout: float = 10) -> tuple[str, int] | None:
215
217
  """Read a View menu item's shortcut — read-only, never clicks.
216
218
 
217
219
  Returns (cmdChar, cmdModifiers), or None when unreadable.
@@ -220,7 +222,7 @@ def _view_menu_shortcut(item: str) -> tuple[str, int] | None:
220
222
  8 means no key equivalent at all.
221
223
  """
222
224
  try:
223
- raw = _run_osascript(_MENU_SHORTCUT_SCRIPT, [item])
225
+ raw = _run_osascript(_MENU_SHORTCUT_SCRIPT, [item], timeout=timeout)
224
226
  except (GestureError, OSError, subprocess.TimeoutExpired):
225
227
  return None
226
228
  char, sep, mods = raw.partition(",")
@@ -232,27 +234,29 @@ def _view_menu_shortcut(item: str) -> tuple[str, int] | None:
232
234
  return None
233
235
 
234
236
 
235
- def _run_view_menu_command(item: str) -> bool:
237
+ def _run_view_menu_command(item: str, timeout: float = 10) -> bool:
236
238
  """Trigger a View menu command of iPhone Mirroring.
237
239
 
238
240
  Primary: the item's shortcut as a real Command chord (works on any
239
241
  UI language). Fallback: clicking the English menu item. Returns
240
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.
241
245
  """
242
- shortcut = _view_menu_shortcut(item)
246
+ shortcut = _view_menu_shortcut(item, timeout=timeout)
243
247
  if shortcut is not None:
244
248
  char, mods = shortcut
245
249
  keycode = inp.keycode_for_char(char) if mods == 0 else None
246
250
  if keycode is not None:
247
251
  try:
248
- ensure_frontmost()
252
+ ensure_frontmost(timeout=timeout)
249
253
  inp._cmd_chord(keycode)
250
254
  return True
251
- except (inp.InputError, WindowError):
255
+ except (inp.InputError, WindowError, OSError, subprocess.TimeoutExpired):
252
256
  pass # fall through to clicking the menu item
253
257
  try:
254
- ensure_frontmost()
255
- _run_osascript(_CLICK_MENU_ITEM_SCRIPT, [item])
258
+ ensure_frontmost(timeout=timeout)
259
+ _run_osascript(_CLICK_MENU_ITEM_SCRIPT, [item], timeout=timeout)
256
260
  return True
257
261
  except (GestureError, OSError, subprocess.TimeoutExpired, WindowError):
258
262
  return False
@@ -275,7 +279,8 @@ def open_spotlight() -> bool:
275
279
  SPOTLIGHT_MIN_DIFF = 6.0
276
280
 
277
281
 
278
- def open_spotlight_checked(settle_s=1.0, *, luma=None, sleep=time.sleep, opener=None, home=None, home_settle_s=0.8) -> bool:
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:
279
284
  """Go to the Home Screen, open Spotlight, and confirm it (F17 guard).
280
285
 
281
286
  Two layers of protection, in order:
@@ -296,19 +301,53 @@ def open_spotlight_checked(settle_s=1.0, *, luma=None, sleep=time.sleep, opener=
296
301
  SPOTLIGHT_MIN_DIFF (calibrated for the single home-screen →
297
302
  Spotlight transition).
298
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
+
299
317
  ``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.
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.
302
321
  """
303
322
  if luma is None:
304
323
  luma = verify.window_luma
324
+ if read_screen is None:
325
+ read_screen = vision.read_screen
305
326
  if opener is None:
306
327
  opener = open_spotlight
307
328
  if home is None:
308
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()
309
343
  if not home():
310
344
  return False
311
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
312
351
  before = luma()
313
352
  if not opener():
314
353
  return False
@@ -328,6 +367,16 @@ _LABEL_LOOKALIKES = {
328
367
  }
329
368
 
330
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
+
331
380
  def _norm_label(s: str) -> str:
332
381
  """Normalize an app label (or query) for exact comparison.
333
382
 
@@ -359,20 +408,37 @@ def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
359
408
  forbidden: "X" must never hit "Xcode" or "X Corp". When several
360
409
  rows match, the topmost (smallest ny) wins. Returns None when
361
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.
362
422
  """
363
423
  want = _norm_label(name)
424
+ header = _tophit_header(hits)
425
+ if header is None:
426
+ return None
364
427
  best = None
365
428
  for hit in hits:
366
429
  if _norm_label(hit.text) != want:
367
430
  continue
368
- if hit.ny >= 0.88:
431
+ if hit.ny >= SEARCH_FIELD_NY:
369
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)
370
435
  if best is None or hit.ny < best.ny:
371
436
  best = hit
372
437
  return best
373
438
 
374
439
 
375
- def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep):
440
+ def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep,
441
+ deadline=None, clock=time.monotonic):
376
442
  """Read the screen up to ``attempts`` times for a Spotlight result row.
377
443
 
378
444
  Each pass calls ``read_screen()`` for OCR hits and hands them to
@@ -388,26 +454,37 @@ def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep):
388
454
  single-character labels, and they are recognized more reliably
389
455
  without it. F27: Vision's full-frame pass can also skip such a label
390
456
  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
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
393
461
  stays exact either way. Long names keep the exact original
394
- read/sleep sequence.
462
+ read/sleep sequence. ``deadline`` (a ``clock()`` value) is checked
463
+ before every read; once reached, no further read happens.
395
464
  """
396
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}]
397
477
  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)
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)
407
486
  if hit is not None:
408
487
  return hit
409
- if i + 1 < attempts:
410
- sleep(delay_s)
411
488
  return None
412
489
 
413
490
 
@@ -416,24 +493,85 @@ def find_app_hit(read_screen, name, attempts=2, delay_s=1.0, sleep=time.sleep):
416
493
  # 0.218,单位为窗口高度比例)。
417
494
  SPOTLIGHT_ICON_ABOVE_LABEL = 0.052
418
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
+
419
502
  # 待真机标定:打开 App 前后整窗 luma 帧差下限。
420
503
  OPEN_MIN_DIFF = 12.0
421
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
+
422
550
 
423
551
  def _tophit_header(hits):
424
552
  """The OCR hit for the Spotlight "Top Hit" card header, or None.
425
553
 
426
554
  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.
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).
429
558
  """
430
- want = _norm_label("Top Hit")
431
559
  for hit in hits:
432
- if _norm_label(hit.text) == want:
560
+ if _norm_label(hit.text) in TOP_HIT_LABELS:
433
561
  return hit
434
562
  return None
435
563
 
436
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
+
569
+
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
+
437
575
  def _tap_and_confirm_open(nx, ny, *, luma, sleep, tap, read_screen):
438
576
  """Tap (nx, ny) and confirm the app actually opened (F24 ②).
439
577
 
@@ -459,7 +597,9 @@ def _tap_and_confirm_open(nx, ny, *, luma, sleep, tap, read_screen):
459
597
 
460
598
  def open_app(name: str, *, spotlight_open: bool = False,
461
599
  read_screen=None, luma=None, sleep=time.sleep, tap=None,
462
- home=None, clear_text=None, type_text=None) -> str:
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:
463
603
  """Open an app by name: Spotlight → clear → type → OCR → tap → CONFIRM.
464
604
 
465
605
  ``spotlight_open`` lets a caller that already ran
@@ -480,7 +620,9 @@ def open_app(name: str, *, spotlight_open: bool = False,
480
620
  keeps the previous Spotlight query, so the new name would be
481
621
  appended to it and no result row would match (F17). Results are
482
622
  then read up to twice (find_app_hit) because they can lag the
483
- keystrokes.
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.
484
626
 
485
627
  The top hit is never opened with Return — it may belong to a
486
628
  different app than the requested one.
@@ -497,28 +639,37 @@ def open_app(name: str, *, spotlight_open: bool = False,
497
639
  (still moving → the last read is authoritative).
498
640
  ② tap the row, then confirm via _tap_and_confirm_open (frame
499
641
  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.
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.
505
647
  ④ still nothing confirmed → back to the Home Screen (View ▸
506
648
  Home Screen), reported as not_confirmed.
507
649
 
508
650
  A capture failure after the hit is found (WindowError /
509
651
  CaptureError, F25) counts as unconfirmed — no further taps.
510
652
 
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
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
515
665
  opened; nothing was typed or tapped).
516
666
 
517
667
  ``read_screen`` (default vision.read_screen), ``luma`` (default
518
668
  verify.window_luma), ``sleep``, ``tap`` (default inp.tap),
519
669
  ``home`` (default View ▸ Home Screen), ``clear_text`` and
520
670
  ``type_text`` are injectable so tests can drive this without a
521
- phone.
671
+ phone. ``report`` (a dict), when given, receives ``home``: whether
672
+ the last trip back to the Home Screen worked.
522
673
  """
523
674
  if read_screen is None:
524
675
  read_screen = vision.read_screen
@@ -527,23 +678,44 @@ def open_app(name: str, *, spotlight_open: bool = False,
527
678
  if tap is None:
528
679
  tap = inp.tap
529
680
  if home is None:
530
- home = lambda: _run_view_menu_command("Home Screen")
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
+
531
690
  if clear_text is None:
532
691
  clear_text = inp.clear_text
533
692
  pending: list = []
534
693
  if type_text is None:
535
694
  def type_text(text):
536
- return inp.type_text(text, pending=pending)
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)
537
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]
538
703
 
539
704
  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).
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).
542
707
  hits = raw_read(**kwargs)
543
708
  for restore in pending:
544
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
545
714
  return hits
546
715
 
716
+ def out_of_time():
717
+ return deadline is not None and clock() >= deadline
718
+
547
719
  short = len(_norm_label(name)) <= 2
548
720
 
549
721
  def reread():
@@ -554,26 +726,64 @@ def open_app(name: str, *, spotlight_open: bool = False,
554
726
  return read_screen(also_sweep=True) if short else read_screen()
555
727
 
556
728
  # 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.
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.
559
731
  if not spotlight_open and not (open_spotlight_checked()
560
732
  or open_spotlight_checked()):
561
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"
562
739
  clear_text() # iOS kept the last query; new input would append (F17)
563
740
  sleep(0.3)
564
741
  typed = type_text(name)
565
742
  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)
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
571
774
  if hit is None:
572
775
  # Leave the phone tidy: back to the home screen (View ▸ Home Screen).
573
- home()
574
- return "not_found"
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"
575
782
 
576
783
  try:
784
+ if out_of_time():
785
+ tidy()
786
+ return "deadline"
577
787
  # ① the Spotlight results can still be reflowing when
578
788
  # find_app_hit returns; re-read after 0.5s and re-pick.
579
789
  sleep(0.5)
@@ -590,22 +800,27 @@ def open_app(name: str, *, spotlight_open: bool = False,
590
800
  hit = once_more
591
801
  # else: the two reads agree — the first hit stands
592
802
 
593
- # ② tap the row (the label inside the Top Hit card) and confirm
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).
594
809
  opened, hits = _tap_and_confirm_open(
595
810
  hit.nx, hit.ny, luma=luma, sleep=sleep, tap=tap,
596
- read_screen=read_screen)
811
+ read_screen=reread)
597
812
  if opened:
598
813
  return "opened"
599
814
 
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):
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():
606
821
  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)
822
+ again.nx, again.ny - SPOTLIGHT_ICON_ABOVE_LABEL,
823
+ luma=luma, sleep=sleep, tap=tap, read_screen=reread)
609
824
  if opened:
610
825
  return "opened"
611
826
  except Exception as exc:
@@ -615,7 +830,7 @@ def open_app(name: str, *, spotlight_open: bool = False,
615
830
  # no further taps; wrap up unconfirmed below.
616
831
 
617
832
  # ④ leave the phone tidy and say the taps were not confirmed
618
- home()
833
+ tidy()
619
834
  return "not_confirmed"
620
835
 
621
836
 
@@ -629,15 +844,19 @@ def status() -> dict:
629
844
 
630
845
  Keys: running; and when running: window {x,y,w,h} (AX bounds), window_id, onscreen, frontmost,
631
846
  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).
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).
633
850
  """
634
851
  from .window import (
635
852
  get_overlay, get_window_info, is_frontmost, is_paused, is_running,
853
+ is_setup_screen,
636
854
  )
637
855
 
638
856
  running = is_running()
639
857
  info = {"running": running}
640
858
  if running:
859
+ b = None
641
860
  try:
642
861
  b = get_bounds()
643
862
  info["window"] = {"x": b.x, "y": b.y, "w": b.width, "h": b.height}
@@ -651,7 +870,9 @@ def status() -> dict:
651
870
  overlay = get_overlay()
652
871
  info["live"] = overlay["live"]
653
872
  info["overlay"] = overlay["overlay"]
654
- 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
655
876
  return info
656
877
 
657
878