| 1 | |
| 2 | |
| 3 | import AppKit |
| 4 | import ScreenCaptureKit |
| 5 | import ImageIO |
| 6 | |
| 7 | struct MacPhoneDesktopInput: Decodable { |
| 8 | let id: String |
| 9 | var width, height: Int? |
| 10 | var pixel_ratio: Double? |
| 11 | var type, document, focus, text, key: String? |
| 12 | var x, y, dx, dy: Double? |
| 13 | } |
| 14 | |
| 15 | func phoneDesktopJPEG(_ image: CGImage) throws -> Data { |
| 16 | for quality in [0.9, 0.78, 0.62, 0.45] { |
| 17 | let data = try encodedImage(image, type: .jpeg, |
| 18 | properties: [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary) |
| 19 | |
| 20 | if data.count <= 2 << 20 { return data } |
| 21 | } |
| 22 | throw Failure(8, "frame_limit") |
| 23 | } |
| 24 | |
| 25 | private func matchesPhoneFocus(_ requested: String?, token: String, previous: AXUIElement?, current: AXUIElement?, password: Bool) -> Bool { |
| 26 | guard !token.isEmpty, requested == token, let previous, let current, !password else { return false } |
| 27 | return CFEqual(previous, current) |
| 28 | } |
| 29 | |
| 30 | @MainActor |
| 31 | final class MacPhoneDesktop { |
| 32 | static let shared = MacPhoneDesktop() |
| 33 | |
| 34 | @MainActor private final class Session { |
| 35 | let id, secret: String |
| 36 | let epoch: UInt64 |
| 37 | let canvas = ClaudeCanvasSession() |
| 38 | var width: Int |
| 39 | var height: Int |
| 40 | var ratio: Double |
| 41 | var geometry = "" |
| 42 | var document = "" |
| 43 | var focus = "" |
| 44 | var focusedElement: AXUIElement? |
| 45 | var window: CGWindowID? |
| 46 | var pid: pid_t? |
| 47 | var touched = Date() |
| 48 | |
| 49 | init(_ input: MacPhoneDesktopInput, secret: String, epoch: UInt64) throws { |
| 50 | let size = try MacPhoneDesktop.viewport(input) |
| 51 | id = input.id |
| 52 | self.secret = secret |
| 53 | self.epoch = epoch |
| 54 | width = size.0; height = size.1; ratio = size.2 |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | private var current: Session? |
| 59 | |
| 60 | private static func viewport(_ input: MacPhoneDesktopInput) throws -> (Int, Int, Double) { |
| 61 | guard let width = input.width, let height = input.height, |
| 62 | (240...1440).contains(width), (160...1600).contains(height) else { |
| 63 | throw Failure(8, "invalid_input") |
| 64 | } |
| 65 | let ratio = input.pixel_ratio ?? 1 |
| 66 | guard ratio.isFinite, (1...8).contains(ratio) else { throw Failure(8, "invalid_input") } |
| 67 | return (width, height, ratio) |
| 68 | } |
| 69 | |
| 70 | private func validate(_ session: Session) throws { |
| 71 | guard current === session, Date().timeIntervalSince(session.touched) < 120 else { |
| 72 | throw Failure(7, "phone_session_ended") |
| 73 | } |
| 74 | do { try MacGUISession.shared.validate(session.epoch) } |
| 75 | catch { current = nil; throw error } |
| 76 | session.touched = Date() |
| 77 | } |
| 78 | |
| 79 | func handle(_ request: Request) async throws -> [String: Any] { |
| 80 | guard let input = request.phone, UUID(uuidString: input.id) != nil, |
| 81 | let secret = request.phone_token, (32...128).contains(secret.utf8.count) else { |
| 82 | throw Failure(8, "invalid_input") |
| 83 | } |
| 84 | if request.action == "phone-close" { |
| 85 | if current?.id == input.id && current?.secret == secret { current = nil } |
| 86 | return ["id": input.id] |
| 87 | } |
| 88 | if request.action == "phone-open" { |
| 89 | let epoch = try MacGUISession.shared.validate() |
| 90 | let session = try Session(input, secret: secret, epoch: epoch) |
| 91 | current = session |
| 92 | do { |
| 93 | try await launchClaudeWindow() |
| 94 | try validate(session) |
| 95 | } catch { |
| 96 | if current === session { current = nil } |
| 97 | throw error |
| 98 | } |
| 99 | return ["id": session.id] |
| 100 | } |
| 101 | guard let session = current, session.id == input.id, session.secret == secret else { |
| 102 | throw Failure(7, "phone_session_ended") |
| 103 | } |
| 104 | try validate(session) |
| 105 | switch request.action { |
| 106 | case "phone-frame": |
| 107 | return try await frame(session) |
| 108 | case "phone-action": |
| 109 | if input.type == "resize" { |
| 110 | let (width, height, ratio) = try Self.viewport(input) |
| 111 | session.width = width; session.height = height; session.ratio = ratio |
| 112 | session.document = ""; session.focus = ""; session.focusedElement = nil |
| 113 | return ["id": session.id] |
| 114 | } |
| 115 | try await action(input, session: session) |
| 116 | return ["id": session.id] |
| 117 | default: |
| 118 | throw Failure(8, "unknown_action") |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | private func frame(_ session: Session) async throws -> [String: Any] { |
| 123 | var (window, selection) = try await selectedWindow() |
| 124 | try validate(session) |
| 125 | let capture = selection ?? SCContentFilter(desktopIndependentWindow: window) |
| 126 | let layout = try await session.canvas.layout(window, filter: capture, |
| 127 | width: max(320, session.width), height: max(240, session.height), scale: min(2, session.ratio)) |
| 128 | try validate(session) |
| 129 | if window.frame != layout.frame { |
| 130 | (window, selection) = try await selectedWindow() |
| 131 | guard window.windowID == layout.id, window.owningApplication?.processID == layout.pid else { |
| 132 | throw Failure(7, "window_changed") |
| 133 | } |
| 134 | } |
| 135 | let raw = try await session.canvas.capture(window, |
| 136 | filter: selection ?? SCContentFilter(desktopIndependentWindow: window), |
| 137 | layout: layout, binary: true, phoneJPEG: true) |
| 138 | try validate(session) |
| 139 | guard let data = raw["imageBytes"] as? Data, let geometry = raw["geometry"] as? String else { |
| 140 | throw Failure(8, "capture_failed") |
| 141 | } |
| 142 | if session.geometry != geometry || session.document.isEmpty { |
| 143 | session.document = UUID().uuidString |
| 144 | session.focus = ""; session.focusedElement = nil |
| 145 | } |
| 146 | session.geometry = geometry; session.window = layout.id; session.pid = layout.pid |
| 147 | let focus = editableFocus(window, session: session) |
| 148 | if let element = focus.element { |
| 149 | if session.focusedElement.map({ CFEqual($0, element) }) != true { |
| 150 | session.focus = UUID().uuidString |
| 151 | } |
| 152 | session.focusedElement = element |
| 153 | } else { |
| 154 | session.focusedElement = nil; session.focus = "" |
| 155 | } |
| 156 | let reply: [String: Any] = ["id": session.id, "document": session.document, |
| 157 | "image": data.base64EncodedString(), "width": session.width, "height": session.height, |
| 158 | "content_width": layout.content.width, "content_height": layout.content.height, |
| 159 | "pixel_width": raw["pixelWidth"] ?? 0, "pixel_height": raw["pixelHeight"] ?? 0, |
| 160 | "requested_pixel_ratio": session.ratio, "pixel_ratio_control": true, |
| 161 | "focus": session.focus, "password": focus.password, "window": "desktop", "shared": true, |
| 162 | "login_supported": false] |
| 163 | guard try JSONSerialization.data(withJSONObject: reply).count <= 3 << 20 else { |
| 164 | throw Failure(8, "frame_limit") |
| 165 | } |
| 166 | return reply |
| 167 | } |
| 168 | |
| 169 | private func editableFocus(_ window: SCWindow, session: Session) -> (element: AXUIElement?, password: Bool) { |
| 170 | guard (try? session.canvas.inputGeometry(session.geometry, window: window)) != nil, |
| 171 | let pid = window.owningApplication?.processID else { return (nil, false) } |
| 172 | func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? { |
| 173 | var value: CFTypeRef? |
| 174 | return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil |
| 175 | } |
| 176 | let application = AXUIElementCreateApplication(pid) |
| 177 | guard let raw = attribute(application, kAXFocusedUIElementAttribute), CFGetTypeID(raw) == AXUIElementGetTypeID(), |
| 178 | let owner = attribute(application, kAXFocusedWindowAttribute) else { return (nil, false) } |
| 179 | let element = raw as! AXUIElement |
| 180 | guard let elementWindow = attribute(element, kAXWindowAttribute), CFEqual(owner, elementWindow), |
| 181 | let role = attribute(element, kAXRoleAttribute) as? String, |
| 182 | [kAXTextFieldRole, kAXTextAreaRole, kAXComboBoxRole].contains(role) else { return (nil, false) } |
| 183 | let password = attribute(element, kAXSubroleAttribute) as? String == kAXSecureTextFieldSubrole |
| 184 | return (element, password) |
| 185 | } |
| 186 | |
| 187 | private func action(_ input: MacPhoneDesktopInput, session: Session) async throws { |
| 188 | guard !session.document.isEmpty, input.document == session.document else { throw Failure(7, "phone_document_changed") } |
| 189 | let (window, _) = try await selectedWindow() |
| 190 | try validate(session) |
| 191 | guard window.windowID == session.window, window.owningApplication?.processID == session.pid else { |
| 192 | throw Failure(7, "window_changed") |
| 193 | } |
| 194 | let canvas = try session.canvas.inputGeometry(session.geometry, window: window) |
| 195 | var native = Request(action: "") |
| 196 | var scrollX: Double = 0 |
| 197 | let typing = input.type == "text" || (input.type == "key" && !["Tab", "Escape", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].contains(input.key ?? "")) |
| 198 | if typing { |
| 199 | let fresh = editableFocus(window, session: session) |
| 200 | guard matchesPhoneFocus(input.focus, token: session.focus, previous: session.focusedElement, |
| 201 | current: fresh.element, password: fresh.password) else { throw Failure(7, "phone_focus_changed") } |
| 202 | } |
| 203 | switch input.type { |
| 204 | case "text": |
| 205 | native = Request(action: "text", text: input.text) |
| 206 | case "key": |
| 207 | if let key = input.key, key.utf8.count == 1, let scalar = key.unicodeScalars.first, (32...126).contains(scalar.value) { |
| 208 | native = Request(action: "text", text: key) |
| 209 | } else { native = Request(action: "key", key: input.key) } |
| 210 | case "tap", "scroll": |
| 211 | guard let x = input.x, let y = input.y, x.isFinite, y.isFinite, |
| 212 | (0..<Double(canvas.content.width)).contains(x), (0..<Double(canvas.content.height)).contains(y) else { |
| 213 | throw Failure(8, "invalid_input") |
| 214 | } |
| 215 | native = Request(action: input.type == "tap" ? "click" : "scroll", |
| 216 | x: x / Double(canvas.content.width), y: y / Double(canvas.content.height), delta: input.dy) |
| 217 | if input.type == "scroll" { |
| 218 | guard let dx = input.dx, let dy = input.dy, dx.isFinite, dy.isFinite, |
| 219 | (-3200...3200).contains(dx), (-3200...3200).contains(dy) else { throw Failure(8, "invalid_input") } |
| 220 | scrollX = dx |
| 221 | native.delta = dy |
| 222 | } |
| 223 | default: |
| 224 | throw Failure(8, "invalid_input") |
| 225 | } |
| 226 | native.window = window.windowID; native.pid = window.owningApplication?.processID |
| 227 | try sendInput(native, window: window, canvas: canvas, maxTextBytes: 8192, scrollX: scrollX, maxScroll: 32000) |
| 228 | } |
| 229 | |
| 230 | static func selfTest() throws { |
| 231 | let local = AXUIElementCreateApplication(getpid()) |
| 232 | let other = AXUIElementCreateApplication(getpid() + 1) |
| 233 | let accepts = matchesPhoneFocus("focus", token: "focus", previous: local, current: local, password: false) |
| 234 | let rejects = [ |
| 235 | matchesPhoneFocus("", token: "", previous: local, current: local, password: false), |
| 236 | matchesPhoneFocus("old", token: "focus", previous: local, current: local, password: false), |
| 237 | matchesPhoneFocus("focus", token: "focus", previous: local, current: other, password: false), |
| 238 | matchesPhoneFocus("focus", token: "focus", previous: local, current: nil, password: false), |
| 239 | matchesPhoneFocus("focus", token: "focus", previous: local, current: local, password: true) |
| 240 | ] |
| 241 | guard accepts, rejects.allSatisfy({ !$0 }) else { throw Failure(8, "focus_test_failed") } |
| 242 | guard let context = CGContext(data: nil, width: 640, height: 480, bitsPerComponent: 8, |
| 243 | bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { throw Failure(8, "image_test_failed") } |
| 244 | context.setFillColor(CGColor(red: 0.1, green: 0.2, blue: 0.3, alpha: 1)) |
| 245 | context.fill(CGRect(x: 0, y: 0, width: 640, height: 480)) |
| 246 | guard let image = context.makeImage() else { throw Failure(8, "image_test_failed") } |
| 247 | let jpeg = try phoneDesktopJPEG(image) |
| 248 | guard jpeg.starts(with: [0xff, 0xd8]), let source = CGImageSourceCreateWithData(jpeg as CFData, nil), |
| 249 | let decoded = CGImageSourceCreateImageAtIndex(source, 0, nil), decoded.width == 640, decoded.height == 480, |
| 250 | try JSONSerialization.data(withJSONObject: ["image": jpeg.base64EncodedString()]).count < 3 << 20 else { throw Failure(8, "jpeg_test_failed") } |
| 251 | print("phone desktop focus token and real AX identity checks passed; JPEG 640x480 encoding and total JSON limit passed") |
| 252 | } |
| 253 | } |