@ondeinference / xcrs-controlkit Mirror · read-only / commits / 6c8f712
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

Make the macOS runner able to drive and capture a real app

Driving a Tauri app on macOS hit several walls: clicks failed with "the application frame is empty", web buttons looked nameless, launching an app that was already open hung for minutes, and a bundle ID picked the copy in /Applications instead of the build under test. Runner: - Click coordinates are screen points, anchored on the window under the point. The application element has no frame on macOS. - Every method that names an app accepts `path` as well as `bundleId`. - New device.apps.activate foregrounds a running app without relaunching. - New device.screenshot returns a base64 PNG of the main window or screen. - New macOS methods: device.io.key (with modifiers), device.io.drag, device.io.scroll and device.window.resize (optional move first; reports the frame it got and whether it was clamped). - device.ui.tap matches `title` on macOS and takes `type` and `index` for text a web view repeats on a control and its label. - device.dump.ui takes raw: true to return XCTest's debugDescription. Parser: XCTest prints a macOS control's text as `title: '...'` and a static text's value unquoted. Read both, with title as the label. Tested end to end against the SplitFire AI macOS app (WebKit/Tauri): open panel via cmd+shift+g, a full separation, scrolling, and 2560x1440 window captures. Builds for macOS, tvOS, watchOS and visionOS. The iOS build still fails on HingeReader (UIHinge needs the iOS 27.1 SDK), which this change does not touch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Seto Elkahfi committed Nov 13, 2026 at 10:44 UTC 6c8f71215a7c8846f041728d6a39c8e71c4b2f9a
4 files changed +470 -34
Runners/Shared/ControlKitRPCServer.swift
+382 -29
@@ -1,4 +1,5 @@
1 import Foundation
2 +import ImageIO
3 import NIOCore
4 import NIOHTTP1
5 import NIOPosix
@@ -52,6 +53,7 @@ final class ControlKitRPCServer {
53
54 private static let protocolVersion = 1
55 private static let supportedMethods = [
56 + "device.apps.activate",
57 "device.apps.launch",
58 "device.apps.terminate",
59 "device.capabilities",
@@ -60,13 +62,18 @@ final class ControlKitRPCServer {
62 "device.info",
63 "device.io.button",
64 "device.io.click",
65 + "device.io.drag",
66 + "device.io.key",
67 "device.io.orientation.get",
68 "device.io.orientation.set",
69 + "device.io.scroll",
70 "device.io.spatial.tap",
71 "device.io.swipe",
72 "device.io.tap",
73 "device.io.text",
69 - "device.ui.tap"
74 + "device.screenshot",
75 + "device.ui.tap",
76 + "device.window.resize"
77 ]
78
79 private static var platform: XCRSControlKitPlatform {
@@ -136,31 +143,87 @@ final class ControlKitRPCServer {
143 id: request.id
144 )
145 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
146 + let target = try requiredApplication(request.params)
147 + let (hierarchy, debugDescription) = try accessibilityHierarchy(
148 + target.application,
149 + name: target.name
150 )
145 - return try response(result: dictionary(hierarchy), id: request.id)
151 + var result = try dictionary(hierarchy)
152 + if (request.params["raw"] as? Bool) == true {
153 + result["debugDescription"] = debugDescription
154 + }
155 + return try response(result: result, id: request.id)
156 case "device.ui.tap":
147 - let bundleIdentifier = try stringParameter("bundleId", request.params)
157 + let target = try requiredApplication(request.params)
158 let element = try stringParameter("element", request.params)
159 .trimmingCharacters(in: .whitespacesAndNewlines)
160 guard !element.isEmpty else {
161 throw RunnerError.invalidParameter("element")
162 }
153 - try tapElement(named: element, in: bundleIdentifier)
163 + let elementType: XCUIElement.ElementType
164 + if let typeName = request.params["type"] as? String, !typeName.isEmpty {
165 + guard let resolved = Self.elementTypes[typeName.lowercased()] else {
166 + throw RunnerError.invalidParameter("type")
167 + }
168 + elementType = resolved
169 + } else {
170 + elementType = .any
171 + }
172 + let index = (request.params["index"] as? NSNumber)?.intValue
173 + try tapElement(
174 + named: element,
175 + ofType: elementType,
176 + index: index,
177 + in: target.application,
178 + name: target.name
179 + )
180 return try response(result: ["success": true], id: request.id)
181 case "device.apps.launch":
156 - let bundleIdentifier = try stringParameter("bundleId", request.params)
157 - let application = XCUIApplication(bundleIdentifier: bundleIdentifier)
158 - application.launch()
182 + try requiredApplication(request.params).application.launch()
183 return try response(result: ["success": true], id: request.id)
184 + case "device.apps.activate":
185 + // Unlike launch, activate leaves an already-running app alone and only
186 + // brings it to the foreground. launch() on an app that something else
187 + // started (Finder, `open`, a second copy at another path) can block
188 + // for minutes and then fail with "does not have a process ID".
189 + let application = try requiredApplication(request.params).application
190 + application.activate()
191 + return try response(
192 + result: ["success": true, "state": Self.stateName(application.state)],
193 + id: request.id
194 + )
195 case "device.apps.terminate":
161 - let bundleIdentifier = try stringParameter("bundleId", request.params)
162 - XCUIApplication(bundleIdentifier: bundleIdentifier).terminate()
196 + try requiredApplication(request.params).application.terminate()
197 + return try response(result: ["success": true], id: request.id)
198 + case "device.screenshot":
199 + return try response(result: screenshot(request.params), id: request.id)
200 + case "device.io.drag":
201 + #if os(macOS)
202 + try drag(request.params)
203 + return try response(result: ["success": true], id: request.id)
204 + #else
205 + throw RunnerError.unsupportedInteraction("pointer drag")
206 + #endif
207 + case "device.io.scroll":
208 + #if os(macOS)
209 + try scroll(request.params)
210 + return try response(result: ["success": true], id: request.id)
211 + #else
212 + throw RunnerError.unsupportedInteraction("scroll wheel")
213 + #endif
214 + case "device.io.key":
215 + #if os(macOS)
216 + try typeKey(request.params)
217 return try response(result: ["success": true], id: request.id)
218 + #else
219 + throw RunnerError.unsupportedInteraction("keyboard shortcut")
220 + #endif
221 + case "device.window.resize":
222 + #if os(macOS)
223 + return try response(result: resizeWindow(request.params), id: request.id)
224 + #else
225 + throw RunnerError.unsupportedInteraction("window resize")
226 + #endif
227 case "device.io.tap":
228 #if os(tvOS) || os(visionOS) || os(macOS)
229 throw RunnerError.unsupportedInteraction("touch")
@@ -219,7 +282,7 @@ final class ControlKitRPCServer {
282 )
283 case "device.io.text":
284 let text = try stringParameter("text", request.params)
222 - foregroundApplication(request.params).typeText(text)
285 + application(request.params).typeText(text)
286 return try response(result: ["success": true], id: request.id)
287 case "device.io.button":
288 let button = try stringParameter("button", request.params)
@@ -259,45 +322,122 @@ final class ControlKitRPCServer {
322 }
323 }
324
262 - private func foregroundApplication(_ params: [String: Any]) -> XCUIApplication {
263 - if let bundleIdentifier = params["bundleId"] as? String {
325 + /// Resolves the app a request targets.
326 + ///
327 + /// On macOS `path` wins over `bundleId`: a bundle identifier resolves through
328 + /// LaunchServices, which picks one copy when several are installed (an App
329 + /// Store build in /Applications and a staged build elsewhere, say), and the
330 + /// runner then reports the copy you actually started as "not in the
331 + /// foreground". A path names exactly one bundle.
332 + private func application(_ params: [String: Any]) -> XCUIApplication {
333 + #if os(macOS)
334 + if let path = params["path"] as? String, !path.isEmpty {
335 + return XCUIApplication(url: URL(fileURLWithPath: path))
336 + }
337 + #endif
338 + if let bundleIdentifier = params["bundleId"] as? String, !bundleIdentifier.isEmpty {
339 return XCUIApplication(bundleIdentifier: bundleIdentifier)
340 }
341 return XCUIApplication()
342 }
343
344 + /// Like `application(_:)`, but the request must name the app.
345 + private func requiredApplication(
346 + _ params: [String: Any]
347 + ) throws -> (application: XCUIApplication, name: String) {
348 + #if os(macOS)
349 + if let path = params["path"] as? String, !path.isEmpty {
350 + return (application(params), path)
351 + }
352 + #endif
353 + let bundleIdentifier = try stringParameter("bundleId", params)
354 + return (XCUIApplication(bundleIdentifier: bundleIdentifier), bundleIdentifier)
355 + }
356 +
357 private func accessibilityHierarchy(
358 _ application: XCUIApplication,
271 - bundleIdentifier: String
272 - ) throws -> XCRSControlKitAccessibilityNode {
359 + name: String
360 + ) throws -> (XCRSControlKitAccessibilityNode, String) {
361 guard application.state == .runningForeground else {
274 - throw RunnerError.applicationNotInForeground(bundleIdentifier)
362 + throw RunnerError.applicationNotInForeground(name)
363 }
364 let debugDescription = application.debugDescription
365 guard application.state == .runningForeground else {
278 - throw RunnerError.applicationNotInForeground(bundleIdentifier)
366 + throw RunnerError.applicationNotInForeground(name)
367 }
280 - return try XCRSControlKitAccessibilityParser.parse(
368 + let hierarchy = try XCRSControlKitAccessibilityParser.parse(
369 debugDescription: debugDescription
370 )
371 + return (hierarchy, debugDescription)
372 }
373
285 - private func tapElement(named element: String, in bundleIdentifier: String) throws {
286 - let application = XCUIApplication(bundleIdentifier: bundleIdentifier)
374 + /// Element types `device.ui.tap` can narrow a match to, by the names
375 + /// `device.dump.ui` reports in `type`.
376 + private static let elementTypes: [String: XCUIElement.ElementType] = [
377 + "button": .button,
378 + "link": .link,
379 + "statictext": .staticText,
380 + "textfield": .textField,
381 + "securetextfield": .secureTextField,
382 + "textview": .textView,
383 + "searchfield": .searchField,
384 + "checkbox": .checkBox,
385 + "radiobutton": .radioButton,
386 + "switch": .switch,
387 + "toggle": .toggle,
388 + "slider": .slider,
389 + "image": .image,
390 + "cell": .cell,
391 + "menuitem": .menuItem,
392 + "menubaritem": .menuBarItem,
393 + "popupbutton": .popUpButton,
394 + "tab": .tab,
395 + "other": .other
396 + ]
397 +
398 + private func tapElement(
399 + named element: String,
400 + ofType elementType: XCUIElement.ElementType,
401 + index: Int?,
402 + in application: XCUIApplication,
403 + name: String
404 + ) throws {
405 guard application.state == .runningForeground else {
288 - throw RunnerError.applicationNotInForeground(bundleIdentifier)
406 + throw RunnerError.applicationNotInForeground(name)
407 }
408 + // macOS controls usually carry their text as `title` (a button's caption),
409 + // not `label`, so match it too there.
410 + #if os(macOS)
411 + let predicate = NSPredicate(
412 + format: "label == %@ OR identifier == %@ OR value == %@ OR title == %@",
413 + element,
414 + element,
415 + element,
416 + element
417 + )
418 + #else
419 let predicate = NSPredicate(
420 format: "label == %@ OR identifier == %@ OR value == %@",
421 element,
422 element,
423 element
424 )
296 - let matches = application.descendants(matching: .any).matching(predicate)
425 + #endif
426 + // Web views repeat a control's text on the control and on the static
427 + // text inside it (and often on a nav link too), so callers can narrow
428 + // by type, or pick one of several matches by index (document order).
429 + let matches = application.descendants(matching: elementType).matching(predicate)
430 let matchCount = matches.count
431 guard matchCount > 0 else {
432 throw RunnerError.elementNotFound(element)
433 }
434 + if let index {
435 + guard index >= 0, index < matchCount else {
436 + throw RunnerError.invalidParameter("index")
437 + }
438 + try activate(matches.element(boundBy: index), named: element)
439 + return
440 + }
441 guard matchCount == 1 else {
442 throw RunnerError.ambiguousElement(element, matchCount)
443 }
@@ -334,16 +474,222 @@ final class ControlKitRPCServer {
474 /// Querying a stopped application records an XCTest failure, which ends the
475 /// runner's only test case and takes the server down with it.
476 private func runningApplication(_ params: [String: Any]) throws -> XCUIApplication {
337 - let application = foregroundApplication(params)
477 + let application = application(params)
478 guard application.state != .notRunning else {
339 - throw RunnerError.applicationNotRunning((params["bundleId"] as? String) ?? "the app under test")
479 + throw RunnerError.applicationNotRunning(
480 + (params["path"] as? String) ?? (params["bundleId"] as? String) ?? "the app under test"
481 + )
482 }
483 return application
484 }
485
486 + private static func stateName(_ state: XCUIApplication.State) -> String {
487 + switch state {
488 + case .notRunning: return "notRunning"
489 + #if !os(macOS)
490 + case .runningBackgroundSuspended: return "runningBackgroundSuspended"
491 + #endif
492 + case .runningBackground: return "runningBackground"
493 + case .runningForeground: return "runningForeground"
494 + default: return "unknown"
495 + }
496 + }
497 +
498 + /// PNG of the app's main window (`target: "window"`, the default when an app
499 + /// is named) or of the whole main screen (`target: "screen"`), base64-encoded.
500 + /// Pixel sizes are read back from the PNG, so they include the display scale.
501 + private func screenshot(_ params: [String: Any]) throws -> [String: Any] {
502 + let named = params["path"] != nil || params["bundleId"] != nil
503 + let target = (params["target"] as? String) ?? (named ? "window" : "screen")
504 + let png: Data
505 + switch target {
506 + case "screen":
507 + png = XCUIScreen.main.screenshot().pngRepresentation
508 + case "window":
509 + let application = try runningApplication(params)
510 + png = try mainWindow(of: application).screenshot().pngRepresentation
511 + default:
512 + throw RunnerError.invalidParameter("target")
513 + }
514 + var result: [String: Any] = ["png": png.base64EncodedString(), "target": target]
515 + if
516 + let source = CGImageSourceCreateWithData(png as CFData, nil),
517 + let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]
518 + {
519 + result["width"] = properties[kCGImagePropertyPixelWidth]
520 + result["height"] = properties[kCGImagePropertyPixelHeight]
521 + }
522 + return result
523 + }
524 +
525 + /// The app's largest on-screen window. `windows.firstMatch` is not enough on
526 + /// macOS: WebKit-based apps (Tauri, Electron) also own small hidden helper
527 + /// windows that can come first.
528 + private func mainWindow(of application: XCUIApplication) throws -> XCUIElement {
529 + let windows = application.windows.allElementsBoundByIndex.filter { window in
530 + let frame = window.frame
531 + return frame.width > 1 && frame.height > 1
532 + }
533 + guard let window = windows.max(by: { left, right in
534 + left.frame.width * left.frame.height < right.frame.width * right.frame.height
535 + }) else {
536 + throw RunnerError.noWindow
537 + }
538 + return window
539 + }
540 +
541 + #if os(macOS)
542 + /// Maps a screen point (the space `device.dump.ui` reports rects in) to a
543 + /// coordinate anchored on the window under it. The application element has
544 + /// no frame of its own on macOS, so it cannot be the anchor there.
545 + private func screenCoordinate(
546 + x: Double,
547 + y: Double,
548 + in application: XCUIApplication
549 + ) throws -> (coordinate: XCUICoordinate, window: XCUIElement) {
550 + let point = CGPoint(x: x, y: y)
551 + let windows = application.windows.allElementsBoundByIndex.filter { window in
552 + let frame = window.frame
553 + return frame.width > 1 && frame.height > 1
554 + }
555 + guard let window = windows.first(where: { $0.frame.contains(point) }) ?? windows.first else {
556 + throw RunnerError.noWindow
557 + }
558 + let origin = window.frame.origin
559 + let coordinate = window
560 + .coordinate(withNormalizedOffset: .zero)
561 + .withOffset(CGVector(dx: x - origin.x, dy: y - origin.y))
562 + return (coordinate, window)
563 + }
564 +
565 + private func drag(_ params: [String: Any]) throws {
566 + let application = try runningApplication(params)
567 + let x1 = try doubleParameter("x1", params)
568 + let y1 = try doubleParameter("y1", params)
569 + let start = try screenCoordinate(x: x1, y: y1, in: application).coordinate
570 + // Anchor the end on the same window as the start, so a drag that leaves
571 + // the window (resizing it, dropping onto another app) still lands where
572 + // it was asked to.
573 + let end = start.withOffset(CGVector(
574 + dx: try doubleParameter("x2", params) - x1,
575 + dy: try doubleParameter("y2", params) - y1
576 + ))
577 + let holdMs = (try? doubleParameter("holdMs", params)) ?? 100
578 + start.press(forDuration: max(0.05, holdMs / 1000), thenDragTo: end)
579 + }
580 +
581 + private func scroll(_ params: [String: Any]) throws {
582 + let application = try runningApplication(params)
583 + let coordinate = try screenCoordinate(
584 + x: try doubleParameter("x", params),
585 + y: try doubleParameter("y", params),
586 + in: application
587 + ).coordinate
588 + coordinate.scroll(
589 + byDeltaX: (try? doubleParameter("dx", params)) ?? 0,
590 + deltaY: (try? doubleParameter("dy", params)) ?? 0
591 + )
592 + }
593 +
594 + private func typeKey(_ params: [String: Any]) throws {
595 + let name = try stringParameter("key", params)
596 + let key: String
597 + if let named = Self.namedKeys[name.lowercased()] {
598 + key = named.rawValue
599 + } else if name.count == 1 {
600 + key = name
601 + } else {
602 + throw RunnerError.unsupportedKey(name)
603 + }
604 + var flags: XCUIElement.KeyModifierFlags = []
605 + for modifier in (params["modifiers"] as? [String]) ?? [] {
606 + switch modifier.lowercased() {
607 + case "command", "cmd": flags.insert(.command)
608 + case "shift": flags.insert(.shift)
609 + case "option", "alt": flags.insert(.option)
610 + case "control", "ctrl": flags.insert(.control)
611 + case "function", "fn": flags.insert(.function)
612 + default: throw RunnerError.invalidParameter("modifiers")
613 + }
614 + }
615 + application(params).typeKey(key, modifierFlags: flags)
616 + }
617 +
618 + private static let namedKeys: [String: XCUIKeyboardKey] = [
619 + "return": .return,
620 + "enter": .enter,
621 + "escape": .escape,
622 + "tab": .tab,
623 + "space": .space,
624 + "delete": .delete,
625 + "backspace": .delete,
626 + "forwarddelete": .forwardDelete,
627 + "up": .upArrow,
628 + "down": .downArrow,
629 + "left": .leftArrow,
630 + "right": .rightArrow,
631 + "home": .home,
632 + "end": .end,
633 + "pageup": .pageUp,
634 + "pagedown": .pageDown
635 + ]
636 +
637 + /// Resizes the app's main window by dragging its bottom-right corner, then
638 + /// reports the frame the window actually ended up with. Windows enforce their
639 + /// own minimum and maximum sizes, and a full-screen window cannot be resized
640 + /// at all, so callers should compare the returned size with what they asked for.
641 + private func resizeWindow(_ params: [String: Any]) throws -> [String: Any] {
642 + let application = try runningApplication(params)
643 + let window = try mainWindow(of: application)
644 + let width = try doubleParameter("width", params)
645 + let height = try doubleParameter("height", params)
646 + guard width > 0, height > 0 else {
647 + throw RunnerError.invalidParameter(width > 0 ? "height" : "width")
648 + }
649 + // A window cannot grow past the screen edge, so move it first when asked:
650 + // drag a point in the title bar (clear of the traffic lights on the left)
651 + // until the window's top-left corner sits at x, y.
652 + if let x = try? doubleParameter("x", params), let y = try? doubleParameter("y", params) {
653 + let frame = window.frame
654 + let grab = window
655 + .coordinate(withNormalizedOffset: .zero)
656 + .withOffset(CGVector(dx: min(frame.width / 2, 160), dy: 8))
657 + grab.press(forDuration: 0.2, thenDragTo: grab.withOffset(CGVector(
658 + dx: x - frame.origin.x,
659 + dy: y - frame.origin.y
660 + )))
661 + }
662 + let before = window.frame
663 + // Grab two points inside the corner: far enough in to hit the resize
664 + // area rather than miss the window, close enough not to hit content.
665 + let corner = window
666 + .coordinate(withNormalizedOffset: .zero)
667 + .withOffset(CGVector(dx: before.width - 2, dy: before.height - 2))
668 + let target = corner.withOffset(CGVector(
669 + dx: width - before.width,
670 + dy: height - before.height
671 + ))
672 + corner.press(forDuration: 0.2, thenDragTo: target)
673 + let after = window.frame
674 + return [
675 + "x": after.origin.x,
676 + "y": after.origin.y,
677 + "width": after.width,
678 + "height": after.height,
679 + "requestedWidth": width,
680 + "requestedHeight": height,
681 + // The screen edge or the window's own size limits stopped the drag.
682 + "clamped": abs(after.width - width) > 1 || abs(after.height - height) > 1
683 + ]
684 + }
685 + #endif
686 +
687 #if !os(tvOS)
688 /// Maps a point in the application's frame to an `XCUICoordinate`, clamped to the frame.
689 private func coordinate(x: Double, y: Double, in application: XCUIApplication) throws -> XCUICoordinate {
690 + #if os(macOS)
691 + return try screenCoordinate(x: x, y: y, in: application).coordinate
692 + #else
693 let frame = application.frame
694 guard frame.width > 0, frame.height > 0 else {
695 throw RunnerError.emptyFrame
@@ -354,6 +700,7 @@ final class ControlKitRPCServer {
700 dy: max(0, min(1, y / Double(frame.height)))
701 )
702 )
703 + #endif
704 }
705
706 private func tap(_ params: [String: Any]) throws {
@@ -515,13 +862,15 @@ private enum RunnerError: LocalizedError {
862 case elementNotHittable(String)
863 case emptyFrame
864 case elementNotFocused(String)
865 + case noWindow
866 case unsupportedButton(String)
867 case unsupportedInteraction(String)
868 + case unsupportedKey(String)
869
870 var errorDescription: String? {
871 switch self {
872 case .ambiguousElement(let element, let count):
524 - return "Multiple accessibility elements matched \(element): \(count)"
873 + return "Multiple accessibility elements matched \(element): \(count). Narrow with type (e.g. Button) or pick one with index"
874 case .applicationNotRunning(let application):
875 return "Application \(application) is not running"
876 case .emptyFrame:
@@ -538,6 +887,10 @@ private enum RunnerError: LocalizedError {
887 return "Accessibility element is not hittable: \(element)"
888 case .elementNotFocused(let element):
889 return "Accessibility element is not focused on tvOS: \(element)"
890 + case .noWindow:
891 + return "The application has no on-screen window"
892 + case .unsupportedKey(let key):
893 + return "Unsupported key: \(key). Use a single character or one of return, enter, escape, tab, space, delete, forwardDelete, up, down, left, right, home, end, pageUp, pageDown"
894 case .unsupportedButton(let button):
895 return "Unsupported button: \(button)"
896 case .unsupportedInteraction(let interaction):
Runners/macOS/README.md
+22 -3
@@ -4,9 +4,28 @@ This folder holds the macOS host application (`ControlKitRunnerApp.swift` and
4 `Assets.xcassets`) for the `ControlKit-macOS` target in the shared
5 `XCRSControlKitRunner.xcodeproj`.
6
7 -macOS is pointer-driven: `device.io.click` performs an `XCUICoordinate` click and
8 -`device.io.text` types through the keyboard, while raw `device.io.tap` (touch),
9 -`home`, and orientation controls are intentionally unsupported. The JSON-RPC
7 +macOS is pointer-driven: `device.io.click` clicks, `device.io.drag` presses and
8 +drags, `device.io.scroll` turns the scroll wheel, `device.io.text` types and
9 +`device.io.key` presses a key with optional modifiers (`command`, `shift`,
10 +`option`, `control`, `function`). Coordinates are screen points, the space
11 +`device.dump.ui` reports rects in; the runner anchors them on the app window
12 +under the point, because the application element itself has no frame on macOS.
13 +`device.window.resize` moves and resizes the main window, and
14 +`device.screenshot` captures it (or the whole screen) as a PNG. Raw
15 +`device.io.tap` (touch), `device.io.swipe`, `home`, and orientation controls
16 +are intentionally unsupported.
17 +
18 +Every method that names an app accepts `path` (the `.app` bundle) as well as
19 +`bundleId`. A bundle identifier resolves through LaunchServices, which picks
20 +one copy when several are installed, so name the path when testing a build that
21 +is not the one in `/Applications`. `device.apps.activate` foregrounds an app
22 +that is already running; `device.apps.launch` on an app started outside the
23 +runner can block for minutes and then fail with "does not have a process ID".
24 +
25 +XCTest prints a macOS control's text as `title` and a static text's value
26 +unquoted. `device.dump.ui` reports the title as `label` and reads the unquoted
27 +value, and `device.ui.tap` matches titles, narrowed with `type` (for example
28 +`Button`) or `index` when a web view repeats the same text. The JSON-RPC
29 transport and server live in `../Shared` and are compiled into the
30 `ControlKit-macOS-UITests` target.
31
Sources/XCRSControlKit/XCRSControlKit.swift
+30 -2
@@ -248,9 +248,13 @@ public enum XCRSControlKitAccessibilityParser {
248 return ParsedNode(
249 node: XCRSControlKitAccessibilityNode(
250 type: type,
251 - label: quotedAttribute("label", in: content),
251 + // macOS reports a control's visible text as `title` (buttons,
252 + // links, menu items) and rarely sets `label`, so title stands in.
253 + label: quotedAttribute("label", in: content)
254 + ?? quotedAttribute("title", in: content),
255 name: identifier,
253 - value: quotedAttribute("value", in: content),
256 + value: quotedAttribute("value", in: content)
257 + ?? unquotedValue(in: content),
258 placeholderValue: quotedAttribute("placeholderValue", in: content),
259 rawIdentifier: identifier,
260 rect: rect,
@@ -346,6 +350,30 @@ public enum XCRSControlKitAccessibilityParser {
350 return nil
351 }
352
353 + /// macOS prints a static text's value without quotes, as the last attribute:
354 + /// `StaticText, 0x1, {{0.0, 0.0}, {10.0, 10.0}}, value: No file selected`.
355 + /// It runs to the end of the line, less any trailing standalone flags.
356 + private static func unquotedValue(in line: String) -> String? {
357 + guard
358 + let valueStart = line.range(of: ", value: ")?.upperBound,
359 + line[valueStart...].first != "'"
360 + else {
361 + return nil
362 + }
363 + var value = String(line[valueStart...])
364 + let flags = ["Disabled", "Selected", "Focused"]
365 + var stripped = true
366 + while stripped {
367 + stripped = false
368 + for flag in flags where value.hasSuffix(", \(flag)") {
369 + value.removeLast(flag.count + 2)
370 + stripped = true
371 + }
372 + }
373 + value = value.trimmingCharacters(in: .whitespaces)
374 + return value.isEmpty ? nil : value
375 + }
376 +
377 private static func hasStandaloneAttribute(
378 _ attribute: String,
379 in line: String
Tests/XCRSControlKitTests/XCRSControlKitTests.swift
+36
@@ -156,6 +156,42 @@ final class XCRSControlKitTests: XCTestCase {
156 XCTAssertEqual(button.selected, true)
157 }
158
159 + /// Lines as XCTest prints them for a WebKit (Tauri) window on macOS: controls
160 + /// carry `title`, static text an unquoted trailing `value`.
161 + func testAccessibilityParserReadsMacOSTitlesAndUnquotedValues() throws {
162 + let hierarchy = """
163 + Element subtree:
164 + →Application, 0x1, pid: 52989, title: 'SplitFire AI', Disabled
165 + Window (Main), 0x2, {{356.0, 107.0}, {800.0, 600.0}}, title: 'SplitFire AI', Disabled
166 + StaticText, 0x3, {{440.0, 270.0}, {139.0, 17.0}}, value: No file selected
167 + Button, 0x4, {{950.0, 256.0}, {122.0, 45.0}}, title: 'CHOOSE FILE'
168 + Button, 0x5, {{420.0, 618.0}, {672.0, 61.0}}, title: 'SEPARATE', Disabled
169 + StaticText, 0x6, {{1.0, 2.0}, {3.0, 4.0}}, value: 01 — SOURCE AUDIO, Disabled
170 + Button, 0x7, {{1.0, 2.0}, {3.0, 4.0}}, identifier: 'close', label: 'Close', title: 'Ignored'
171 + Path to element:
172 + """
173 +
174 + let root = try XCRSControlKitAccessibilityParser.parse(
175 + debugDescription: hierarchy
176 + )
177 +
178 + XCTAssertEqual(root.label, "SplitFire AI")
179 + let window = try XCTUnwrap(root.children.first)
180 + XCTAssertEqual(window.label, "SplitFire AI")
181 + XCTAssertEqual(window.enabled, false)
182 + let children = window.children
183 + XCTAssertEqual(children.count, 5)
184 + XCTAssertEqual(children[0].value, "No file selected")
185 + XCTAssertNil(children[0].label)
186 + XCTAssertEqual(children[1].label, "CHOOSE FILE")
187 + XCTAssertEqual(children[1].rect, XCRSControlKitRect(x: 950, y: 256, width: 122, height: 45))
188 + XCTAssertEqual(children[2].label, "SEPARATE")
189 + XCTAssertEqual(children[2].enabled, false)
190 + XCTAssertEqual(children[3].value, "01 — SOURCE AUDIO")
191 + XCTAssertEqual(children[3].enabled, false)
192 + XCTAssertEqual(children[4].label, "Close", "an explicit label wins over title")
193 + }
194 +
195 func testAccessibilityParserRejectsMultipleRootElements() {
196 let hierarchy = """
197 Element subtree: