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.
@@ -64,12 +64,12 @@ end tell
64
64
  '''
65
65
 
66
66
 
67
- def _run_osascript(script: str, *, strip: bool = True) -> str:
67
+ def _run_osascript(script: str, *, strip: bool = True, timeout: float = 10) -> str:
68
68
  result = subprocess.run(
69
69
  ["osascript", "-e", script],
70
70
  capture_output=True,
71
71
  text=True,
72
- timeout=10,
72
+ timeout=timeout,
73
73
  )
74
74
  if result.returncode != 0:
75
75
  raise WindowError(f"osascript failed: {result.stderr.strip()}")
@@ -101,24 +101,52 @@ def ensure_running() -> None:
101
101
  raise WindowError("iPhone Mirroring did not start within 10s")
102
102
 
103
103
 
104
- def ensure_frontmost() -> None:
104
+ def ensure_frontmost(timeout: float = 10) -> None:
105
105
  """Bring the iPhone Mirroring window to the front.
106
106
 
107
107
  CGEvents are delivered to the frontmost app; if another window
108
108
  covers the mirroring window, taps would land on the wrong target.
109
+ F31: when the app had to be activated (possibly switching Spaces), wait
110
+ until the window yields a real frame before returning, so the caller's
111
+ next capture is not a transition frame refused as capture_failed.
112
+ ``timeout`` bounds each osascript run (a tidy-up passes a short one).
109
113
  """
110
- if _run_osascript(_FRONTMOST_SCRIPT) == "true":
114
+ if _run_osascript(_FRONTMOST_SCRIPT, timeout=timeout) == "true":
111
115
  return
112
116
  subprocess.run(
113
117
  ["osascript", "-e", f'tell application "{APP_NAME}" to activate'],
114
118
  capture_output=True,
115
- timeout=10,
119
+ timeout=timeout,
116
120
  )
117
121
  import time
118
122
 
119
123
  time.sleep(0.4) # let the window server settle
120
- if _run_osascript(_FRONTMOST_SCRIPT) != "true":
124
+ if _run_osascript(_FRONTMOST_SCRIPT, timeout=timeout) != "true":
121
125
  raise WindowError("could not bring iPhone Mirroring to front")
126
+ _wait_capturable()
127
+
128
+
129
+ def _wait_capturable(timeout_s: float = 2.0, poll_s: float = 0.2) -> bool:
130
+ """Poll until the mirror window gives a valid frame (F31); best effort.
131
+
132
+ Uses verify.window_luma(), which refuses off-screen windows and blank
133
+ transition frames (F25). Returns True once a frame passes, False after
134
+ ``timeout_s`` — it never raises: a caller whose own capture still fails
135
+ reports capture_failed as before.
136
+ """
137
+ import time
138
+
139
+ from . import verify # runtime import: verify imports this module
140
+
141
+ deadline = time.monotonic() + timeout_s
142
+ while True:
143
+ try:
144
+ verify.window_luma()
145
+ return True
146
+ except Exception:
147
+ if time.monotonic() >= deadline:
148
+ return False
149
+ time.sleep(poll_s)
122
150
 
123
151
 
124
152
  def get_bounds() -> WindowBounds:
@@ -157,7 +185,10 @@ def get_bounds() -> WindowBounds:
157
185
  # "iPhone in use", …) that group gains child elements (image / static text / button). Overlay text
158
186
  # is localized, so the decision never matches on text — only on structure (child count, classes).
159
187
  # Labels can span multiple lines and nameless elements coerce to the literal "missing value";
160
- # both are normalized so one element = exactly one `<class>\t<label>` line.
188
+ # both are normalized so one element = exactly one `<class>\t<label>\t<subrole>\t<child classes>`
189
+ # line (tabs inside labels are collapsed too). F28: the subrole and, for groups, the classes of
190
+ # their children let parse_overlay_ex tell the window's own hover controls (close / minimize /
191
+ # zoom buttons and the small toolbar group) apart from a real overlay.
161
192
  _OVERLAY_SCRIPT = '''
162
193
  on collapseBreaks(s)
163
194
  set tid to AppleScript's text item delimiters
@@ -169,6 +200,10 @@ on collapseBreaks(s)
169
200
  set parts to text items of s
170
201
  set AppleScript's text item delimiters to " "
171
202
  set s to parts as text
203
+ set AppleScript's text item delimiters to tab
204
+ set parts to text items of s
205
+ set AppleScript's text item delimiters to " "
206
+ set s to parts as text
172
207
  set AppleScript's text item delimiters to tid
173
208
  return s
174
209
  end collapseBreaks
@@ -195,7 +230,20 @@ tell application "System Events"
195
230
  if v is not "missing value" then set lbl to v
196
231
  end try
197
232
  end if
198
- set out to out & c & tab & (my collapseBreaks(lbl)) & linefeed
233
+ set sr to ""
234
+ try
235
+ set sr to (subrole of e) as text
236
+ if sr is "missing value" then set sr to ""
237
+ end try
238
+ set kids to ""
239
+ if c is "group" then
240
+ try
241
+ repeat with k in (UI elements of e)
242
+ set kids to kids & ((class of k) as text) & ","
243
+ end repeat
244
+ end try
245
+ end if
246
+ set out to out & c & tab & (my collapseBreaks(lbl)) & tab & sr & tab & kids & linefeed
199
247
  end repeat
200
248
  return out
201
249
  end tell
@@ -204,12 +252,29 @@ end tell
204
252
  '''
205
253
 
206
254
  # Clicks the Resume control of the paused overlay. Only ever invoked after _OVERLAY_SCRIPT
207
- # reported exactly one button under group 1 (static script, no interpolated parameters).
255
+ # reported exactly one overlay button under group 1 (static script, no interpolated
256
+ # parameters). F29: "button 1 of group 1" was the window's Close button whenever the
257
+ # pointer rested on the window, so window controls are skipped by AX subrole and the
258
+ # click happens only when exactly one other button remains; prints CLICKED or SKIP.
208
259
  _CLICK_RESUME_SCRIPT = '''
209
260
  tell application "System Events"
210
261
  tell process "iPhone Mirroring"
211
262
  tell window 1
212
- click button 1 of group 1
263
+ set target to missing value
264
+ set n to 0
265
+ repeat with b in (buttons of group 1)
266
+ set sr to ""
267
+ try
268
+ set sr to (subrole of b) as text
269
+ end try
270
+ if sr is not "AXCloseButton" and sr is not "AXMinimizeButton" and sr is not "AXZoomButton" and sr is not "AXFullScreenButton" then
271
+ set n to n + 1
272
+ set target to contents of b
273
+ end if
274
+ end repeat
275
+ if n is not 1 then return "SKIP"
276
+ click target
277
+ return "CLICKED"
213
278
  end tell
214
279
  end tell
215
280
  end tell
@@ -251,52 +316,92 @@ def get_window_info() -> dict | None:
251
316
 
252
317
 
253
318
  def is_frontmost() -> bool:
254
- """True when iPhone Mirroring is the frontmost application."""
319
+ """True when iPhone Mirroring is the frontmost application, asked fresh on every call.
320
+
321
+ F26 runs this right before synthesized input events. F30: the in-process
322
+ NSWorkspace.frontmostApplication() query used before is a snapshot in a process
323
+ without a run loop (imctl's case) — after Finder came to the front it still answered
324
+ "iPhone Mirroring", so the re-checks inside one operation could never fire. System
325
+ Events reads the live process list (about 0.1 s per osascript call). Any failure
326
+ counts as not frontmost, so input is refused rather than sent blind.
327
+ """
255
328
  try:
256
329
  return _run_osascript(_FRONTMOST_SCRIPT) == "true"
257
- except WindowError:
330
+ except (WindowError, subprocess.TimeoutExpired, OSError):
258
331
  return False
259
332
 
260
333
 
261
- def parse_overlay(raw: str) -> dict:
262
- """Parse _OVERLAY_SCRIPT output into {"live", "overlay", "buttons"}.
334
+ # F28: controls iPhone Mirroring adds to group 1 while the pointer rests on its window
335
+ # (the title-bar buttons), identified by AX subrole — never by localized text.
336
+ _CHROME_SUBROLES = frozenset(
337
+ {"AXCloseButton", "AXMinimizeButton", "AXZoomButton", "AXFullScreenButton"}
338
+ )
339
+
340
+
341
+ def parse_overlay_ex(raw: str) -> tuple[dict, bool]:
342
+ """Parse _OVERLAY_SCRIPT output into ({"live", "overlay", "buttons"}, hover).
263
343
 
264
344
  Rules (structure only, never localized text):
265
- - "" (group 1 has no children) -> live=True, overlay=None, buttons=0
266
- - child lines "<class>\t<name-or-value>" -> live=False, overlay=static texts joined with " / "
267
- (None when no text), buttons=button count
268
- - "NO_WINDOW" / "NO_GROUP" / unparseable -> live=None, overlay=None, buttons=0
345
+ - "" (group 1 has no children) -> live=True, overlay=None, buttons=0
346
+ - child lines "<class>\\t<label>[\\t<subrole>\\t<child classes>]"
347
+ -> live=False, overlay=static texts joined
348
+ with " / " (None when no text),
349
+ buttons=button count
350
+ - "NO_WINDOW" / "NO_GROUP" / unparseable -> live=None, overlay=None, buttons=0
351
+
352
+ F28: while the pointer rests on the mirror window, group 1 also holds the window's own
353
+ title-bar buttons (subroles AXCloseButton / AXMinimizeButton / AXZoomButton) and a small
354
+ toolbar (a group whose children are only buttons). hover is True when those buttons are
355
+ present; they and the toolbar group are not an overlay and are never counted. Without
356
+ them the rules above apply unchanged: any other child still means not live.
269
357
  """
270
358
  unknown = {"live": None, "overlay": None, "buttons": 0}
271
359
  if raw is None:
272
- return unknown
360
+ return unknown, False
273
361
  if raw.strip() in ("NO_WINDOW", "NO_GROUP"):
274
- return unknown
362
+ return unknown, False
275
363
  # Keep lines as-is (a trailing tab is significant: "button\t" means a nameless button);
276
364
  # only filter out blank lines.
277
365
  lines = [ln for ln in raw.split("\n") if ln.strip()]
278
366
  if not lines:
279
- return {"live": True, "overlay": None, "buttons": 0}
280
- buttons = 0
281
- texts: list[str] = []
367
+ return {"live": True, "overlay": None, "buttons": 0}, False
368
+ elements = []
282
369
  for ln in lines:
283
370
  parts = ln.split("\t", 1)
284
371
  if len(parts) != 2:
285
- return unknown # unexpected format -> unknown, never guess
286
- cls, label = parts[0].strip(), parts[1].strip()
287
- if cls == "button":
288
- buttons += 1
289
- elif cls == "static text" and label:
290
- texts.append(label)
372
+ return unknown, False # unexpected format -> unknown, never guess
373
+ cls, rest = parts[0].strip(), parts[1]
374
+ if rest.count("\t") >= 2: # current script: label, subrole, child classes
375
+ label, subrole, kids = rest.rsplit("\t", 2)
376
+ else: # two-field form (label only)
377
+ label, subrole, kids = rest, "", ""
378
+ child_classes = [k.strip() for k in kids.split(",") if k.strip()]
379
+ elements.append((cls, label.strip(), subrole.strip(), child_classes))
380
+ hover = any(c == "button" and s in _CHROME_SUBROLES for c, _, s, _ in elements)
381
+ rest_els = [e for e in elements if not (e[0] == "button" and e[2] in _CHROME_SUBROLES)]
382
+ if hover:
383
+ # The hover toolbar: a group holding only buttons (or nothing yet, mid-animation).
384
+ rest_els = [
385
+ e for e in rest_els if not (e[0] == "group" and all(k == "button" for k in e[3]))
386
+ ]
387
+ if not rest_els:
388
+ return {"live": True, "overlay": None, "buttons": 0}, hover
389
+ buttons = sum(1 for e in rest_els if e[0] == "button")
390
+ texts = [e[1] for e in rest_els if e[0] == "static text" and e[1]]
291
391
  return {
292
392
  "live": False,
293
393
  "overlay": " / ".join(texts) if texts else None,
294
394
  "buttons": buttons,
295
- }
395
+ }, hover
296
396
 
297
397
 
298
- def get_overlay() -> dict:
299
- """Return the current overlay state: {"live", "overlay", "buttons"}.
398
+ def parse_overlay(raw: str) -> dict:
399
+ """Parse _OVERLAY_SCRIPT output into {"live", "overlay", "buttons"} (see parse_overlay_ex)."""
400
+ return parse_overlay_ex(raw)[0]
401
+
402
+
403
+ def overlay_snapshot() -> tuple[dict, bool]:
404
+ """(overlay state, hover) from one probe; the state is what get_overlay() returns.
300
405
 
301
406
  Fail-open: any osascript failure (app not running, AX hiccup, timeout) returns
302
407
  live=None so callers can decide; this never raises.
@@ -306,8 +411,53 @@ def get_overlay() -> dict:
306
411
  # str.strip() would eat it and make the last line unparseable.
307
412
  raw = _run_osascript(_OVERLAY_SCRIPT, strip=False)
308
413
  except Exception:
309
- return {"live": None, "overlay": None, "buttons": 0}
310
- return parse_overlay(raw)
414
+ return {"live": None, "overlay": None, "buttons": 0}, False
415
+ return parse_overlay_ex(raw)
416
+
417
+
418
+ def get_overlay() -> dict:
419
+ """Return the current overlay state: {"live", "overlay", "buttons"} (fail-open)."""
420
+ return overlay_snapshot()[0]
421
+
422
+
423
+ # F37 (2026-11-05, macOS 27.2): the first launch after the macOS upgrade showed a welcome
424
+ # screen ("iPhone on Your Mac …") in a 640×660 window. Its button made it look like the paused
425
+ # overlay: phone_status reported paused=true, phone_launch told the user to lock the iPhone, and
426
+ # resume() clicks an overlay's lone button as if it were Resume. The mirror window itself — live
427
+ # or paused — is phone-shaped: elongated, portrait (measured 236×524, 329×727, 354×781 — about
428
+ # 2.2:1) or, for an app that rotates, landscape. A setup, welcome or permission screen is close to
429
+ # square, so a click is only ever sent on an elongated window. 1.7 keeps the 16:9 iPhone SE
430
+ # (≈1.78) in and a wide dialog (e.g. 800×520 ≈ 1.54) out. Geometry, not text: language-
431
+ # independent like the rest of the overlay probe.
432
+ PHONE_MIN_ASPECT = 1.7
433
+
434
+
435
+ def is_phone_shaped(bounds: WindowBounds | None = None) -> bool | None:
436
+ """True when the mirror window is elongated like a phone, portrait or landscape (F37).
437
+
438
+ The long side must be at least PHONE_MIN_ASPECT times the short side. None when the
439
+ bounds cannot be read.
440
+ """
441
+ try:
442
+ b = bounds if bounds is not None else get_bounds()
443
+ except Exception:
444
+ return None
445
+ if b.width <= 0 or b.height <= 0:
446
+ return None # degenerate bounds say nothing about the shape
447
+ long_side, short_side = max(b.width, b.height), min(b.width, b.height)
448
+ return long_side >= PHONE_MIN_ASPECT * short_side
449
+
450
+
451
+ def is_setup_screen(overlay: dict | None = None,
452
+ bounds: WindowBounds | None = None) -> bool:
453
+ """True when an overlay is up in a window that is not phone-shaped (F37).
454
+
455
+ Such a screen (first-run welcome, setup, permission prompt) is the user's to
456
+ finish: resume() never clicks it and phone_launch says so. Unknown bounds → False.
457
+ """
458
+ if overlay is None:
459
+ overlay = get_overlay()
460
+ return overlay["live"] is False and is_phone_shaped(bounds) is False
311
461
 
312
462
 
313
463
  def is_paused(overlay: dict | None = None) -> bool | None:
@@ -326,24 +476,73 @@ def is_paused(overlay: dict | None = None) -> bool | None:
326
476
  return None
327
477
 
328
478
 
479
+ def _move_pointer_off_window() -> bool:
480
+ """Move the pointer just outside the mirror window (a move, never a click).
481
+
482
+ F28/F29: with the pointer on the window its title-bar buttons share group 1 with
483
+ the overlay; moving off hides them before resume() reads and clicks. Picks the
484
+ first point beside the window that lies on an active display. Best effort:
485
+ returns False when Quartz is unavailable or nothing qualifies.
486
+ """
487
+ try:
488
+ import Quartz # type: ignore
489
+
490
+ b = get_bounds()
491
+ err, ids, count = Quartz.CGGetActiveDisplayList(16, None, None)
492
+ if err:
493
+ return False
494
+ rects = [Quartz.CGDisplayBounds(d) for d in list(ids)[:count]]
495
+ candidates = [
496
+ (b.x - 24, b.y + b.height / 2),
497
+ (b.x + b.width + 24, b.y + b.height / 2),
498
+ (b.x + b.width / 2, b.y + b.height + 24),
499
+ (b.x + b.width / 2, b.y - 24),
500
+ ]
501
+ for x, y in candidates:
502
+ for r in rects:
503
+ if (r.origin.x <= x < r.origin.x + r.size.width
504
+ and r.origin.y <= y < r.origin.y + r.size.height):
505
+ ev = Quartz.CGEventCreateMouseEvent(
506
+ None, Quartz.kCGEventMouseMoved, (x, y), Quartz.kCGMouseButtonLeft
507
+ )
508
+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev)
509
+ return True
510
+ except Exception:
511
+ return False
512
+ return False
513
+
514
+
329
515
  def resume() -> bool:
330
516
  """Click the Resume control when the session is paused (language-independent).
331
517
 
332
- Live already -> True. Paused overlay with exactly one button -> click it, then poll up
333
- to ~6 s (0.5 s interval) until the stream is live again. Anything else (multiple
334
- buttons, no button, unknown state) -> do not click, return False. The phone may still
335
- ask for Face ID / passcode on its own screen; that part cannot be automated from the Mac.
518
+ Live already -> True. F28/F29: when the pointer rests on the window its title-bar
519
+ buttons appear in the same AX group, so the pointer is first moved off the window
520
+ and the state read again; window controls are never counted or clicked. Paused
521
+ overlay with exactly one other button -> click it, then poll up to ~6 s (0.5 s
522
+ interval) until the stream is live again. Anything else (several buttons, none,
523
+ unknown state) -> do not click, return False. The iPhone must be locked and near
524
+ the Mac for the stream to come back.
336
525
  """
337
526
  import time
338
527
 
339
- overlay = get_overlay()
528
+ overlay, hover = overlay_snapshot()
529
+ if hover:
530
+ _move_pointer_off_window()
531
+ time.sleep(0.6)
532
+ overlay, hover = overlay_snapshot()
340
533
  if overlay["live"] is True:
341
534
  return True
342
535
  if overlay["live"] is not False or overlay["buttons"] != 1:
343
536
  return False
537
+ if is_phone_shaped() is not True:
538
+ # F37: a button in a window that is not phone-shaped belongs to a setup /
539
+ # welcome / permission screen — never ours to click. Unknown bounds: no click either.
540
+ return False
344
541
  try:
345
- _run_osascript(_CLICK_RESUME_SCRIPT)
346
- except WindowError:
542
+ clicked = _run_osascript(_CLICK_RESUME_SCRIPT)
543
+ except (WindowError, subprocess.TimeoutExpired):
544
+ return False
545
+ if clicked != "CLICKED":
347
546
  return False
348
547
  for _ in range(12): # up to ~6 s for the stream to come back
349
548
  time.sleep(0.5)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "noracu",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "mcpName": "io.github.sgInnora/noracu",
5
5
  "description": "Local MCP server: macOS apps and a browser by element index, plus iPhone Mirroring (experimental).",
6
6
  "type": "module",