import AppKit import Darwin import Foundation import RealityDriverSupport struct RealityFixturePassThroughInterception: Error, CustomStringConvertible { let detail: String var description: String { "Reality driver: \(detail)" } static func fromMessage(_ message: String) -> Self? { let signal = "Expected FixtureApp pass-through was intercepted" guard message == signal || message.hasPrefix(signal + ";") else { return nil } return Self(detail: message) } } @MainActor final class RealityDriver { let appURL: URL private(set) var host: NSRunningApplication? private var listener: DriverSocket? private var connection: DriverSocket? private var directory: URL? private var storage: RealityStorage? private var pending = Data() private var exchanging = false private var nextID: UInt64 = 1 private let exchangeAuditID = UUID().uuidString var auditURL: URL? private(set) var inputAudit: [RealityInputAudit] = [] init(appURL: URL) { self.appURL = appURL } func start() async throws { guard host == nil else { return } let helper = appURL.appendingPathComponent("Contents/Helpers/ParcelRealityDriver") guard FileManager.default.isExecutableFile(atPath: helper.path) else { throw RealityError("Missing embedded reality driver: \(appURL.path); build it with mise run reality") } let directory = URL(fileURLWithPath: "/tmp/prd-\(UUID().uuidString.prefix(8))", isDirectory: true) .resolvingSymlinksInPath() try FileManager.default.createDirectory( at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) self.directory = directory let path = directory.appendingPathComponent("driver.sock").path listener = try DriverSocket.listen(path: path) let configuration = NSWorkspace.OpenConfiguration() configuration.activates = false configuration.addsToRecentItems = false configuration.createsNewApplicationInstance = true let storage = try RealityStorage(parent: directory) self.storage = storage configuration.arguments = ["--reality-driver-host"] configuration.environment = storage.environment.merging(["PARCEL_REALITY_DRIVER_SOCKET": path]) { _, value in value } host = try await NSWorkspace.shared.openApplication(at: appURL, configuration: configuration) guard host?.bundleURL?.resolvingSymlinksInPath() == appURL.resolvingSymlinksInPath() else { throw RealityError("Safety stop: Launch Services did not open the requested reality host") } let deadline = ContinuousClock.now.advanced(by: .seconds(15)) while ContinuousClock.now < deadline { guard host?.isTerminated == false else { throw RealityError("Reality host exited before connecting") } if let connection = try listener?.accept() { self.connection = connection let fd = connection.handle.fileDescriptor guard fcntl(fd, F_SETFL, O_NONBLOCK) == 0 else { throw RealityError("Cannot make driver socket nonblocking: \(errno)") } return } try await Task.sleep(for: .milliseconds(10)) } throw RealityError("Reality host did not connect; this must be a reality-only debug bundle") } func send(_ command: DriverCommand, timeout: Duration = .seconds(15)) async throws -> DriverResponse { let input: Bool switch command { case .key, .heldKeys, .drag, .recoverKey, .pressTourTidy, .clickTourTidy: input = true default: input = false } if input { if auditURL != nil { try requireObservedEffects() } try await preflight() } let id = nextID nextID += 1 var data = try JSONEncoder().encode(DriverRequest(id: id, command: command)) data.append(10) if input { inputAudit.append(RealityInputAudit(id: id, command: command, receipts: [], outcome: .pending)) try writeInputAudit() } do { let response = try await exchange(data, id: id, timeout: timeout) if input { guard response.error != nil || response.input?.isEmpty == false else { throw RealityError("Safety stop: driver omitted the input target/outcome receipt") } inputAudit[inputAudit.count - 1] = RealityInputAudit( id: id, command: command, receipts: response.input ?? [], outcome: response.error.map(RealityInputOutcome.failed) ?? .acknowledged) try writeInputAudit() } if let error = response.error { if let interception = RealityFixturePassThroughInterception.fromMessage(error) { throw interception } throw RealityError("Reality driver: \(error)") } return response } catch { if input { inputAudit[inputAudit.count - 1].outcome = .failed(String(describing: error)) try writeInputAudit() } throw error } } func confirmObservedEffect(_ description: String) throws { guard let index = inputAudit.indices.last, inputAudit[index].outcome == .acknowledged, inputAudit[index].needsEffectVerification else { return } guard !description.isEmpty else { throw RealityError("Input effect evidence must not be empty") } inputAudit[index].observedEffect = description try writeInputAudit() } func requireObservedEffects() throws { let pending = inputAudit.filter(\.needsEffectVerification).map(\.id) guard pending.isEmpty else { throw RealityError( "Shortcut/drag effects are unverified for requests \(pending); further input withheld") } } private func writeInputAudit() throws { if let auditURL { try encodeJSON(inputAudit, to: auditURL) } } func exchange(_ data: Data, id: UInt64, timeout: Duration = .seconds(15)) async throws -> DriverResponse { guard !exchanging else { throw RealityError("Safety stop: another driver request is outstanding; input withheld") } exchanging = true defer { exchanging = false } try await start() guard let connection, host?.isTerminated == false else { throw RealityError("Safety stop: reality driver exited; external state is unverified") } try recordExchange(data, id: id, sent: false) try connection.handle.write(contentsOf: data) try recordExchange(data, id: id, sent: true) let deadline = ContinuousClock.now.advanced(by: timeout) var buffer = [UInt8](repeating: 0, count: 8192) repeat { if let newline = pending.firstIndex(of: 10) { let line = pending.prefix(upTo: newline) pending.removeSubrange(...newline) let response = try JSONDecoder().decode(DriverResponse.self, from: line) guard response.id == id else { throw RealityError("Safety stop: reality driver response ID \(response.id) does not match \(id)") } try recordExchange(data, id: id, sent: true, response: response) return response } let count = Darwin.read(connection.handle.fileDescriptor, &buffer, buffer.count) if count > 0 { pending.append(contentsOf: buffer.prefix(count)) guard pending.count <= 1_048_576 else { throw RealityError("Safety stop: reality driver response exceeded 1 MiB") } continue } if count == 0 || host?.isTerminated != false { throw RealityError("Safety stop: reality driver exited before response \(id)") } guard errno == EAGAIN || errno == EINTR else { throw RealityError("Safety stop: reality driver socket read failed: \(errno)") } try await Task.sleep(for: .milliseconds(10)) } while ContinuousClock.now < deadline throw RealityError("Safety stop: reality driver timed out responding to request \(id)") } private func recordExchange(_ data: Data, id: UInt64, sent: Bool, response: DriverResponse? = nil) throws { guard let path = ProcessInfo.processInfo.environment["PARCEL_REALITY_SPIKE_ARTIFACTS"] else { return } guard path.hasPrefix("/") else { throw RealityError("Driver exchange artifacts require an absolute directory") } struct Receipt: Codable { let request: Data let sent: Bool let response: DriverResponse? } let url = URL(fileURLWithPath: path).appendingPathComponent("input-wire-\(exchangeAuditID)-\(id).json") try encodeJSON(Receipt(request: data, sent: sent, response: response), to: url) } @discardableResult func preflight() async throws -> DriverPreflight { let response = try await send(.preflight) guard let status = response.preflight else { throw RealityError("Safety stop: reality driver omitted preflight status") } try DriverWire.requireProtocolVersion(status.protocolVersion) let peerPID = try connection?.peerPID() guard status.processID == peerPID, status.parentProcessID == host?.processIdentifier else { throw RealityError( "Safety stop: reality driver ancestry mismatch: helper=\(String(describing: status.processID)), peer=\(String(describing: peerPID)), parent=\(String(describing: status.parentProcessID)), host=\(String(describing: host?.processIdentifier))" ) } guard status.axTrusted, status.postEventAccess else { throw RealityError( "Safety stop: the embedded reality driver lacks inherited Accessibility/HID access from \(appURL.path). No consent prompt was opened." ) } return status } func inputState() async throws -> DriverInputState { let response = try await send(.inputState) guard let state = response.inputState else { throw RealityError("Safety stop: reality driver omitted combined input state") } return state } @discardableResult func register(_ window: OwnedWindow) async throws -> [String] { let response = try await send(.register(pid: window.pid, windowID: window.id)) return response.identificationWarnings ?? [] } func key(_ binding: RealityKeybinding) async throws { _ = try await send(.key(virtualKey: binding.virtualKey, flags: binding.flags.rawValue)) } static func titleBarPickup(in frame: ScreenRect) -> CGPoint { // The centered document proxy starts a file drag instead of moving the window. CGPoint(x: frame.x + min(120, frame.width / 4), y: frame.y + 12) } func drag(window: OwnedWindow, from: ScreenRect, to: ScreenRect, flags: UInt64) async throws -> [DriverFrame] { let rows = try FrameOracle.read(allLayers: true, onScreenOnly: true) if let auditURL { try encodeJSON( rows, to: auditURL.deletingLastPathComponent().appendingPathComponent("drag-pickup-windows.json")) } let pickup = Self.titleBarPickup(in: from) let response = try await send( .drag( pid: window.pid, windowID: window.id, fromX: pickup.x, fromY: pickup.y, toX: to.x + to.width / 2, toY: to.y + to.height / 2, flags: flags)) guard let frames = response.dragFrames else { throw RealityError("Driver omitted native drag frame readbacks") } return frames } func stop() async throws { var failures: [String] = [] if connection != nil, host?.isTerminated == false { do { _ = try await send(.quit, timeout: .seconds(2)) } catch { failures.append(String(describing: error)) } } do { try connection?.close() } catch { failures.append(String(describing: error)) } connection = nil if let host { let deadline = ContinuousClock.now.advanced(by: .seconds(3)) while !host.isTerminated, ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) } if !host.isTerminated { do { try await terminate(host) } catch { failures.append(String(describing: error)) } } } if host?.isTerminated != false { self.host = nil } do { try listener?.close() } catch { failures.append(String(describing: error)) } listener = nil if host == nil { do { try storage?.removePreferences() if let directory { try FileManager.default.removeItem(at: directory) } storage = nil directory = nil } catch { failures.append(String(describing: error)) } } else { failures.append("Safety stop: live reality host retains its owned storage") } pending = Data() if !failures.isEmpty { throw RealityError("Reality driver teardown: \(failures.joined(separator: "; "))") } } }