@namzu/computer-use 4.4.0 → 4.5.0

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.
Files changed (124) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/SubprocessComputerUseHost.d.ts +8 -1
  3. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  4. package/dist/SubprocessComputerUseHost.js +15 -4
  5. package/dist/SubprocessComputerUseHost.js.map +1 -1
  6. package/dist/a11y/a11y.d.ts +15 -7
  7. package/dist/a11y/a11y.d.ts.map +1 -1
  8. package/dist/a11y/a11y.js +12 -5
  9. package/dist/a11y/a11y.js.map +1 -1
  10. package/dist/a11y/index.d.ts +7 -1
  11. package/dist/a11y/index.d.ts.map +1 -1
  12. package/dist/a11y/index.js +4 -1
  13. package/dist/a11y/index.js.map +1 -1
  14. package/dist/a11y/macos-helper.d.ts +80 -0
  15. package/dist/a11y/macos-helper.d.ts.map +1 -0
  16. package/dist/a11y/macos-helper.js +436 -0
  17. package/dist/a11y/macos-helper.js.map +1 -0
  18. package/dist/a11y/macos-signing.d.ts +56 -0
  19. package/dist/a11y/macos-signing.d.ts.map +1 -0
  20. package/dist/a11y/macos-signing.js +228 -0
  21. package/dist/a11y/macos-signing.js.map +1 -0
  22. package/dist/a11y/macos.d.ts +173 -0
  23. package/dist/a11y/macos.d.ts.map +1 -0
  24. package/dist/a11y/macos.js +271 -0
  25. package/dist/a11y/macos.js.map +1 -0
  26. package/dist/a11y/windows.d.ts +13 -2
  27. package/dist/a11y/windows.d.ts.map +1 -1
  28. package/dist/a11y/windows.js +29 -6
  29. package/dist/a11y/windows.js.map +1 -1
  30. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  31. package/dist/adapters/cua-driver/adapter.js +48 -10
  32. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  33. package/dist/adapters/cua-driver/ui-tree.d.ts +1 -0
  34. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  35. package/dist/adapters/cua-driver/ui-tree.js +2 -0
  36. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  37. package/dist/adapters/darwin-ax.d.ts +94 -0
  38. package/dist/adapters/darwin-ax.d.ts.map +1 -0
  39. package/dist/adapters/darwin-ax.js +754 -0
  40. package/dist/adapters/darwin-ax.js.map +1 -0
  41. package/dist/adapters/darwin.d.ts +43 -2
  42. package/dist/adapters/darwin.d.ts.map +1 -1
  43. package/dist/adapters/darwin.js +145 -7
  44. package/dist/adapters/darwin.js.map +1 -1
  45. package/dist/adapters/png.d.ts +6 -0
  46. package/dist/adapters/png.d.ts.map +1 -0
  47. package/dist/adapters/png.js +7 -0
  48. package/dist/adapters/png.js.map +1 -0
  49. package/dist/adapters/win32-native.d.ts +53 -0
  50. package/dist/adapters/win32-native.d.ts.map +1 -0
  51. package/dist/adapters/win32-native.js +279 -0
  52. package/dist/adapters/win32-native.js.map +1 -0
  53. package/dist/adapters/win32.d.ts +19 -1
  54. package/dist/adapters/win32.d.ts.map +1 -1
  55. package/dist/adapters/win32.js +34 -8
  56. package/dist/adapters/win32.js.map +1 -1
  57. package/dist/foreground/ladder.d.ts.map +1 -1
  58. package/dist/foreground/ladder.js +5 -1
  59. package/dist/foreground/ladder.js.map +1 -1
  60. package/dist/foreground/types.d.ts +6 -0
  61. package/dist/foreground/types.d.ts.map +1 -1
  62. package/dist/foreground/types.js.map +1 -1
  63. package/dist/foreground/windows.d.ts +2 -0
  64. package/dist/foreground/windows.d.ts.map +1 -1
  65. package/dist/foreground/windows.js +23 -11
  66. package/dist/foreground/windows.js.map +1 -1
  67. package/dist/native/a11y.d.ts +61 -0
  68. package/dist/native/a11y.d.ts.map +1 -0
  69. package/dist/native/a11y.js +197 -0
  70. package/dist/native/a11y.js.map +1 -0
  71. package/dist/native/foreground-monitor.d.ts +51 -0
  72. package/dist/native/foreground-monitor.d.ts.map +1 -0
  73. package/dist/native/foreground-monitor.js +120 -0
  74. package/dist/native/foreground-monitor.js.map +1 -0
  75. package/dist/native/presence.d.ts +24 -0
  76. package/dist/native/presence.d.ts.map +1 -0
  77. package/dist/native/presence.js +47 -0
  78. package/dist/native/presence.js.map +1 -0
  79. package/dist/native/process.d.ts +73 -0
  80. package/dist/native/process.d.ts.map +1 -0
  81. package/dist/native/process.js +292 -0
  82. package/dist/native/process.js.map +1 -0
  83. package/dist/native/protocol.d.ts +408 -0
  84. package/dist/native/protocol.d.ts.map +1 -0
  85. package/dist/native/protocol.js +527 -0
  86. package/dist/native/protocol.js.map +1 -0
  87. package/dist/native/shared.d.ts +16 -0
  88. package/dist/native/shared.d.ts.map +1 -0
  89. package/dist/native/shared.js +62 -0
  90. package/dist/native/shared.js.map +1 -0
  91. package/dist/presence/presence.d.ts +3 -2
  92. package/dist/presence/presence.d.ts.map +1 -1
  93. package/dist/presence/presence.js.map +1 -1
  94. package/dist/presence/windows.d.ts +2 -0
  95. package/dist/presence/windows.d.ts.map +1 -1
  96. package/dist/presence/windows.js +14 -0
  97. package/dist/presence/windows.js.map +1 -1
  98. package/helper-macos/main.swift +1756 -0
  99. package/package.json +3 -2
  100. package/src/SubprocessComputerUseHost.ts +26 -2
  101. package/src/a11y/a11y.ts +25 -11
  102. package/src/a11y/index.ts +28 -1
  103. package/src/a11y/macos-helper.ts +538 -0
  104. package/src/a11y/macos-signing.ts +280 -0
  105. package/src/a11y/macos.ts +496 -0
  106. package/src/a11y/windows.ts +29 -4
  107. package/src/adapters/cua-driver/adapter.ts +55 -15
  108. package/src/adapters/cua-driver/ui-tree.ts +2 -0
  109. package/src/adapters/darwin-ax.ts +920 -0
  110. package/src/adapters/darwin.ts +184 -4
  111. package/src/adapters/png.ts +5 -0
  112. package/src/adapters/win32-native.ts +328 -0
  113. package/src/adapters/win32.ts +52 -5
  114. package/src/foreground/ladder.ts +5 -1
  115. package/src/foreground/types.ts +6 -0
  116. package/src/foreground/windows.ts +24 -11
  117. package/src/native/a11y.ts +267 -0
  118. package/src/native/foreground-monitor.ts +165 -0
  119. package/src/native/presence.ts +58 -0
  120. package/src/native/process.ts +335 -0
  121. package/src/native/protocol.ts +963 -0
  122. package/src/native/shared.ts +75 -0
  123. package/src/presence/presence.ts +3 -2
  124. package/src/presence/windows.ts +14 -0
@@ -0,0 +1,1756 @@
1
+ // Namzu Helper: the macOS accessibility and window-capture helper of @namzu/computer-use.
2
+ //
3
+ // A small background app (no Dock icon) that LaunchServices starts in the person's own GUI
4
+ // session, so the Accessibility and Screen Recording permissions belong to "Namzu Helper" and
5
+ // not to a terminal or to sshd. It answers JSON lines over a unix socket (mode 0600, owner only):
6
+ //
7
+ // permissions, windows, displays, snapshot, seq, wait_change, identity, resolve, act,
8
+ // focus, capture_window, scroll, selfcheck, quit (ends the connection), shutdown (ends the app)
9
+ //
10
+ // Every request is {"id": n, "cmd": "...", ...}; every reply is {"id": n, "ok": true, ...} or
11
+ // {"id": n, "ok": false, "code": "...", "message": "..."}. The first line the helper sends on a
12
+ // connection is {"ok": true, "hello": true, "version": 1, ...}.
13
+ //
14
+ // Rectangles are physical pixels of the main display (points times its backing scale), the unit
15
+ // the host contract uses; window ids are CGWindowIDs.
16
+
17
+ import AppKit
18
+ import ApplicationServices
19
+ import CoreGraphics
20
+ import Foundation
21
+ import ScreenCaptureKit
22
+
23
+ // MARK: - Private SPI (long-standing, used by every accessibility client to map a window)
24
+
25
+ @_silgen_name("_AXUIElementGetWindow")
26
+ func _AXUIElementGetWindow(_ element: AXUIElement, _ identifier: UnsafeMutablePointer<CGWindowID>) -> AXError
27
+
28
+ // MARK: - Constants
29
+
30
+ let protocolVersion = 1
31
+ let buildId = CommandLine.arguments.firstIndex(of: "--build").flatMap { i in
32
+ i + 1 < CommandLine.arguments.count ? CommandLine.arguments[i + 1] : nil
33
+ } ?? "dev"
34
+ let socketPath: String = CommandLine.arguments.firstIndex(of: "--socket").flatMap { i in
35
+ i + 1 < CommandLine.arguments.count ? CommandLine.arguments[i + 1] : nil
36
+ } ?? ""
37
+ let idleExitSeconds: TimeInterval = 15 * 60
38
+
39
+ typealias Json = [String: Any]
40
+
41
+ // MARK: - Small helpers
42
+
43
+ func fnv(_ text: String) -> String {
44
+ var h: UInt64 = 0xcbf29ce484222325
45
+ for b in text.utf8 {
46
+ h ^= UInt64(b)
47
+ h = h &* 0x100000001b3
48
+ }
49
+ return String(h, radix: 16)
50
+ }
51
+
52
+ struct HelperError: Error {
53
+ let code: String
54
+ let message: String
55
+ }
56
+
57
+ func num(_ v: Any?, _ fallback: Double = 0) -> Double {
58
+ if let n = v as? NSNumber { return n.doubleValue }
59
+ return fallback
60
+ }
61
+
62
+ func intOf(_ v: Any?) -> Int? {
63
+ if let n = v as? NSNumber { return n.intValue }
64
+ // A window id may arrive as text, decimal or 0x…
65
+ if let t = (v as? String)?.trimmingCharacters(in: .whitespaces).lowercased(), !t.isEmpty {
66
+ if t.hasPrefix("0x") { return Int(t.dropFirst(2), radix: 16) }
67
+ return Int(t)
68
+ }
69
+ return nil
70
+ }
71
+
72
+ /// Runs on the main thread (AppKit's screens and workspace are read there), without waiting on itself.
73
+ func onMain<T>(_ body: () throws -> T) rethrows -> T {
74
+ try Thread.isMainThread ? body() : DispatchQueue.main.sync(execute: body)
75
+ }
76
+
77
+ /// Window ids of windows this helper draws itself (the self-test's demo window).
78
+ /// AppKit answers an accessibility call about its own windows on the calling thread, so a call made from a
79
+ /// request thread would touch AppKit views off the main thread and can lock up the main thread behind it.
80
+ /// Anything that reads or acts on such a window runs on the main thread.
81
+ let ownWindows = OwnWindows()
82
+ final class OwnWindows {
83
+ private let lock = NSLock()
84
+ private var ids = Set<Int>()
85
+ func add(_ id: Int) { lock.lock(); ids.insert(id); lock.unlock() }
86
+ func remove(_ id: Int) { lock.lock(); ids.remove(id); lock.unlock() }
87
+ func contains(_ id: Int?) -> Bool {
88
+ guard let id = id else { return false }
89
+ lock.lock(); defer { lock.unlock() }
90
+ return ids.contains(id)
91
+ }
92
+ }
93
+
94
+ /// Pixels per point of the main display, as a capture sees it.
95
+ func mainScale() -> Double {
96
+ onMain { Double(NSScreen.screens.first?.backingScaleFactor ?? 1) }
97
+ }
98
+
99
+ func nowMs() -> Double { Date().timeIntervalSince1970 * 1000 }
100
+
101
+ // MARK: - Permissions
102
+
103
+ func accessibilityTrusted(prompt: Bool) -> Bool {
104
+ if prompt {
105
+ let key = kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String
106
+ return AXIsProcessTrustedWithOptions([key: true] as CFDictionary)
107
+ }
108
+ return AXIsProcessTrusted()
109
+ }
110
+
111
+ func screenCaptureAllowed(prompt: Bool) -> Bool {
112
+ if prompt { return CGRequestScreenCaptureAccess() }
113
+ return CGPreflightScreenCaptureAccess()
114
+ }
115
+
116
+ /// macOS 27 renamed the Accessibility switch "Device Control and Data Access".
117
+ func accessibilityPaneName() -> String {
118
+ ProcessInfo.processInfo.operatingSystemVersion.majorVersion >= 27 ? "Device Control and Data Access" : "Accessibility"
119
+ }
120
+
121
+ func permissionsReply(prompt: Bool) -> Json {
122
+ let ax = accessibilityTrusted(prompt: prompt)
123
+ let sc = screenCaptureAllowed(prompt: prompt)
124
+ let appName = (Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String) ?? "Namzu Helper"
125
+ var steps: [String] = []
126
+ let axPane = accessibilityPaneName()
127
+ let remove = " If an older \"\(appName)\" row is already in the list, remove it first with the minus button, then add this one."
128
+ if !ax {
129
+ steps.append("System Settings > Privacy & Security > \(axPane): turn on \"\(appName)\".\(remove)")
130
+ }
131
+ if !sc {
132
+ steps.append("System Settings > Privacy & Security > Screen & System Audio Recording: turn on \"\(appName)\".\(remove)")
133
+ }
134
+ return [
135
+ "accessibility": ax,
136
+ "screenCapture": sc,
137
+ "app": appName,
138
+ "bundleId": Bundle.main.bundleIdentifier ?? "",
139
+ "path": Bundle.main.bundlePath,
140
+ "steps": steps,
141
+ ]
142
+ }
143
+
144
+ // MARK: - Process info
145
+
146
+ final class ProcessInfoCache {
147
+ private let lock = NSLock()
148
+ private var starts: [pid_t: Double] = [:]
149
+ private var chromium: [pid_t: Bool] = [:]
150
+ private var activated: Set<pid_t> = []
151
+
152
+ func start(_ pid: pid_t) -> Double {
153
+ lock.lock(); defer { lock.unlock() }
154
+ if let s = starts[pid] { return s }
155
+ var value: Double = 0
156
+ if let d = NSRunningApplication(processIdentifier: pid)?.launchDate {
157
+ value = (d.timeIntervalSince1970 * 1000).rounded()
158
+ }
159
+ starts[pid] = value
160
+ return value
161
+ }
162
+
163
+ func isChromium(_ pid: pid_t) -> Bool {
164
+ lock.lock(); defer { lock.unlock() }
165
+ if let c = chromium[pid] { return c }
166
+ var result = false
167
+ if let app = NSRunningApplication(processIdentifier: pid) {
168
+ let id = app.bundleIdentifier ?? ""
169
+ let prefixes = [
170
+ "com.google.Chrome", "org.chromium", "com.microsoft.edgemac", "com.brave.Browser",
171
+ "company.thebrowser", "com.operasoftware", "com.vivaldi", "com.github.Electron",
172
+ ]
173
+ if prefixes.contains(where: { id.hasPrefix($0) }) { result = true }
174
+ if let url = app.bundleURL {
175
+ let fm = FileManager.default
176
+ let frameworks = url.appendingPathComponent("Contents/Frameworks")
177
+ for name in ["Electron Framework.framework", "Chromium Embedded Framework.framework"] {
178
+ if fm.fileExists(atPath: frameworks.appendingPathComponent(name).path) { result = true }
179
+ }
180
+ }
181
+ }
182
+ chromium[pid] = result
183
+ return result
184
+ }
185
+
186
+ /// Chromium and Electron build their accessibility tree only when asked; this asks, once per process.
187
+ func activateChromium(_ pid: pid_t, app: AXUIElement) {
188
+ lock.lock()
189
+ let already = activated.contains(pid)
190
+ activated.insert(pid)
191
+ lock.unlock()
192
+ if already { return }
193
+ AXUIElementSetAttributeValue(app, "AXManualAccessibility" as CFString, kCFBooleanTrue)
194
+ AXUIElementSetAttributeValue(app, "AXEnhancedUserInterface" as CFString, kCFBooleanTrue)
195
+ }
196
+ }
197
+
198
+ let procInfo = ProcessInfoCache()
199
+
200
+ // MARK: - Windows
201
+
202
+ struct WindowEntry {
203
+ let id: Int
204
+ let pid: pid_t
205
+ let owner: String
206
+ let title: String
207
+ let bounds: CGRect // points
208
+ let layer: Int
209
+ let z: Int
210
+ }
211
+
212
+ func listWindowEntries() -> [WindowEntry] {
213
+ let opts: CGWindowListOption = [.optionOnScreenOnly, .excludeDesktopElements]
214
+ guard let raw = CGWindowListCopyWindowInfo(opts, kCGNullWindowID) as? [[String: Any]] else { return [] }
215
+ var out: [WindowEntry] = []
216
+ var z = 0
217
+ for w in raw {
218
+ let layer = (w[kCGWindowLayer as String] as? Int) ?? 0
219
+ guard layer == 0 else { continue }
220
+ let alpha = (w[kCGWindowAlpha as String] as? Double) ?? 1
221
+ if alpha <= 0.01 { continue }
222
+ guard let id = w[kCGWindowNumber as String] as? Int,
223
+ let pid = w[kCGWindowOwnerPID as String] as? Int,
224
+ let bd = w[kCGWindowBounds as String] as? [String: Any] else { continue }
225
+ let rect = CGRect(
226
+ x: num(bd["X"]), y: num(bd["Y"]), width: num(bd["Width"]), height: num(bd["Height"]))
227
+ if rect.width < 24 || rect.height < 24 { continue }
228
+ out.append(WindowEntry(
229
+ id: id, pid: pid_t(pid), owner: (w[kCGWindowOwnerName as String] as? String) ?? "",
230
+ title: (w[kCGWindowName as String] as? String) ?? "", bounds: rect, layer: layer, z: z))
231
+ z += 1
232
+ }
233
+ return out
234
+ }
235
+
236
+ func appElement(_ pid: pid_t) -> AXUIElement {
237
+ let el = AXUIElementCreateApplication(pid)
238
+ AXUIElementSetMessagingTimeout(el, 2.0)
239
+ return el
240
+ }
241
+
242
+ func attr(_ el: AXUIElement, _ name: String) -> CFTypeRef? {
243
+ var v: CFTypeRef?
244
+ let err = AXUIElementCopyAttributeValue(el, name as CFString, &v)
245
+ return err == .success ? v : nil
246
+ }
247
+
248
+ func frontmostPid() -> pid_t? {
249
+ onMain { NSWorkspace.shared.frontmostApplication?.processIdentifier }
250
+ }
251
+
252
+ func focusedWindowId(pid: pid_t) -> Int? {
253
+ let app = appElement(pid)
254
+ guard let w = attr(app, kAXFocusedWindowAttribute as String) else { return nil }
255
+ var id: CGWindowID = 0
256
+ if _AXUIElementGetWindow(w as! AXUIElement, &id) == .success, id != 0 { return Int(id) }
257
+ return nil
258
+ }
259
+
260
+ func windowsReply() -> Json {
261
+ let scale = mainScale()
262
+ let front = frontmostPid()
263
+ var frontId: Int?
264
+ if let f = front { frontId = focusedWindowId(pid: f) }
265
+ let me = ProcessInfo.processInfo.processIdentifier
266
+ var list: [Json] = []
267
+ var firstOfFront: Int?
268
+ let entries = listWindowEntries().filter { $0.pid != me }
269
+ for e in entries where e.pid == front && firstOfFront == nil { firstOfFront = e.id }
270
+ let focusedId = frontId ?? firstOfFront
271
+ for e in entries {
272
+ list.append([
273
+ "hwnd": e.id, "pid": Int(e.pid), "process": e.owner, "title": e.title,
274
+ "x": Int((e.bounds.origin.x * scale).rounded()), "y": Int((e.bounds.origin.y * scale).rounded()),
275
+ "width": Int((e.bounds.width * scale).rounded()), "height": Int((e.bounds.height * scale).rounded()),
276
+ "minimized": false, "focused": e.id == focusedId, "z": e.z,
277
+ ])
278
+ }
279
+ return ["windows": list]
280
+ }
281
+
282
+ func displaysReply() -> Json {
283
+ var out: [Json] = []
284
+ onMain {
285
+ let screens = NSScreen.screens
286
+ let main = screens.first
287
+ let scale = Double(main?.backingScaleFactor ?? 1)
288
+ let mainHeight = main?.frame.height ?? 0
289
+ for (i, s) in screens.enumerated() {
290
+ let did = (s.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?.intValue ?? i
291
+ // Cocoa has a bottom-left origin; the host uses a top-left one, as CGWindowList does.
292
+ let f = s.frame
293
+ let v = s.visibleFrame
294
+ let top = mainHeight - f.maxY
295
+ let vtop = mainHeight - v.maxY
296
+ out.append([
297
+ "id": String(did), "x": Int((f.origin.x * scale).rounded()), "y": Int((top * scale).rounded()),
298
+ "width": Int((f.width * scale).rounded()), "height": Int((f.height * scale).rounded()),
299
+ "workX": Int((v.origin.x * scale).rounded()), "workY": Int((vtop * scale).rounded()),
300
+ "workWidth": Int((v.width * scale).rounded()), "workHeight": Int((v.height * scale).rounded()),
301
+ "scale": Double(s.backingScaleFactor), "primary": i == 0,
302
+ ])
303
+ }
304
+ }
305
+ return ["displays": out]
306
+ }
307
+
308
+ // MARK: - Element registry (a ref names the control, not one reading of it)
309
+
310
+ final class ElementRegistry {
311
+ private let lock = NSLock()
312
+ private var byRuntime: [String: AXUIElement] = [:]
313
+ private var order: [String] = []
314
+ private let cap = 30_000
315
+
316
+ func put(_ id: String, _ el: AXUIElement) {
317
+ lock.lock(); defer { lock.unlock() }
318
+ if byRuntime[id] == nil { order.append(id) }
319
+ byRuntime[id] = el
320
+ if order.count > cap {
321
+ let drop = order.prefix(order.count - cap)
322
+ for k in drop { byRuntime.removeValue(forKey: k) }
323
+ order.removeFirst(order.count - cap)
324
+ }
325
+ }
326
+
327
+ func get(_ id: String) -> AXUIElement? {
328
+ lock.lock(); defer { lock.unlock() }
329
+ return byRuntime[id]
330
+ }
331
+ }
332
+
333
+ let registry = ElementRegistry()
334
+
335
+ func runtimeId(_ el: AXUIElement, pid: pid_t) -> String { "\(pid):\(CFHash(el))" }
336
+
337
+ // MARK: - Reading the tree
338
+
339
+ struct Fingerprint {
340
+ var runtimeId: String
341
+ var automationId: String
342
+ var role: String
343
+ var nameHash: String
344
+ var parentPath: String
345
+ var ordinal: Int
346
+ var processStart: Double
347
+
348
+ var json: Json {
349
+ [
350
+ "runtimeId": runtimeId, "automationId": automationId, "role": role, "nameHash": nameHash,
351
+ "parentPath": parentPath, "ordinal": ordinal, "processStart": processStart,
352
+ ]
353
+ }
354
+
355
+ static func from(_ j: Json) -> Fingerprint {
356
+ Fingerprint(
357
+ runtimeId: (j["runtimeId"] as? String) ?? "", automationId: (j["automationId"] as? String) ?? "",
358
+ role: (j["role"] as? String) ?? "", nameHash: (j["nameHash"] as? String) ?? "",
359
+ parentPath: (j["parentPath"] as? String) ?? "", ordinal: intOf(j["ordinal"]) ?? 0,
360
+ processStart: num(j["processStart"]))
361
+ }
362
+ }
363
+
364
+ final class ReadNode {
365
+ var element: AXUIElement
366
+ var parent: Int
367
+ var depth: Int
368
+ var role = ""
369
+ var subrole = ""
370
+ var name = ""
371
+ var identifier = ""
372
+ var rect = CGRect.zero // points
373
+ var enabled = true
374
+ var focused = false
375
+ var selected: Bool?
376
+ var value: String?
377
+ var toggle: String?
378
+ var expand: String?
379
+ var actions: [String] = []
380
+ var childCount: Int?
381
+ var children: [Int] = []
382
+ var fingerprint: Fingerprint?
383
+
384
+ init(_ e: AXUIElement, parent: Int, depth: Int) {
385
+ element = e
386
+ self.parent = parent
387
+ self.depth = depth
388
+ }
389
+ }
390
+
391
+ struct Snapshot {
392
+ var revision: Int
393
+ var windowId: Int
394
+ var pid: pid_t
395
+ var nodes: [ReadNode] // depth-first order
396
+ var total: Int
397
+ var truncated: Bool
398
+ var readMs: Int
399
+ var selectedText: String?
400
+ var app: String
401
+ var title: String
402
+ }
403
+
404
+ func cfString(_ v: CFTypeRef?) -> String? {
405
+ guard let v = v else { return nil }
406
+ if CFGetTypeID(v) == CFStringGetTypeID() { return (v as! String) }
407
+ return nil
408
+ }
409
+
410
+ func cfBool(_ v: CFTypeRef?) -> Bool? {
411
+ guard let v = v else { return nil }
412
+ if CFGetTypeID(v) == CFBooleanGetTypeID() { return CFBooleanGetValue((v as! CFBoolean)) }
413
+ return nil
414
+ }
415
+
416
+ func axPoint(_ v: CFTypeRef?) -> CGPoint? {
417
+ guard let v = v, CFGetTypeID(v) == AXValueGetTypeID() else { return nil }
418
+ var p = CGPoint.zero
419
+ return AXValueGetValue(v as! AXValue, .cgPoint, &p) ? p : nil
420
+ }
421
+
422
+ func axSize(_ v: CFTypeRef?) -> CGSize? {
423
+ guard let v = v, CFGetTypeID(v) == AXValueGetTypeID() else { return nil }
424
+ var s = CGSize.zero
425
+ return AXValueGetValue(v as! AXValue, .cgSize, &s) ? s : nil
426
+ }
427
+
428
+ let batchNames: [String] = [
429
+ kAXRoleAttribute, kAXSubroleAttribute, kAXTitleAttribute, kAXDescriptionAttribute, kAXValueAttribute,
430
+ "AXIdentifier", kAXPositionAttribute, kAXSizeAttribute, kAXEnabledAttribute, kAXFocusedAttribute,
431
+ kAXSelectedAttribute, kAXChildrenAttribute, kAXExpandedAttribute, "AXDisclosing", kAXPlaceholderValueAttribute,
432
+ ]
433
+
434
+ let noActionRoles: Set<String> = ["AXStaticText", "AXImage", "AXSplitter", "AXLayoutArea", "AXLayoutItem", "AXUnknown"]
435
+ let toggleRoles: Set<String> = ["AXCheckBox", "AXSwitch", "AXToggle", "AXMenuItem", "AXRadioButton"]
436
+ let lazyRoles: Set<String> = ["AXMenuBarItem", "AXMenuItem"]
437
+
438
+ func isSettable(_ el: AXUIElement, _ name: String) -> Bool {
439
+ var s: DarwinBoolean = false
440
+ return AXUIElementIsAttributeSettable(el, name as CFString, &s) == .success && s.boolValue
441
+ }
442
+
443
+ func readNode(_ node: ReadNode, expandChildren: Bool) -> [AXUIElement] {
444
+ let el = node.element
445
+ var raw: CFArray?
446
+ let err = AXUIElementCopyMultipleAttributeValues(
447
+ el, batchNames as CFArray, AXCopyMultipleAttributeOptions(rawValue: 0), &raw)
448
+ var values: [CFTypeRef?] = Array(repeating: nil, count: batchNames.count)
449
+ if err == .success, let arr = raw as? [AnyObject] {
450
+ for (i, v) in arr.enumerated() where i < values.count {
451
+ let ref = v as CFTypeRef
452
+ // A missing attribute comes back as an AXValue of type .axError.
453
+ if CFGetTypeID(ref) == AXValueGetTypeID(), AXValueGetType(ref as! AXValue) == .axError { continue }
454
+ values[i] = ref
455
+ }
456
+ }
457
+ node.role = cfString(values[0]) ?? ""
458
+ node.subrole = cfString(values[1]) ?? ""
459
+ let title = cfString(values[2]) ?? ""
460
+ let desc = cfString(values[3]) ?? ""
461
+ let placeholder = cfString(values[14]) ?? ""
462
+ node.identifier = cfString(values[5]) ?? ""
463
+ var valueText: String?
464
+ if let v = values[4] {
465
+ if let s = cfString(v) { valueText = s }
466
+ else if CFGetTypeID(v) == CFNumberGetTypeID() { valueText = (v as! NSNumber).stringValue }
467
+ else if let b = cfBool(v) { valueText = b ? "1" : "0" }
468
+ }
469
+ if node.role == "AXStaticText" {
470
+ node.name = !title.isEmpty ? title : (!desc.isEmpty ? desc : (valueText ?? ""))
471
+ } else {
472
+ node.name = !title.isEmpty ? title : (!desc.isEmpty ? desc : placeholder)
473
+ }
474
+ if let p = axPoint(values[6]), let s = axSize(values[7]) { node.rect = CGRect(origin: p, size: s) }
475
+ node.enabled = cfBool(values[8]) ?? true
476
+ node.focused = cfBool(values[9]) ?? false
477
+ node.selected = cfBool(values[10])
478
+ if toggleRoles.contains(node.role), node.role != "AXMenuItem" || node.subrole == "AXMenuItemMarkChar" {
479
+ if let v = values[4] {
480
+ let n = (v as? NSNumber)?.intValue ?? -1
481
+ node.toggle = n == 0 ? "off" : (n == 1 ? "on" : (n == 2 ? "mixed" : nil))
482
+ }
483
+ } else if node.role == "AXCheckBox" {
484
+ node.toggle = nil
485
+ }
486
+ if node.toggle == nil, let v = valueText, node.role != "AXStaticText" {
487
+ node.value = String(v.prefix(2000))
488
+ }
489
+ if let e = cfBool(values[12]) ?? cfBool(values[13]) { node.expand = e ? "expanded" : "collapsed" }
490
+
491
+ if !noActionRoles.contains(node.role) {
492
+ var names: CFArray?
493
+ if AXUIElementCopyActionNames(el, &names) == .success, let list = names as? [String] {
494
+ if list.contains("AXPress") || list.contains("AXOpen") || list.contains("AXConfirm") || list.contains("AXPick") {
495
+ node.actions.append("invoke")
496
+ }
497
+ if list.contains("AXIncrement") || list.contains("AXDecrement") { node.actions.append("value") }
498
+ if list.contains("AXShowMenu") && node.actions.isEmpty { /* context menu only: not a plain action */ }
499
+ }
500
+ if isSettable(el, kAXValueAttribute as String), !node.actions.contains("value"),
501
+ node.role != "AXCheckBox", node.role != "AXRadioButton", node.role != "AXSwitch" {
502
+ node.actions.append("value")
503
+ }
504
+ if node.toggle != nil, !node.actions.contains("toggle") { node.actions.append("toggle") }
505
+ if node.expand != nil || node.role == "AXDisclosureTriangle" {
506
+ if !node.actions.contains("expandCollapse") { node.actions.append("expandCollapse") }
507
+ }
508
+ if node.selected != nil, isSettable(el, kAXSelectedAttribute as String) || node.role == "AXRadioButton" || node.role == "AXTab" {
509
+ node.actions.append("selectionItem")
510
+ } else if node.role == "AXRadioButton" || node.role == "AXTab" || node.role == "AXRow" && node.selected != nil {
511
+ node.actions.append("selectionItem")
512
+ }
513
+ if node.role == "AXScrollArea" || node.role == "AXScrollBar" { node.actions.append("scroll") }
514
+ }
515
+
516
+ var kids: [AXUIElement] = []
517
+ if let arr = values[11], CFGetTypeID(arr) == CFArrayGetTypeID() {
518
+ kids = (arr as! [AnyObject]).map { $0 as! AXUIElement }
519
+ }
520
+ node.childCount = kids.count
521
+ if node.role == "AXMenuBar" || node.role == "AXMenu" || node.role == "AXMenuBarItem" || node.role == "AXMenuItem" {
522
+ // Menus have their children listed when asked for, as a window's do.
523
+ }
524
+ if lazyRoles.contains(node.role) && !expandChildren { return [] }
525
+ return kids
526
+ }
527
+
528
+ func fingerprintFor(_ nodes: [ReadNode], at i: Int, pid: pid_t) -> Fingerprint {
529
+ let n = nodes[i]
530
+ let label = n.name.isEmpty ? (n.value ?? "") : n.name
531
+ var chain: [String] = []
532
+ var p = n.parent
533
+ while p >= 0 && chain.count < 8 {
534
+ let a = nodes[p]
535
+ chain.append("\(a.role)|\(fnv(a.name))")
536
+ p = a.parent
537
+ }
538
+ var ordinal = 0
539
+ if n.parent >= 0 {
540
+ for sib in nodes[n.parent].children {
541
+ if sib == i { break }
542
+ let s = nodes[sib]
543
+ if s.role == n.role && fnv(s.name) == fnv(n.name) { ordinal += 1 }
544
+ }
545
+ }
546
+ return Fingerprint(
547
+ runtimeId: runtimeId(n.element, pid: pid), automationId: n.identifier, role: n.role,
548
+ nameHash: fnv(label.isEmpty ? "" : (n.name.isEmpty ? "" : n.name)), parentPath: chain.reversed().joined(separator: "/"),
549
+ ordinal: ordinal, processStart: procInfo.start(pid))
550
+ }
551
+
552
+ final class SnapshotCache {
553
+ private let lock = NSLock()
554
+ private var byWindow: [Int: Snapshot] = [:]
555
+ private var revision = 0
556
+
557
+ func nextRevision() -> Int {
558
+ lock.lock(); defer { lock.unlock() }
559
+ revision += 1
560
+ return revision
561
+ }
562
+
563
+ func put(_ s: Snapshot) {
564
+ lock.lock(); defer { lock.unlock() }
565
+ byWindow[s.windowId] = s
566
+ }
567
+
568
+ func get(_ w: Int) -> Snapshot? {
569
+ lock.lock(); defer { lock.unlock() }
570
+ return byWindow[w]
571
+ }
572
+ }
573
+
574
+ let snapshots = SnapshotCache()
575
+
576
+ func axWindowElement(windowId: Int, pid: pid_t) -> AXUIElement? {
577
+ let app = appElement(pid)
578
+ guard let list = attr(app, kAXWindowsAttribute as String), CFGetTypeID(list) == CFArrayGetTypeID() else { return nil }
579
+ let all = (list as! [AnyObject]).map { $0 as! AXUIElement }
580
+ for el in all {
581
+ var id: CGWindowID = 0
582
+ if _AXUIElementGetWindow(el, &id) == .success, Int(id) == windowId { return el }
583
+ }
584
+ // The private call is not answered for every window; the window's own place and size name it as well.
585
+ guard let entry = listWindowEntries().first(where: { $0.id == windowId }) else { return nil }
586
+ let sameFrame = all.filter { el in
587
+ guard let p = axPoint(attr(el, kAXPositionAttribute as String)), let s = axSize(attr(el, kAXSizeAttribute as String)) else { return false }
588
+ return abs(p.x - entry.bounds.origin.x) < 2 && abs(p.y - entry.bounds.origin.y) < 2
589
+ && abs(s.width - entry.bounds.width) < 2 && abs(s.height - entry.bounds.height) < 2
590
+ }
591
+ if sameFrame.count == 1 { return sameFrame[0] }
592
+ if sameFrame.count > 1, !entry.title.isEmpty,
593
+ let titled = sameFrame.first(where: { cfString(attr($0, kAXTitleAttribute as String)) == entry.title }) {
594
+ return titled
595
+ }
596
+ return nil
597
+ }
598
+
599
+ func entryFor(windowId: Int) throws -> WindowEntry {
600
+ if let e = listWindowEntries().first(where: { $0.id == windowId }) { return e }
601
+ throw HelperError(code: "window_gone", message: "that window is not on screen any more; list the windows again")
602
+ }
603
+
604
+ /// Accessibility is needed for any other app's windows; reading this helper's own windows needs none,
605
+ /// which is what lets the helper test itself before the person has granted anything.
606
+ func requireAccessibility(pid: pid_t? = nil) throws {
607
+ if let p = pid, p == ProcessInfo.processInfo.processIdentifier { return }
608
+ if !AXIsProcessTrusted() {
609
+ let name = (Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String) ?? "Namzu Helper"
610
+ throw HelperError(
611
+ code: "accessibility_denied",
612
+ message: "Accessibility is off for \(name). Open System Settings > Privacy & Security > \(accessibilityPaneName()) and turn on \"\(name)\", then try again.")
613
+ }
614
+ }
615
+
616
+ func readTree(
617
+ rootElement: AXUIElement, rootParent: Int = -1, windowId: Int, pid: pid_t, windowTitle: String,
618
+ appName: String, maxNodes: Int, maxDepth: Int, deadline: Date, includeMenuBar: Bool, drillRoot: Bool
619
+ ) -> Snapshot {
620
+ let started = Date()
621
+ var nodes: [ReadNode] = []
622
+ let root = ReadNode(rootElement, parent: -1, depth: 0)
623
+ nodes.append(root)
624
+ var queue: [Int] = [0]
625
+ var head = 0
626
+ var truncated = false
627
+ var expandedRoot = false
628
+ while head < queue.count {
629
+ let i = queue[head]; head += 1
630
+ if Date() > deadline { truncated = true; break }
631
+ let node = nodes[i]
632
+ let kids = readNode(node, expandChildren: drillRoot && !expandedRoot)
633
+ if i == 0 { expandedRoot = true }
634
+ if node.depth >= maxDepth { if !kids.isEmpty { truncated = true }; continue }
635
+ for k in kids {
636
+ if nodes.count >= maxNodes { truncated = true; break }
637
+ let child = ReadNode(k, parent: i, depth: node.depth + 1)
638
+ nodes.append(child)
639
+ node.children.append(nodes.count - 1)
640
+ queue.append(nodes.count - 1)
641
+ }
642
+ }
643
+ // The nodes that were queued but never read (a cut) still need their own facts.
644
+ if head < queue.count {
645
+ for j in head..<queue.count where nodes[j].role.isEmpty {
646
+ if Date() > deadline.addingTimeInterval(1.5) { break }
647
+ _ = readNode(nodes[j], expandChildren: false)
648
+ }
649
+ }
650
+ if includeMenuBar, !truncated || nodes.count < maxNodes {
651
+ let app = appElement(pid)
652
+ if let mb = attr(app, kAXMenuBarAttribute as String) {
653
+ let bar = ReadNode(mb as! AXUIElement, parent: 0, depth: 1)
654
+ let kids = readNode(bar, expandChildren: true)
655
+ nodes.append(bar)
656
+ nodes[0].children.append(nodes.count - 1)
657
+ let barIndex = nodes.count - 1
658
+ for k in kids {
659
+ if nodes.count >= maxNodes + 40 { break }
660
+ let item = ReadNode(k, parent: barIndex, depth: 2)
661
+ _ = readNode(item, expandChildren: false)
662
+ nodes.append(item)
663
+ nodes[barIndex].children.append(nodes.count - 1)
664
+ }
665
+ }
666
+ }
667
+ // Depth-first order, so a node's index is its place in reading order.
668
+ var order: [Int] = []
669
+ func walk(_ i: Int) {
670
+ order.append(i)
671
+ for c in nodes[i].children { walk(c) }
672
+ }
673
+ walk(0)
674
+ var remap = [Int: Int]()
675
+ for (n, old) in order.enumerated() { remap[old] = n }
676
+ var sorted: [ReadNode] = []
677
+ for old in order {
678
+ let n = nodes[old]
679
+ n.parent = n.parent < 0 ? -1 : (remap[n.parent] ?? -1)
680
+ n.children = n.children.compactMap { remap[$0] }
681
+ sorted.append(n)
682
+ }
683
+ for i in sorted.indices {
684
+ let fp = fingerprintFor(sorted, at: i, pid: pid)
685
+ sorted[i].fingerprint = fp
686
+ registry.put(fp.runtimeId, sorted[i].element)
687
+ }
688
+ var hidden = 0
689
+ for n in sorted where n.children.isEmpty { hidden += n.childCount ?? 0 }
690
+ var selectedText: String?
691
+ let app = appElement(pid)
692
+ if let focused = attr(app, kAXFocusedUIElementAttribute as String),
693
+ let t = cfString(attr(focused as! AXUIElement, kAXSelectedTextAttribute as String)), !t.isEmpty {
694
+ selectedText = String(t.prefix(2000))
695
+ }
696
+ return Snapshot(
697
+ revision: snapshots.nextRevision(), windowId: windowId, pid: pid, nodes: sorted,
698
+ total: sorted.count + hidden, truncated: truncated,
699
+ readMs: Int(Date().timeIntervalSince(started) * 1000), selectedText: selectedText, app: appName, title: windowTitle)
700
+ }
701
+
702
+ func nodeJson(_ n: ReadNode, index: Int, scale: Double, window: CGRect) -> Json {
703
+ var j: Json = [
704
+ "index": index, "parent": n.parent, "depth": n.depth, "role": n.role,
705
+ "rect": [
706
+ Int((n.rect.origin.x * scale).rounded()), Int((n.rect.origin.y * scale).rounded()),
707
+ Int((n.rect.width * scale).rounded()), Int((n.rect.height * scale).rounded()),
708
+ ],
709
+ "enabled": n.enabled,
710
+ "offscreen": n.rect.width <= 0 || n.rect.height <= 0 || !n.rect.intersects(window),
711
+ "focused": n.focused, "actions": n.actions,
712
+ ]
713
+ if !n.name.isEmpty { j["name"] = String(n.name.prefix(400)) }
714
+ if !n.identifier.isEmpty { j["automationId"] = n.identifier }
715
+ if !n.subrole.isEmpty { j["className"] = n.subrole }
716
+ if let v = n.value { j["value"] = v }
717
+ if let t = n.toggle { j["toggle"] = t }
718
+ if let e = n.expand { j["expand"] = e }
719
+ if let s = n.selected { j["selected"] = s }
720
+ if n.children.isEmpty, let c = n.childCount, c > 0 { j["childCount"] = c }
721
+ return j
722
+ }
723
+
724
+ func snapshotReply(_ req: Json) throws -> Json {
725
+ guard let windowId = intOf(req["hwnd"]) else { throw HelperError(code: "bad_request", message: "hwnd is required") }
726
+ let entry = try entryFor(windowId: windowId)
727
+ try requireAccessibility(pid: entry.pid)
728
+ let allowChromium = (req["allowChromium"] as? Bool) == true
729
+ let app = appElement(entry.pid)
730
+ if procInfo.isChromium(entry.pid) {
731
+ if !allowChromium {
732
+ throw HelperError(
733
+ code: "chromium_not_activated",
734
+ message: "\(entry.owner) is a Chromium or Electron app; reading it switches its accessibility on for the rest of the session. Ask again with allowChromium.")
735
+ }
736
+ procInfo.activateChromium(entry.pid, app: app)
737
+ }
738
+ guard let windowElement = axWindowElement(windowId: windowId, pid: entry.pid) else {
739
+ var probe: CFTypeRef?
740
+ let err = AXUIElementCopyAttributeValue(app, kAXWindowsAttribute as CFString, &probe)
741
+ throw HelperError(
742
+ code: "no_ax_window",
743
+ message: "\(entry.owner) did not expose that window to accessibility (\(axErrorText(err)), \((probe as? [AnyObject])?.count ?? -1) windows)")
744
+ }
745
+ let maxNodes = max(1, intOf(req["maxNodes"]) ?? 400)
746
+ let maxDepth = max(1, intOf(req["maxDepth"]) ?? 12)
747
+ let timeoutMs = max(200, intOf(req["timeoutMs"]) ?? 8000)
748
+ let deadline = Date().addingTimeInterval(Double(timeoutMs) / 1000.0 * 0.85)
749
+ let skeleton = (req["skeleton"] as? Bool) == true
750
+ var rootEl = windowElement
751
+ var drill = false
752
+ var includeMenu = !skeleton
753
+ if let rootFp = req["root"] as? Json {
754
+ let fp = Fingerprint.from(rootFp)
755
+ guard let el = try locate(fp, windowId: windowId, pid: entry.pid, allowFresh: false).element else {
756
+ throw HelperError(code: "not_found", message: "the region is no longer in the window")
757
+ }
758
+ rootEl = el
759
+ drill = true
760
+ includeMenu = false
761
+ }
762
+ let snap = readTree(
763
+ rootElement: rootEl, windowId: windowId, pid: entry.pid, windowTitle: entry.title, appName: entry.owner,
764
+ maxNodes: skeleton ? min(maxNodes, 60) : maxNodes, maxDepth: skeleton ? 2 : maxDepth, deadline: deadline,
765
+ includeMenuBar: includeMenu, drillRoot: drill)
766
+ if !drill { snapshots.put(snap) }
767
+ let scale = mainScale()
768
+ var nodes: [Json] = []
769
+ for (i, n) in snap.nodes.enumerated() {
770
+ var j = nodeJson(n, index: i, scale: scale, window: entry.bounds)
771
+ if let fp = n.fingerprint { j["fp"] = fp.json }
772
+ nodes.append(j)
773
+ }
774
+ var reply: Json = [
775
+ "rev": snap.revision, "nodes": nodes, "total": snap.total, "truncated": snap.truncated,
776
+ "skeleton": skeleton, "readMs": snap.readMs, "app": snap.app, "title": snap.title, "pid": Int(snap.pid),
777
+ ]
778
+ if let t = snap.selectedText { reply["selectedText"] = t }
779
+ return reply
780
+ }
781
+
782
+ // MARK: - Finding a control again
783
+
784
+ struct Located {
785
+ var element: AXUIElement?
786
+ var via: String
787
+ var code: String?
788
+ var candidates: Int?
789
+ var index: Int?
790
+ var revision: Int?
791
+ }
792
+
793
+ func elementIsLive(_ el: AXUIElement) -> Bool {
794
+ var v: CFTypeRef?
795
+ let err = AXUIElementCopyAttributeValue(el, kAXRoleAttribute as CFString, &v)
796
+ return err == .success
797
+ }
798
+
799
+ func locate(_ fp: Fingerprint, windowId: Int, pid: pid_t, allowFresh: Bool) throws -> Located {
800
+ if fp.processStart != 0, procInfo.start(pid) != fp.processStart {
801
+ return Located(element: nil, via: "", code: "not_found", candidates: nil, index: nil, revision: nil)
802
+ }
803
+ if let el = registry.get(fp.runtimeId), elementIsLive(el) {
804
+ let role = cfString(attr(el, kAXRoleAttribute as String)) ?? ""
805
+ if fp.role.isEmpty || role == fp.role {
806
+ return Located(element: el, via: "runtimeId", code: nil, candidates: nil, index: nil, revision: nil)
807
+ }
808
+ }
809
+ guard allowFresh else {
810
+ return Located(element: nil, via: "", code: "not_found", candidates: nil, index: nil, revision: nil)
811
+ }
812
+ let entry = try entryFor(windowId: windowId)
813
+ guard let win = axWindowElement(windowId: windowId, pid: pid) else {
814
+ return Located(element: nil, via: "", code: "not_found", candidates: nil, index: nil, revision: nil)
815
+ }
816
+ let snap = readTree(
817
+ rootElement: win, windowId: windowId, pid: pid, windowTitle: entry.title, appName: entry.owner,
818
+ maxNodes: 3000, maxDepth: 16, deadline: Date().addingTimeInterval(6), includeMenuBar: true, drillRoot: false)
819
+ snapshots.put(snap)
820
+ func result(_ idx: [Int], _ via: String) -> Located? {
821
+ if idx.count == 1 {
822
+ return Located(
823
+ element: snap.nodes[idx[0]].element, via: via, code: nil, candidates: nil, index: idx[0], revision: snap.revision)
824
+ }
825
+ return nil
826
+ }
827
+ if !fp.automationId.isEmpty {
828
+ let c = snap.nodes.indices.filter { snap.nodes[$0].fingerprint?.automationId == fp.automationId && snap.nodes[$0].role == fp.role }
829
+ if let r = result(c, "automationId") { return r }
830
+ if c.count > 1 {
831
+ let byName = c.filter { snap.nodes[$0].fingerprint?.nameHash == fp.nameHash }
832
+ if let r = result(byName, "automationId") { return r }
833
+ return Located(element: nil, via: "", code: "ambiguous", candidates: c.count, index: nil, revision: snap.revision)
834
+ }
835
+ }
836
+ var c = snap.nodes.indices.filter { snap.nodes[$0].role == fp.role && snap.nodes[$0].fingerprint?.nameHash == fp.nameHash }
837
+ if let r = result(c, "name") { return r }
838
+ if c.count > 1 {
839
+ let byPath = c.filter { snap.nodes[$0].fingerprint?.parentPath == fp.parentPath }
840
+ if let r = result(byPath, "name") { return r }
841
+ if !byPath.isEmpty { c = byPath }
842
+ let byOrd = c.filter { snap.nodes[$0].fingerprint?.ordinal == fp.ordinal && snap.nodes[$0].fingerprint?.parentPath == fp.parentPath }
843
+ if let r = result(byOrd, "name") { return r }
844
+ return Located(element: nil, via: "", code: "ambiguous", candidates: c.count, index: nil, revision: snap.revision)
845
+ }
846
+ return Located(element: nil, via: "", code: "not_found", candidates: nil, index: nil, revision: snap.revision)
847
+ }
848
+
849
+ func fingerprintFromRequest(_ req: Json) throws -> (Fingerprint, Int, pid_t) {
850
+ guard let windowId = intOf(req["hwnd"]) else { throw HelperError(code: "bad_request", message: "hwnd is required") }
851
+ let entry = try entryFor(windowId: windowId)
852
+ if let f = req["fingerprint"] as? Json { return (Fingerprint.from(f), windowId, entry.pid) }
853
+ if let index = intOf(req["index"]) {
854
+ guard let snap = snapshots.get(windowId), index >= 0, index < snap.nodes.count, let fp = snap.nodes[index].fingerprint else {
855
+ throw HelperError(code: "stale_snapshot", message: "that read of the window is gone; take a new snapshot")
856
+ }
857
+ if let rev = intOf(req["rev"]), rev != snap.revision {
858
+ throw HelperError(code: "stale_snapshot", message: "the window was read again since that snapshot")
859
+ }
860
+ return (fp, windowId, entry.pid)
861
+ }
862
+ throw HelperError(code: "bad_request", message: "index or fingerprint is required")
863
+ }
864
+
865
+ func identityReply(_ req: Json) throws -> Json {
866
+ let (fp, _, _) = try fingerprintFromRequest(req)
867
+ return ["fingerprint": fp.json]
868
+ }
869
+
870
+ func resolveReply(_ req: Json) throws -> Json {
871
+ guard let windowId = intOf(req["hwnd"]), let fpj = req["fingerprint"] as? Json else {
872
+ throw HelperError(code: "bad_request", message: "hwnd and fingerprint are required")
873
+ }
874
+ let entry = try entryFor(windowId: windowId)
875
+ try requireAccessibility(pid: entry.pid)
876
+ let loc = try locate(Fingerprint.from(fpj), windowId: windowId, pid: entry.pid, allowFresh: true)
877
+ if loc.element != nil {
878
+ // A runtime-id hit did not read the window; the index is in the latest read when there is one.
879
+ var idx = loc.index
880
+ var rev = loc.revision
881
+ if idx == nil, let snap = snapshots.get(windowId) {
882
+ let rid = Fingerprint.from(fpj).runtimeId
883
+ idx = snap.nodes.firstIndex { $0.fingerprint?.runtimeId == rid }
884
+ rev = snap.revision
885
+ }
886
+ return ["found": true, "index": idx ?? -1, "via": loc.via, "rev": rev ?? 0]
887
+ }
888
+ var r: Json = ["found": false, "code": loc.code ?? "not_found"]
889
+ if let c = loc.candidates { r["candidates"] = c }
890
+ return r
891
+ }
892
+
893
+ // MARK: - Acting
894
+
895
+ func perform(_ el: AXUIElement, _ action: String) -> AXError {
896
+ AXUIElementPerformAction(el, action as CFString)
897
+ }
898
+
899
+ func readState(_ el: AXUIElement) -> String {
900
+ if let v = attr(el, kAXValueAttribute as String) {
901
+ if let s = cfString(v) { return s }
902
+ if let n = v as? NSNumber { return n.stringValue }
903
+ }
904
+ if let e = cfBool(attr(el, kAXExpandedAttribute as String)) { return e ? "expanded" : "collapsed" }
905
+ if let s = cfBool(attr(el, kAXSelectedAttribute as String)) { return s ? "selected" : "not selected" }
906
+ return ""
907
+ }
908
+
909
+ func axErrorText(_ e: AXError) -> String {
910
+ switch e {
911
+ case .success: return "ok"
912
+ case .apiDisabled: return "accessibility is off for this helper"
913
+ case .actionUnsupported: return "the control does not offer that action"
914
+ case .attributeUnsupported: return "the control does not have that property"
915
+ case .cannotComplete: return "the app did not answer in time"
916
+ case .invalidUIElement: return "the control is gone"
917
+ case .notImplemented: return "the app does not implement accessibility for this control"
918
+ case .noValue: return "the control has no value"
919
+ default: return "accessibility error \(e.rawValue)"
920
+ }
921
+ }
922
+
923
+ /// "Press" a control that is not a button: AXPress, else the action it offers instead (AXOpen, AXConfirm, AXPick),
924
+ /// else select it (the items of a file panel's columns take only that).
925
+ func pressLike(_ el: AXUIElement) -> AXError {
926
+ var err = perform(el, "AXPress")
927
+ if err == .success { return err }
928
+ var names: CFArray?
929
+ let offered = (AXUIElementCopyActionNames(el, &names) == .success ? (names as? [String]) : nil) ?? []
930
+ for alt in ["AXOpen", "AXConfirm", "AXPick"] where offered.contains(alt) {
931
+ err = perform(el, alt)
932
+ if err == .success { return err }
933
+ }
934
+ if isSettable(el, kAXSelectedAttribute as String) {
935
+ return AXUIElementSetAttributeValue(el, kAXSelectedAttribute as CFString, kCFBooleanTrue)
936
+ }
937
+ // A list or column takes its selection as a whole: the items it lists are the "selected children".
938
+ if let parentRef = attr(el, kAXParentAttribute as String), CFGetTypeID(parentRef) == AXUIElementGetTypeID() {
939
+ let parent = parentRef as! AXUIElement
940
+ if isSettable(parent, "AXSelectedChildren") {
941
+ return AXUIElementSetAttributeValue(parent, "AXSelectedChildren" as CFString, [el] as CFArray)
942
+ }
943
+ }
944
+ return err
945
+ }
946
+
947
+ func actReply(_ req: Json) throws -> Json {
948
+ let (fp, windowId, pid) = try fingerprintFromRequest(req)
949
+ try requireAccessibility(pid: pid)
950
+ let loc = try locate(fp, windowId: windowId, pid: pid, allowFresh: true)
951
+ guard let el = loc.element else {
952
+ let code = loc.code == "ambiguous" ? "AMBIGUOUS_TARGET" : "STALE_REF"
953
+ throw HelperError(code: code, message: loc.code == "ambiguous"
954
+ ? "\(loc.candidates ?? 2) controls fit that reference; take a new snapshot"
955
+ : "the control is no longer in the window; take a new snapshot")
956
+ }
957
+ let action = (req["action"] as? String) ?? "invoke"
958
+ let value = req["value"] as? String
959
+ let before = readState(el)
960
+ var expected: String?
961
+ var err: AXError = .success
962
+ switch action {
963
+ case "invoke", "press":
964
+ err = pressLike(el)
965
+ case "show_menu": err = perform(el, "AXShowMenu")
966
+ case "raise": err = perform(el, "AXRaise")
967
+ case "increment": err = perform(el, "AXIncrement")
968
+ case "decrement": err = perform(el, "AXDecrement")
969
+ case "scroll_into_view": err = perform(el, "AXScrollToVisible")
970
+ case "focus":
971
+ err = AXUIElementSetAttributeValue(el, kAXFocusedAttribute as CFString, kCFBooleanTrue)
972
+ case "set_value":
973
+ guard let v = value else { throw HelperError(code: "bad_request", message: "set_value needs a value") }
974
+ expected = v
975
+ let role = cfString(attr(el, kAXRoleAttribute as String)) ?? ""
976
+ if role == "AXSlider" || role == "AXStepper" || role == "AXIncrementor", let d = Double(v) {
977
+ err = AXUIElementSetAttributeValue(el, kAXValueAttribute as CFString, NSNumber(value: d))
978
+ } else {
979
+ _ = AXUIElementSetAttributeValue(el, kAXFocusedAttribute as CFString, kCFBooleanTrue)
980
+ err = AXUIElementSetAttributeValue(el, kAXValueAttribute as CFString, v as CFString)
981
+ }
982
+ case "toggle":
983
+ err = perform(el, "AXPress")
984
+ case "select":
985
+ if isSettable(el, kAXSelectedAttribute as String) {
986
+ err = AXUIElementSetAttributeValue(el, kAXSelectedAttribute as CFString, kCFBooleanTrue)
987
+ expected = "selected"
988
+ } else {
989
+ err = pressLike(el)
990
+ }
991
+ case "expand", "collapse":
992
+ let want = action == "expand"
993
+ expected = want ? "expanded" : "collapsed"
994
+ let name = attr(el, "AXDisclosing" as String) != nil ? "AXDisclosing" : (kAXExpandedAttribute as String)
995
+ if isSettable(el, name) {
996
+ err = AXUIElementSetAttributeValue(el, name as CFString, want ? kCFBooleanTrue : kCFBooleanFalse)
997
+ } else {
998
+ let state = cfBool(attr(el, name))
999
+ if state == want { err = .success } else { err = perform(el, "AXPress") }
1000
+ }
1001
+ default:
1002
+ throw HelperError(code: "bad_request", message: "unknown action \(action)")
1003
+ }
1004
+ if err != .success {
1005
+ return [
1006
+ "done": false, "delivery": "not_delivered", "detail": axErrorText(err), "axError": Int(err.rawValue),
1007
+ ]
1008
+ }
1009
+ // Let the app apply it, then read it back.
1010
+ Thread.sleep(forTimeInterval: 0.12)
1011
+ var after = readState(el)
1012
+ if action == "toggle" || action == "invoke" || action == "press" || action == "select" {
1013
+ if after == before && (action == "toggle" || action == "select") {
1014
+ Thread.sleep(forTimeInterval: 0.25)
1015
+ after = readState(el)
1016
+ }
1017
+ }
1018
+ var reply: Json = ["done": true, "via": loc.via, "before": before, "after": after]
1019
+ if let e = expected {
1020
+ reply["expected"] = e
1021
+ reply["verified"] = (after == e)
1022
+ } else if action == "toggle" {
1023
+ reply["verified"] = (after != before)
1024
+ reply["expected"] = "not \(before)"
1025
+ }
1026
+ return reply
1027
+ }
1028
+
1029
+ // MARK: - Focus, scroll, capture
1030
+
1031
+ func focusReply(_ req: Json) throws -> Json {
1032
+ guard let windowId = intOf(req["hwnd"]) else { throw HelperError(code: "bad_request", message: "hwnd is required") }
1033
+ let entry = try entryFor(windowId: windowId)
1034
+ onMain {
1035
+ if let app = NSRunningApplication(processIdentifier: entry.pid) {
1036
+ app.activate(options: [.activateAllWindows])
1037
+ }
1038
+ }
1039
+ if AXIsProcessTrusted(), let win = axWindowElement(windowId: windowId, pid: entry.pid) {
1040
+ _ = perform(win, "AXRaise")
1041
+ _ = AXUIElementSetAttributeValue(win, kAXMainAttribute as CFString, kCFBooleanTrue)
1042
+ }
1043
+ Thread.sleep(forTimeInterval: 0.2)
1044
+ let front = frontmostPid()
1045
+ var focused: Int?
1046
+ if let f = front { focused = focusedWindowId(pid: f) ?? listWindowEntries().first(where: { $0.pid == f })?.id }
1047
+ return ["focusedId": focused as Any? ?? NSNull(), "ok": focused == windowId]
1048
+ }
1049
+
1050
+ func scrollReply(_ req: Json) throws -> Json {
1051
+ try requireAccessibility()
1052
+ let entry: WindowEntry? = try intOf(req["hwnd"]).map { try entryFor(windowId: $0) }
1053
+ guard entry != nil || (req["x"] != nil && req["y"] != nil) else {
1054
+ throw HelperError(code: "bad_request", message: "hwnd or x and y are required")
1055
+ }
1056
+ let direction = (req["direction"] as? String) ?? "down"
1057
+ let amount = max(1, intOf(req["amount"]) ?? 3)
1058
+ var at = CGPoint(x: entry?.bounds.midX ?? 0, y: entry?.bounds.midY ?? 0)
1059
+ if let x = req["x"] as? NSNumber, let y = req["y"] as? NSNumber {
1060
+ // Points of the global screen space.
1061
+ at = CGPoint(x: x.doubleValue, y: y.doubleValue)
1062
+ }
1063
+ var dy: Int32 = 0
1064
+ var dx: Int32 = 0
1065
+ switch direction {
1066
+ case "up": dy = Int32(amount)
1067
+ case "down": dy = -Int32(amount)
1068
+ case "left": dx = Int32(amount)
1069
+ case "right": dx = -Int32(amount)
1070
+ default: throw HelperError(code: "bad_request", message: "unknown direction \(direction)")
1071
+ }
1072
+ guard let ev = CGEvent(scrollWheelEvent2Source: nil, units: .line, wheelCount: 2, wheel1: dy, wheel2: dx, wheel3: 0) else {
1073
+ throw HelperError(code: "event_failed", message: "could not create a scroll event")
1074
+ }
1075
+ ev.location = at
1076
+ if let e = entry { ev.postToPid(e.pid) } else { ev.post(tap: .cghidEventTap) }
1077
+ Thread.sleep(forTimeInterval: 0.1)
1078
+ return ["done": true]
1079
+ }
1080
+
1081
+ // MARK: - Input to a window (posted to its process, not to the screen's front)
1082
+
1083
+ func post(_ ev: CGEvent?, pid: pid_t?) {
1084
+ guard let ev = ev else { return }
1085
+ if let p = pid { ev.postToPid(p) } else { ev.post(tap: .cghidEventTap) }
1086
+ }
1087
+
1088
+ func flagsOf(_ names: [String]) -> CGEventFlags {
1089
+ var f: CGEventFlags = []
1090
+ for n in names {
1091
+ switch n {
1092
+ case "command": f.insert(.maskCommand)
1093
+ case "control": f.insert(.maskControl)
1094
+ case "option": f.insert(.maskAlternate)
1095
+ case "shift": f.insert(.maskShift)
1096
+ default: break
1097
+ }
1098
+ }
1099
+ return f
1100
+ }
1101
+
1102
+ func clickReply(_ req: Json) throws -> Json {
1103
+ try requireAccessibility()
1104
+ guard let x = req["x"] as? NSNumber, let y = req["y"] as? NSNumber else {
1105
+ throw HelperError(code: "bad_request", message: "x and y are required")
1106
+ }
1107
+ let pid: pid_t? = try intOf(req["hwnd"]).map { try entryFor(windowId: $0).pid }
1108
+ let at = CGPoint(x: x.doubleValue, y: y.doubleValue)
1109
+ let button = (req["button"] as? String) ?? "left"
1110
+ let count = max(1, min(3, intOf(req["count"]) ?? 1))
1111
+ let (downType, upType, cgButton): (CGEventType, CGEventType, CGMouseButton) =
1112
+ button == "right" ? (.rightMouseDown, .rightMouseUp, .right) : (.leftMouseDown, .leftMouseUp, .left)
1113
+ if let to = req["to"] as? Json, let tx = to["x"] as? NSNumber, let ty = to["y"] as? NSNumber {
1114
+ let dragType: CGEventType = button == "right" ? .rightMouseDragged : .leftMouseDragged
1115
+ post(CGEvent(mouseEventSource: nil, mouseType: downType, mouseCursorPosition: at, mouseButton: cgButton), pid: pid)
1116
+ let steps = 12
1117
+ for i in 1...steps {
1118
+ let t = Double(i) / Double(steps)
1119
+ let p = CGPoint(x: at.x + (tx.doubleValue - at.x) * t, y: at.y + (ty.doubleValue - at.y) * t)
1120
+ post(CGEvent(mouseEventSource: nil, mouseType: dragType, mouseCursorPosition: p, mouseButton: cgButton), pid: pid)
1121
+ Thread.sleep(forTimeInterval: 0.012)
1122
+ }
1123
+ post(CGEvent(mouseEventSource: nil, mouseType: upType, mouseCursorPosition: CGPoint(x: tx.doubleValue, y: ty.doubleValue), mouseButton: cgButton), pid: pid)
1124
+ return ["done": true]
1125
+ }
1126
+ for n in 1...count {
1127
+ let down = CGEvent(mouseEventSource: nil, mouseType: downType, mouseCursorPosition: at, mouseButton: cgButton)
1128
+ down?.setIntegerValueField(.mouseEventClickState, value: Int64(n))
1129
+ post(down, pid: pid)
1130
+ let up = CGEvent(mouseEventSource: nil, mouseType: upType, mouseCursorPosition: at, mouseButton: cgButton)
1131
+ up?.setIntegerValueField(.mouseEventClickState, value: Int64(n))
1132
+ post(up, pid: pid)
1133
+ Thread.sleep(forTimeInterval: 0.03)
1134
+ }
1135
+ return ["done": true]
1136
+ }
1137
+
1138
+ func typeReply(_ req: Json) throws -> Json {
1139
+ try requireAccessibility()
1140
+ guard let text = req["text"] as? String else { throw HelperError(code: "bad_request", message: "text is required") }
1141
+ let pid: pid_t? = try intOf(req["hwnd"]).map { try entryFor(windowId: $0).pid }
1142
+ let units = Array(text.utf16)
1143
+ var i = 0
1144
+ while i < units.count {
1145
+ let chunk = Array(units[i..<min(i + 16, units.count)])
1146
+ i += chunk.count
1147
+ for down in [true, false] {
1148
+ let ev = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: down)
1149
+ ev?.keyboardSetUnicodeString(stringLength: chunk.count, unicodeString: chunk)
1150
+ post(ev, pid: pid)
1151
+ }
1152
+ Thread.sleep(forTimeInterval: 0.008)
1153
+ }
1154
+ return ["done": true]
1155
+ }
1156
+
1157
+ func keyReply(_ req: Json) throws -> Json {
1158
+ try requireAccessibility()
1159
+ guard let code = intOf(req["code"]) else { throw HelperError(code: "bad_request", message: "code is required") }
1160
+ let pid: pid_t? = try intOf(req["hwnd"]).map { try entryFor(windowId: $0).pid }
1161
+ let flags = flagsOf((req["flags"] as? [String]) ?? [])
1162
+ for down in [true, false] {
1163
+ let ev = CGEvent(keyboardEventSource: nil, virtualKey: CGKeyCode(code), keyDown: down)
1164
+ ev?.flags = flags
1165
+ post(ev, pid: pid)
1166
+ Thread.sleep(forTimeInterval: 0.01)
1167
+ }
1168
+ return ["done": true]
1169
+ }
1170
+
1171
+ func pngData(_ image: CGImage) -> Data? {
1172
+ let rep = NSBitmapImageRep(cgImage: image)
1173
+ return rep.representation(using: .png, properties: [:])
1174
+ }
1175
+
1176
+ func captureWithScreenCaptureKit(windowId: Int, scale: Double, rect: CGRect) -> (CGImage?, String?) {
1177
+ var result: CGImage?
1178
+ var failure: String?
1179
+ let sem = DispatchSemaphore(value: 0)
1180
+ Task {
1181
+ do {
1182
+ let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
1183
+ guard let w = content.windows.first(where: { Int($0.windowID) == windowId }) else {
1184
+ failure = "the window is not in the shareable window list"
1185
+ sem.signal(); return
1186
+ }
1187
+ let filter = SCContentFilter(desktopIndependentWindow: w)
1188
+ let cfg = SCStreamConfiguration()
1189
+ cfg.width = max(1, Int((rect.width * scale).rounded()))
1190
+ cfg.height = max(1, Int((rect.height * scale).rounded()))
1191
+ cfg.showsCursor = false
1192
+ cfg.capturesAudio = false
1193
+ result = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: cfg)
1194
+ } catch {
1195
+ failure = "\(error)"
1196
+ }
1197
+ sem.signal()
1198
+ }
1199
+ if sem.wait(timeout: .now() + 12) == .timedOut { return (nil, "screen capture timed out") }
1200
+ return (result, failure)
1201
+ }
1202
+
1203
+ func captureReply(_ req: Json) throws -> Json {
1204
+ guard let windowId = intOf(req["hwnd"]), let dir = req["dir"] as? String else {
1205
+ throw HelperError(code: "bad_request", message: "hwnd and dir are required")
1206
+ }
1207
+ let entry = try entryFor(windowId: windowId)
1208
+ if !CGPreflightScreenCaptureAccess() {
1209
+ let name = (Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String) ?? "Namzu Helper"
1210
+ throw HelperError(
1211
+ code: "screen_capture_denied",
1212
+ message: "Screen Recording is off for \(name). Open System Settings > Privacy & Security > Screen & System Audio Recording and turn on \"\(name)\", then try again.")
1213
+ }
1214
+ let scale = mainScale()
1215
+ let path = (dir as NSString).appendingPathComponent("w\(windowId)-\(UUID().uuidString.prefix(8)).png")
1216
+ let (image, why) = captureWithScreenCaptureKit(windowId: windowId, scale: scale, rect: entry.bounds)
1217
+ if let image = image, let data = pngData(image) {
1218
+ try data.write(to: URL(fileURLWithPath: path), options: [.atomic])
1219
+ return ["path": path, "width": image.width, "height": image.height, "via": "screencapturekit"]
1220
+ }
1221
+ // The built-in tool, started from this app, is covered by this app's permission too.
1222
+ let p = Process()
1223
+ p.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
1224
+ p.arguments = ["-x", "-o", "-l", String(windowId), path]
1225
+ try p.run()
1226
+ p.waitUntilExit()
1227
+ if p.terminationStatus == 0, let data = FileManager.default.contents(atPath: path), data.count > 24 {
1228
+ let w = Int(UInt32(bigEndian: data.subdata(in: 16..<20).withUnsafeBytes { $0.loadUnaligned(as: UInt32.self) }))
1229
+ let h = Int(UInt32(bigEndian: data.subdata(in: 20..<24).withUnsafeBytes { $0.loadUnaligned(as: UInt32.self) }))
1230
+ return ["path": path, "width": w, "height": h, "via": "screencapture"]
1231
+ }
1232
+ throw HelperError(code: "capture_failed", message: "could not capture the window: \(why ?? "unknown")")
1233
+ }
1234
+
1235
+ // MARK: - Change events
1236
+
1237
+ struct ChangeEvent {
1238
+ let seq: Int
1239
+ let kind: String
1240
+ let pid: pid_t
1241
+ let at: Double
1242
+ }
1243
+
1244
+ final class EventLog {
1245
+ let cond = NSCondition()
1246
+ private(set) var counter = 0
1247
+ private var events: [ChangeEvent] = []
1248
+ var observers: [pid_t: AXObserver] = [:]
1249
+ var known: [Int: Set<Int>] = [:] // window id -> window ids of the app when armed
1250
+
1251
+ func record(kind: String, pid: pid_t) {
1252
+ cond.lock()
1253
+ counter += 1
1254
+ events.append(ChangeEvent(seq: counter, kind: kind, pid: pid, at: nowMs()))
1255
+ if events.count > 5000 { events.removeFirst(2000) }
1256
+ cond.broadcast()
1257
+ cond.unlock()
1258
+ }
1259
+
1260
+ func current() -> Int {
1261
+ cond.lock(); defer { cond.unlock() }
1262
+ return counter
1263
+ }
1264
+
1265
+ /// Events of one process after `since`, of the wanted kinds; the lock must be held.
1266
+ func matching(pid: pid_t, since: Int, kinds: Set<String>) -> [ChangeEvent] {
1267
+ events.filter { $0.seq > since && $0.pid == pid && kinds.contains($0.kind) }
1268
+ }
1269
+ }
1270
+
1271
+ let eventLog = EventLog()
1272
+
1273
+ let structureNotes = [
1274
+ "AXCreated", "AXUIElementDestroyed", "AXWindowCreated", "AXMenuOpened", "AXMenuClosed",
1275
+ "AXRowCountChanged", "AXLayoutChanged", "AXSelectedChildrenChanged", "AXSelectedRowsChanged",
1276
+ "AXRowExpanded", "AXRowCollapsed", "AXSheetCreated", "AXDrawerCreated",
1277
+ ]
1278
+ let propertyNotes = [
1279
+ "AXValueChanged", "AXTitleChanged", "AXFocusedUIElementChanged", "AXSelectedTextChanged",
1280
+ "AXFocusedWindowChanged", "AXMainWindowChanged", "AXApplicationActivated", "AXApplicationDeactivated",
1281
+ ]
1282
+ let locationNotes = ["AXMoved", "AXResized"]
1283
+
1284
+ let observerCallback: AXObserverCallback = { _, _, notification, refcon in
1285
+ guard let refcon = refcon else { return }
1286
+ let pid = pid_t(Int(bitPattern: refcon))
1287
+ let name = notification as String
1288
+ let kind = structureNotes.contains(name) ? "structure" : (locationNotes.contains(name) ? "location" : "property")
1289
+ eventLog.record(kind: kind, pid: pid)
1290
+ }
1291
+
1292
+ func armObserver(pid: pid_t, windowElement: AXUIElement?) {
1293
+ eventLog.cond.lock()
1294
+ let existing = eventLog.observers[pid]
1295
+ eventLog.cond.unlock()
1296
+ if existing != nil { return }
1297
+ var obs: AXObserver?
1298
+ guard AXObserverCreate(pid, observerCallback, &obs) == .success, let observer = obs else { return }
1299
+ let refcon = UnsafeMutableRawPointer(bitPattern: Int(pid))
1300
+ let app = appElement(pid)
1301
+ for name in structureNotes + propertyNotes + locationNotes {
1302
+ AXObserverAddNotification(observer, app, name as CFString, refcon)
1303
+ if let w = windowElement { AXObserverAddNotification(observer, w, name as CFString, refcon) }
1304
+ }
1305
+ CFRunLoopAddSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(observer), .defaultMode)
1306
+ eventLog.cond.lock()
1307
+ eventLog.observers[pid] = observer
1308
+ eventLog.cond.unlock()
1309
+ }
1310
+
1311
+ func windowIdsOf(pid: pid_t) -> Set<Int> {
1312
+ Set(listWindowEntries().filter { $0.pid == pid }.map { $0.id })
1313
+ }
1314
+
1315
+ func seqReply(_ req: Json) throws -> Json {
1316
+ if let windowId = intOf(req["hwnd"]) {
1317
+ let entry = try entryFor(windowId: windowId)
1318
+ try requireAccessibility(pid: entry.pid)
1319
+ armObserver(pid: entry.pid, windowElement: axWindowElement(windowId: windowId, pid: entry.pid))
1320
+ eventLog.cond.lock()
1321
+ eventLog.known[windowId] = windowIdsOf(pid: entry.pid)
1322
+ eventLog.cond.unlock()
1323
+ }
1324
+ return ["seq": eventLog.current()]
1325
+ }
1326
+
1327
+ func waitReply(_ req: Json) throws -> Json {
1328
+ guard let windowId = intOf(req["hwnd"]) else { throw HelperError(code: "bad_request", message: "hwnd is required") }
1329
+ let entry = try entryFor(windowId: windowId)
1330
+ try requireAccessibility(pid: entry.pid)
1331
+ let pid = entry.pid
1332
+ armObserver(pid: pid, windowElement: axWindowElement(windowId: windowId, pid: pid))
1333
+ let timeoutMs = Double(min(intOf(req["timeoutMs"]) ?? 2000, 10_000))
1334
+ let quietMs = Double(intOf(req["quietMs"]) ?? 120)
1335
+ var kinds: Set<String> = ["structure", "property", "location"]
1336
+ if let k = req["kinds"] as? [String], !k.isEmpty { kinds = Set(k) }
1337
+ let started = nowMs()
1338
+ eventLog.cond.lock()
1339
+ let since = intOf(req["since"]) ?? eventLog.counter
1340
+ if eventLog.known[windowId] == nil { eventLog.known[windowId] = windowIdsOf(pid: pid) }
1341
+ let knownBefore = eventLog.known[windowId] ?? []
1342
+ var first: ChangeEvent?
1343
+ var last: ChangeEvent?
1344
+ var count = 0
1345
+ var settled = false
1346
+ let deadline = Date().addingTimeInterval(timeoutMs / 1000)
1347
+ while true {
1348
+ let found = eventLog.matching(pid: pid, since: since, kinds: kinds)
1349
+ if let f = found.first, let l = found.last {
1350
+ first = f; last = l; count = found.count
1351
+ let quietFor = nowMs() - l.at
1352
+ if quietFor >= quietMs { settled = true; break }
1353
+ let remaining = min(deadline.timeIntervalSinceNow, (quietMs - quietFor) / 1000)
1354
+ if remaining <= 0 { break }
1355
+ _ = eventLog.cond.wait(until: Date().addingTimeInterval(remaining))
1356
+ } else {
1357
+ let remaining = deadline.timeIntervalSinceNow
1358
+ if remaining <= 0 { break }
1359
+ _ = eventLog.cond.wait(until: Date().addingTimeInterval(remaining))
1360
+ }
1361
+ if deadline.timeIntervalSinceNow <= 0 {
1362
+ let found2 = eventLog.matching(pid: pid, since: since, kinds: kinds)
1363
+ if let f = found2.first, let l = found2.last { first = f; last = l; count = found2.count }
1364
+ break
1365
+ }
1366
+ }
1367
+ eventLog.cond.unlock()
1368
+ let elapsed = nowMs() - started
1369
+ if let f = first, let l = last {
1370
+ let now = windowIdsOf(pid: pid)
1371
+ let fresh = now.subtracting(knownBefore).sorted()
1372
+ return [
1373
+ "changed": true, "settled": settled, "firstEventMs": Int(f.at - started), "settledMs": Int(max(0, l.at - started)),
1374
+ "events": count, "newWindows": fresh,
1375
+ ]
1376
+ }
1377
+ return ["changed": false, "timedOut": true, "settledMs": Int(elapsed)]
1378
+ }
1379
+
1380
+ // MARK: - Self check
1381
+
1382
+ func selfcheckReply() -> Json {
1383
+ var checks: [Json] = []
1384
+ func add(_ name: String, _ ok: Bool, _ detail: String = "") {
1385
+ checks.append(["name": name, "ok": ok, "detail": detail])
1386
+ }
1387
+ add("accessibility_trusted", AXIsProcessTrusted(), AXIsProcessTrusted() ? "" : "turn on Namzu Helper in Privacy & Security > \(accessibilityPaneName())")
1388
+ add("screen_capture_allowed", CGPreflightScreenCaptureAccess(), "")
1389
+ let wins = listWindowEntries()
1390
+ add("cgwindowlist", !wins.isEmpty, "\(wins.count) windows")
1391
+ let titled = wins.filter { !$0.title.isEmpty }.count
1392
+ add("window_titles", titled > 0 || wins.isEmpty, "\(titled) of \(wins.count) windows have a title (titles of other apps need Screen Recording)")
1393
+ if let f = frontmostPid() {
1394
+ let app = appElement(f)
1395
+ var role: CFTypeRef?
1396
+ let err = AXUIElementCopyAttributeValue(app, kAXRoleAttribute as CFString, &role)
1397
+ add("ax_read_frontmost", err == .success, err == .success ? "" : axErrorText(err))
1398
+ }
1399
+ var obs: AXObserver?
1400
+ let oerr = AXObserverCreate(ProcessInfo.processInfo.processIdentifier, observerCallback, &obs)
1401
+ add("ax_observer", oerr == .success, "")
1402
+ add("main_display_scale", mainScale() >= 1, "\(mainScale())")
1403
+ return [
1404
+ "checks": checks, "pid": Int(ProcessInfo.processInfo.processIdentifier), "build": buildId,
1405
+ "path": Bundle.main.bundlePath, "os": ProcessInfo.processInfo.operatingSystemVersionString,
1406
+ ]
1407
+ }
1408
+
1409
+
1410
+ // MARK: - Self test on a window of the helper's own
1411
+
1412
+ final class DemoState: NSObject {
1413
+ var window: NSWindow?
1414
+ let status = NSTextField(labelWithString: "idle")
1415
+ let field = NSTextField(string: "")
1416
+ @objc func pressed(_ sender: Any?) { status.stringValue = "pressed" }
1417
+ }
1418
+
1419
+ let demo = DemoState()
1420
+
1421
+ func ensureDemoWindow() -> Int? {
1422
+ onMain {
1423
+ if demo.window == nil {
1424
+ let w = NSWindow(
1425
+ contentRect: NSRect(x: 220, y: 220, width: 420, height: 240),
1426
+ styleMask: [.titled, .closable], backing: .buffered, defer: false)
1427
+ w.title = "Namzu Helper Demo"
1428
+ demo.status.stringValue = "idle"
1429
+ demo.field.stringValue = ""
1430
+ w.isReleasedWhenClosed = false
1431
+ let content = NSView(frame: NSRect(x: 0, y: 0, width: 420, height: 240))
1432
+ let button = NSButton(title: "Press me", target: demo, action: #selector(DemoState.pressed(_:)))
1433
+ button.frame = NSRect(x: 20, y: 180, width: 120, height: 30)
1434
+ button.setAccessibilityIdentifier("demo.press")
1435
+ let check = NSButton(checkboxWithTitle: "Check me", target: nil, action: nil)
1436
+ check.frame = NSRect(x: 20, y: 140, width: 160, height: 24)
1437
+ check.setAccessibilityIdentifier("demo.check")
1438
+ demo.field.frame = NSRect(x: 20, y: 100, width: 300, height: 24)
1439
+ demo.field.isEditable = true
1440
+ demo.field.setAccessibilityIdentifier("demo.field")
1441
+ demo.status.frame = NSRect(x: 20, y: 60, width: 300, height: 24)
1442
+ for v in [button, check, demo.field, demo.status] as [NSView] { content.addSubview(v) }
1443
+ w.contentView = content
1444
+ let menu = NSMenu()
1445
+ let top = NSMenuItem(title: "Format", action: nil, keyEquivalent: "")
1446
+ let sub = NSMenu(title: "Format")
1447
+ sub.addItem(NSMenuItem(title: "Make Plain Text", action: nil, keyEquivalent: ""))
1448
+ top.submenu = sub
1449
+ menu.addItem(top)
1450
+ NSApp.mainMenu = menu
1451
+ demo.window = w
1452
+ }
1453
+ demo.window?.orderFrontRegardless()
1454
+ }
1455
+ for _ in 0..<60 {
1456
+ if let e = listWindowEntries().first(where: { $0.pid == ProcessInfo.processInfo.processIdentifier && $0.title == "Namzu Helper Demo" }) {
1457
+ ownWindows.add(e.id)
1458
+ return e.id
1459
+ }
1460
+ Thread.sleep(forTimeInterval: 0.05)
1461
+ }
1462
+ return nil
1463
+ }
1464
+
1465
+ func closeDemoWindow() {
1466
+ // Closed and dropped, so the next self-test starts from a window in its first state.
1467
+ onMain {
1468
+ demo.window?.close()
1469
+ demo.window = nil
1470
+ }
1471
+ }
1472
+
1473
+ func selftestReply() -> Json {
1474
+ var results: [Json] = []
1475
+ func check(_ name: String, _ ok: Bool, _ detail: String = "") {
1476
+ results.append(["name": name, "ok": ok, "detail": detail])
1477
+ }
1478
+ guard let wid = ensureDemoWindow() else {
1479
+ check("demo_window", false, "the demo window did not appear on screen (is there a desktop session?)")
1480
+ return ["checks": results]
1481
+ }
1482
+ check("demo_window", true, "window \(wid)")
1483
+ func read() throws -> [Json] {
1484
+ let r = try onMain { try snapshotReply(["hwnd": wid, "maxNodes": 300, "allowChromium": true]) }
1485
+ return (r["nodes"] as? [Json]) ?? []
1486
+ }
1487
+ func find(_ nodes: [Json], role: String, name: String? = nil, id: String? = nil) -> Json? {
1488
+ nodes.first { n in
1489
+ (n["role"] as? String) == role && (name == nil || (n["name"] as? String) == name)
1490
+ && (id == nil || (n["automationId"] as? String) == id)
1491
+ }
1492
+ }
1493
+ do {
1494
+ let nodes = try read()
1495
+ check("snapshot_reads_controls", nodes.count >= 5, "\(nodes.count) nodes")
1496
+ let button = find(nodes, role: "AXButton", id: "demo.press")
1497
+ let check1 = find(nodes, role: "AXCheckBox", id: "demo.check")
1498
+ let field = find(nodes, role: "AXTextField", id: "demo.field")
1499
+ check("finds_button_checkbox_field", button != nil && check1 != nil && field != nil,
1500
+ "button \(button != nil) checkbox \(check1 != nil) field \(field != nil)")
1501
+ check("button_offers_invoke", ((button?["actions"] as? [String]) ?? []).contains("invoke"), "\(button?["actions"] ?? "none")")
1502
+ check("checkbox_reads_toggle", (check1?["toggle"] as? String) == "off", "\(check1?["toggle"] ?? "none")")
1503
+ check("field_offers_value", ((field?["actions"] as? [String]) ?? []).contains("value"), "\(field?["actions"] ?? "none")")
1504
+ let menuBar = nodes.contains { ($0["role"] as? String) == "AXMenuBar" }
1505
+ let menuItem = find(nodes, role: "AXMenuBarItem", name: "Format")
1506
+ // A background app (this helper has no Dock icon) is not in front, and macOS then lists only its Apple and
1507
+ // app menus; the menu bar itself is what must be there. A real app's menu is proven by the real check.
1508
+ check("menu_bar_in_window_tree", menuBar, "menu bar \(menuBar); Format item \(menuItem != nil ? "listed" : "not listed while the helper is in the background")")
1509
+
1510
+ if let button = button, let fp = button["fp"] as? Json {
1511
+ let r = try onMain { try actReply(["hwnd": wid, "fingerprint": fp, "action": "invoke"]) }
1512
+ check("act_invoke_button", (r["done"] as? Bool) == true, "\(r)")
1513
+ let after = try read()
1514
+ check("button_press_visible_in_tree", find(after, role: "AXStaticText", name: "pressed") != nil, "status label now reads pressed")
1515
+ let again = find(after, role: "AXButton", id: "demo.press")
1516
+ let same = ((again?["fp"] as? Json)?["runtimeId"] as? String) == (fp["runtimeId"] as? String)
1517
+ check("runtime_id_survives_snapshot", same, "\(fp["runtimeId"] ?? "")")
1518
+ var stale = fp
1519
+ stale["runtimeId"] = "0:0"
1520
+ let found = try onMain { try resolveReply(["hwnd": wid, "fingerprint": stale]) }
1521
+ check("resolve_by_automation_id", (found["found"] as? Bool) == true && (found["via"] as? String) == "automationId", "\(found)")
1522
+ var renamed = fp
1523
+ renamed["runtimeId"] = "0:0"
1524
+ renamed["automationId"] = ""
1525
+ let byName = try onMain { try resolveReply(["hwnd": wid, "fingerprint": renamed]) }
1526
+ check("resolve_by_name", (byName["found"] as? Bool) == true && (byName["via"] as? String) == "name", "\(byName)")
1527
+ }
1528
+ if let c = check1, let fp = c["fp"] as? Json {
1529
+ let seq0 = try seqReply(["hwnd": wid])
1530
+ let r = try onMain { try actReply(["hwnd": wid, "fingerprint": fp, "action": "toggle"]) }
1531
+ check("act_toggle_checkbox", (r["done"] as? Bool) == true && (r["verified"] as? Bool) == true, "\(r)")
1532
+ let waited = try waitReply(["hwnd": wid, "since": seq0["seq"] ?? 0, "timeoutMs": 1500, "quietMs": 100])
1533
+ check("wait_change_sees_toggle", (waited["changed"] as? Bool) == true, "\(waited)")
1534
+ }
1535
+ if let f = field, let fp = f["fp"] as? Json {
1536
+ let r = try onMain { try actReply(["hwnd": wid, "fingerprint": fp, "action": "set_value", "value": "hello namzu"]) }
1537
+ check("act_set_value", (r["done"] as? Bool) == true && (r["verified"] as? Bool) == true, "\(r)")
1538
+ }
1539
+ if let item = menuItem, let fp = item["fp"] as? Json {
1540
+ let r = try onMain { try snapshotReply(["hwnd": wid, "root": fp, "maxNodes": 50, "maxDepth": 3]) }
1541
+ let sub = ((r["nodes"] as? [Json]) ?? []).contains { ($0["name"] as? String) == "Make Plain Text" }
1542
+ check("menu_item_opens_by_root", sub, "nodes \((r["nodes"] as? [Json])?.count ?? 0)")
1543
+ }
1544
+ } catch let e as HelperError {
1545
+ check("selftest_aborted", false, "\(e.code): \(e.message)")
1546
+ } catch {
1547
+ check("selftest_aborted", false, "\(error)")
1548
+ }
1549
+ closeDemoWindow()
1550
+ return ["checks": results]
1551
+ }
1552
+
1553
+ // MARK: - Server
1554
+
1555
+ /// Commands that read or act on one window's controls. For a window of the helper's own they run on the main thread.
1556
+ let controlCommands: Set<String> = ["snapshot", "act", "resolve", "identity", "scroll", "click", "type", "key"]
1557
+
1558
+ func dispatch(_ cmd: String, _ req: Json) throws -> Json {
1559
+ if controlCommands.contains(cmd), ownWindows.contains(intOf(req["hwnd"])) {
1560
+ return try onMain { try dispatchNow(cmd, req) }
1561
+ }
1562
+ return try dispatchNow(cmd, req)
1563
+ }
1564
+
1565
+ func dispatchNow(_ cmd: String, _ req: Json) throws -> Json {
1566
+ switch cmd {
1567
+ case "permissions": return permissionsReply(prompt: (req["prompt"] as? Bool) == true)
1568
+ case "windows": return windowsReply()
1569
+ case "displays": return displaysReply()
1570
+ case "snapshot": return try snapshotReply(req)
1571
+ case "seq": return try seqReply(req)
1572
+ case "wait_change": return try waitReply(req)
1573
+ case "identity": return try identityReply(req)
1574
+ case "resolve": return try resolveReply(req)
1575
+ case "act": return try actReply(req)
1576
+ case "focus": return try focusReply(req)
1577
+ case "scroll": return try scrollReply(req)
1578
+ case "click": return try clickReply(req)
1579
+ case "type": return try typeReply(req)
1580
+ case "key": return try keyReply(req)
1581
+ case "capture_window": return try captureReply(req)
1582
+ case "selfcheck": return selfcheckReply()
1583
+ case "selftest": return selftestReply()
1584
+ default: throw HelperError(code: "unknown_command", message: "unknown command \(cmd)")
1585
+ }
1586
+ }
1587
+
1588
+ /// Lets exactly one of the answer and the timeout reply to a request.
1589
+ final class ReplyOnce {
1590
+ private let lock = NSLock()
1591
+ private var done = false
1592
+ func claim() -> Bool {
1593
+ lock.lock(); defer { lock.unlock() }
1594
+ if done { return false }
1595
+ done = true
1596
+ return true
1597
+ }
1598
+ }
1599
+
1600
+ /// How long one request may take before the client is told so.
1601
+ func opLimitSeconds(_ cmd: String, _ req: Json) -> Double {
1602
+ switch cmd {
1603
+ case "wait_change": return Double(min(intOf(req["timeoutMs"]) ?? 2000, 10_000)) / 1000 + 8
1604
+ case "selftest": return 20
1605
+ case "capture_window": return 25
1606
+ case "type": return 15 + Double((req["text"] as? String)?.count ?? 0) * 0.01
1607
+ default: return 12
1608
+ }
1609
+ }
1610
+
1611
+ final class Connection {
1612
+ let fd: Int32
1613
+ private let writeLock = NSLock()
1614
+ init(_ fd: Int32) { self.fd = fd }
1615
+
1616
+ func send(_ obj: Json) {
1617
+ var obj = obj
1618
+ if !JSONSerialization.isValidJSONObject(obj) {
1619
+ obj = ["id": obj["id"] ?? 0, "ok": false, "code": "bad_reply", "message": "the helper could not encode its own answer"]
1620
+ }
1621
+ guard let data = try? JSONSerialization.data(withJSONObject: obj, options: []) else { return }
1622
+ var bytes = [UInt8](data)
1623
+ bytes.append(10)
1624
+ writeLock.lock(); defer { writeLock.unlock() }
1625
+ var off = 0
1626
+ while off < bytes.count {
1627
+ let n = bytes[off...].withUnsafeBytes { write(fd, $0.baseAddress, $0.count) }
1628
+ if n <= 0 { return }
1629
+ off += n
1630
+ }
1631
+ }
1632
+
1633
+ func serve() {
1634
+ send(["ok": true, "hello": true, "version": protocolVersion, "helper": "macos-ax", "pid": Int(getpid()), "build": buildId])
1635
+ var buffer = Data()
1636
+ var chunk = [UInt8](repeating: 0, count: 65536)
1637
+ let queue = DispatchQueue(label: "namzu.requests", attributes: .concurrent)
1638
+ readLoop: while true {
1639
+ let n = read(fd, &chunk, chunk.count)
1640
+ if n <= 0 { break }
1641
+ buffer.append(chunk, count: n)
1642
+ while let nl = buffer.firstIndex(of: 10) {
1643
+ let line = buffer.subdata(in: buffer.startIndex..<nl)
1644
+ buffer.removeSubrange(buffer.startIndex...nl)
1645
+ guard let obj = (try? JSONSerialization.jsonObject(with: line)) as? Json else { continue }
1646
+ let id = obj["id"] ?? 0
1647
+ let cmd = (obj["cmd"] as? String) ?? ""
1648
+ if cmd == "quit" { break readLoop }
1649
+ if cmd == "shutdown" {
1650
+ send(["id": id, "ok": true])
1651
+ exit(0)
1652
+ }
1653
+ // No request may leave its client without an answer: whatever one is stuck on, the client
1654
+ // gets `op_timeout` when the limit passes, and the loop above keeps reading.
1655
+ let once = ReplyOnce()
1656
+ queue.async {
1657
+ var reply: Json
1658
+ do {
1659
+ reply = try dispatch(cmd, obj)
1660
+ reply["ok"] = true
1661
+ } catch let e as HelperError {
1662
+ reply = ["ok": false, "code": e.code, "message": e.message]
1663
+ } catch {
1664
+ reply = ["ok": false, "code": "error", "message": "\(error)"]
1665
+ }
1666
+ reply["id"] = id
1667
+ if once.claim() { self.send(reply) }
1668
+ }
1669
+ DispatchQueue.global().asyncAfter(deadline: .now() + opLimitSeconds(cmd, obj)) {
1670
+ if once.claim() {
1671
+ self.send(["id": id, "ok": false, "code": "op_timeout", "message": "the helper did not finish \(cmd) in time; it is still running, and other requests are answered"])
1672
+ }
1673
+ }
1674
+ }
1675
+ }
1676
+ close(fd)
1677
+ }
1678
+ }
1679
+
1680
+ var activeConnections = 0
1681
+ var lastActivity = Date()
1682
+ let connectionLock = NSLock()
1683
+
1684
+ func startServer() {
1685
+ guard !socketPath.isEmpty else {
1686
+ FileHandle.standardError.write(Data("namzu-helper: --socket <path> is required\n".utf8))
1687
+ exit(64)
1688
+ }
1689
+ let dir = (socketPath as NSString).deletingLastPathComponent
1690
+ try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
1691
+ // The folder must be a real directory of ours, not one another user made first.
1692
+ var dirStat = stat()
1693
+ if lstat(dir, &dirStat) != 0 || (dirStat.st_mode & S_IFMT) != S_IFDIR || dirStat.st_uid != getuid() {
1694
+ FileHandle.standardError.write(Data("namzu-helper: socket folder is not owned by this user\n".utf8))
1695
+ exit(65)
1696
+ }
1697
+ chmod(dir, 0o700)
1698
+ unlink(socketPath)
1699
+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)
1700
+ var addr = sockaddr_un()
1701
+ addr.sun_family = sa_family_t(AF_UNIX)
1702
+ let pathBytes = Array(socketPath.utf8)
1703
+ guard pathBytes.count < MemoryLayout.size(ofValue: addr.sun_path) else {
1704
+ FileHandle.standardError.write(Data("namzu-helper: socket path too long\n".utf8))
1705
+ exit(64)
1706
+ }
1707
+ withUnsafeMutableBytes(of: &addr.sun_path) { raw in
1708
+ for (i, b) in pathBytes.enumerated() { raw[i] = b }
1709
+ raw[pathBytes.count] = 0
1710
+ }
1711
+ let size = socklen_t(MemoryLayout<sockaddr_un>.size)
1712
+ let bound = withUnsafePointer(to: &addr) {
1713
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, size) }
1714
+ }
1715
+ guard bound == 0 else {
1716
+ FileHandle.standardError.write(Data("namzu-helper: cannot bind \(socketPath)\n".utf8))
1717
+ exit(65)
1718
+ }
1719
+ chmod(socketPath, 0o600)
1720
+ listen(fd, 8)
1721
+ Thread.detachNewThread {
1722
+ while true {
1723
+ let client = accept(fd, nil, nil)
1724
+ if client < 0 { continue }
1725
+ var uid: uid_t = 0
1726
+ var gid: gid_t = 0
1727
+ if getpeereid(client, &uid, &gid) != 0 || uid != getuid() { close(client); continue }
1728
+ connectionLock.lock(); activeConnections += 1; lastActivity = Date(); connectionLock.unlock()
1729
+ Thread.detachNewThread {
1730
+ Connection(client).serve()
1731
+ connectionLock.lock(); activeConnections -= 1; lastActivity = Date(); connectionLock.unlock()
1732
+ }
1733
+ }
1734
+ }
1735
+ Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { _ in
1736
+ connectionLock.lock()
1737
+ let idle = activeConnections == 0 && Date().timeIntervalSince(lastActivity) > idleExitSeconds
1738
+ connectionLock.unlock()
1739
+ if idle { unlink(socketPath); exit(0) }
1740
+ }
1741
+ }
1742
+
1743
+ // MARK: - Main
1744
+
1745
+ if CommandLine.arguments.contains("--selfcheck") {
1746
+ let r = selfcheckReply()
1747
+ if let d = try? JSONSerialization.data(withJSONObject: r, options: [.prettyPrinted]), let s = String(data: d, encoding: .utf8) { print(s) }
1748
+ exit(0)
1749
+ }
1750
+
1751
+ signal(SIGPIPE, SIG_IGN)
1752
+ signal(SIGTERM) { _ in unlink(socketPath); exit(0) }
1753
+ let application = NSApplication.shared
1754
+ application.setActivationPolicy(.accessory)
1755
+ startServer()
1756
+ application.run()