| 1 | |
| 2 | import AppKit |
| 3 | import ApplicationServices |
| 4 | import ScreenCaptureKit |
| 5 | import Security |
| 6 | |
| 7 | private let appURL = URL(fileURLWithPath: "/Applications/Claude.app") |
| 8 | private let requirement = #"anchor apple generic and identifier "com.anthropic.claudefordesktop" and certificate leaf[subject.OU] = "Q6L2SF6YDW" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists"# |
| 9 | |
| 10 | struct Request: Decodable { |
| 11 | let action: String |
| 12 | var window: UInt32? |
| 13 | var pid: Int32? |
| 14 | var x, y, delta: Double? |
| 15 | var deltaX: Double? |
| 16 | var key, text: String? |
| 17 | var code, phase, mode, context, session: String? |
| 18 | var down, control, alt: Bool? |
| 19 | var button, buttons, clicks: Int? |
| 20 | var shift, command: Bool? |
| 21 | var project, nonce, geometry: String? |
| 22 | var width, height: Int? |
| 23 | var scale: Double? |
| 24 | var after: String? |
| 25 | var keepAlive: Bool? |
| 26 | var refresh: Bool? |
| 27 | var wait, binary: Bool? |
| 28 | var id, kind: String? |
| 29 | var ids: [String]? |
| 30 | var transfer: String? |
| 31 | var sequence: Int? |
| 32 | var path: String? |
| 33 | var error: String? |
| 34 | var files: [String]? |
| 35 | var length: Int? |
| 36 | var phone: MacPhoneDesktopInput? |
| 37 | var phone_token: String? |
| 38 | } |
| 39 | |
| 40 | func consoleUser() throws { |
| 41 | var info = stat() |
| 42 | guard stat("/dev/console", &info) == 0, info.st_uid >= 500, info.st_uid == getuid(), |
| 43 | (CGSessionCopyCurrentDictionary() as? [String:Any])?["CGSSessionScreenIsLocked"] as? Bool != true else { |
| 44 | throw Failure(4, "requires_gui_login") |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | private func verifiedInstall() throws { |
| 49 | var rule: SecRequirement? |
| 50 | var code: SecStaticCode? |
| 51 | guard SecRequirementCreateWithString(requirement as CFString, [], &rule) == errSecSuccess, let rule, |
| 52 | SecStaticCodeCreateWithPath(appURL as CFURL, [], &code) == errSecSuccess, let code, |
| 53 | SecStaticCodeCheckValidity(code, [], rule) == errSecSuccess else { |
| 54 | throw Failure(5, "identity_error") |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | |
| 59 | |
| 60 | @available(macOS 15.2, *) |
| 61 | @MainActor |
| 62 | private final class ClaudePicker: NSObject, SCContentSharingPickerObserver { |
| 63 | static let shared = ClaudePicker() |
| 64 | private(set) var selection: SCContentFilter? |
| 65 | func choose() { |
| 66 | let picker = SCContentSharingPicker.shared |
| 67 | picker.remove(self) |
| 68 | picker.add(self) |
| 69 | var config = SCContentSharingPickerConfiguration() |
| 70 | config.allowedPickerModes = [.singleWindow] |
| 71 | config.allowsChangingSelectedContent = false |
| 72 | picker.defaultConfiguration = config |
| 73 | picker.isActive = true |
| 74 | picker.present(using: .window) |
| 75 | } |
| 76 | nonisolated func contentSharingPicker(_ picker: SCContentSharingPicker, didUpdateWith filter: SCContentFilter, for stream: SCStream?) { |
| 77 | Task { @MainActor in |
| 78 | let window = filter.includedWindows.first |
| 79 | guard filter.style == .window, filter.includedWindows.count == 1, |
| 80 | let owner = window?.owningApplication, |
| 81 | owner.bundleIdentifier == "com.anthropic.claudefordesktop", |
| 82 | (try? claudePIDs().contains(owner.processID)) == true else { self.selection = nil; return } |
| 83 | self.selection = filter |
| 84 | } |
| 85 | } |
| 86 | nonisolated func contentSharingPicker(_ picker: SCContentSharingPicker, didCancelFor stream: SCStream?) {} |
| 87 | nonisolated func contentSharingPickerStartDidFailWithError(_ error: Error) {} |
| 88 | } |
| 89 | |
| 90 | @MainActor |
| 91 | func selectedWindow() async throws -> (SCWindow, SCContentFilter?) { |
| 92 | if #available(macOS 15.2, *), let filter = ClaudePicker.shared.selection, let window = filter.includedWindows.first { |
| 93 | let pids = try claudePIDs() |
| 94 | guard let owner = window.owningApplication, pids.contains(owner.processID) else { throw Failure(7, "window_changed") } |
| 95 | |
| 96 | let list = CGWindowListCopyWindowInfo([.optionIncludingWindow], window.windowID) as? [[String:Any]] |
| 97 | guard let exact = list?.first, exact[kCGWindowOwnerPID as String] as? Int32 == owner.processID, |
| 98 | exact[kCGWindowIsOnscreen as String] as? Bool == true else { throw Failure(7, "window_changed") } |
| 99 | return (window, filter) |
| 100 | } |
| 101 | return (try await claudeWindow(), nil) |
| 102 | } |
| 103 | |
| 104 | @MainActor |
| 105 | func sendInput(_ input: Request, window: SCWindow, canvas: ClaudeCanvas? = nil, maxTextBytes: Int = 8192, scrollX: Double = 0, maxScroll: Double = 1200, inputSession: MacWindowInputSession? = nil) throws { |
| 106 | let target = try checkedMacInputWindow(input, window: window) |
| 107 | try MacWindowInputSession.requirePointerOwner(inputSession) |
| 108 | let focused = target.focused, pid = target.pid |
| 109 | let origin = target.origin, extent = target.extent |
| 110 | let source = CGEventSource(stateID: .privateState) |
| 111 | func keyPair(_ key: CGKeyCode, flags: CGEventFlags = [], text: String? = nil) throws { |
| 112 | for down in [true, false] { |
| 113 | guard let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: down) else { throw Failure(8, "input_failed") } |
| 114 | event.flags = flags |
| 115 | if let text { |
| 116 | let chars = Array(text.utf16) |
| 117 | chars.withUnsafeBufferPointer { event.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: $0.baseAddress) } |
| 118 | } |
| 119 | event.postToPid(pid) |
| 120 | } |
| 121 | } |
| 122 | switch input.action { |
| 123 | case "text": |
| 124 | guard let text = input.text, !text.isEmpty, text.utf8.count <= maxTextBytes else { throw Failure(8, "invalid_input") } |
| 125 | for character in text { try keyPair(0, text: String(character)) } |
| 126 | case "key": |
| 127 | if input.code != nil { |
| 128 | guard let inputSession else { throw Failure(8, "input_connection_required") } |
| 129 | try inputSession.key(input, target: target, window: window) |
| 130 | return |
| 131 | } |
| 132 | let keys: [String: CGKeyCode] = ["Enter":36, "Tab":48, "Backspace":51, "Escape":53, "Delete":117, "ArrowLeft":123, "ArrowRight":124, "ArrowDown":125, "ArrowUp":126, "a":0, "z":6] |
| 133 | guard let key = input.key, let code = keys[key], (input.command == true) == ["a", "z"].contains(key) else { throw Failure(8, "invalid_input") } |
| 134 | var flags: CGEventFlags = [] |
| 135 | if input.shift == true { flags.insert(.maskShift) } |
| 136 | if input.command == true { flags.insert(.maskCommand) } |
| 137 | try keyPair(code, flags: flags) |
| 138 | case "pointer": |
| 139 | guard let inputSession else { throw Failure(8, "input_connection_required") } |
| 140 | try inputSession.pointer(input, target: target, window: window, canvas: canvas) |
| 141 | case "click", "scroll", "project-click": |
| 142 | guard let x = input.x, let y = input.y, (0..<1).contains(x), (0..<1).contains(y) else { throw Failure(8, "invalid_input") } |
| 143 | let crop = canvas?.cropTop ?? 0 |
| 144 | let point = CGPoint(x: origin.x + extent.width * x, y: origin.y + crop + (extent.height-crop) * y) |
| 145 | if input.action == "project-click" { |
| 146 | |
| 147 | |
| 148 | |
| 149 | var visited = 0 |
| 150 | func attribute(_ node: AXUIElement, _ name: String) -> CFTypeRef? { |
| 151 | var result: CFTypeRef? |
| 152 | guard AXUIElementCopyAttributeValue(node, name as CFString, &result) == .success else { return nil } |
| 153 | return result |
| 154 | } |
| 155 | func buttonAtPoint(_ node: AXUIElement, depth: Int) -> AXUIElement? { |
| 156 | guard depth <= 14, visited < 2048 else { return nil } |
| 157 | visited += 1 |
| 158 | if attribute(node, kAXRoleAttribute) as? String == kAXButtonRole, |
| 159 | attribute(node, kAXTitleAttribute) as? String == "Use Project", |
| 160 | let pos = attribute(node, kAXPositionAttribute), CFGetTypeID(pos) == AXValueGetTypeID(), |
| 161 | let dim = attribute(node, kAXSizeAttribute), CFGetTypeID(dim) == AXValueGetTypeID() { |
| 162 | var p = CGPoint.zero, s = CGSize.zero |
| 163 | if AXValueGetValue(pos as! AXValue, .cgPoint, &p), AXValueGetValue(dim as! AXValue, .cgSize, &s), |
| 164 | CGRect(origin: p, size: s).contains(point) { return node } |
| 165 | } |
| 166 | for child in attribute(node, kAXChildrenAttribute) as? [AXUIElement] ?? [] { |
| 167 | if let match = buttonAtPoint(child, depth: depth + 1) { return match } |
| 168 | } |
| 169 | return nil |
| 170 | } |
| 171 | guard let button = buttonAtPoint(focused, depth: 0), |
| 172 | AXUIElementPerformAction(button, kAXPressAction as CFString) == .success else { |
| 173 | throw Failure(8, "project_button_not_hit") |
| 174 | } |
| 175 | return |
| 176 | } |
| 177 | |
| 178 | |
| 179 | |
| 180 | if input.action == "click", let button = macPressTarget(target, point: point) { |
| 181 | guard AXUIElementPerformAction(button, kAXPressAction as CFString) == .success else { throw Failure(8, "input_failed") } |
| 182 | return |
| 183 | } |
| 184 | let events: [CGEvent?] |
| 185 | if input.action == "scroll" { |
| 186 | let horizontal = input.deltaX ?? scrollX |
| 187 | guard let delta = input.delta, delta.isFinite, horizontal.isFinite, |
| 188 | (-maxScroll...maxScroll).contains(delta), (-maxScroll...maxScroll).contains(horizontal) else { throw Failure(8, "invalid_input") } |
| 189 | events = [CGEvent(scrollWheelEvent2Source: source, units: .pixel, wheelCount: horizontal == 0 ? 1 : 2, wheel1: Int32(-delta), wheel2: Int32(-horizontal), wheel3: 0)] |
| 190 | } else { |
| 191 | |
| 192 | |
| 193 | |
| 194 | let local = CGPoint(x: point.x-origin.x, y: extent.height-(point.y-origin.y)) |
| 195 | let types: [NSEvent.EventType] = [.leftMouseDown, .leftMouseUp] |
| 196 | events = types.map { type in |
| 197 | NSEvent.mouseEvent(with: type, location: local, modifierFlags: [], |
| 198 | timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: Int(window.windowID), |
| 199 | context: nil, eventNumber: 0, clickCount: 1, pressure: type == .leftMouseDown ? 1 : 0)?.cgEvent |
| 200 | } |
| 201 | } |
| 202 | for item in events { |
| 203 | guard let event = item else { throw Failure(8, "input_failed") } |
| 204 | event.location = point |
| 205 | event.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: Int64(window.windowID)) |
| 206 | event.setIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: Int64(window.windowID)) |
| 207 | event.setIntegerValueField(.mouseEventClickState, value: 1) |
| 208 | event.postToPid(pid) |
| 209 | } |
| 210 | default: throw Failure(8, "invalid_input") |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | @MainActor |
| 215 | func launchClaudeWindow() async throws { |
| 216 | try verifiedInstall() |
| 217 | let configuration = NSWorkspace.OpenConfiguration() |
| 218 | configuration.activates = true |
| 219 | let application = try await NSWorkspace.shared.openApplication(at: appURL, configuration: configuration) |
| 220 | if AXIsProcessTrusted(), try claudePIDs().contains(application.processIdentifier) { |
| 221 | let element = AXUIElementCreateApplication(application.processIdentifier) |
| 222 | _ = AXUIElementSetAttributeValue(element, "AXManualAccessibility" as CFString, kCFBooleanTrue) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | @MainActor |
| 227 | private func handle(_ input: Request, inputSession: MacWindowInputSession) async throws -> [String: Any] { |
| 228 | try requireGuest() |
| 229 | if input.action.hasPrefix("phone-") { |
| 230 | return try await MacPhoneDesktop.shared.handle(input) |
| 231 | } |
| 232 | try consoleUser() |
| 233 | switch input.action { |
| 234 | case "files-start": |
| 235 | let (window, _) = try await selectedWindow() |
| 236 | guard input.pid == window.owningApplication?.processID, input.window == window.windowID else { throw Failure(7, "window_changed") } |
| 237 | return try MacDesktopFiles.shared.start(window: window, kind: input.kind ?? "") |
| 238 | case "files-add": |
| 239 | return try MacDesktopFiles.shared.add(input.id ?? "", files: input.files ?? []) |
| 240 | case "files-validate": |
| 241 | return try MacDesktopFiles.shared.validate(input.id ?? "") |
| 242 | case "files-finish": |
| 243 | return try await MacDesktopFiles.shared.finish(input.id ?? "") |
| 244 | case "files-finish-image": |
| 245 | return try await MacDesktopFiles.shared.finishImage(input.id ?? "") |
| 246 | case "files-cancel": |
| 247 | return await MacDesktopFiles.shared.cancel(input.id ?? "") |
| 248 | case "files-poll": |
| 249 | return try await MacDesktopFiles.shared.poll() |
| 250 | case "files-download-open", "files-download-read", "files-download-close", "files-download-retry", "files-download-ack": |
| 251 | return try MacDesktopDownloads.shared.read(input) |
| 252 | case "files-open-claim", "files-open-complete": |
| 253 | return try MacDesktopFiles.shared.openAction(input.id ?? "", complete: input.action == "files-open-complete") |
| 254 | case "audio-status": |
| 255 | return MacAudioCapture.status() |
| 256 | case "setup-status": |
| 257 | return ["screen": CGPreflightScreenCaptureAccess(), "input": AXIsProcessTrusted()] |
| 258 | case "setup-password-focus": |
| 259 | return try MacSetupPassword.probe() |
| 260 | case "setup-screen", "setup-input", "setup-projects": |
| 261 | let purpose: String |
| 262 | if input.action == "setup-screen" { |
| 263 | if !CGPreflightScreenCaptureAccess() { _ = CGRequestScreenCaptureAccess() } |
| 264 | purpose = "screen" |
| 265 | } else if input.action == "setup-input" { |
| 266 | let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary |
| 267 | _ = AXIsProcessTrustedWithOptions(options) |
| 268 | purpose = "input" |
| 269 | } else { |
| 270 | let vendor = URL(fileURLWithPath: "/Applications/macFUSE.app") |
| 271 | let configuration = NSWorkspace.OpenConfiguration() |
| 272 | configuration.activates = false |
| 273 | _ = try await NSWorkspace.shared.openApplication(at: vendor, configuration: configuration) |
| 274 | purpose = "projects" |
| 275 | } |
| 276 | guard let url = MacMaintenance.settingsURL(for: purpose), NSWorkspace.shared.open(url) else { throw Failure(7, "settings_unavailable") } |
| 277 | return ["ok":true] |
| 278 | case "status": |
| 279 | let installed = FileManager.default.fileExists(atPath: appURL.path) |
| 280 | let running = ((try? claudePIDs())?.isEmpty == false) |
| 281 | var screen = CGPreflightScreenCaptureAccess() |
| 282 | if #available(macOS 15.2, *) { screen = screen || ClaudePicker.shared.selection != nil } |
| 283 | return ["version": (Bundle(url: appURL)?.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String) ?? "", "installed": installed, "running": running, "screen": screen, "input": AXIsProcessTrusted(), "input_protocol": 1, "persistent": true, "push_frames": true] |
| 284 | case "launch": |
| 285 | try await launchClaudeWindow() |
| 286 | return ["ok": true] |
| 287 | case "stop": |
| 288 | for pid in try claudePIDs() { |
| 289 | guard let app = NSRunningApplication(processIdentifier: pid), app.terminate() else { throw Failure(7, "window_changed") } |
| 290 | } |
| 291 | return ["ok": true] |
| 292 | case "request-screen": |
| 293 | if #available(macOS 15.2, *) { ClaudePicker.shared.choose() } else { _ = CGRequestScreenCaptureAccess() } |
| 294 | return ["screen": CGPreflightScreenCaptureAccess()] |
| 295 | case "request-input": |
| 296 | let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary |
| 297 | return ["input": AXIsProcessTrustedWithOptions(options)] |
| 298 | case "frame": |
| 299 | if input.wait != true && input.refresh != true && MacWindowStream.shared.unchanged(after: input.after) { |
| 300 | return ["unchanged": true, "sequence": input.after!] |
| 301 | } |
| 302 | let (window, filter) = try await selectedWindow() |
| 303 | if input.width != nil || input.height != nil || input.scale != nil { |
| 304 | guard let width=input.width, let height=input.height, let scale=input.scale else { throw Failure(8,"invalid_input") } |
| 305 | let capture = filter ?? SCContentFilter(desktopIndependentWindow: window) |
| 306 | let canvas = ClaudeCanvasSession.shared |
| 307 | let layout = try await canvas.layout(window, filter:capture, width:width, height:height, scale:scale) |
| 308 | |
| 309 | |
| 310 | var target = window, source = capture |
| 311 | if abs(window.frame.width - layout.frame.width) >= 1 || abs(window.frame.height - layout.frame.height) >= 1 { |
| 312 | let (fresh, selection) = try await selectedWindow() |
| 313 | guard fresh.windowID == layout.id, fresh.owningApplication?.processID == layout.pid else { |
| 314 | throw Failure(7, "window_changed") |
| 315 | } |
| 316 | target = fresh |
| 317 | source = selection ?? SCContentFilter(desktopIndependentWindow: fresh) |
| 318 | } |
| 319 | let reply = try await canvas.capture(target, filter:source, layout:layout, after:input.after, wait:input.wait == true, binary:input.binary == true) |
| 320 | try consoleUser() |
| 321 | return reply |
| 322 | } |
| 323 | let data = try await screenshot(window, filter: filter) |
| 324 | guard data.count < 8 << 20, let owner = window.owningApplication, try claudePIDs().contains(owner.processID) else { |
| 325 | throw Failure(7, "window_changed") |
| 326 | } |
| 327 | try consoleUser() |
| 328 | return ["image": data.base64EncodedString(), "window": window.windowID, "pid": owner.processID] |
| 329 | case "input-reset": |
| 330 | inputSession.reset() |
| 331 | return ["ok": true] |
| 332 | case "ime": |
| 333 | let (window, _) = try await selectedWindow() |
| 334 | let canvas = try input.geometry.map { try ClaudeCanvasSession.shared.inputGeometry($0, window: window) } |
| 335 | return try inputSession.ime(input, window: window, canvas: canvas) { value in |
| 336 | if value.isEmpty { return } |
| 337 | var text = Request(action: "text") |
| 338 | text.pid = input.pid; text.window = input.window; text.geometry = input.geometry; text.text = value |
| 339 | try sendInput(text, window: window, canvas: canvas, inputSession: inputSession) |
| 340 | } |
| 341 | case "text", "key", "click", "scroll", "pointer": |
| 342 | let (window, _) = try await selectedWindow() |
| 343 | let canvas = try input.geometry.map { try ClaudeCanvasSession.shared.inputGeometry($0, window:window) } |
| 344 | try sendInput(input, window: window, canvas:canvas, inputSession: inputSession) |
| 345 | return ["ok": true] |
| 346 | case "project-frame", "project-click": |
| 347 | guard let path = input.project else { throw Failure(7, "no_project_panel") } |
| 348 | let panel = try pendingProjectPanel(path) |
| 349 | let window = try await visibleProjectPanel(panel) |
| 350 | if input.action == "project-click" { |
| 351 | guard input.nonce == panel.nonce, try pendingProjectPanel(path) == panel else { throw Failure(7, "window_changed") } |
| 352 | try sendInput(input, window: window) |
| 353 | for _ in 0..<16 { |
| 354 | try await Task.sleep(nanoseconds: 100_000_000) |
| 355 | if (try? pendingProjectPanel(path)) != panel { return ["ok": true] } |
| 356 | } |
| 357 | throw Failure(8, "project_panel_still_open") |
| 358 | } |
| 359 | let data = try await screenshot(window) |
| 360 | guard data.count < 8 << 20, try pendingProjectPanel(path) == panel else { throw Failure(7, "window_changed") } |
| 361 | try consoleUser() |
| 362 | return ["image": data.base64EncodedString(), "window": panel.windowNumber, "pid": panel.pid, "nonce": panel.nonce] |
| 363 | default: throw Failure(8, "unknown_action") |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | private func respond(_ fd: Int32) async { |
| 368 | let inputSession = await MainActor.run { MacWindowInputSession() } |
| 369 | await respondConnection(fd, inputSession: inputSession) |
| 370 | await MainActor.run { inputSession.reset() } |
| 371 | } |
| 372 | |
| 373 | private func respondConnection(_ fd: Int32, inputSession: MacWindowInputSession) async { |
| 374 | let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true) |
| 375 | var timeout = timeval(tv_sec: 6, tv_usec: 0) |
| 376 | setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) |
| 377 | setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) |
| 378 | var peer = uid_t(), group = gid_t() |
| 379 | guard getpeereid(fd, &peer, &group) == 0, peer == getuid() else { return } |
| 380 | var body = Data() |
| 381 | do { |
| 382 | repeat { |
| 383 | while !body.contains(10) { |
| 384 | var chunk = [UInt8](repeating: 0, count: (64 << 10) - body.count) |
| 385 | let count = Darwin.read(fd, &chunk, chunk.count) |
| 386 | if count < 0 && errno == EINTR { continue } |
| 387 | guard count > 0 else { return } |
| 388 | body.append(contentsOf: chunk.prefix(count)) |
| 389 | guard body.count < (64 << 10) || body.contains(10) else { return } |
| 390 | } |
| 391 | let line = body.prefix(while: { $0 != 10 }) |
| 392 | let request = try JSONDecoder().decode(Request.self, from: line) |
| 393 | body.removeFirst(line.count + 1) |
| 394 | if request.action == "audio-capture" { |
| 395 | guard body.isEmpty else { return } |
| 396 | await MacAudioCapture.respond(fd) |
| 397 | return |
| 398 | } |
| 399 | var reply: [String:Any] |
| 400 | do { |
| 401 | if request.action == "paste-image" { |
| 402 | guard let length = request.length, length > 0, length <= 20 * 1024 * 1024, body.count <= length else { throw Failure(8, "attachment_size_limit") } |
| 403 | let (window, _) = try await selectedWindow() |
| 404 | guard request.pid == window.owningApplication?.processID, request.window == window.windowID else { throw Failure(7, "window_changed") } |
| 405 | var image = body |
| 406 | body.removeAll() |
| 407 | while image.count < length { |
| 408 | guard let chunk = try file.read(upToCount: min(65536, length - image.count)), !chunk.isEmpty else { throw Failure(8, "attachment_incomplete") } |
| 409 | image.append(chunk) |
| 410 | } |
| 411 | reply = try await MacDesktopFiles.shared.pasteImage(image, window: window) |
| 412 | } else { reply = try await handle(request, inputSession: inputSession) } |
| 413 | } |
| 414 | catch { |
| 415 | let reason = (error as? Failure)?.message.components(separatedBy: ":").first ?? "window_unavailable" |
| 416 | GuestDiagnostic.record("window", reason) |
| 417 | reply = ["error": reason] |
| 418 | } |
| 419 | if request.binary == true && request.action == "frame" { |
| 420 | let pixels = reply.removeValue(forKey: "imageBytes") as? Data ?? Data() |
| 421 | reply["imageLength"] = pixels.count |
| 422 | let header = try JSONSerialization.data(withJSONObject: reply) |
| 423 | var length = UInt32(header.count).bigEndian |
| 424 | try file.write(contentsOf: withUnsafeBytes(of: &length) { Data($0) }) |
| 425 | try file.write(contentsOf: header) |
| 426 | try file.write(contentsOf: pixels) |
| 427 | } else { |
| 428 | var data = try JSONSerialization.data(withJSONObject: reply) |
| 429 | data.append(10) |
| 430 | try file.write(contentsOf: data) |
| 431 | } |
| 432 | if request.keepAlive != true { return } |
| 433 | } while true |
| 434 | } catch { |
| 435 | let reason = (error as? Failure)?.message.components(separatedBy: ":").first ?? "window_unavailable" |
| 436 | GuestDiagnostic.record("window", reason) |
| 437 | if let data = try? JSONSerialization.data(withJSONObject: ["error": reason]) { try? file.write(contentsOf: data) } |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | @main |
| 442 | struct ClaudeWindowService { |
| 443 | static func main() { |
| 444 | let arguments = Array(CommandLine.arguments.dropFirst()) |
| 445 | if arguments == ["--setup-password-probe"] { MacSetupPassword.runStream() } |
| 446 | if arguments.count == 2 && ["--maintenance-open", "--maintenance-probe", "--maintenance-password-probe"].contains(arguments[0]) { |
| 447 | if arguments[0] == "--maintenance-password-probe" { MacMaintenance.runPasswordProbe(purpose: arguments[1]) } |
| 448 | let result: [String: Any] |
| 449 | do { result = try MacMaintenance.run(arguments[0] == "--maintenance-open" ? "open" : "probe", purpose: arguments[1]) } |
| 450 | catch { result = ["error": (error as? Failure)?.message ?? "maintenance_unavailable"] } |
| 451 | if let data = try? JSONSerialization.data(withJSONObject: result) { |
| 452 | FileHandle.standardOutput.write(data) |
| 453 | FileHandle.standardOutput.write(Data([10])) |
| 454 | } |
| 455 | return |
| 456 | } |
| 457 | if CommandLine.arguments.dropFirst() == ["--setup-password-self-test"] { |
| 458 | do { try MacSetupPassword.selfTest(); return } |
| 459 | catch { fputs("macOS setup password self-test failed\n", stderr); exit(1) } |
| 460 | } |
| 461 | if CommandLine.arguments.dropFirst() == ["--native-open-self-test"] { |
| 462 | do { try MacNativeOpen.selfTest(); return } |
| 463 | catch { fputs("macOS native open self-test failed (\((error as? Failure)?.message ?? "unknown error"))\n", stderr); exit(1) } |
| 464 | } |
| 465 | if CommandLine.arguments.dropFirst() == ["--phone-self-test"] { |
| 466 | do { try MacPhoneDesktop.selfTest(); return } |
| 467 | catch { fputs("macOS phone desktop self-test failed\n", stderr); exit(1) } |
| 468 | } |
| 469 | if CommandLine.arguments.dropFirst() == ["--audio-self-test"] { |
| 470 | do { try MacAudioCapture.selfTest(); return } |
| 471 | catch { fputs("macOS audio self-test failed\n", stderr); exit(1) } |
| 472 | } |
| 473 | guard (try? requireGuest()) != nil, (try? consoleUser()) != nil else { exit(2) } |
| 474 | _ = signal(SIGPIPE, SIG_IGN) |
| 475 | let storage = UnsafeMutablePointer<UnsafeMutablePointer<Int32>>.allocate(capacity: 1) |
| 476 | var count: Int = 0 |
| 477 | guard launch_activate_socket("Window", storage, &count) == 0, count == 1 else { exit(3) } |
| 478 | let sockets = storage.pointee |
| 479 | storage.deallocate() |
| 480 | let listener = sockets[0] |
| 481 | free(sockets) |
| 482 | GuestDiagnostic.record("window", "started") |
| 483 | NSApplication.shared.setActivationPolicy(.accessory) |
| 484 | MacNativeOpen.shared.install() |
| 485 | Task { @MainActor in |
| 486 | do { try await MacNativeOpen.shared.prepareMetadata() } |
| 487 | catch { GuestDiagnostic.record("files", (error as? Failure)?.message ?? "file_open_metadata_failed") } |
| 488 | } |
| 489 | DispatchQueue.global(qos: .userInitiated).async { |
| 490 | let connections = DispatchSemaphore(value: 16) |
| 491 | while true { |
| 492 | connections.wait() |
| 493 | let fd = accept(listener, nil, nil) |
| 494 | if fd < 0 { connections.signal(); if errno == EINTR { continue }; exit(4) } |
| 495 | Task { await respond(fd); connections.signal() } |
| 496 | } |
| 497 | } |
| 498 | NSApplication.shared.run() |
| 499 | } |
| 500 | } |