@ondeinference / xcrs-controlkit Mirror · read-only
Fork 0

Read-only mirror of github.com/ondeinference/xcrs-controlkit.

Mirrored from https://github.com/ondeinference/xcrs-controlkit.git

Synced Nov 24, 19:30 UTC

1 import Foundation
2 import NIOCore
3 import NIOHTTP1
4 import NIOPosix
5 import XCTest
6 import XCRSControlKit
7 #if os(iOS)
8 import UIKit
9 #endif
10
11 private struct JSONRPCRequest {
12 let method: String
13 let params: [String: Any]
14 let id: Any?
15 }
16
17 @MainActor
18 final class ControlKitRPCServer {
19 // MARK: - Internal
20
21 init() {
22 port = UInt16(ProcessInfo.processInfo.environment["CONTROLKIT_LISTEN_PORT"] ?? "12004") ?? 12004
23 host = ProcessInfo.processInfo.environment["CONTROLKIT_LISTEN_HOST"] ?? "127.0.0.1"
24 }
25
26 func start() async throws {
27 let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
28 defer {
29 try? group.syncShutdownGracefully()
30 }
31 let requestHandler: (HTTPMethod, String, Data) async -> Data = { [self] method, path, body in
32 if method == .GET && path == "/health" {
33 return Data("OK".utf8)
34 }
35 return await handle(body)
36 }
37 let channel = try await ServerBootstrap(group: group)
38 .serverChannelOption(ChannelOptions.backlog, value: 256)
39 .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
40 .childChannelInitializer { channel in
41 channel.pipeline.configureHTTPServerPipeline().flatMap {
42 channel.pipeline.addHandler(RPCHandler(requestHandler: requestHandler))
43 }
44 }
45 .childChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
46 .bind(host: host, port: Int(port))
47 .get()
48 try await channel.closeFuture.get()
49 }
50
51 // MARK: - Private
52
53 private static let protocolVersion = 1
54 private static let supportedMethods = [
55 "device.apps.launch",
56 "device.apps.terminate",
57 "device.capabilities",
58 "device.dump.ui",
59 "device.hinge.get",
60 "device.info",
61 "device.io.button",
62 "device.io.click",
63 "device.io.orientation.get",
64 "device.io.orientation.set",
65 "device.io.spatial.tap",
66 "device.io.swipe",
67 "device.io.tap",
68 "device.io.text",
69 "device.ui.tap"
70 ]
71
72 private static var platform: XCRSControlKitPlatform {
73 #if os(tvOS)
74 return .tvOS
75 #elseif os(visionOS)
76 return .visionOS
77 #elseif os(macOS)
78 return .macOS
79 #elseif os(watchOS)
80 return .watchOS
81 #else
82 return .iOS
83 #endif
84 }
85
86 private let port: UInt16
87 private let host: String
88
89 private func handle(_ body: Data) async -> Data {
90 do {
91 if body == Data("health".utf8) {
92 return try JSONSerialization.data(withJSONObject: ["status": "ok"])
93 }
94
95 guard
96 let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
97 let method = object["method"] as? String
98 else {
99 return try response(error: -32600, message: "Invalid Request", id: nil)
100 }
101
102 let request = JSONRPCRequest(
103 method: method,
104 params: object["params"] as? [String: Any] ?? [:],
105 id: object["id"]
106 )
107 return try await dispatch(request)
108 } catch {
109 return (try? response(error: -32603, message: error.localizedDescription, id: nil)) ?? Data()
110 }
111 }
112
113 private func dispatch(_ request: JSONRPCRequest) async throws -> Data {
114 switch request.method {
115 case "device.capabilities":
116 var capabilities = XCRSControlKitCapabilities.standard(for: Self.platform).values
117 if await hingeSnapshot() != nil {
118 capabilities.insert(.hinge)
119 }
120 return try response(
121 result: [
122 "platform": Self.platform.rawValue,
123 "capabilities": capabilities.map(\.rawValue).sorted(),
124 "methods": Self.supportedMethods
125 ],
126 id: request.id
127 )
128 case "device.info":
129 return try response(
130 result: [
131 "port": port,
132 "runner": "XCRSControlKit",
133 "protocolVersion": Self.protocolVersion,
134 "methods": Self.supportedMethods
135 ],
136 id: request.id
137 )
138 case "device.dump.ui":
139 let bundleIdentifier = try stringParameter("bundleId", request.params)
140 let application = XCUIApplication(bundleIdentifier: bundleIdentifier)
141 let hierarchy = try accessibilityHierarchy(
142 application,
143 bundleIdentifier: bundleIdentifier
144 )
145 return try response(result: dictionary(hierarchy), id: request.id)
146 case "device.ui.tap":
147 let bundleIdentifier = try stringParameter("bundleId", request.params)
148 let element = try stringParameter("element", request.params)
149 .trimmingCharacters(in: .whitespacesAndNewlines)
150 guard !element.isEmpty else {
151 throw RunnerError.invalidParameter("element")
152 }
153 try tapElement(named: element, in: bundleIdentifier)
154 return try response(result: ["success": true], id: request.id)
155 case "device.apps.launch":
156 let bundleIdentifier = try stringParameter("bundleId", request.params)
157 let application = XCUIApplication(bundleIdentifier: bundleIdentifier)
158 application.launch()
159 return try response(result: ["success": true], id: request.id)
160 case "device.apps.terminate":
161 let bundleIdentifier = try stringParameter("bundleId", request.params)
162 XCUIApplication(bundleIdentifier: bundleIdentifier).terminate()
163 return try response(result: ["success": true], id: request.id)
164 case "device.io.tap":
165 #if os(tvOS) || os(visionOS) || os(macOS)
166 throw RunnerError.unsupportedInteraction("touch")
167 #else
168 try tap(request.params)
169 return try response(result: ["success": true], id: request.id)
170 #endif
171 case "device.io.click":
172 #if os(macOS)
173 try tap(request.params)
174 return try response(result: ["success": true], id: request.id)
175 #else
176 throw RunnerError.unsupportedInteraction("pointer click")
177 #endif
178 case "device.io.spatial.tap":
179 #if os(visionOS)
180 try tap(request.params)
181 return try response(result: ["success": true], id: request.id)
182 #else
183 throw RunnerError.unsupportedInteraction("spatial tap")
184 #endif
185 case "device.io.swipe":
186 #if os(iOS)
187 try swipe(request.params)
188 return try response(result: ["success": true], id: request.id)
189 #else
190 throw RunnerError.unsupportedInteraction("swipe")
191 #endif
192 case "device.io.orientation.get":
193 #if os(iOS)
194 return try response(
195 result: ["orientation": Self.orientationName(XCUIDevice.shared.orientation)],
196 id: request.id
197 )
198 #else
199 throw RunnerError.unsupportedInteraction("orientation")
200 #endif
201 case "device.io.orientation.set":
202 #if os(iOS)
203 let name = try stringParameter("orientation", request.params)
204 guard let orientation = Self.orientation(named: name) else {
205 throw RunnerError.invalidParameter("orientation")
206 }
207 XCUIDevice.shared.orientation = orientation
208 return try response(result: ["success": true], id: request.id)
209 #else
210 throw RunnerError.unsupportedInteraction("orientation")
211 #endif
212 case "device.hinge.get":
213 guard let hinge = await hingeSnapshot() else {
214 return try response(result: ["status": "unsupported"], id: request.id)
215 }
216 return try response(
217 result: ["status": hinge.status, "angle": hinge.angle],
218 id: request.id
219 )
220 case "device.io.text":
221 let text = try stringParameter("text", request.params)
222 foregroundApplication(request.params).typeText(text)
223 return try response(result: ["success": true], id: request.id)
224 case "device.io.button":
225 let button = try stringParameter("button", request.params)
226 #if os(tvOS)
227 let press: XCUIRemote.Button
228 switch button {
229 case "menu":
230 press = .menu
231 case "select":
232 press = .select
233 case "playPause":
234 press = .playPause
235 case "up":
236 press = .up
237 case "down":
238 press = .down
239 case "left":
240 press = .left
241 case "right":
242 press = .right
243 default:
244 throw RunnerError.unsupportedButton(button)
245 }
246 XCUIRemote.shared.press(press)
247 return try response(result: ["success": true], id: request.id)
248 #elseif os(iOS)
249 guard button == "home" else {
250 throw RunnerError.unsupportedButton(button)
251 }
252 XCUIDevice.shared.press(.home)
253 return try response(result: ["success": true], id: request.id)
254 #else
255 throw RunnerError.unsupportedButton(button)
256 #endif
257 default:
258 return try response(error: -32601, message: "Method not found", id: request.id)
259 }
260 }
261
262 private func foregroundApplication(_ params: [String: Any]) -> XCUIApplication {
263 if let bundleIdentifier = params["bundleId"] as? String {
264 return XCUIApplication(bundleIdentifier: bundleIdentifier)
265 }
266 return XCUIApplication()
267 }
268
269 private func accessibilityHierarchy(
270 _ application: XCUIApplication,
271 bundleIdentifier: String
272 ) throws -> XCRSControlKitAccessibilityNode {
273 guard application.state == .runningForeground else {
274 throw RunnerError.applicationNotInForeground(bundleIdentifier)
275 }
276 let debugDescription = application.debugDescription
277 guard application.state == .runningForeground else {
278 throw RunnerError.applicationNotInForeground(bundleIdentifier)
279 }
280 return try XCRSControlKitAccessibilityParser.parse(
281 debugDescription: debugDescription
282 )
283 }
284
285 private func tapElement(named element: String, in bundleIdentifier: String) throws {
286 let application = XCUIApplication(bundleIdentifier: bundleIdentifier)
287 guard application.state == .runningForeground else {
288 throw RunnerError.applicationNotInForeground(bundleIdentifier)
289 }
290 let predicate = NSPredicate(
291 format: "label == %@ OR identifier == %@ OR value == %@",
292 element,
293 element,
294 element
295 )
296 let matches = application.descendants(matching: .any).matching(predicate)
297 let matchCount = matches.count
298 guard matchCount > 0 else {
299 throw RunnerError.elementNotFound(element)
300 }
301 guard matchCount == 1 else {
302 throw RunnerError.ambiguousElement(element, matchCount)
303 }
304 try activate(matches.element(boundBy: 0), named: element)
305 }
306
307 private func activate(_ element: XCUIElement, named name: String) throws {
308 #if os(tvOS)
309 guard element.hasFocus else {
310 throw RunnerError.elementNotFocused(name)
311 }
312 XCUIRemote.shared.press(.select)
313 #else
314 guard element.isHittable else {
315 throw RunnerError.elementNotHittable(name)
316 }
317 #if os(macOS)
318 element.click()
319 #else
320 element.tap()
321 #endif
322 #endif
323 }
324
325 private func dictionary(_ node: XCRSControlKitAccessibilityNode) throws -> [String: Any] {
326 let data = try JSONEncoder().encode(node)
327 guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
328 throw RunnerError.invalidAccessibilityHierarchy
329 }
330 return object
331 }
332
333 /// Like `foregroundApplication`, but fails cleanly when the app is not running.
334 /// Querying a stopped application records an XCTest failure, which ends the
335 /// runner's only test case and takes the server down with it.
336 private func runningApplication(_ params: [String: Any]) throws -> XCUIApplication {
337 let application = foregroundApplication(params)
338 guard application.state != .notRunning else {
339 throw RunnerError.applicationNotRunning((params["bundleId"] as? String) ?? "the app under test")
340 }
341 return application
342 }
343
344 #if !os(tvOS)
345 /// Maps a point in the application's frame to an `XCUICoordinate`, clamped to the frame.
346 private func coordinate(x: Double, y: Double, in application: XCUIApplication) throws -> XCUICoordinate {
347 let frame = application.frame
348 guard frame.width > 0, frame.height > 0 else {
349 throw RunnerError.emptyFrame
350 }
351 return application.coordinate(
352 withNormalizedOffset: CGVector(
353 dx: max(0, min(1, x / Double(frame.width))),
354 dy: max(0, min(1, y / Double(frame.height)))
355 )
356 )
357 }
358
359 private func tap(_ params: [String: Any]) throws {
360 let x = try doubleParameter("x", params)
361 let y = try doubleParameter("y", params)
362 try coordinate(x: x, y: y, in: runningApplication(params)).tap()
363 }
364 #endif
365
366 #if os(iOS)
367 private func swipe(_ params: [String: Any]) throws {
368 let application = try runningApplication(params)
369 let start = try coordinate(
370 x: try doubleParameter("x1", params),
371 y: try doubleParameter("y1", params),
372 in: application
373 )
374 let end = try coordinate(
375 x: try doubleParameter("x2", params),
376 y: try doubleParameter("y2", params),
377 in: application
378 )
379 let durationMs = (try? doubleParameter("durationMs", params)) ?? 300
380 start.press(forDuration: max(0.05, durationMs / 1000), thenDragTo: end)
381 }
382
383 private static func orientationName(_ orientation: UIDeviceOrientation) -> String {
384 orientation.isLandscape ? "LANDSCAPE" : "PORTRAIT"
385 }
386
387 private static func orientation(named name: String) -> UIDeviceOrientation? {
388 switch name.uppercased() {
389 case "PORTRAIT":
390 return .portrait
391 case "LANDSCAPE":
392 return .landscapeLeft
393 default:
394 return nil
395 }
396 }
397 #endif
398
399 private struct HingeSnapshot {
400 let status: String
401 let angle: Double
402 }
403
404 /// Reads the hinge, or returns nil when this platform or device reports none.
405 private func hingeSnapshot() async -> HingeSnapshot? {
406 #if os(iOS)
407 if #available(iOS 27.1, *) {
408 guard let hinge = await HingeReader.read() else { return nil }
409 return HingeSnapshot(status: hinge.status, angle: hinge.angle)
410 }
411 #endif
412 return nil
413 }
414
415 private func stringParameter(_ name: String, _ params: [String: Any]) throws -> String {
416 guard let value = params[name] as? String, !value.isEmpty else {
417 throw RunnerError.invalidParameter(name)
418 }
419 return value
420 }
421
422 private func doubleParameter(_ name: String, _ params: [String: Any]) throws -> Double {
423 if let value = params[name] as? Double {
424 return value
425 }
426 if let value = params[name] as? NSNumber {
427 return value.doubleValue
428 }
429 throw RunnerError.invalidParameter(name)
430 }
431
432 private func response(result: [String: Any], id: Any?) throws -> Data {
433 try JSONSerialization.data(withJSONObject: [
434 "jsonrpc": "2.0",
435 "result": result,
436 "id": id ?? NSNull()
437 ])
438 }
439
440 private func response(error code: Int, message: String, id: Any?) throws -> Data {
441 try JSONSerialization.data(withJSONObject: [
442 "jsonrpc": "2.0",
443 "error": ["code": code, "message": message],
444 "id": id ?? NSNull()
445 ])
446 }
447 }
448
449 private final class RPCHandler: ChannelInboundHandler {
450 // MARK: - Internal
451
452 typealias InboundIn = HTTPServerRequestPart
453 typealias OutboundOut = HTTPServerResponsePart
454
455 init(requestHandler: @escaping (HTTPMethod, String, Data) async -> Data) {
456 self.requestHandler = requestHandler
457 }
458
459 func channelRead(context: ChannelHandlerContext, data: NIOAny) {
460 switch unwrapInboundIn(data) {
461 case .head(let head):
462 requestHead = head
463 requestBody.removeAll(keepingCapacity: true)
464 case .body(var buffer):
465 if let bytes = buffer.readBytes(length: buffer.readableBytes) {
466 requestBody.append(contentsOf: bytes)
467 }
468 case .end:
469 guard let requestHead else {
470 context.close(promise: nil)
471 return
472 }
473
474 let method = requestHead.method
475 let path = requestHead.uri
476 let body = requestBody
477 Task {
478 let responseBody = await requestHandler(method, path, body)
479 context.eventLoop.execute {
480 var headers = HTTPHeaders()
481 headers.add(name: "Content-Type", value: "application/json")
482 headers.add(name: "Content-Length", value: "\(responseBody.count)")
483 headers.add(name: "Connection", value: "close")
484 let responseHead = HTTPResponseHead(
485 version: requestHead.version,
486 status: .ok,
487 headers: headers
488 )
489 var buffer = context.channel.allocator.buffer(capacity: responseBody.count)
490 buffer.writeBytes(responseBody)
491 context.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
492 context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil)
493 context.writeAndFlush(self.wrapOutboundOut(.end(nil))).whenComplete { _ in
494 context.close(promise: nil)
495 }
496 }
497 }
498 }
499 }
500
501 // MARK: - Private
502
503 private let requestHandler: (HTTPMethod, String, Data) async -> Data
504 private var requestHead: HTTPRequestHead?
505 private var requestBody = Data()
506 }
507
508 private enum RunnerError: LocalizedError {
509 case ambiguousElement(String, Int)
510 case applicationNotRunning(String)
511 case applicationNotInForeground(String)
512 case invalidAccessibilityHierarchy
513 case invalidParameter(String)
514 case elementNotFound(String)
515 case elementNotHittable(String)
516 case emptyFrame
517 case elementNotFocused(String)
518 case unsupportedButton(String)
519 case unsupportedInteraction(String)
520
521 var errorDescription: String? {
522 switch self {
523 case .ambiguousElement(let element, let count):
524 return "Multiple accessibility elements matched \(element): \(count)"
525 case .applicationNotRunning(let application):
526 return "Application \(application) is not running"
527 case .emptyFrame:
528 return "The application frame is empty, so there is nothing to tap"
529 case .applicationNotInForeground(let bundleIdentifier):
530 return "Application is not running in the foreground: \(bundleIdentifier)"
531 case .invalidAccessibilityHierarchy:
532 return "Could not serialize the accessibility hierarchy"
533 case .invalidParameter(let name):
534 return "Missing or invalid parameter: \(name)"
535 case .elementNotFound(let element):
536 return "No accessibility element matched: \(element)"
537 case .elementNotHittable(let element):
538 return "Accessibility element is not hittable: \(element)"
539 case .elementNotFocused(let element):
540 return "Accessibility element is not focused on tvOS: \(element)"
541 case .unsupportedButton(let button):
542 return "Unsupported button: \(button)"
543 case .unsupportedInteraction(let interaction):
544 return "Unsupported interaction: \(interaction)"
545 }
546 }
547 }
548
549 #if os(iOS)
550 /// `UIHinge` is only delivered through a `UIHingeInteraction` attached to a view,
551 /// so the reader hosts a one-off view in the runner's first window scene.
552 @available(iOS 27.1, *)
553 @MainActor
554 private enum HingeReader {
555 static func read() async -> (status: String, angle: Double)? {
556 guard let scene = UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }).first else {
557 return nil
558 }
559 let window = scene.windows.first ?? UIWindow(windowScene: scene)
560 let view = UIView()
561 window.addSubview(view)
562 defer { view.removeFromSuperview() }
563
564 let result: (status: String, angle: Double)? = await withCheckedContinuation { continuation in
565 var resumed = false
566 let finish: ((status: String, angle: Double)?) -> Void = { value in
567 guard !resumed else { return }
568 resumed = true
569 continuation.resume(returning: value)
570 }
571 let interaction = UIHingeInteraction { _, update in
572 guard let hinge = update.hinge else {
573 finish(nil)
574 return
575 }
576 finish((statusName(hinge.status), Double(hinge.angle)))
577 }
578 view.addInteraction(interaction)
579 interaction.isEnabled = true
580 Task { @MainActor in
581 try? await Task.sleep(nanoseconds: 2_000_000_000)
582 finish(nil)
583 }
584 }
585 return result
586 }
587
588 private static func statusName(_ status: UIHinge.Status) -> String {
589 switch status {
590 case .closed: return "closed"
591 case .partiallyOpen: return "partiallyOpen"
592 case .fullyOpen: return "fullyOpen"
593 default: return "unknown"
594 }
595 }
596 }
597 #endif