| 1 | |
| 2 | import AppKit |
| 3 | import ScreenCaptureKit |
| 4 | |
| 5 | private func fileAttribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? { |
| 6 | var value: CFTypeRef? |
| 7 | return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil |
| 8 | } |
| 9 | |
| 10 | private func fileChildren(_ element: AXUIElement) -> [AXUIElement] { |
| 11 | (fileAttribute(element, kAXChildrenAttribute) as? [AXUIElement] ?? []) + |
| 12 | (fileAttribute(element, "AXSheets") as? [AXUIElement] ?? []) |
| 13 | } |
| 14 | |
| 15 | private func filePanelButton(_ panel: AXUIElement, cancel: Bool = false) -> AXUIElement? { |
| 16 | if let value = fileAttribute(panel, cancel ? kAXCancelButtonAttribute : kAXDefaultButtonAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() { |
| 17 | return (value as! AXUIElement) |
| 18 | } |
| 19 | var pending = fileChildren(panel), visited = 0 |
| 20 | while visited < pending.count && visited < 1024 { |
| 21 | let element = pending[visited]; visited += 1 |
| 22 | if fileAttribute(element, kAXRoleAttribute) as? String == kAXButtonRole, |
| 23 | fileAttribute(element, "AXIdentifier") as? String == (cancel ? "CancelButton" : "OKButton") { return element } |
| 24 | pending.append(contentsOf: fileChildren(element)) |
| 25 | } |
| 26 | return nil |
| 27 | } |
| 28 | |
| 29 | private func filePanelPresent(_ panel: AXUIElement, pid: pid_t) -> Bool { |
| 30 | var pending = fileAttribute(AXUIElementCreateApplication(pid), kAXWindowsAttribute) as? [AXUIElement] ?? [], visited = 0 |
| 31 | while visited < pending.count && visited < 1024 { |
| 32 | let element = pending[visited]; visited += 1 |
| 33 | if CFEqual(element, panel) { return true } |
| 34 | pending.append(contentsOf: fileChildren(element)) |
| 35 | } |
| 36 | return false |
| 37 | } |
| 38 | |
| 39 | private func filePanelFocused(_ panel: AXUIElement, pid: pid_t) -> Bool { |
| 40 | var current = fileAttribute(AXUIElementCreateApplication(pid), kAXFocusedUIElementAttribute) |
| 41 | for _ in 0..<32 { |
| 42 | guard let value = current, CFGetTypeID(value) == AXUIElementGetTypeID() else { return false } |
| 43 | let element = value as! AXUIElement |
| 44 | if CFEqual(element, panel) { return true } |
| 45 | current = fileAttribute(element, kAXParentAttribute) |
| 46 | } |
| 47 | return false |
| 48 | } |
| 49 | |
| 50 | private func containsFileBrowser(_ element: AXUIElement) -> Bool { |
| 51 | var pending = fileChildren(element) |
| 52 | var visited = 0 |
| 53 | while !pending.isEmpty && visited < 1024 { |
| 54 | let child = pending.removeLast() |
| 55 | visited += 1 |
| 56 | if [kAXOutlineRole, kAXBrowserRole, kAXTableRole].contains(fileAttribute(child, kAXRoleAttribute) as? String ?? "") { return true } |
| 57 | pending.append(contentsOf: fileChildren(child)) |
| 58 | } |
| 59 | return false |
| 60 | } |
| 61 | |
| 62 | private func selectedFilePaths(_ panel: AXUIElement, expected: Set<String>) -> Set<String> { |
| 63 | var pending = [panel], selected: [AXUIElement] = [] |
| 64 | var visited = 0 |
| 65 | while !pending.isEmpty && visited < 2048 { |
| 66 | let element = pending.removeLast() |
| 67 | visited += 1 |
| 68 | selected.append(contentsOf: fileAttribute(element, kAXSelectedRowsAttribute) as? [AXUIElement] ?? []) |
| 69 | selected.append(contentsOf: fileAttribute(element, kAXSelectedChildrenAttribute) as? [AXUIElement] ?? []) |
| 70 | pending.append(contentsOf: fileChildren(element)) |
| 71 | } |
| 72 | var paths = Set<String>() |
| 73 | func selectedPath(_ value: String) { |
| 74 | let path: String |
| 75 | if let canonical = realpath(value, nil) { |
| 76 | path = String(cString: canonical); free(canonical) |
| 77 | } else { path = URL(fileURLWithPath: value).standardizedFileURL.path } |
| 78 | let prefix = path.hasSuffix("/") ? path : path + "/" |
| 79 | |
| 80 | |
| 81 | if expected.contains(where: { $0.hasPrefix(prefix) }) { return } |
| 82 | paths.insert(path) |
| 83 | } |
| 84 | visited = 0 |
| 85 | while !selected.isEmpty && visited < 4096 { |
| 86 | let element = selected.removeLast() |
| 87 | visited += 1 |
| 88 | for attribute in [kAXURLAttribute, kAXValueAttribute] { |
| 89 | let raw = fileAttribute(element, attribute) |
| 90 | if let url = raw as? URL, url.isFileURL { selectedPath(url.path) } |
| 91 | if let value = raw as? String { |
| 92 | if value.hasPrefix("/") { selectedPath(value) } |
| 93 | if let url = URL(string: value), url.isFileURL { selectedPath(url.path) } |
| 94 | } |
| 95 | } |
| 96 | selected.append(contentsOf: fileChildren(element)) |
| 97 | } |
| 98 | return paths |
| 99 | } |
| 100 | |
| 101 | private func openFilePanel(_ pid: pid_t) -> AXUIElement? { |
| 102 | var pending = fileAttribute(AXUIElementCreateApplication(pid), kAXWindowsAttribute) as? [AXUIElement] ?? [] |
| 103 | var visited = 0 |
| 104 | while !pending.isEmpty && visited < 2048 { |
| 105 | let element = pending.removeLast() |
| 106 | visited += 1 |
| 107 | let role = fileAttribute(element, kAXRoleAttribute) as? String |
| 108 | let subrole = fileAttribute(element, kAXSubroleAttribute) as? String |
| 109 | if role == kAXSheetRole || subrole == kAXDialogSubrole, |
| 110 | let button = filePanelButton(element), filePanelButton(element, cancel: true) != nil, |
| 111 | let title = fileAttribute(button, kAXTitleAttribute) as? String, |
| 112 | ["Open", "Choose", "Select", "打开", "開啟", "选择", "選擇"].contains(title), containsFileBrowser(element) { |
| 113 | return element |
| 114 | } |
| 115 | pending.append(contentsOf: fileChildren(element)) |
| 116 | } |
| 117 | return nil |
| 118 | } |
| 119 | |
| 120 | private func saveFilePanel(_ pid: pid_t) -> (AXUIElement, AXUIElement)? { |
| 121 | var pending = fileAttribute(AXUIElementCreateApplication(pid), kAXWindowsAttribute) as? [AXUIElement] ?? [] |
| 122 | var visited = 0 |
| 123 | while !pending.isEmpty && visited < 2048 { |
| 124 | let panel = pending.removeLast() |
| 125 | visited += 1 |
| 126 | let role = fileAttribute(panel, kAXRoleAttribute) as? String |
| 127 | let subrole = fileAttribute(panel, kAXSubroleAttribute) as? String |
| 128 | if (role == kAXSheetRole || subrole == kAXDialogSubrole), |
| 129 | let button = filePanelButton(panel), |
| 130 | let title = fileAttribute(button, kAXTitleAttribute) as? String, |
| 131 | ["Save", "保存", "儲存", "Enregistrer", "Sichern", "Guardar", "Сохранить", "저장"].contains(title), |
| 132 | filePanelButton(panel, cancel: true) != nil { |
| 133 | var children = fileChildren(panel), count = 0 |
| 134 | while count < children.count && count < 1024 { |
| 135 | let element = children[count] |
| 136 | count += 1 |
| 137 | if fileAttribute(element, kAXRoleAttribute) as? String == kAXTextFieldRole, |
| 138 | fileAttribute(element, "AXIdentifier") as? String == "saveAsNameTextField", |
| 139 | let name = fileAttribute(element, kAXValueAttribute) as? String, MacDesktopDownloads.validName(name) { |
| 140 | return (panel, element) |
| 141 | } |
| 142 | children.append(contentsOf: fileChildren(element)) |
| 143 | } |
| 144 | } |
| 145 | pending.append(contentsOf: fileChildren(panel)) |
| 146 | } |
| 147 | return nil |
| 148 | } |
| 149 | |
| 150 | private func clipboardRequest(_ request: [String: Any]) async throws -> [String: Any] { |
| 151 | let data = try JSONSerialization.data(withJSONObject: request) + Data([10]) |
| 152 | guard data.count <= 30 * 1024 * 1024 else { throw Failure(8, "attachment_size_limit") } |
| 153 | return try await withCheckedThrowingContinuation { continuation in |
| 154 | DispatchQueue.global(qos: .userInitiated).async { |
| 155 | let process = Process() |
| 156 | process.executableURL = URL(fileURLWithPath: "/Applications/Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard") |
| 157 | process.arguments = ["--client", "request"] |
| 158 | let input = Pipe(), output = Pipe() |
| 159 | process.standardInput = input |
| 160 | process.standardOutput = output |
| 161 | process.standardError = FileHandle.nullDevice |
| 162 | let timeout = DispatchWorkItem { if process.isRunning { process.terminate() } } |
| 163 | defer { timeout.cancel(); try? input.fileHandleForWriting.close(); if process.isRunning { process.terminate() } } |
| 164 | do { |
| 165 | try process.run() |
| 166 | DispatchQueue.global().asyncAfter(deadline: .now() + 15, execute: timeout) |
| 167 | try input.fileHandleForWriting.write(contentsOf: data) |
| 168 | try input.fileHandleForWriting.close() |
| 169 | var reply = Data() |
| 170 | while let chunk = try output.fileHandleForReading.read(upToCount: 4096), !chunk.isEmpty { |
| 171 | reply.append(chunk) |
| 172 | guard reply.count <= 65536 else { throw Failure(7, "clipboard_reply_invalid") } |
| 173 | } |
| 174 | process.waitUntilExit() |
| 175 | guard process.terminationStatus == 0, |
| 176 | let value = try JSONSerialization.jsonObject(with: reply) as? [String: Any], value["error"] == nil else { |
| 177 | throw Failure(7, "clipboard_operation_failed") |
| 178 | } |
| 179 | continuation.resume(returning: value) |
| 180 | } catch { continuation.resume(throwing: error) } |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | @MainActor |
| 186 | final class MacDesktopFiles { |
| 187 | static let shared = MacDesktopFiles() |
| 188 | private final class Batch { |
| 189 | let pid: pid_t |
| 190 | let window: CGWindowID |
| 191 | let kind: String |
| 192 | let panel: AXUIElement? |
| 193 | let focusedWindow: AXUIElement? |
| 194 | let focusedElement: AXUIElement? |
| 195 | let epoch: UInt64 |
| 196 | let created = Date() |
| 197 | var files: [String] = [] |
| 198 | var busy = false |
| 199 | init(pid: pid_t, window: CGWindowID, kind: String, epoch: UInt64, panel: AXUIElement? = nil) { |
| 200 | self.pid = pid; self.window = window; self.kind = kind; self.panel = panel |
| 201 | self.epoch = epoch |
| 202 | if let value = fileAttribute(AXUIElementCreateApplication(pid), kAXFocusedWindowAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() { |
| 203 | focusedWindow = (value as! AXUIElement) |
| 204 | } else { focusedWindow = nil } |
| 205 | if let value = fileAttribute(AXUIElementCreateApplication(pid), kAXFocusedUIElementAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() { |
| 206 | focusedElement = (value as! AXUIElement) |
| 207 | } else { focusedElement = nil } |
| 208 | } |
| 209 | } |
| 210 | private var batches: [String: Batch] = [:] |
| 211 | private var savingPanel: AXUIElement? |
| 212 | private struct OpenRequest { |
| 213 | let path: String |
| 214 | let action: String |
| 215 | let epoch: UInt64 |
| 216 | let validate: () throws -> Void |
| 217 | let created = Date() |
| 218 | var claimed = false |
| 219 | } |
| 220 | private var opens: [String: OpenRequest] = [:] |
| 221 | |
| 222 | private func expireOpens() { |
| 223 | let epoch = try? MacGUISession.shared.validate() |
| 224 | opens = opens.filter { _, request in |
| 225 | epoch == request.epoch && Date().timeIntervalSince(request.created) < (request.claimed ? 1800 : 60) |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | func queueOpen(path: String, action: String, validate: @escaping () throws -> Void) throws { |
| 230 | try queueOpen(paths: [path], action: action, validate: validate) |
| 231 | } |
| 232 | |
| 233 | func queueOpen(paths: [String], action: String, validate: @escaping () throws -> Void) throws { |
| 234 | guard !paths.isEmpty, paths.count <= 32, paths.allSatisfy({ ($0 as NSString).isAbsolutePath && $0.utf8.count <= 32768 && !$0.contains("\0") }), |
| 235 | ["open", "reveal"].contains(action) else { throw Failure(8, "file_open_request_invalid") } |
| 236 | let epoch = try MacGUISession.shared.validate() |
| 237 | expireOpens(); try validate() |
| 238 | guard opens.count + paths.count <= 32 else { throw Failure(8, "file_open_request_limit") } |
| 239 | for path in paths { |
| 240 | opens[UUID().uuidString.lowercased()] = OpenRequest(path: URL(fileURLWithPath: path).standardizedFileURL.path, action: action, epoch: epoch, validate: validate) |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | func openSnapshot() -> [[String: String]] { |
| 245 | expireOpens() |
| 246 | return opens.filter { !$0.value.claimed }.map { ["id": $0.key] } |
| 247 | } |
| 248 | |
| 249 | func openAction(_ id: String, complete: Bool) throws -> [String: Any] { |
| 250 | expireOpens() |
| 251 | guard var request = opens[id] else { return [complete ? "ok" : "handled": true] } |
| 252 | if complete { |
| 253 | opens.removeValue(forKey: id) |
| 254 | try? request.validate() |
| 255 | return ["ok": true] |
| 256 | } |
| 257 | if request.claimed { return ["handled": true] } |
| 258 | do { try request.validate() } |
| 259 | catch { opens.removeValue(forKey: id); throw Failure(7, "file_open_target_changed") } |
| 260 | var result: [String: Any] = ["id": id, "action": request.action] |
| 261 | if let download = try MacDesktopDownloads.shared.find(path: request.path) { |
| 262 | result["download_id"] = download.id; result["directory"] = download.directory |
| 263 | } else { result["path"] = request.path } |
| 264 | request.claimed = true; opens[id] = request |
| 265 | return result |
| 266 | } |
| 267 | |
| 268 | private func valid(_ batch: Batch) throws { |
| 269 | try consoleUser() |
| 270 | try MacGUISession.shared.validate(batch.epoch) |
| 271 | guard AXIsProcessTrusted() else { throw Failure(9, "accessibility_permission") } |
| 272 | guard Date().timeIntervalSince(batch.created) < 1800, try claudePIDs().contains(batch.pid), |
| 273 | NSWorkspace.shared.frontmostApplication?.processIdentifier == batch.pid else { throw Failure(7, "window_changed") } |
| 274 | if let panel = batch.panel { |
| 275 | guard filePanelPresent(panel, pid: batch.pid), filePanelFocused(panel, pid: batch.pid) else { throw Failure(7, "file_dialog_changed") } |
| 276 | } else { |
| 277 | let windows = CGWindowListCopyWindowInfo([.optionIncludingWindow], batch.window) as? [[String: Any]] |
| 278 | guard let window = windows?.first, window[kCGWindowOwnerPID as String] as? Int32 == batch.pid, |
| 279 | window[kCGWindowIsOnscreen as String] as? Bool == true else { throw Failure(7, "window_changed") } |
| 280 | guard let focused = fileAttribute(AXUIElementCreateApplication(batch.pid), kAXFocusedWindowAttribute), |
| 281 | let original = batch.focusedWindow, CFEqual(focused, original), |
| 282 | let input = fileAttribute(AXUIElementCreateApplication(batch.pid), kAXFocusedUIElementAttribute), |
| 283 | let originalInput = batch.focusedElement, CFEqual(input, originalInput), |
| 284 | let position = fileAttribute(original, kAXPositionAttribute), CFGetTypeID(position) == AXValueGetTypeID(), |
| 285 | let size = fileAttribute(original, kAXSizeAttribute), CFGetTypeID(size) == AXValueGetTypeID(), |
| 286 | let bounds = window[kCGWindowBounds as String] as? [String: Any], |
| 287 | let frame = CGRect(dictionaryRepresentation: bounds as CFDictionary) else { throw Failure(7, "window_changed") } |
| 288 | var origin = CGPoint.zero, extent = CGSize.zero |
| 289 | guard AXValueGetValue(position as! AXValue, .cgPoint, &origin), AXValueGetValue(size as! AXValue, .cgSize, &extent), |
| 290 | abs(origin.x - frame.minX) < 2, abs(origin.y - frame.minY) < 2, |
| 291 | abs(extent.width - frame.width) < 2, abs(extent.height - frame.height) < 2 else { throw Failure(7, "window_changed") } |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | private func batch(_ id: String) throws -> Batch { |
| 296 | guard UUID(uuidString: id) != nil, let value = batches[id] else { throw Failure(8, "attachment_request_invalid") } |
| 297 | try valid(value) |
| 298 | return value |
| 299 | } |
| 300 | |
| 301 | private func key(_ pid: pid_t, _ code: CGKeyCode, flags: CGEventFlags = [], panel: AXUIElement? = nil, epoch: UInt64? = nil) throws { |
| 302 | guard AXIsProcessTrusted(), try claudePIDs().contains(pid), NSWorkspace.shared.frontmostApplication?.processIdentifier == pid else { |
| 303 | throw Failure(7, "window_changed") |
| 304 | } |
| 305 | let source = CGEventSource(stateID: .privateState) |
| 306 | for down in [true, false] { |
| 307 | try consoleUser() |
| 308 | try MacGUISession.shared.validate(epoch) |
| 309 | guard NSWorkspace.shared.frontmostApplication?.processIdentifier == pid, |
| 310 | panel.map({ filePanelPresent($0, pid: pid) && filePanelFocused($0, pid: pid) }) ?? true else { throw Failure(7, "file_dialog_changed") } |
| 311 | guard let event = CGEvent(keyboardEventSource: source, virtualKey: code, keyDown: down) else { throw Failure(8, "input_failed") } |
| 312 | event.flags = flags |
| 313 | if panel != nil { |
| 314 | |
| 315 | |
| 316 | guard CGPreflightPostEventAccess() else { throw Failure(9, "accessibility_permission") } |
| 317 | event.post(tap: .cghidEventTap) |
| 318 | } else { event.postToPid(pid) } |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | func start(window: SCWindow, kind: String) throws -> [String: Any] { |
| 323 | guard ["paste", "drop", "image"].contains(kind), let pid = window.owningApplication?.processID else { throw Failure(8, "attachment_request_invalid") } |
| 324 | for (id, value) in batches where Date().timeIntervalSince(value.created) >= 1800 { |
| 325 | batches.removeValue(forKey: id) |
| 326 | if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } } |
| 327 | } |
| 328 | guard batches.count < 12 else { throw Failure(8, "attachment_limit") } |
| 329 | let value = Batch(pid: pid, window: window.windowID, kind: kind, epoch: try MacGUISession.shared.validate()) |
| 330 | try valid(value) |
| 331 | let id = UUID().uuidString.lowercased() |
| 332 | batches[id] = value |
| 333 | return ["ok": true, "id": id] |
| 334 | } |
| 335 | |
| 336 | func add(_ id: String, files: [String]) throws -> [String: Any] { |
| 337 | let value = try batch(id) |
| 338 | guard !value.busy, !files.isEmpty, value.files.count + files.count <= 100 else { throw Failure(8, "attachment_limit") } |
| 339 | for path in files { |
| 340 | var info = stat() |
| 341 | let url = URL(fileURLWithPath: path) |
| 342 | guard url.standardizedFileURL.path == path, path.hasPrefix("/"), !path.contains("\0"), |
| 343 | url.deletingLastPathComponent().lastPathComponent.hasPrefix("cage-clipboard-"), |
| 344 | lstat(path, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_size <= 2 * 1024 * 1024 * 1024 else { |
| 345 | throw Failure(8, "attachment_path_invalid") |
| 346 | } |
| 347 | } |
| 348 | value.files.append(contentsOf: files) |
| 349 | return ["ok": true, "id": id] |
| 350 | } |
| 351 | |
| 352 | func validate(_ id: String) throws -> [String: Any] { |
| 353 | let value = try batch(id) |
| 354 | guard !value.busy else { throw Failure(8, "attachment_busy") } |
| 355 | return ["ok": true] |
| 356 | } |
| 357 | |
| 358 | func cancel(_ id: String) async -> [String: Any] { |
| 359 | guard let value = batches.removeValue(forKey: id) else { return ["ok": true] } |
| 360 | if let panel = value.panel, (try? valid(value)) != nil, |
| 361 | let button = filePanelButton(panel, cancel: true) { |
| 362 | _ = AXUIElementPerformAction(button, kAXPressAction as CFString) |
| 363 | } |
| 364 | if !value.files.isEmpty { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } |
| 365 | return ["ok": true] |
| 366 | } |
| 367 | |
| 368 | func finish(_ id: String) async throws -> [String: Any] { |
| 369 | let value = try batch(id) |
| 370 | guard value.kind != "image", !value.busy, !value.files.isEmpty else { throw Failure(8, "attachment_incomplete") } |
| 371 | value.busy = true |
| 372 | defer { value.busy = false } |
| 373 | if let panel = value.panel { |
| 374 | |
| 375 | |
| 376 | let copied = try await clipboardRequest(["operation": "prepare-files", "files": value.files]) |
| 377 | guard let files = copied["paths"] as? [String], files.count == value.files.count, !files.isEmpty else { throw Failure(7, "clipboard_reply_invalid") } |
| 378 | guard batches[id] === value else { |
| 379 | _ = try? await clipboardRequest(["operation": "discard", "files": files]) |
| 380 | throw Failure(8, "attachment_cancelled") |
| 381 | } |
| 382 | let previous = value.files |
| 383 | value.files = files |
| 384 | _ = try? await clipboardRequest(["operation": "discard", "files": previous]) |
| 385 | guard batches[id] === value else { throw Failure(8, "attachment_cancelled") } |
| 386 | try valid(value) |
| 387 | try key(value.pid, 5, flags: [.maskCommand, .maskShift], panel: panel, epoch: value.epoch) |
| 388 | let app = AXUIElementCreateApplication(value.pid) |
| 389 | var field: AXUIElement? |
| 390 | for _ in 0..<20 { |
| 391 | try await Task.sleep(nanoseconds: 100_000_000) |
| 392 | guard batches[id] === value else { throw Failure(8, "attachment_cancelled") } |
| 393 | try valid(value) |
| 394 | if let focus = fileAttribute(app, kAXFocusedUIElementAttribute), CFGetTypeID(focus) == AXUIElementGetTypeID(), |
| 395 | [kAXTextFieldRole, kAXComboBoxRole].contains(fileAttribute(focus as! AXUIElement, kAXRoleAttribute) as? String ?? "") { |
| 396 | field = (focus as! AXUIElement); break |
| 397 | } |
| 398 | } |
| 399 | let destination = files.count == 1 ? files[0] : (files[0] as NSString).deletingLastPathComponent |
| 400 | guard let field, AXUIElementSetAttributeValue(field, kAXValueAttribute as CFString, destination as CFString) == .success else { |
| 401 | throw Failure(7, "file_dialog_navigation_failed") |
| 402 | } |
| 403 | try key(value.pid, 36, panel: panel, epoch: value.epoch) |
| 404 | var resolved = false |
| 405 | for _ in 0..<20 { |
| 406 | try await Task.sleep(nanoseconds: 100_000_000) |
| 407 | guard batches[id] === value else { throw Failure(8, "attachment_cancelled") } |
| 408 | try valid(value) |
| 409 | if let focus = fileAttribute(app, kAXFocusedUIElementAttribute), !CFEqual(focus, field) { resolved = true; break } |
| 410 | } |
| 411 | guard resolved else { throw Failure(7, "file_dialog_navigation_failed") } |
| 412 | if files.count > 1 { |
| 413 | try key(value.pid, 0, flags: .maskCommand, panel: panel, epoch: value.epoch) |
| 414 | try await Task.sleep(nanoseconds: 150_000_000) |
| 415 | guard batches[id] === value else { throw Failure(8, "attachment_cancelled") } |
| 416 | try valid(value) |
| 417 | } |
| 418 | let expected = try Set(files.map { path -> String in |
| 419 | guard let resolved = realpath(path, nil) else { throw Failure(7, "file_dialog_selection_mismatch") } |
| 420 | defer { free(resolved) } |
| 421 | return String(cString: resolved) |
| 422 | }) |
| 423 | guard selectedFilePaths(panel, expected: expected) == expected else { throw Failure(7, "file_dialog_selection_mismatch") } |
| 424 | guard let button = filePanelButton(panel), |
| 425 | fileAttribute(button, kAXEnabledAttribute) as? Bool == true, |
| 426 | AXUIElementPerformAction(button, kAXPressAction as CFString) == .success else { |
| 427 | throw Failure(7, "file_dialog_navigation_failed") |
| 428 | } |
| 429 | var accepted = false |
| 430 | for _ in 0..<20 { |
| 431 | try await Task.sleep(nanoseconds: 100_000_000) |
| 432 | if let current = openFilePanel(value.pid), CFEqual(current, panel) { continue } |
| 433 | accepted = true; break |
| 434 | } |
| 435 | guard accepted else { throw Failure(7, "file_dialog_still_open") } |
| 436 | } else { |
| 437 | let written = try await clipboardRequest(["operation": "write", "files": value.files]) |
| 438 | guard batches[id] === value, let revision = written["revision"] as? Int, NSPasteboard.general.changeCount == revision else { |
| 439 | throw Failure(8, "attachment_cancelled") |
| 440 | } |
| 441 | try valid(value) |
| 442 | try key(value.pid, 9, flags: .maskCommand) |
| 443 | } |
| 444 | batches.removeValue(forKey: id) |
| 445 | return ["ok": true] |
| 446 | } |
| 447 | |
| 448 | private func save(_ panel: AXUIElement, field: AXUIElement, pid: pid_t, path: String, epoch: UInt64) async throws { |
| 449 | func validate() throws { |
| 450 | try MacGUISession.shared.validate(epoch) |
| 451 | guard AXIsProcessTrusted(), try claudePIDs().contains(pid), NSWorkspace.shared.frontmostApplication?.processIdentifier == pid, |
| 452 | filePanelPresent(panel, pid: pid), filePanelFocused(panel, pid: pid) else { throw Failure(7, "file_dialog_changed") } |
| 453 | } |
| 454 | try validate() |
| 455 | try key(pid, 5, flags: [.maskCommand, .maskShift], panel: panel, epoch: epoch) |
| 456 | let app = AXUIElementCreateApplication(pid) |
| 457 | var location: AXUIElement? |
| 458 | for _ in 0..<20 { |
| 459 | try await Task.sleep(nanoseconds: 100_000_000) |
| 460 | try validate() |
| 461 | if let focus = fileAttribute(app, kAXFocusedUIElementAttribute), CFGetTypeID(focus) == AXUIElementGetTypeID(), |
| 462 | !CFEqual(focus, field), [kAXTextFieldRole, kAXComboBoxRole].contains(fileAttribute(focus as! AXUIElement, kAXRoleAttribute) as? String ?? "") { |
| 463 | location = (focus as! AXUIElement); break |
| 464 | } |
| 465 | } |
| 466 | guard let location, AXUIElementSetAttributeValue(location, kAXValueAttribute as CFString, (path as NSString).deletingLastPathComponent as CFString) == .success else { |
| 467 | throw Failure(7, "file_dialog_navigation_failed") |
| 468 | } |
| 469 | try key(pid, 36, panel: panel, epoch: epoch) |
| 470 | var resolved = false |
| 471 | for _ in 0..<20 { |
| 472 | try await Task.sleep(nanoseconds: 100_000_000) |
| 473 | try validate() |
| 474 | if let focus = fileAttribute(app, kAXFocusedUIElementAttribute), !CFEqual(focus, location) { resolved = true; break } |
| 475 | } |
| 476 | guard resolved, AXUIElementSetAttributeValue(field, kAXValueAttribute as CFString, (path as NSString).lastPathComponent as CFString) == .success, |
| 477 | let button = filePanelButton(panel), |
| 478 | fileAttribute(button, kAXEnabledAttribute) as? Bool == true else { throw Failure(7, "file_dialog_navigation_failed") } |
| 479 | try validate() |
| 480 | guard AXUIElementPerformAction(button, kAXPressAction as CFString) == .success else { throw Failure(7, "file_dialog_navigation_failed") } |
| 481 | for _ in 0..<20 { |
| 482 | try await Task.sleep(nanoseconds: 100_000_000) |
| 483 | if let current = saveFilePanel(pid), CFEqual(current.0, panel) { continue } |
| 484 | return |
| 485 | } |
| 486 | throw Failure(7, "file_dialog_still_open") |
| 487 | } |
| 488 | |
| 489 | func poll() async throws -> [String: Any] { |
| 490 | let epoch = try MacGUISession.shared.validate() |
| 491 | for (id, value) in batches where value.epoch != epoch || Date().timeIntervalSince(value.created) >= 1800 { |
| 492 | batches.removeValue(forKey: id) |
| 493 | if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } } |
| 494 | } |
| 495 | guard AXIsProcessTrusted(), let pid = try? claudePIDs().first else { |
| 496 | return ["available": false, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "downloadAck": true, "opens": openSnapshot()] |
| 497 | } |
| 498 | if let (panel, field) = saveFilePanel(pid) { |
| 499 | if savingPanel == nil || !CFEqual(savingPanel!, panel) { |
| 500 | savingPanel = panel |
| 501 | let name = fileAttribute(field, kAXValueAttribute) as? String ?? "" |
| 502 | try await MacDesktopDownloads.shared.reserve(name: name, pid: pid) { path in |
| 503 | try await self.save(panel, field: field, pid: pid, path: path, epoch: epoch) |
| 504 | } |
| 505 | } |
| 506 | } else { savingPanel = nil } |
| 507 | guard let panel = openFilePanel(pid) else { |
| 508 | for (id, value) in batches where value.panel != nil && !value.busy { |
| 509 | batches.removeValue(forKey: id) |
| 510 | if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } } |
| 511 | } |
| 512 | return ["available": true, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "downloadAck": true, "opens": openSnapshot()] |
| 513 | } |
| 514 | let existing = batches.first { $0.value.pid == pid && $0.value.panel.map { CFEqual($0, panel) } == true } |
| 515 | let id: String |
| 516 | if let existing { id = existing.key } |
| 517 | else { |
| 518 | guard batches.count < 12 else { throw Failure(8, "attachment_limit") } |
| 519 | id = UUID().uuidString.lowercased() |
| 520 | batches[id] = Batch(pid: pid, window: 0, kind: "chooser", epoch: try MacGUISession.shared.validate(), panel: panel) |
| 521 | } |
| 522 | return ["available": true, "uploads": [["id": id, "kind": "chooser", "multiple": true, "directory": false, "target": "desktop"]], "downloads": try MacDesktopDownloads.shared.snapshot(), "downloadAck": true, "opens": openSnapshot()] |
| 523 | } |
| 524 | |
| 525 | func pasteImage(_ data: Data, window: SCWindow) async throws -> [String: Any] { |
| 526 | guard data.count <= 20 * 1024 * 1024, let pid = window.owningApplication?.processID else { throw Failure(8, "attachment_size_limit") } |
| 527 | let value = Batch(pid: pid, window: window.windowID, kind: "paste", epoch: try MacGUISession.shared.validate()) |
| 528 | return try await deliverImage(data, batch: value) |
| 529 | } |
| 530 | |
| 531 | func finishImage(_ id: String) async throws -> [String: Any] { |
| 532 | let value = try batch(id) |
| 533 | guard value.kind == "image", !value.busy, value.files.count == 1 else { throw Failure(8, "attachment_incomplete") } |
| 534 | value.busy = true |
| 535 | do { |
| 536 | let file = try FileHandle(forReadingFrom: URL(fileURLWithPath: value.files[0])) |
| 537 | defer { try? file.close() } |
| 538 | let data = try file.read(upToCount: 20 * 1024 * 1024 + 1) ?? Data() |
| 539 | guard !data.isEmpty, data.count <= 20 * 1024 * 1024 else { throw Failure(8, "attachment_size_limit") } |
| 540 | let result = try await deliverImage(data, batch: value) |
| 541 | _ = await cancel(id) |
| 542 | return result |
| 543 | } catch { |
| 544 | _ = await cancel(id) |
| 545 | throw error |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | private func deliverImage(_ data: Data, batch value: Batch) async throws -> [String: Any] { |
| 550 | try valid(value) |
| 551 | let written = try await clipboardRequest(["operation": "write", "png": data.base64EncodedString()]) |
| 552 | guard let revision = written["revision"] as? Int, NSPasteboard.general.changeCount == revision else { throw Failure(8, "attachment_cancelled") } |
| 553 | try valid(value) |
| 554 | try key(value.pid, 9, flags: .maskCommand, epoch: value.epoch) |
| 555 | return ["ok": true] |
| 556 | } |
| 557 | } |