noracu 0.3.0 → 0.3.2

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.
@@ -34,36 +34,70 @@ class WindowBounds:
34
34
  return (self.x + self.width // 2, self.y + self.height // 2)
35
35
 
36
36
  def denormalize(self, nx: float, ny: float) -> tuple[int, int]:
37
- """Convert normalized (0-1) coordinates to screen coordinates."""
37
+ """Convert normalized (0-1) coordinates to screen coordinates.
38
+
39
+ The window covers x .. x + width - 1: 1.0 (and anything that rounds past it) is its last point,
40
+ not the first point outside it.
41
+ """
38
42
  if not (0.0 <= nx <= 1.0 and 0.0 <= ny <= 1.0):
39
43
  raise ValueError(f"normalized coords out of range: ({nx}, {ny})")
40
44
  return (
41
- round(self.x + nx * self.width),
42
- round(self.y + ny * self.height),
45
+ min(round(self.x + nx * self.width), self.x + max(self.width, 1) - 1),
46
+ min(round(self.y + ny * self.height), self.y + max(self.height, 1) - 1),
43
47
  )
44
48
 
45
49
 
46
50
  # Device run 2026-11-07: while the phone's keyboard is composing (a Pinyin "x" with its underline),
47
51
  # iPhone Mirroring adds a 397x28 AXDialog window — the candidate bar — and System Events lists it as
48
52
  # window 1, ahead of the phone (AXStandardWindow). Every script that reads the mirror window starts
49
- # with this static block: mi is the index of the first AXStandardWindow, else 1 as before. Fixed text
50
- # joined into the scripts below — no runtime value is interpolated (invariant 1).
53
+ # with this static block: mi is the index of the first standard window shaped like a phone (as
54
+ # is_phone_shaped: PHONE_MIN_SHORT_SIDE, PHONE_MIN_ASPECT), else of the first standard window, else 1 as
55
+ # before — review 2026-11-17: another standard window of the process (one near square: a settings or
56
+ # welcome window) can be listed ahead of the phone. Fixed text joined into the scripts below — no runtime
57
+ # value is interpolated (invariant 1).
51
58
  # Device run 2026-11-08 03:44: the first version kept `contents of cand`, which System Events turns
52
59
  # into a reference BY NAME (window "iPhone Mirroring"); during a connection blip that name did not
53
60
  # resolve and `position of` failed with -1728. The index is re-read on every call, like window 1 was.
54
61
  _PICK_WINDOW = '''
55
- set mi to 1
62
+ set cands to {}
56
63
  repeat with i from 1 to (count of windows)
64
+ set sr to ""
65
+ set wh to {0, 0}
57
66
  try
58
- if ((subrole of window i) as text) is "AXStandardWindow" then
59
- set mi to i
60
- exit repeat
61
- end if
67
+ set sr to (subrole of window i) as text
68
+ end try
69
+ try
70
+ set wh to size of window i
62
71
  end try
72
+ set end of cands to {sr, item 1 of wh, item 2 of wh}
63
73
  end repeat
74
+ set mi to my pickWindow(cands)
75
+ '''
76
+ # the choice itself, a handler at the top of each script: {subrole, width, height} per window → an index
77
+ _PICK_HANDLER = '''
78
+ on pickWindow(cands)
79
+ set firstStd to 0
80
+ repeat with i from 1 to (count of cands)
81
+ set c to item i of cands
82
+ if (item 1 of c) is "AXStandardWindow" then
83
+ if firstStd is 0 then set firstStd to i
84
+ set w to (item 2 of c) as real
85
+ set h to (item 3 of c) as real
86
+ set shortSide to w
87
+ set longSide to h
88
+ if w > h then
89
+ set shortSide to h
90
+ set longSide to w
91
+ end if
92
+ if shortSide >= 120 and longSide >= 1.7 * shortSide then return i
93
+ end if
94
+ end repeat
95
+ if firstStd > 0 then return firstStd
96
+ return 1
97
+ end pickWindow
64
98
  '''
65
99
 
66
- _GET_BOUNDS_SCRIPT = '''
100
+ _GET_BOUNDS_SCRIPT = _PICK_HANDLER + '''
67
101
  tell application "System Events"
68
102
  tell process "iPhone Mirroring"
69
103
  set winCount to count of windows
@@ -127,7 +161,7 @@ def ensure_frontmost(timeout: float = 10) -> None:
127
161
 
128
162
  CGEvents are delivered to the frontmost app; if another window
129
163
  covers the mirroring window, taps would land on the wrong target.
130
- F31: when the app had to be activated (possibly switching Spaces), wait
164
+ When the app had to be activated (possibly switching Spaces), wait
131
165
  until the window yields a real frame before returning, so the caller's
132
166
  next capture is not a transition frame refused as capture_failed.
133
167
  ``timeout`` bounds each osascript run (a tidy-up passes a short one).
@@ -148,10 +182,10 @@ def ensure_frontmost(timeout: float = 10) -> None:
148
182
 
149
183
 
150
184
  def _wait_capturable(timeout_s: float = 2.0, poll_s: float = 0.2) -> bool:
151
- """Poll until the mirror window gives a valid frame (F31); best effort.
185
+ """Poll until the mirror window gives a valid frame; best effort.
152
186
 
153
187
  Uses verify.window_luma(), which refuses off-screen windows and blank
154
- transition frames (F25). Returns True once a frame passes, False after
188
+ transition frames. Returns True once a frame passes, False after
155
189
  ``timeout_s`` — it never raises: a caller whose own capture still fails
156
190
  reports capture_failed as before.
157
191
  """
@@ -215,10 +249,10 @@ def get_bounds() -> WindowBounds:
215
249
  # is localized, so the decision never matches on text — only on structure (child count, classes).
216
250
  # Labels can span multiple lines and nameless elements coerce to the literal "missing value";
217
251
  # both are normalized so one element = exactly one `<class>\t<label>\t<subrole>\t<child classes>`
218
- # line (tabs inside labels are collapsed too). F28: the subrole and, for groups, the classes of
252
+ # line (tabs inside labels are collapsed too). The subrole and, for groups, the classes of
219
253
  # their children let parse_overlay_ex tell the window's own hover controls (close / minimize /
220
254
  # zoom buttons and the small toolbar group) apart from a real overlay.
221
- _OVERLAY_SCRIPT = '''
255
+ _OVERLAY_SCRIPT = _PICK_HANDLER + '''
222
256
  on collapseBreaks(s)
223
257
  set tid to AppleScript's text item delimiters
224
258
  set AppleScript's text item delimiters to linefeed
@@ -283,10 +317,10 @@ end tell
283
317
 
284
318
  # Clicks the Resume control of the paused overlay. Only ever invoked after _OVERLAY_SCRIPT
285
319
  # reported exactly one overlay button under group 1 (static script, no interpolated
286
- # parameters). F29: "button 1 of group 1" was the window's Close button whenever the
320
+ # parameters). "button 1 of group 1" was the window's Close button whenever the
287
321
  # pointer rested on the window, so window controls are skipped by AX subrole and the
288
322
  # click happens only when exactly one other button remains; prints CLICKED or SKIP.
289
- _CLICK_RESUME_SCRIPT = '''
323
+ _CLICK_RESUME_SCRIPT = _PICK_HANDLER + '''
290
324
  tell application "System Events"
291
325
  tell process "iPhone Mirroring"
292
326
  ''' + _PICK_WINDOW + '''
@@ -349,7 +383,7 @@ def get_window_info() -> dict | None:
349
383
  def is_frontmost() -> bool:
350
384
  """True when iPhone Mirroring is the frontmost application, asked fresh on every call.
351
385
 
352
- F26 runs this right before synthesized input events. F30: the in-process
386
+ This runs right before synthesized input events. The in-process
353
387
  NSWorkspace.frontmostApplication() query used before is a snapshot in a process
354
388
  without a run loop (imctl's case) — after Finder came to the front it still answered
355
389
  "iPhone Mirroring", so the re-checks inside one operation could never fire. System
@@ -362,7 +396,7 @@ def is_frontmost() -> bool:
362
396
  return False
363
397
 
364
398
 
365
- # F28: controls iPhone Mirroring adds to group 1 while the pointer rests on its window
399
+ # Controls iPhone Mirroring adds to group 1 while the pointer rests on its window
366
400
  # (the title-bar buttons), identified by AX subrole — never by localized text.
367
401
  _CHROME_SUBROLES = frozenset(
368
402
  {"AXCloseButton", "AXMinimizeButton", "AXZoomButton", "AXFullScreenButton"}
@@ -380,11 +414,12 @@ def parse_overlay_ex(raw: str) -> tuple[dict, bool]:
380
414
  buttons=button count
381
415
  - "NO_WINDOW" / "NO_GROUP" / unparseable -> live=None, overlay=None, buttons=0
382
416
 
383
- F28: while the pointer rests on the mirror window, group 1 also holds the window's own
417
+ While the pointer rests on the mirror window, group 1 also holds the window's own
384
418
  title-bar buttons (subroles AXCloseButton / AXMinimizeButton / AXZoomButton) and a small
385
- toolbar (a group whose children are only buttons). hover is True when those buttons are
386
- present; they and the toolbar group are not an overlay and are never counted. Without
387
- them the rules above apply unchanged: any other child still means not live.
419
+ toolbar (a group whose children are only buttons; an empty group is not it). hover is True when those buttons are
420
+ present; they and the toolbar group — one group, the first such — are not an overlay and
421
+ are never counted. Without them the rules above apply unchanged: any other child, a second
422
+ group of buttons or a second empty group included, still means not live.
388
423
  """
389
424
  unknown = {"live": None, "overlay": None, "buttons": 0}
390
425
  if raw is None:
@@ -411,10 +446,17 @@ def parse_overlay_ex(raw: str) -> tuple[dict, bool]:
411
446
  hover = any(c == "button" and s in _CHROME_SUBROLES for c, _, s, _ in elements)
412
447
  rest_els = [e for e in elements if not (e[0] == "button" and e[2] in _CHROME_SUBROLES)]
413
448
  if hover:
414
- # The hover toolbar: a group holding only buttons (or nothing yet, mid-animation).
415
- rest_els = [
416
- e for e in rest_els if not (e[0] == "group" and all(k == "button" for k in e[3]))
417
- ]
449
+ # The hover toolbar: one group holding only buttons. There is one of it: a second such group is
450
+ # something else, stays, and the window does not read as live. An empty group is not taken for it
451
+ # (all() of nothing is True): it may be an overlay that has not drawn its content yet, and a window
452
+ # that is not known to be live gets no input.
453
+ kept, toolbar = [], False
454
+ for e in rest_els:
455
+ if not toolbar and e[0] == "group" and e[3] and all(k == "button" for k in e[3]):
456
+ toolbar = True
457
+ continue
458
+ kept.append(e)
459
+ rest_els = kept
418
460
  if not rest_els:
419
461
  return {"live": True, "overlay": None, "buttons": 0}, hover
420
462
  buttons = sum(1 for e in rest_els if e[0] == "button")
@@ -458,7 +500,7 @@ def get_overlay() -> dict:
458
500
  return overlay_snapshot()[0]
459
501
 
460
502
 
461
- # F37 (2026-11-05, macOS 27.2): the first launch after the macOS upgrade showed a welcome
503
+ # 2026-11-05, macOS 27.2: the first launch after the macOS upgrade showed a welcome
462
504
  # screen ("iPhone on Your Mac …") in a 640×660 window. Its button made it look like the paused
463
505
  # overlay: phone_status reported paused=true, phone_launch told the user to lock the iPhone, and
464
506
  # resume() clicks an overlay's lone button as if it were Resume. The mirror window itself — live
@@ -468,13 +510,17 @@ def get_overlay() -> dict:
468
510
  # (≈1.78) in and a wide dialog (e.g. 800×520 ≈ 1.54) out. Geometry, not text: language-
469
511
  # independent like the rest of the overlay probe.
470
512
  PHONE_MIN_ASPECT = 1.7
513
+ # The short side of a phone's picture: the keyboard's candidate bar (397x28, an AXDialog window of the same
514
+ # process) is elongated too, and is the window the scripts fall back to when no standard window is listed.
515
+ PHONE_MIN_SHORT_SIDE = 120
471
516
 
472
517
 
473
518
  def is_phone_shaped(bounds: WindowBounds | None = None) -> bool | None:
474
- """True when the mirror window is elongated like a phone, portrait or landscape (F37).
519
+ """True when the mirror window is elongated like a phone, portrait or landscape.
475
520
 
476
- The long side must be at least PHONE_MIN_ASPECT times the short side. None when the
477
- bounds cannot be read.
521
+ The long side must be at least PHONE_MIN_ASPECT times the short side, and the short side
522
+ at least PHONE_MIN_SHORT_SIDE: a strip such as the keyboard's candidate bar is not a phone.
523
+ None when the bounds cannot be read.
478
524
  """
479
525
  try:
480
526
  b = bounds if bounds is not None else get_bounds()
@@ -483,12 +529,12 @@ def is_phone_shaped(bounds: WindowBounds | None = None) -> bool | None:
483
529
  if b.width <= 0 or b.height <= 0:
484
530
  return None # degenerate bounds say nothing about the shape
485
531
  long_side, short_side = max(b.width, b.height), min(b.width, b.height)
486
- return long_side >= PHONE_MIN_ASPECT * short_side
532
+ return short_side >= PHONE_MIN_SHORT_SIDE and long_side >= PHONE_MIN_ASPECT * short_side
487
533
 
488
534
 
489
535
  def is_setup_screen(overlay: dict | None = None,
490
536
  bounds: WindowBounds | None = None) -> bool:
491
- """True when an overlay is up in a window that is not phone-shaped (F37).
537
+ """True when an overlay is up in a window that is not phone-shaped.
492
538
 
493
539
  Such a screen (first-run welcome, setup, permission prompt) is the user's to
494
540
  finish: resume() never clicks it and phone_launch says so. Unknown bounds → False.
@@ -517,7 +563,7 @@ def is_paused(overlay: dict | None = None) -> bool | None:
517
563
  def _move_pointer_off_window() -> bool:
518
564
  """Move the pointer just outside the mirror window (a move, never a click).
519
565
 
520
- F28/F29: with the pointer on the window its title-bar buttons share group 1 with
566
+ With the pointer on the window its title-bar buttons share group 1 with
521
567
  the overlay; moving off hides them before resume() reads and clicks. Picks the
522
568
  first point beside the window that lies on an active display. Best effort:
523
569
  returns False when Quartz is unavailable or nothing qualifies.
@@ -555,7 +601,7 @@ def _move_pointer_off_window() -> bool:
555
601
  def resume() -> bool:
556
602
  """Click the Resume control when the session is paused (language-independent).
557
603
 
558
- Live already -> True. F28/F29: when the pointer rests on the window its title-bar
604
+ Live already -> True. When the pointer rests on the window its title-bar
559
605
  buttons appear in the same AX group, so the pointer is first moved off the window
560
606
  and the state read again; window controls are never counted or clicked. Paused
561
607
  overlay with exactly one other button -> click it, then poll up to ~6 s (0.5 s
@@ -575,7 +621,7 @@ def resume() -> bool:
575
621
  if overlay["live"] is not False or overlay["buttons"] != 1:
576
622
  return False
577
623
  if is_phone_shaped() is not True:
578
- # F37: a button in a window that is not phone-shaped belongs to a setup /
624
+ # A button in a window that is not phone-shaped belongs to a setup /
579
625
  # welcome / permission screen — never ours to click. Unknown bounds: no click either.
580
626
  return False
581
627
  try:
@@ -8,7 +8,88 @@ import Network
8
8
  // What this runner was built from: a hash of its own sources, kept up to date by scripts/gen-runner-build.mjs
9
9
  // (a test fails when it is not). It goes out on the ready line; the Mac side does not use a runner whose build
10
10
  // is not the one its own copy of these sources names.
11
- let noracuRunnerBuild = "c6905871df8d"
11
+ let noracuRunnerBuild = "043fbc1f2a62"
12
+
13
+ // MARK: - pure rules (no XCTest: test/ios-runner-rules.mjs compiles this block on its own and runs it)
14
+
15
+ enum NoracuRules {
16
+ // 32 characters, each 0-9 or a-f, ASCII only
17
+ static func validToken(_ t: String) -> Bool {
18
+ let u = Array(t.utf8)
19
+ return u.count == 32 && u.allSatisfy { ($0 >= 48 && $0 <= 57) || ($0 >= 97 && $0 <= 102) }
20
+ }
21
+
22
+ // NORACU_BIND: a loopback address, or the unique-local (fc00::/7) address of the CoreDevice tunnel — never a
23
+ // wildcard (0.0.0.0, ::), a link-local address or a Wi-Fi / cellular address: those listen beyond the tunnel.
24
+ // IPv4 is checked first: IPv6Address("127.0.0.1") may parse as a mapped address.
25
+ static func bind(_ s: String) -> (host: NWEndpoint.Host, v6: IPv6Address?, loopback: Bool)? {
26
+ if let v4 = IPv4Address(s) {
27
+ guard v4.rawValue[0] == 127 else { return nil }
28
+ return (.ipv4(v4), nil, true)
29
+ }
30
+ if let v6 = IPv6Address(s) {
31
+ let r = v6.rawValue
32
+ guard v6.isLoopback || (r.count == 16 && (r[0] & 0xfe) == 0xfc) else { return nil }
33
+ return (.ipv6(v6), v6, v6.isLoopback)
34
+ }
35
+ return nil
36
+ }
37
+
38
+ // NORACU_PORT: 49152-65535
39
+ static func port(_ s: String) -> NWEndpoint.Port? {
40
+ guard let p = Int(s), (49152...65535).contains(p) else { return nil }
41
+ return NWEndpoint.Port(rawValue: UInt16(p))
42
+ }
43
+
44
+ // the setting that is wrong, in the order they are checked; nil when all three are good. An address that
45
+ // parses but is not one the runner listens on is bad_bind (it was reported as bad_port).
46
+ static func problem(_ env: [String: String]) -> String? {
47
+ if !validToken(env["NORACU_TOKEN"] ?? "") { return "bad_token" }
48
+ if bind(env["NORACU_BIND"] ?? "") == nil { return "bad_bind" }
49
+ if port(env["NORACU_PORT"] ?? "") == nil { return "bad_port" }
50
+ return nil
51
+ }
52
+ }
53
+
54
+ // The listener's states as the ready wait and the serve loop read them. Waiting is not a failure: NWListener says
55
+ // .waiting while the network path is not there yet (the CoreDevice tunnel coming up) and may still become ready
56
+ // within the wait. Failed or cancelled is: the listener is gone. Every state that was not ready is kept (the
57
+ // first eight) for the bind_failed detail, the failure ahead of a waiting. After ready, a listener that is gone
58
+ // ends the session: nothing listens any more, and the runner would otherwise stay up until its 12 hours ran out.
59
+ struct NoracuListenerWatch {
60
+ private(set) var ready = false
61
+ private(set) var failure: String?
62
+ private(set) var waiting: String?
63
+ private(set) var notes: [String] = []
64
+
65
+ mutating func note(_ kind: String, _ detail: String = "") {
66
+ switch kind {
67
+ case "ready": ready = true; waiting = nil
68
+ case "waiting": waiting = detail; remember("waiting: \(detail)")
69
+ case "failed": failure = "failed: \(detail)"; remember(failure!)
70
+ case "cancelled": failure = "cancelled"; remember("cancelled")
71
+ default: break
72
+ }
73
+ }
74
+ private mutating func remember(_ s: String) { if notes.count < 8 { notes.append(s) } }
75
+
76
+ // the ready wait ends: ready, or the listener gone (a waiting listener is waited for until the deadline)
77
+ var settled: Bool { ready || failure != nil }
78
+ // why it is not ready, for bind_failed: the failure, else the latest waiting, else nil (the deadline passed)
79
+ var notReadyDetail: String? { failure ?? waiting.map { "waiting: \($0)" } }
80
+ // after ready: the listener is gone
81
+ var gone: Bool { ready && failure != nil }
82
+ }
83
+
84
+ extension IPv6Address {
85
+ var isLoopback: Bool {
86
+ // ::1
87
+ let raw = self.rawValue
88
+ return raw.count == 16 && raw[15] == 1 && raw[0..<15].allSatisfy({ $0 == 0 })
89
+ }
90
+ }
91
+
92
+ // MARK: - end of pure rules
12
93
 
13
94
  // MARK: - shared state
14
95
 
@@ -23,14 +104,10 @@ final class RunnerBox: @unchecked Sendable {
23
104
  let bindIPv6: IPv6Address?
24
105
  // listener state, written on the listener queue, read on main
25
106
  private let stateLock = NSLock()
26
- private var _ready = false
27
- private var _listenerError: String?
28
- var ready: Bool { stateLock.lock(); defer { stateLock.unlock() }; return _ready }
29
- var listenerError: String? { stateLock.lock(); defer { stateLock.unlock() }; return _listenerError }
30
-
31
- func setReady() { stateLock.lock(); _ready = true; stateLock.unlock() }
32
- func setListenerError(_ e: String) {
33
- stateLock.lock(); if _listenerError == nil { _listenerError = e }; stateLock.unlock()
107
+ private var _watch = NoracuListenerWatch()
108
+ var listener: NoracuListenerWatch { stateLock.lock(); defer { stateLock.unlock() }; return _watch }
109
+ func noteListener(_ kind: String, _ detail: String = "") {
110
+ stateLock.lock(); _watch.note(kind, detail); stateLock.unlock()
34
111
  }
35
112
 
36
113
  // failures XCTest recorded while the test ran (see NoracuRunner.record)
@@ -45,45 +122,16 @@ final class RunnerBox: @unchecked Sendable {
45
122
  // NORACU_SELFTEST=1 (set by the live test only) makes the runner answer the selftest_issue op
46
123
  let selftest: Bool
47
124
 
48
- // 32 characters, each 0-9 or a-f, ASCII only
49
- static func validToken(_ t: String) -> Bool {
50
- let u = Array(t.utf8)
51
- return u.count == 32 && u.allSatisfy { ($0 >= 48 && $0 <= 57) || ($0 >= 97 && $0 <= 102) }
52
- }
53
-
54
125
  init?(env: [String: String]) {
55
- let token = env["NORACU_TOKEN"] ?? ""
56
- guard RunnerBox.validToken(token) else { return nil }
57
- self.token = token
126
+ guard NoracuRules.problem(env) == nil,
127
+ let b = NoracuRules.bind(env["NORACU_BIND"] ?? ""),
128
+ let p = NoracuRules.port(env["NORACU_PORT"] ?? "") else { return nil }
129
+ self.token = env["NORACU_TOKEN"] ?? ""
58
130
  self.selftest = env["NORACU_SELFTEST"] == "1"
59
- let bind = env["NORACU_BIND"] ?? ""
60
- // check IPv4 first: IPv6Address("127.0.0.1") may parse as a mapped address
61
- // review S4A-s8-g-2: only a loopback address, or the unique-local (fc00::/7) address of the CoreDevice tunnel —
62
- // never a wildcard (0.0.0.0, ::), a link-local address or a Wi-Fi / cellular address: those listen beyond the tunnel
63
- if let v4 = IPv4Address(bind) {
64
- guard v4.rawValue[0] == 127 else { return nil }
65
- self.bindHost = .ipv4(v4)
66
- self.bindIPv6 = nil
67
- self.isLoopbackBind = v4.rawValue[0] == 127
68
- } else if let v6 = IPv6Address(bind) {
69
- let r = v6.rawValue
70
- guard v6.isLoopback || (r.count == 16 && (r[0] & 0xfe) == 0xfc) else { return nil }
71
- self.bindHost = .ipv6(v6)
72
- self.bindIPv6 = v6
73
- self.isLoopbackBind = v6.isLoopback
74
- } else {
75
- return nil
76
- }
77
- guard let p = Int(env["NORACU_PORT"] ?? ""), (49152...65535).contains(p) else { return nil }
78
- self.port = NWEndpoint.Port(rawValue: UInt16(p))!
79
- }
80
- }
81
-
82
- extension IPv6Address {
83
- var isLoopback: Bool {
84
- // ::1
85
- let raw = self.rawValue
86
- return raw.count == 16 && raw[15] == 1 && raw[0..<15].allSatisfy({ $0 == 0 })
131
+ self.bindHost = b.host
132
+ self.bindIPv6 = b.v6
133
+ self.isLoopbackBind = b.loopback
134
+ self.port = p
87
135
  }
88
136
  }
89
137
 
@@ -115,14 +163,11 @@ final class NoracuRunner: XCTestCase {
115
163
  func testServe() throws {
116
164
  let env = ProcessInfo.processInfo.environment
117
165
  guard let box = RunnerBox(env: env) else {
118
- // distinguish which part was bad
119
- let token = env["NORACU_TOKEN"] ?? ""
120
- if !RunnerBox.validToken(token) {
121
- bail("bad_token", "token len=\(token.count)")
122
- } else if IPv4Address(env["NORACU_BIND"] ?? "") == nil && IPv6Address(env["NORACU_BIND"] ?? "") == nil {
123
- bail("bad_bind", "bind=\(env["NORACU_BIND"] ?? "<nil>")")
124
- } else {
125
- bail("bad_port", "port=\(env["NORACU_PORT"] ?? "<nil>")")
166
+ // which setting was bad
167
+ switch NoracuRules.problem(env) {
168
+ case "bad_token": bail("bad_token", "token len=\((env["NORACU_TOKEN"] ?? "").count)")
169
+ case "bad_bind": bail("bad_bind", "bind=\(env["NORACU_BIND"] ?? "<nil>") (a loopback or fc00::/7 address only)")
170
+ default: bail("bad_port", "port=\(env["NORACU_PORT"] ?? "<nil>")")
126
171
  }
127
172
  return
128
173
  }
@@ -139,9 +184,10 @@ final class NoracuRunner: XCTestCase {
139
184
  let server = RunnerServer(box: box)
140
185
  listener.stateUpdateHandler = { st in
141
186
  switch st {
142
- case .ready: box.setReady()
143
- case .failed(let e): box.setListenerError("failed: \(e)")
144
- case .waiting(let e): box.setListenerError("waiting: \(e)")
187
+ case .ready: box.noteListener("ready")
188
+ case .failed(let e): box.noteListener("failed", "\(e)")
189
+ case .waiting(let e): box.noteListener("waiting", "\(e)")
190
+ case .cancelled: box.noteListener("cancelled")
145
191
  default: break
146
192
  }
147
193
  }
@@ -149,11 +195,12 @@ final class NoracuRunner: XCTestCase {
149
195
  listener.start(queue: q)
150
196
 
151
197
  let readyDeadline = Date().addingTimeInterval(10)
152
- while !box.ready && box.listenerError == nil && Date() < readyDeadline {
198
+ while !box.listener.settled && Date() < readyDeadline {
153
199
  RunLoop.current.run(until: Date().addingTimeInterval(0.05))
154
200
  }
155
- if !box.ready {
156
- let detail = box.listenerError ?? "listener not ready after 10s"
201
+ let w = box.listener
202
+ if !w.ready {
203
+ let detail = (w.notReadyDetail ?? "listener not ready after 10s") + (w.notes.count > 1 ? " (states: \(w.notes.joined(separator: "; ")))" : "")
157
204
  listener.cancel()
158
205
  bail("bind_failed", detail)
159
206
  return
@@ -162,9 +209,15 @@ final class NoracuRunner: XCTestCase {
162
209
  fflush(stdout)
163
210
 
164
211
  let deadline = Date().addingTimeInterval(12 * 3600)
165
- while !box.done && Date() < deadline {
212
+ while !box.done && !box.listener.gone && Date() < deadline {
166
213
  RunLoop.current.run(until: Date().addingTimeInterval(0.2))
167
214
  }
215
+ // the listener went away while the runner served: say so and end, instead of staying up with nothing listening
216
+ if box.listener.gone {
217
+ print("NORACU_RUNNER error listener_failed")
218
+ NSLog("NORACU_RUNNER error listener_failed: \(box.listener.failure ?? "")")
219
+ fflush(stdout)
220
+ }
168
221
  listener.cancel()
169
222
  print("NORACU_RUNNER exit served=\(box.served) by_quit=\(box.done)")
170
223
  fflush(stdout)
@@ -5,6 +5,15 @@
5
5
  import XCTest
6
6
  import Foundation
7
7
 
8
+ // MARK: - pure rules (no XCTest: test/ios-runner-rules.mjs compiles this block on its own and runs it)
9
+
10
+ // SpringBoard's frame as XCUITest read it is the screen only when it has an area. A read that failed comes back as
11
+ // a zero rect, and against it nothing is "shown" — no icon, no alert: that read as "no system alert" and let text
12
+ // and keys through. Such a frame is taken as unreadable, and what needs it fails closed.
13
+ func noracuScreenReadable(_ r: CGRect) -> Bool { !r.isNull && !r.isInfinite && r.width > 0 && r.height > 0 }
14
+
15
+ // MARK: - end of pure rules
16
+
8
17
  enum RunnerCommands {
9
18
  // MARK: helpers
10
19
 
@@ -312,6 +321,7 @@ enum RunnerCommands {
312
321
  let snap: XCUIElementSnapshot
313
322
  do { snap = try app("com.apple.springboard").snapshot() } catch { return nil }
314
323
  let scr = screen()
324
+ guard noracuScreenReadable(scr) else { return nil } // unread: the callers fail closed, as for no snapshot
315
325
  var icons = 0
316
326
  var alerts: [SBAlert] = []
317
327
  func shown(_ s: XCUIElementSnapshot) -> Bool { s.frame.width > 0 && s.frame.height > 0 && s.frame.intersects(scr) }
@@ -321,7 +331,7 @@ enum RunnerCommands {
321
331
  }
322
332
  func walk(_ s: XCUIElementSnapshot) {
323
333
  if shown(s) && s.elementType == .icon { icons += 1 }
324
- // an alert only: a sheet's frame can cover the whole screen (pre-review P3)
334
+ // an alert only: a sheet's frame can cover the whole screen
325
335
  if shown(s) && s.elementType == .alert {
326
336
  var b: [CGRect] = []
327
337
  buttons(s, &b)
@@ -335,7 +345,7 @@ enum RunnerCommands {
335
345
 
336
346
  enum SBInput { case tap, press, drag, text }
337
347
 
338
- // review S4A-s8-g-1: a system alert (a permission prompt, say) sits over the app in front while the app still reads
348
+ // A system alert (a permission prompt, say) sits over the app in front while the app still reads
339
349
  // "in front", and the app's own snapshot does not show it. Input named for an app is not sent while one is up: a tap
340
350
  // at the app's point would press the alert's button, and text would go to the alert's field. SpringBoard that
341
351
  // cannot be read fails closed. Returns the refusal, or nil.
@@ -352,7 +362,7 @@ enum RunnerCommands {
352
362
  // tap whose point lies on a button of one of SpringBoard's alerts (a system prompt). A sheet does not count
353
363
  // (its frame can cover the screen), and nothing else is sent: no long press, no drag, no text and no key —
354
364
  // text goes wherever the keyboard focus is, which the public API does not show, and a second Return would
355
- // land on whatever the alert was covering (pre-review P3). Returns the refusal, or nil.
365
+ // land on whatever the alert was covering. Returns the refusal, or nil.
356
366
  @MainActor
357
367
  static func springboardRefusal(_ args: [String: Any], _ kind: SBInput, at point: CGPoint? = nil) -> [String: Any]? {
358
368
  guard let raw = args["springboard_only"] else { return nil }
@@ -442,7 +452,7 @@ enum RunnerCommands {
442
452
  case .tabBar: return "tabBar"
443
453
  case .table: return "table"
444
454
  case .textField: return "textField"
445
- case .secureTextField: return "secureTextField" // review S4A-s8-reviewer-1: it fell to "other"
455
+ case .secureTextField: return "secureTextField" // it used to fall to "other"
446
456
  case .textView: return "textView"
447
457
  case .toggle: return "toggle"
448
458
  case .toolbar: return "toolbar"
@@ -100,8 +100,7 @@ final class RunnerServer: @unchecked Sendable {
100
100
  return false
101
101
  }
102
102
  guard let rawId = obj["id"], !RunnerCommands.isBool(rawId), rawId is Int else {
103
- // a missing id, or one that is not a whole number, cannot be matched to its request: the command is not
104
- // run (pre-review P3 and P4)
103
+ // a missing id, or one that is not a whole number, cannot be matched to its request: the command is not run
105
104
  var no = RunnerCommands.fail(0, "invalid_args", "id must be a whole number", sent: RunnerCommands.inputOps.contains(obj["op"] as? String ?? "") ? false : nil)
106
105
  no["id"] = 0
107
106
  send(conn, no)
@@ -27,7 +27,7 @@ xcodebuild test-without-building -project ios-runner/NoracuRunner.xcodeproj -sch
27
27
  ```
28
28
 
29
29
  The runner prints `NORACU_RUNNER ready v=1 port=<port> build=<hash of these sources>` on
30
- its own line when the listener is up (after a change here run `node scripts/gen-runner-build.mjs`), and `NORACU_RUNNER error bad_token|bad_bind|bad_port|bind_failed`
30
+ its own line when the listener is up (after a change here run `node scripts/gen-runner-build.mjs`), and `NORACU_RUNNER error bad_token|bad_bind|bad_port|bind_failed` (or `listener_failed` after the ready line)
31
31
  on invalid start-up values. It ends on `quit` or after 12 hours.
32
32
 
33
33
  ## Protocol
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "noracu",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
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",
@@ -10,10 +10,10 @@
10
10
  },
11
11
  "scripts": {
12
12
  "start": "node src/server.mjs",
13
- "test": "node test/engine-unit.mjs && node test/bg-inject-unit.mjs && node test/release-gate-unit.mjs && node test/ios-xcuitest-unit.mjs && node test/ios-session-unit.mjs && node test/ios-setup-unit.mjs && node test/ios-e2e.mjs && node test/e2e.mjs",
14
- "test:ci": "node test/engine-unit.mjs && node test/bg-inject-unit.mjs && node test/release-gate-unit.mjs && node test/ios-xcuitest-unit.mjs && node test/ios-session-unit.mjs && node test/ios-setup-unit.mjs && node test/ios-e2e.mjs && NORACU_CI=1 node test/e2e.mjs",
13
+ "test": "node test/engine-unit.mjs && node test/bg-inject-unit.mjs && node test/release-gate-unit.mjs && node test/gen-tools-unit.mjs && node test/cli-unit.mjs && node test/cli-no-cliclick.mjs && node test/check-pack-unit.mjs && node test/docs-codes-unit.mjs && node test/ios-xcuitest-unit.mjs && node test/ios-session-unit.mjs && node test/ios-setup-unit.mjs && node test/ios-runner-rules.mjs && node test/ios-e2e.mjs && node test/e2e.mjs && node test/browser-scroll-slow.mjs",
14
+ "test:ci": "node test/engine-unit.mjs && node test/bg-inject-unit.mjs && node test/release-gate-unit.mjs && node test/gen-tools-unit.mjs && node test/cli-unit.mjs && node test/cli-no-cliclick.mjs && node test/check-pack-unit.mjs && node test/docs-codes-unit.mjs && node test/ios-xcuitest-unit.mjs && node test/ios-session-unit.mjs && node test/ios-setup-unit.mjs && node test/ios-runner-rules.mjs && node test/ios-e2e.mjs && NORACU_CI=1 node test/e2e.mjs && node test/browser-scroll-slow.mjs",
15
15
  "test:imctl": "cd imctl && ${NORACU_PYTHON:-python3} tests/test_smoke.py",
16
- "check": "node --check src/server.mjs && node --check src/mac-ax.js && node --check src/approval.js && node --check src/bg-inject.js && node --check src/ios-xcuitest.js && node --check src/ios-session.js && node --check src/ios-setup.js && node --check scripts/gen-tools.mjs && node --check scripts/release-gate.mjs && python3 -c \"import ast,sys; [ast.parse(open(f).read(), f) for f in sys.argv[1:]]\" imctl/src/imctl/*.py",
16
+ "check": "node --check src/server.mjs && node --check src/mac-ax.js && node --check src/approval.js && node --check src/bg-inject.js && node --check src/ios-xcuitest.js && node --check src/ios-session.js && node --check src/ios-setup.js && node --check src/doctor.js && node --check scripts/gen-tools.mjs && node --check scripts/release-gate.mjs && node --check scripts/check-pack.mjs && node --check scripts/pack-rules.mjs && node --check scripts/check-public.mjs && node scripts/check-public.mjs && python3 -c \"import ast,sys; [ast.parse(open(f).read(), f) for f in sys.argv[1:]]\" imctl/src/imctl/*.py",
17
17
  "prepublishOnly": "npm run check && node scripts/release-gate.mjs && node scripts/check-pack.mjs && node scripts/gen-tools.mjs && git diff --exit-code docs/tools.md"
18
18
  },
19
19
  "engines": {
@@ -33,7 +33,10 @@
33
33
  "claude-code",
34
34
  "cursor",
35
35
  "iphone",
36
- "iphone-mirroring"
36
+ "iphone-mirroring",
37
+ "accessibility",
38
+ "desktop-automation",
39
+ "xcuitest"
37
40
  ],
38
41
  "license": "MIT",
39
42
  "dependencies": {
@@ -53,8 +56,12 @@
53
56
  "docs/architecture.md",
54
57
  "docs/tools.md",
55
58
  "docs/usage.md",
59
+ "docs/iphone.md",
60
+ "docs/troubleshooting.md",
61
+ "docs/known-issues.md",
62
+ "docs/apps.md",
56
63
  "README.md",
57
- "README.zh-CN.md",
64
+ "docs/README.zh-CN.md",
58
65
  "LICENSE",
59
66
  "CHANGELOG.md",
60
67
  "SECURITY.md",