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

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

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

Synced Nov 24, 18:15 UTC

Add swipe, orientation and hinge methods to the runner

The runner answered -32601 to device.io.swipe and device.io.orientation.get/set, so the xcrs tools that call them failed on Apple targets. This adds them, plus device.hinge.get for foldable devices. device.dump.ui and device.ui.tap already exist on main and are left as they are. - device.io.swipe uses XCUICoordinate.press(forDuration:thenDragTo:) on iOS and returns unsupported elsewhere. - Orientation maps PORTRAIT and LANDSCAPE to XCUIDevice.orientation (iOS). - device.hinge.get reads UIHinge on iOS 27.1 and later through a UIHingeInteraction. The hinge capability is advertised only when the device reports a hinge. - Taps and swipes that name an app which is not running now fail with an error. XCTest records a test failure for a stopped app, which ended the runner's only test case and took the server down. An empty application frame is refused too. - xcrs-host-inspect gains devicehub-posture, which presses the Closed, Partially Open or Open button in a simulator's Device Hub window through macOS accessibility. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

Seto Elkahfi committed Oct 26, 2026 at 00:14 UTC cc8f5cd37630a69f3d054db23dd18205d6c77451
8 files changed +336 -10
Runners/Shared/ControlKitRPCServer.swift
+177 -9
@@ -4,6 +4,9 @@ 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
@@ -53,13 +56,17 @@ final class ControlKitRPCServer {
56 "device.apps.terminate",
57 "device.capabilities",
58 "device.dump.ui",
56 - "device.ui.tap",
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",
62 - "device.io.text"
68 + "device.io.text",
69 + "device.ui.tap"
70 ]
71
72 private static var platform: XCRSControlKitPlatform {
@@ -106,10 +113,14 @@ final class ControlKitRPCServer {
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,
112 - "capabilities": XCRSControlKitCapabilities.standard(for: Self.platform).values.map(\.rawValue).sorted(),
123 + "capabilities": capabilities.map(\.rawValue).sorted(),
124 "methods": Self.supportedMethods
125 ],
126 id: request.id
@@ -171,6 +182,41 @@ final class ControlKitRPCServer {
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)
@@ -284,22 +330,88 @@ final class ControlKitRPCServer {
330 return object
331 }
332
287 - #if !os(tvOS)
288 - private func tap(_ params: [String: Any]) throws {
289 - let x = try doubleParameter("x", params)
290 - let y = try doubleParameter("y", params)
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
293 - let coordinate = application.coordinate(
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 )
299 - coordinate.tap()
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)
@@ -395,11 +507,13 @@ private final class RPCHandler: ChannelInboundHandler {
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)
@@ -408,6 +522,10 @@ private enum RunnerError: LocalizedError {
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:
@@ -427,3 +545,53 @@ private enum RunnerError: LocalizedError {
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
Runners/iOS/README.md
+5 -1
@@ -5,5 +5,9 @@ and `Assets.xcassets`) for the `ControlKit-iOS` target in the shared
5 `XCRSControlKitRunner.xcodeproj`.
6
7 Touch input is delivered through `XCUICoordinate` taps; the `home` button maps
8 -to `XCUIDevice`. The JSON-RPC transport and server live in `../Shared` and are
8 +to `XCUIDevice`. Swipes use `XCUICoordinate.press(forDuration:thenDragTo:)`,
9 +orientation maps `PORTRAIT`/`LANDSCAPE` to `XCUIDevice.orientation`, and on iOS
10 +27.1 or later `device.hinge.get` reads `UIHinge` through a `UIHingeInteraction`.
11 +The `hinge` capability is advertised only on a device that reports a hinge, such
12 +as the iPhone Duo simulator. The JSON-RPC transport and server live in `../Shared` and are
13 compiled into the `ControlKit-iOS-UITests` target.
Runners/macOS/README.md
+2
@@ -15,3 +15,5 @@ entitlement, so `ControlKit-macOS-UITests.entitlements` additionally grants
15 `com.apple.security.network.server`, allowing the runner to bind its local RPC
16 port. The targets sign locally (`CODE_SIGN_IDENTITY = "-"`), so no team or
17 provisioning profile is required to build and test.
18 +
19 +`device.io.swipe`, `device.io.orientation.*` and `device.hinge.get` are not available on this runner.
Runners/tvOS/README.md
+2
@@ -7,3 +7,5 @@ This folder holds the tvOS host application (`ControlKitRunnerApp.swift` and
7 tvOS is remote-driven: `device.io.button` maps to `XCUIRemote` presses and
8 touch/`home` are intentionally unsupported. The JSON-RPC transport and server
9 live in `../Shared` and are compiled into the `ControlKit-tvOS-UITests` target.
10 +
11 +`device.io.swipe`, `device.io.orientation.*` and `device.hinge.get` are not available on this runner.
Runners/visionOS/README.md
+2
@@ -9,3 +9,5 @@ activation through an `XCUICoordinate` tap, while raw `device.io.tap`, `home`,
9 and orientation controls are intentionally unsupported. The JSON-RPC transport
10 and server live in `../Shared` and are compiled into the
11 `ControlKit-visionOS-UITests` target.
12 +
13 +`device.io.swipe`, `device.io.orientation.*` and `device.hinge.get` are not available on this runner.
Sources/XCRSControlKit/XCRSControlKit.swift
+2
@@ -24,6 +24,8 @@ public enum XCRSControlKitCapability: String, Codable, CaseIterable, Sendable {
24 case pointer
25 case spatialInteraction
26 case pairedDevice
27 + /// Reports a hinge angle and fold state. Advertised at runtime, only by foldable devices.
28 + case hinge
29 }
30
31 /// A simulator or device controlled by a runner.
Sources/XCRSHostInspect/HostInspect.swift
+128
@@ -16,6 +16,7 @@ public struct HostInspectInvocationResult: Sendable {
16
17 #if os(macOS)
18
19 +import ApplicationServices
20 import CoreGraphics
21 import ImageIO
22 import Vision
@@ -145,6 +146,13 @@ public struct HostColorRun: Codable, Equatable, Sendable {
146 public let color: String
147 }
148
149 +public struct HostPostureResult: Codable, Equatable, Sendable {
150 + /// The Device Hub window that was driven.
151 + public let window: String
152 + /// The posture button that was pressed.
153 + public let button: String
154 +}
155 +
156 public struct HostProbeResult: Codable, Equatable, Sendable {
157 public let image: HostInspectImage
158 public let axis: HostProbeAxis
@@ -206,6 +214,105 @@ public enum HostInspect {
214 return HostWindowList(windows: windows)
215 }
216
217 + /// The Device Hub buttons that set a foldable simulator's hinge, by posture.
218 + static let devicePostureButtons = [
219 + "closed": "Closed",
220 + "partiallyOpen": "Partially Open",
221 + "open": "Open"
222 + ]
223 +
224 + /// Presses the hinge button in the Device Hub window for `device` through the
225 + /// macOS accessibility API. The window does not need to be in front. The
226 + /// calling process needs the Accessibility permission.
227 + public static func setDeviceHubPosture(device: String, posture: String) throws -> HostPostureResult {
228 + guard let label = devicePostureButtons[posture] else {
229 + throw HostInspectError.usage(
230 + "--posture must be one of \(devicePostureButtons.keys.sorted().joined(separator: ", ")), got \(posture)"
231 + )
232 + }
233 + guard AXIsProcessTrusted() else {
234 + throw HostInspectError.failure(
235 + "Accessibility access is required to press Device Hub buttons. Allow the app that runs xcrs in System Settings > Privacy & Security > Accessibility, then try again."
236 + )
237 + }
238 +
239 + // A command-line process gets no live NSWorkspace updates, so find Device
240 + // Hub's pid through the window server instead.
241 + let entries = CGWindowListCopyWindowInfo([.optionAll], kCGNullWindowID) as? [[String: Any]] ?? []
242 + let hubs = Set(
243 + entries.compactMap { entry -> pid_t? in
244 + guard entry[kCGWindowOwnerName as String] as? String == "Device Hub" else { return nil }
245 + return (entry[kCGWindowOwnerPID as String] as? Int).map { pid_t($0) }
246 + }
247 + ).sorted()
248 + guard !hubs.isEmpty else {
249 + throw HostInspectError.failure("Device Hub is not running. Open it with the device's window visible, then try again.")
250 + }
251 +
252 + // Device Hub titles a simulator's window "<name> – <runtime>".
253 + var windows: [AXUIElement] = []
254 + for hub in hubs {
255 + let application = AXUIElementCreateApplication(hub)
256 + for window in axChildren(application, attribute: kAXWindowsAttribute) {
257 + let title = axString(window, kAXTitleAttribute)
258 + if title == device || (
259 + title.hasPrefix(device)
260 + && title.dropFirst(device.count).unicodeScalars.first
261 + .map(CharacterSet.whitespaces.contains) == true
262 + ) {
263 + windows.append(window)
264 + }
265 + }
266 + }
267 + guard windows.count == 1, let window = windows.first else {
268 + throw HostInspectError.failure(
269 + windows.isEmpty
270 + ? "Device Hub has no open window for '\(device)'. Open the device in Device Hub, then try again."
271 + : "Device Hub has \(windows.count) windows for '\(device)'; close the extras so the target is unambiguous."
272 + )
273 + }
274 + guard let button = findAXButton(in: window, description: label, depth: 0) else {
275 + throw HostInspectError.failure(
276 + "the '\(device)' window has no '\(label)' button; the device may not be foldable."
277 + )
278 + }
279 + let status = AXUIElementPerformAction(button, kAXPressAction as CFString)
280 + guard status == .success else {
281 + throw HostInspectError.failure("pressing '\(label)' failed (AXError \(status.rawValue))")
282 + }
283 + return HostPostureResult(window: axString(window, kAXTitleAttribute), button: label)
284 + }
285 +
286 + private static func axString(_ element: AXUIElement, _ attribute: String) -> String {
287 + var value: CFTypeRef?
288 + guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else {
289 + return ""
290 + }
291 + return value as? String ?? ""
292 + }
293 +
294 + private static func axChildren(_ element: AXUIElement, attribute: String = kAXChildrenAttribute) -> [AXUIElement] {
295 + var value: CFTypeRef?
296 + guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else {
297 + return []
298 + }
299 + return value as? [AXUIElement] ?? []
300 + }
301 +
302 + private static func findAXButton(in element: AXUIElement, description: String, depth: Int) -> AXUIElement? {
303 + if axString(element, kAXRoleAttribute) == kAXButtonRole,
304 + axString(element, kAXDescriptionAttribute) == description {
305 + return element
306 + }
307 + guard depth < 12 else { return nil }
308 + for child in axChildren(element) {
309 + if let found = findAXButton(in: child, description: description, depth: depth + 1) {
310 + return found
311 + }
312 + }
313 + return nil
314 + }
315 +
316 public static func recognizeText(
317 image path: String,
318 scale: HostInspectScale,
@@ -510,6 +617,9 @@ public enum HostInspectCommand {
617 Write a region of an image to a new PNG.
618 probe --image <png> (--row <y> | --column <x>) [--from <a>] [--to <b>] [--scale <n>]
619 Report quantised colour runs along one line of an image.
620 + devicehub-posture --device <name> --posture <closed|partiallyOpen|open>
621 + Set a foldable simulator's hinge by pressing the button in its Device
622 + Hub window. Needs Device Hub running and the Accessibility permission.
623 help
624 Print this text.
625
@@ -555,6 +665,7 @@ public enum HostInspectCommand {
665 enum Command: Equatable {
666 case help
667 case windows(owner: String?)
668 + case devicePosture(device: String, posture: String)
669 case ocr(image: String, scale: HostInspectScale, languages: [String])
670 case crop(image: String, rect: HostInspectRect, scale: HostInspectScale, out: String)
671 case probe(
@@ -579,6 +690,15 @@ public enum HostInspectCommand {
690 return .help
691 case "windows":
692 return .windows(owner: try scanner.options().owner)
693 + case "devicehub-posture":
694 + let options = try scanner.options()
695 + guard let device = options.device else {
696 + throw HostInspectError.usage("--device is required")
697 + }
698 + guard let posture = options.posture else {
699 + throw HostInspectError.usage("--posture is required")
700 + }
701 + return .devicePosture(device: device, posture: posture)
702 case "ocr":
703 let options = try scanner.options()
704 return .ocr(
@@ -629,6 +749,8 @@ public enum HostInspectCommand {
749 return usage
750 case .windows(let owner):
751 return try encode(HostInspect.windows(owner: owner))
752 + case .devicePosture(let device, let posture):
753 + return try encode(HostInspect.setDeviceHubPosture(device: device, posture: posture))
754 case .ocr(let image, let scale, let languages):
755 return try encode(
756 HostInspect.recognizeText(image: image, scale: scale, languages: languages)
@@ -664,6 +786,8 @@ public enum HostInspectCommand {
786 private struct CommandOptions {
787 var image: String?
788 var owner: String?
789 + var device: String?
790 + var posture: String?
791 var out: String?
792 var rect: String?
793 var scale = HostInspectScale.pixels
@@ -738,6 +862,10 @@ private struct ArgumentScanner {
862 options.image = try value(name: name, inline: inlineValue)
863 case "--owner":
864 options.owner = try value(name: name, inline: inlineValue)
865 + case "--device":
866 + options.device = try value(name: name, inline: inlineValue)
867 + case "--posture":
868 + options.posture = try value(name: name, inline: inlineValue)
869 case "--out":
870 options.out = try value(name: name, inline: inlineValue)
871 case "--rect":
Tests/XCRSHostInspectTests/HostInspectCommandTests.swift
+18
@@ -146,6 +146,24 @@ final class HostInspectCommandTests: XCTestCase {
146 XCTAssertTrue(result.standardError.contains("unknown option --nope"))
147 }
148
149 + func testDevicePostureNeedsDeviceAndPosture() {
150 + let missingDevice = HostInspectCommand.invoke(arguments: ["devicehub-posture", "--posture", "open"])
151 + XCTAssertEqual(missingDevice.exitCode, 2)
152 + XCTAssertTrue(missingDevice.standardError.contains("--device is required"))
153 +
154 + let missingPosture = HostInspectCommand.invoke(arguments: ["devicehub-posture", "--device", "iPhone Duo"])
155 + XCTAssertEqual(missingPosture.exitCode, 2)
156 + XCTAssertTrue(missingPosture.standardError.contains("--posture is required"))
157 + }
158 +
159 + func testUnknownDevicePostureIsAUsageError() {
160 + let result = HostInspectCommand.invoke(
161 + arguments: ["devicehub-posture", "--device", "iPhone Duo", "--posture", "bent"]
162 + )
163 + XCTAssertEqual(result.exitCode, 2)
164 + XCTAssertTrue(result.standardError.contains("--posture must be one of closed, open, partiallyOpen"))
165 + }
166 +
167 func testUnknownCommandIsAUsageError() {
168 let result = HostInspectCommand.invoke(arguments: ["snapshot"])
169 XCTAssertEqual(result.exitCode, 2)