Skip to content

Open source CapCut alternative.

TypeScript

Add local UI element detection service

David Le3768b152d641
diff --git a/apps/Donkey/Package.swift b/apps/Donkey/Package.swift
index 4c5e2f88..2b158e92 100644
--- a/apps/Donkey/Package.swift
+++ b/apps/Donkey/Package.swift
@@ -82,6 +82,9 @@ let package = Package(
"DonkeyRuntime",
"DonkeyUI"
],
+ resources: [
+ .copy("Fixtures")
+ ],
swiftSettings: [
.unsafeFlags([
"-F",
diff --git a/apps/Donkey/Sources/Donkey/DebugUIInspectionCoordinator.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift
similarity index 91%
rename from apps/Donkey/Sources/Donkey/DebugUIInspectionCoordinator.swift
rename to apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift
index efbcd68d..ec7e159f 100644
--- a/apps/Donkey/Sources/Donkey/DebugUIInspectionCoordinator.swift
+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift
@@ -89,11 +89,14 @@ final class DebugUIInspectionCoordinator {
let scopeChanged = newConfig.screenScope != currentConfig.screenScope
let providerChanged = newConfig.provider != currentConfig.provider
let confidenceChanged = newConfig.minConfidence != currentConfig.minConfidence
+ let activeWindowChanged = newConfig.activeWindowOnly != currentConfig.activeWindowOnly
+ let targetFilterChanged = newConfig.targetBundleIdentifiers != currentConfig.targetBundleIdentifiers
+ || newConfig.targetAppNames != currentConfig.targetAppNames
currentConfig = newConfig
- if force || enablementChanged || scopeChanged || providerChanged || confidenceChanged {
+ if force || enablementChanged || scopeChanged || providerChanged || confidenceChanged || activeWindowChanged || targetFilterChanged {
DebugUIInspectionLog.overlay.info(
- "debug inspection config enabled=\(String(newConfig.enabled), privacy: .public) provider=\(newConfig.provider.rawValue, privacy: .public) cadence=\(newConfig.cadenceSeconds, privacy: .public) scope=\(newConfig.screenScope.rawValue, privacy: .public) minConfidence=\(newConfig.minConfidence, privacy: .public)"
+ "debug inspection config enabled=\(String(newConfig.enabled), privacy: .public) provider=\(newConfig.provider.rawValue, privacy: .public) cadence=\(newConfig.cadenceSeconds, privacy: .public) scope=\(newConfig.screenScope.rawValue, privacy: .public) minConfidence=\(newConfig.minConfidence, privacy: .public) activeWindowOnly=\(String(newConfig.activeWindowOnly), privacy: .public) targetBundles=\(newConfig.targetBundleIdentifiers.joined(separator: ","), privacy: .public) targetApps=\(newConfig.targetAppNames.joined(separator: ","), privacy: .public)"
)
}
@@ -108,7 +111,7 @@ final class DebugUIInspectionCoordinator {
RunLoop.main.add(newTimer, forMode: .common)
}
- if enablementChanged || scopeChanged || providerChanged || confidenceChanged {
+ if enablementChanged || scopeChanged || providerChanged || confidenceChanged || activeWindowChanged || targetFilterChanged {
lastFingerprints.removeAll()
trackers.removeAll()
lastRenderedFrames.removeAll()
@@ -197,7 +200,11 @@ final class DebugUIInspectionCoordinator {
private func analyzeAccessibilityScreens(force: Bool) throws {
let results = try accessibilityInspectionService.inspect(
scope: currentConfig.screenScope,
- minConfidence: currentConfig.minConfidence
+ minConfidence: currentConfig.minConfidence,
+ frontmostOnly: currentConfig.activeWindowOnly,
+ focusedOnly: currentConfig.activeWindowOnly,
+ targetBundleIdentifiers: currentConfig.targetBundleIdentifiers,
+ targetAppNames: currentConfig.targetAppNames
)
DebugUIInspectionLog.overlay.debug(
"debug inspection accessibility screens=\(results.count, privacy: .public) force=\(String(force), privacy: .public)"
@@ -206,6 +213,7 @@ final class DebugUIInspectionCoordinator {
let activeScreenIDs = Set(results.map(\.snapshot.screenID))
overlayController.closeScreens(except: activeScreenIDs)
lastRenderedFrames = lastRenderedFrames.filter { activeScreenIDs.contains($0.key) }
+ lastFingerprints = lastFingerprints.filter { activeScreenIDs.contains($0.key) }
for result in results {
let snapshot = result.snapshot
diff --git a/apps/Donkey/Sources/Donkey/DebugUIInspectionOverlayController.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift
similarity index 89%
rename from apps/Donkey/Sources/Donkey/DebugUIInspectionOverlayController.swift
rename to apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift
index 0d774525..caccca0e 100644
--- a/apps/Donkey/Sources/Donkey/DebugUIInspectionOverlayController.swift
+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift
@@ -108,7 +108,7 @@ private final class DebugUIInspectionSurface {
}
CATransaction.begin()
- CATransaction.setAnimationDuration(0.18)
+ CATransaction.setDisableActions(true)
for element in frame.elements {
let layers = elementLayers[element.id] ?? makeLayers(for: element)
elementLayers[element.id] = layers
@@ -186,10 +186,38 @@ private final class DebugUIInspectionSurface {
private func labelText(for element: DebugUIElement) -> String {
let label = element.label.trimmingCharacters(in: .whitespacesAndNewlines)
- if !label.isEmpty {
- return label
+ let baseLabel: String
+ if label.isEmpty {
+ baseLabel = element.type.rawValue.replacingOccurrences(of: "_", with: " ")
+ } else {
+ baseLabel = label
+ }
+
+ guard let sources = element.metadata["localUIElement.sources"],
+ !sources.isEmpty
+ else {
+ return baseLabel
+ }
+ let badge = sources
+ .split(separator: ",")
+ .map { sourceBadge(for: String($0)) }
+ .joined(separator: "+")
+ return "[\(badge)] \(baseLabel)"
+ }
+
+ private func sourceBadge(for source: String) -> String {
+ switch source {
+ case "accessibility": return "AX"
+ case "connectedComponent": return "CC"
+ case "hoverProbe": return "HOVER"
+ case "template": return "TPL"
+ case "shape": return "SHAPE"
+ case "color": return "COLOR"
+ case "layout": return "LAYOUT"
+ case "ocr": return "OCR"
+ default:
+ return source.uppercased()
}
- return element.type.rawValue.replacingOccurrences(of: "_", with: " ")
}
private func labelFrameSize(for text: String, boxFrame: CGRect) -> CGSize {
diff --git a/apps/Donkey/Sources/DonkeyContracts/DebugUIInspectionContracts.swift b/apps/Donkey/Sources/DonkeyContracts/DebugUIInspectionContracts.swift
index 37b9e10d..228e754a 100644
--- a/apps/Donkey/Sources/DonkeyContracts/DebugUIInspectionContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/DebugUIInspectionContracts.swift
@@ -112,6 +112,7 @@ public struct DebugUIElement: Codable, Equatable, Sendable, Identifiable {
public var bbox: DebugUIBoundingBox
public var confidence: Double
public var visualStyle: DebugUIOverlayStyle
+ public var metadata: [String: String]
public init(
id: String,
@@ -120,7 +121,8 @@ public struct DebugUIElement: Codable, Equatable, Sendable, Identifiable {
description: String = "",
bbox: DebugUIBoundingBox,
confidence: Double,
- visualStyle: DebugUIOverlayStyle? = nil
+ visualStyle: DebugUIOverlayStyle? = nil,
+ metadata: [String: String] = [:]
) {
self.id = id
self.type = type
@@ -129,6 +131,7 @@ public struct DebugUIElement: Codable, Equatable, Sendable, Identifiable {
self.bbox = bbox
self.confidence = min(max(confidence, 0), 1)
self.visualStyle = visualStyle ?? DebugUIOverlayStyle.style(for: type)
+ self.metadata = metadata
}
public enum CodingKeys: String, CodingKey {
@@ -139,6 +142,7 @@ public struct DebugUIElement: Codable, Equatable, Sendable, Identifiable {
case bbox
case confidence
case visualStyle = "visual_style"
+ case metadata
}
public init(from decoder: Decoder) throws {
@@ -151,7 +155,8 @@ public struct DebugUIElement: Codable, Equatable, Sendable, Identifiable {
description: try container.decodeIfPresent(String.self, forKey: .description) ?? "",
bbox: try container.decode(DebugUIBoundingBox.self, forKey: .bbox),
confidence: try container.decodeIfPresent(Double.self, forKey: .confidence) ?? 0,
- visualStyle: try container.decodeIfPresent(DebugUIOverlayStyle.self, forKey: .visualStyle)
+ visualStyle: try container.decodeIfPresent(DebugUIOverlayStyle.self, forKey: .visualStyle),
+ metadata: try container.decodeIfPresent([String: String].self, forKey: .metadata) ?? [:]
)
}
@@ -163,7 +168,8 @@ public struct DebugUIElement: Codable, Equatable, Sendable, Identifiable {
description: description,
bbox: bbox,
confidence: confidence,
- visualStyle: visualStyle
+ visualStyle: visualStyle,
+ metadata: metadata
)
}
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
index a49b9ec6..15259a3d 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
@@ -8,7 +8,9 @@ public enum LocalAppControlKind: String, Codable, Equatable, Sendable {
case textField
case searchField
case checkbox
+ case link
case menuItem
+ case listItem
case group
case unknown
}
@@ -135,20 +137,22 @@ public struct LocalAppAccessibilityControlDiscovery: Sendable {
}
let kind = controlKind(for: node)
- if kind != .unknown, let label {
+ let controlLabel = labelForControl(node, kind: kind)
+ if kind != .unknown, let controlLabel {
controls.append(
LocalAppDiscoveredControl(
id: node.nodeID,
kind: kind,
role: node.role,
- label: label,
+ label: controlLabel,
valueSummary: node.valueSummary,
frame: node.frame,
isEnabled: node.isEnabled ?? true,
actions: node.actions,
metadata: [
"accessibility.nodeID": node.nodeID,
- "controlID": inferredControlID(label: label, kind: kind)
+ "controlKind": kind.rawValue,
+ "controlID": inferredControlID(label: controlLabel, kind: kind)
]
)
)
@@ -160,16 +164,60 @@ public struct LocalAppAccessibilityControlDiscovery: Sendable {
}
private func bestLabel(for node: MacAccessibilitySnapshotNode) -> String? {
- [node.label, node.title, node.valueSummary, node.role]
+ [node.label, node.title, node.valueSummary]
.compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }
.first { !$0.isEmpty }
}
+ private func labelForControl(
+ _ node: MacAccessibilitySnapshotNode,
+ kind: LocalAppControlKind
+ ) -> String? {
+ if let label = bestLabel(for: node) {
+ return label
+ }
+ if kind == .listItem {
+ return descendantText(for: node) ?? "list item"
+ }
+ return nil
+ }
+
+ private func descendantText(for node: MacAccessibilitySnapshotNode) -> String? {
+ var labels: [String] = []
+ collectDescendantLabels(node, labels: &labels)
+ let joined = labels
+ .prefix(6)
+ .joined(separator: " ")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ return joined.isEmpty ? nil : joined
+ }
+
+ private func collectDescendantLabels(
+ _ node: MacAccessibilitySnapshotNode,
+ labels: inout [String]
+ ) {
+ for child in node.children {
+ if let label = bestLabel(for: child) {
+ labels.append(label)
+ }
+ collectDescendantLabels(child, labels: &labels)
+ }
+ }
+
private func controlKind(for node: MacAccessibilitySnapshotNode) -> LocalAppControlKind {
let role = node.role ?? ""
if role == "AXButton" { return .button }
+ if role == "AXMenuButton" { return .button }
if role == "AXCheckBox" { return .checkbox }
+ if role == "AXRadioButton" { return .checkbox }
+ if role == "AXLink" { return .link }
if role == "AXMenuItem" { return .menuItem }
+ if role == "AXRow" || role == "AXOutlineRow" { return .listItem }
+ if role == "AXCell",
+ node.frame?.hasPositiveArea == true,
+ descendantText(for: node) != nil {
+ return .listItem
+ }
if role == "AXSearchField" { return .searchField }
if role == "AXTextField" || role == "AXTextArea" || role == "AXComboBox" {
return .textField
@@ -256,7 +304,7 @@ public struct LocalAppAccessibilityActionPlanner: Sendable {
guard let controlID = step.metadata["controlID"],
let control = index.firstControl(
matching: controlID,
- acceptedKinds: [.button, .menuItem, .checkbox]
+ acceptedKinds: [.button, .link, .menuItem, .listItem, .checkbox]
)
else {
return nil
diff --git a/apps/Donkey/Sources/DonkeyRuntime/DebugUIAccessibilityInspectionService.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift
similarity index 52%
rename from apps/Donkey/Sources/DonkeyRuntime/DebugUIAccessibilityInspectionService.swift
rename to apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift
index 26499864..3a3b91a7 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/DebugUIAccessibilityInspectionService.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift
@@ -38,13 +38,19 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
private let capturer: any MacAccessibilitySnapshotCapturing
private let controlDiscovery: LocalAppAccessibilityControlDiscovery
private let screenProvider: any DebugUIScreenMetadataProviding
+ private let screenCapturer: any DebugUIScreenCapturing
+ private let elementDetectionService: LocalUIElementDetectionService
private let currentProcessID: Int32
public init() {
self.init(
windowResolver: MacWindowResolver(),
- capturer: ApplicationServicesMacAccessibilitySnapshotCapturer(),
+ capturer: ApplicationServicesMacAccessibilitySnapshotCapturer(
+ maximumTraversalNanoseconds: 700_000_000
+ ),
screenProvider: AppKitDebugUIScreenMetadataProvider(),
+ screenCapturer: DebugUIScreenCaptureService(),
+ elementDetectionService: LocalUIElementDetectionService(),
currentProcessID: ProcessInfo.processInfo.processIdentifier
)
}
@@ -54,35 +60,279 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
capturer: any MacAccessibilitySnapshotCapturing,
controlDiscovery: LocalAppAccessibilityControlDiscovery = LocalAppAccessibilityControlDiscovery(),
screenProvider: any DebugUIScreenMetadataProviding,
+ screenCapturer: any DebugUIScreenCapturing = EmptyDebugUIScreenCapturer(),
+ elementDetectionService: LocalUIElementDetectionService = LocalUIElementDetectionService(),
currentProcessID: Int32
) {
self.windowResolver = windowResolver
self.capturer = capturer
self.controlDiscovery = controlDiscovery
self.screenProvider = screenProvider
+ self.screenCapturer = screenCapturer
+ self.elementDetectionService = elementDetectionService
self.currentProcessID = currentProcessID
}
public func inspect(
scope: DebugUIInspectionScreenScope,
- minConfidence: Double
+ minConfidence: Double,
+ frontmostOnly: Bool = false,
+ focusedOnly: Bool = false,
+ targetBundleIdentifiers: [String] = [],
+ targetAppNames: [String] = []
) throws -> [DebugUIAccessibilityInspectionResult] {
let screens = try screenProvider.screens(scope: scope)
guard !screens.isEmpty else {
throw DebugUIAccessibilityInspectionError.noScreenAvailable
}
- let targets = visibleInspectableTargets(on: screens)
+ let targets = visibleInspectableTargets(
+ on: screens,
+ frontmostOnly: frontmostOnly,
+ focusedOnly: focusedOnly,
+ targetBundleIdentifiers: targetBundleIdentifiers,
+ targetAppNames: targetAppNames
+ )
guard capturer.trustStatus() == .trusted else {
throw DebugUIAccessibilityInspectionError.accessibilityNotTrusted
}
- return windowFrameResults(
+ guard !targets.isEmpty else {
+ return []
+ }
+
+ return localElementDetectionResults(
screens: screens,
targets: targets,
minConfidence: minConfidence
)
}
+ private func localElementDetectionResults(
+ screens: [DebugUIScreenMetadata],
+ targets: [MacWindowTargetCandidate],
+ minConfidence: Double
+ ) -> [DebugUIAccessibilityInspectionResult] {
+ let screenshotsByScreenID = (try? screenCapturer.captureScreens(scope: screens.count > 1 ? .all : .main))
+ .map { Dictionary(uniqueKeysWithValues: $0.map { ($0.screenID, $0) }) } ?? [:]
+ let candidatesByScreenID = accessibilityCandidatesByScreen(
+ screens: screens,
+ targets: targets
+ )
+
+ return screens.map { screen in
+ let fallbackSnapshot = DebugUIScreenCaptureSnapshot(
+ screenID: screen.screenID,
+ screenFrame: screen.appKitFrame,
+ pixelSize: HotLoopSize(
+ width: screen.captureFrame.width,
+ height: screen.captureFrame.height,
+ space: .screen
+ ),
+ pngData: Data(),
+ fingerprint: Self.fingerprint(
+ for: screen,
+ elements: []
+ )
+ )
+ let snapshot = screenshotsByScreenID[screen.screenID] ?? fallbackSnapshot
+ let accessibilityCandidates = Self.scaleCandidates(
+ candidatesByScreenID[screen.screenID] ?? [],
+ from: screen.captureFrame,
+ to: snapshot.pixelSize
+ )
+ let targetWindowBounds = Self.targetWindowBounds(in: accessibilityCandidates)
+ let trace = elementDetectionService.detect(
+ LocalUIElementDetectionRequest(
+ traceID: "debug-ui-local-\(screen.screenID)-\(snapshot.fingerprint)",
+ screenshotPNGData: snapshot.pngData.isEmpty ? nil : snapshot.pngData,
+ pixelSize: snapshot.pixelSize,
+ accessibilityCandidates: accessibilityCandidates,
+ minConfidence: minConfidence,
+ metadata: [
+ "screen.id": String(screen.screenID),
+ "screen.scope": screens.count > 1 ? "all" : "main",
+ "provider": DebugUIInspectionProvider.accessibility.rawValue
+ ]
+ )
+ )
+ let frame = elementDetectionService.debugInspectionFrame(
+ from: trace.clippedToTargetWindows(targetWindowBounds)
+ )
+ .validated(minConfidence: minConfidence)
+ let fingerprint = Self.fingerprint(for: screen, elements: frame.elements)
+ let outputSnapshot = DebugUIScreenCaptureSnapshot(
+ screenID: snapshot.screenID,
+ screenFrame: snapshot.screenFrame,
+ pixelSize: snapshot.pixelSize,
+ pngData: snapshot.pngData,
+ fingerprint: "\(snapshot.fingerprint)-\(fingerprint)"
+ )
+ return DebugUIAccessibilityInspectionResult(snapshot: outputSnapshot, frame: frame)
+ }
+ }
+
+ private func accessibilityCandidatesByScreen(
+ screens: [DebugUIScreenMetadata],
+ targets: [MacWindowTargetCandidate]
+ ) -> [UInt32: [LocalUIElementCandidate]] {
+ var candidatesByScreenID = Dictionary(
+ uniqueKeysWithValues: screens.map { ($0.screenID, [LocalUIElementCandidate]()) }
+ )
+ let limits = MacAccessibilitySnapshotLimits(
+ maxDepth: 6,
+ maxChildrenPerNode: 90,
+ maxTotalNodes: 1_200,
+ maxTextLength: 120
+ )
+ var occludingWindowBounds: [WindowTargetBounds] = []
+ var visibleWindowIndex = 0
+
+ for target in targets {
+ guard let tree = try? capturer.captureTree(target: target, limits: limits) else {
+ occludingWindowBounds.append(target.bounds)
+ continue
+ }
+ let snapshot = MacAccessibilitySnapshot(
+ target: target,
+ limits: limits,
+ root: tree.root,
+ totalNodeCount: tree.totalNodeCount,
+ isTreeTruncated: tree.isTreeTruncated
+ )
+ let windowBounds = snapshot.root.frame ?? target.bounds
+ defer { occludingWindowBounds.append(windowBounds) }
+
+ guard Self.isVisible(windowBounds, occludingWindowBounds: occludingWindowBounds) else {
+ continue
+ }
+
+ for screen in screens where Self.intersects(windowBounds, screen.captureFrame) {
+ if let candidate = windowCandidate(
+ target: target,
+ windowBounds: windowBounds,
+ screen: screen,
+ visibleWindowIndex: visibleWindowIndex
+ ) {
+ candidatesByScreenID[screen.screenID, default: []].append(candidate)
+ }
+ }
+ visibleWindowIndex += 1
+
+ let controls = controlDiscovery.discover(in: snapshot).controls
+ for control in controls {
+ guard let candidate = accessibilityCandidate(
+ for: control,
+ target: target,
+ windowBounds: windowBounds,
+ screens: screens,
+ occludingWindowBounds: occludingWindowBounds
+ ) else {
+ continue
+ }
+ candidatesByScreenID[candidate.screenID, default: []].append(candidate.candidate)
+ }
+ }
+
+ return candidatesByScreenID
+ }
+
+ private func windowCandidate(
+ target: MacWindowTargetCandidate,
+ windowBounds: WindowTargetBounds,
+ screen: DebugUIScreenMetadata,
+ visibleWindowIndex: Int
+ ) -> LocalUIElementCandidate? {
+ guard let bbox = DebugUIAccessibilityGeometry.boundingBox(
+ for: windowBounds,
+ screenFrame: screen.captureFrame
+ ) else {
+ return nil
+ }
+
+ let label = Self.windowLabel(for: target)
+ return LocalUIElementCandidate(
+ id: "window-\(target.windowID)",
+ source: .accessibility,
+ signalKind: .accessibilityRole,
+ typeHint: .draggable,
+ label: label,
+ role: "AXWindow",
+ bounds: HotLoopRect(
+ x: bbox.x,
+ y: bbox.y,
+ width: bbox.width,
+ height: bbox.height,
+ space: .screen
+ ),
+ confidence: 1,
+ metadata: [
+ "target.windowID": String(target.windowID),
+ "target.appName": target.appName ?? "",
+ "target.title": target.title ?? "",
+ "windowFrameStyle.index": String(visibleWindowIndex),
+ "classification.reason": "accessibilityWindowFrame"
+ ]
+ )
+ }
+
+ private static func targetWindowBounds(
+ in candidates: [LocalUIElementCandidate]
+ ) -> [WindowTargetBounds] {
+ candidates.compactMap { candidate in
+ guard candidate.source == .accessibility,
+ candidate.typeHint == .draggable
+ else {
+ return nil
+ }
+ return WindowTargetBounds(
+ x: candidate.bounds.origin.x,
+ y: candidate.bounds.origin.y,
+ width: candidate.bounds.size.width,
+ height: candidate.bounds.size.height
+ )
+ }
+ }
+
+ private static func scaleCandidates(
+ _ candidates: [LocalUIElementCandidate],
+ from captureFrame: WindowTargetBounds,
+ to pixelSize: HotLoopSize
+ ) -> [LocalUIElementCandidate] {
+ guard captureFrame.width > 0,
+ captureFrame.height > 0,
+ pixelSize.width > 0,
+ pixelSize.height > 0
+ else {
+ return candidates
+ }
+
+ let scaleX = pixelSize.width / captureFrame.width
+ let scaleY = pixelSize.height / captureFrame.height
+ guard abs(scaleX - 1) > 0.0001 || abs(scaleY - 1) > 0.0001 else {
+ return candidates
+ }
+
+ return candidates.map { candidate in
+ var scaled = candidate
+ scaled.bounds = HotLoopRect(
+ x: candidate.bounds.origin.x * scaleX,
+ y: candidate.bounds.origin.y * scaleY,
+ width: candidate.bounds.size.width * scaleX,
+ height: candidate.bounds.size.height * scaleY,
+ space: pixelSize.space
+ )
+ scaled.metadata = candidate.metadata.merging([
+ "coordinate.scaleX": String(format: "%.6f", scaleX),
+ "coordinate.scaleY": String(format: "%.6f", scaleY),
+ "coordinate.source.width": String(captureFrame.width),
+ "coordinate.source.height": String(captureFrame.height),
+ "coordinate.target.width": String(pixelSize.width),
+ "coordinate.target.height": String(pixelSize.height)
+ ]) { current, _ in current }
+ return scaled
+ }
+ }
+
private func accessibilityElementResults(
screens: [DebugUIScreenMetadata],
targets: [MacWindowTargetCandidate],
@@ -227,12 +477,25 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
}
private func visibleInspectableTargets(
- on screens: [DebugUIScreenMetadata]
+ on screens: [DebugUIScreenMetadata],
+ frontmostOnly: Bool = false,
+ focusedOnly: Bool = false,
+ targetBundleIdentifiers: [String] = [],
+ targetAppNames: [String] = []
) -> [MacWindowTargetCandidate] {
- windowResolver.enumerateCandidates()
+ let bundleFilters = Set(targetBundleIdentifiers.map(Self.normalizedTargetFilter))
+ let appNameFilters = Set(targetAppNames.map(Self.normalizedTargetFilter))
+ return windowResolver.enumerateCandidates()
.filter { target in
target.isVisible
&& target.isOnScreen
+ && (!frontmostOnly || target.isFrontmost)
+ && (!focusedOnly || target.isFocused)
+ && Self.matchesTargetFilter(
+ target,
+ bundleFilters: bundleFilters,
+ appNameFilters: appNameFilters
+ )
&& target.safetyAssessment.status == .allowed
&& !target.isIPhoneMirroring
&& target.processID != currentProcessID
@@ -242,6 +505,29 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
}
}
+ private static func matchesTargetFilter(
+ _ target: MacWindowTargetCandidate,
+ bundleFilters: Set<String>,
+ appNameFilters: Set<String>
+ ) -> Bool {
+ guard !bundleFilters.isEmpty || !appNameFilters.isEmpty else {
+ return true
+ }
+ if let bundleIdentifier = target.bundleIdentifier,
+ bundleFilters.contains(normalizedTargetFilter(bundleIdentifier)) {
+ return true
+ }
+ if let appName = target.appName,
+ appNameFilters.contains(normalizedTargetFilter(appName)) {
+ return true
+ }
+ return false
+ }
+
+ private static func normalizedTargetFilter(_ value: String) -> String {
+ value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ }
+
private func debugElement(
for control: LocalAppDiscoveredControl,
target: MacWindowTargetCandidate,
@@ -301,8 +587,12 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
return .input
case .checkbox:
return .checkbox
+ case .link:
+ return .link
case .menuItem:
return .menuItem
+ case .listItem:
+ return .listItem
case .group:
return control.actions.contains("AXPress") ? .button : nil
case .unknown:
@@ -310,6 +600,72 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
}
}
+ private func accessibilityCandidate(
+ for control: LocalAppDiscoveredControl,
+ target: MacWindowTargetCandidate,
+ windowBounds: WindowTargetBounds,
+ screens: [DebugUIScreenMetadata],
+ occludingWindowBounds: [WindowTargetBounds]
+ ) -> (screenID: UInt32, candidate: LocalUIElementCandidate)? {
+ guard control.isEnabled,
+ let rawBounds = control.frame,
+ let type = Self.elementType(for: control)
+ else {
+ return nil
+ }
+
+ guard let bounds = DebugUIAccessibilityGeometry.normalizedBounds(
+ for: rawBounds,
+ targetBounds: windowBounds,
+ rootBounds: windowBounds
+ ),
+ let screen = screens.first(where: { Self.intersects(bounds, $0.captureFrame) }),
+ let bbox = DebugUIAccessibilityGeometry.boundingBox(
+ for: bounds,
+ screenFrame: screen.captureFrame
+ )
+ else {
+ return nil
+ }
+
+ guard Self.isVisible(bounds, occludingWindowBounds: occludingWindowBounds),
+ Self.shouldRender(control: control, type: type, bbox: bbox, screen: screen)
+ else {
+ return nil
+ }
+
+ let label = Self.label(for: control, type: type)
+ return (
+ screen.screenID,
+ LocalUIElementCandidate(
+ id: "ax-\(target.windowID)-\(control.id)",
+ source: .accessibility,
+ signalKind: .accessibilityRole,
+ typeHint: type,
+ label: label,
+ role: control.role,
+ bounds: HotLoopRect(
+ x: bbox.x,
+ y: bbox.y,
+ width: bbox.width,
+ height: bbox.height,
+ space: .screen
+ ),
+ confidence: 1,
+ actions: control.actions,
+ metadata: [
+ "target.windowID": String(target.windowID),
+ "target.appName": target.appName ?? "",
+ "target.title": target.title ?? "",
+ "accessibility.nodeID": control.id,
+ "accessibility.role": control.role ?? "",
+ "accessibility.actions": control.actions.joined(separator: ","),
+ "classification.reason": "accessibilityControlDiscovery"
+ ].merging(control.metadata) { current, _ in current }
+ )
+ )
+ }
+
private static func isWindowControl(_ control: LocalAppDiscoveredControl) -> Bool {
let label = control.label.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
return ["close", "minimize", "zoom", "fullscreen", "full screen"].contains(label)
@@ -318,8 +674,11 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
private static func isToolbarControl(_ control: LocalAppDiscoveredControl) -> Bool {
guard control.kind == .button else { return false }
let role = control.role ?? ""
- let label = control.label.trimmingCharacters(in: .whitespacesAndNewlines)
- return role == "AXButton" && label.count <= 24
+ guard role == "AXButton" else { return false }
+ guard let frame = control.frame else {
+ return control.label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+ return frame.width <= 72 && frame.height <= 56
}
private static func label(
@@ -630,13 +989,16 @@ private struct AppKitDebugUIScreenMetadataProvider: DebugUIScreenMetadataProvidi
switch scope {
case .main:
guard let screen = NSScreen.main ?? NSScreen.screens.first else {
- throw DebugUIAccessibilityInspectionError.noScreenAvailable
+ return try Self.fallbackDisplayIDs(scope: scope).map(Self.metadata(for:))
}
screens = [screen]
case .all:
screens = NSScreen.screens
}
+ if screens.isEmpty {
+ return try Self.fallbackDisplayIDs(scope: scope).map(Self.metadata(for:))
+ }
return try screens.map(Self.metadata(for:))
}
@@ -670,4 +1032,182 @@ private struct AppKitDebugUIScreenMetadataProvider: DebugUIScreenMetadataProvidi
}
return value.uint32Value
}
+
+ private static func metadata(for displayID: CGDirectDisplayID) -> DebugUIScreenMetadata {
+ let captureFrame = CGDisplayBounds(displayID)
+ let bounds = WindowTargetBounds(
+ x: captureFrame.origin.x,
+ y: captureFrame.origin.y,
+ width: captureFrame.width,
+ height: captureFrame.height
+ )
+ return DebugUIScreenMetadata(
+ screenID: displayID,
+ appKitFrame: HotLoopRect(
+ x: bounds.x,
+ y: bounds.y,
+ width: bounds.width,
+ height: bounds.height,
+ space: .screen
+ ),
+ captureFrame: bounds
+ )
+ }
+
+ private static func fallbackDisplayIDs(scope: DebugUIInspectionScreenScope) throws -> [CGDirectDisplayID] {
+ switch scope {
+ case .main:
+ let displayID = CGMainDisplayID()
+ guard displayID != 0 else {
+ throw DebugUIAccessibilityInspectionError.noScreenAvailable
+ }
+ return [displayID]
+ case .all:
+ var count: UInt32 = 0
+ CGGetActiveDisplayList(0, nil, &count)
+ guard count > 0 else {
+ throw DebugUIAccessibilityInspectionError.noScreenAvailable
+ }
+ var displays = [CGDirectDisplayID](repeating: 0, count: Int(count))
+ CGGetActiveDisplayList(count, &displays, &count)
+ return Array(displays.prefix(Int(count))).filter { $0 != 0 }
+ }
+ }
+}
+
+private struct EmptyDebugUIScreenCapturer: DebugUIScreenCapturing {
+ func captureScreens(
+ scope: DebugUIInspectionScreenScope
+ ) throws -> [DebugUIScreenCaptureSnapshot] {
+ []
+ }
+}
+
+private extension LocalUIElementDetectionTrace {
+ func clippedToTargetWindows(
+ _ targetWindowBounds: [WindowTargetBounds]
+ ) -> LocalUIElementDetectionTrace {
+ guard !targetWindowBounds.isEmpty else {
+ return self
+ }
+ let hasAccessibilityControls = elements.contains { element in
+ element.sources.contains(.accessibility) && element.type != .draggable
+ }
+ var copy = self
+ copy.elements = elements.compactMap { element in
+ guard let window = Self.bestWindow(for: element, in: targetWindowBounds),
+ let clippedBounds = Self.intersection(element.bounds, window)
+ else {
+ return nil
+ }
+ guard clippedBounds.size.width >= 4, clippedBounds.size.height >= 4 else {
+ return nil
+ }
+
+ if !element.sources.contains(.accessibility),
+ element.sources.contains(.layout),
+ !Self.contains(window, element.bounds, tolerance: 8) {
+ return nil
+ }
+ if hasAccessibilityControls,
+ !element.sources.contains(.accessibility),
+ !element.sources.contains(.template),
+ !element.sources.contains(.hoverProbe),
+ element.confidence < 0.75 {
+ return nil
+ }
+
+ var clipped = element
+ clipped.bounds = clippedBounds
+ if !Self.nearlyEqual(clippedBounds, element.bounds) {
+ clipped.metadata = clipped.metadata.merging([
+ "debugUIElement.clippedToTargetWindow": "true"
+ ]) { current, _ in current }
+ }
+ return clipped
+ }
+ return copy
+ }
+
+ static func bestWindow(
+ for element: LocalUIElement,
+ in windows: [WindowTargetBounds]
+ ) -> WindowTargetBounds? {
+ windows
+ .compactMap { window -> (window: WindowTargetBounds, overlap: Double)? in
+ guard let intersection = intersection(element.bounds, window) else {
+ return nil
+ }
+ let overlap = intersection.size.width * intersection.size.height
+ return overlap > 0 ? (window, overlap) : nil
+ }
+ .max { lhs, rhs in lhs.overlap < rhs.overlap }?
+ .window
+ }
+
+ static func intersection(
+ _ elementBounds: HotLoopRect,
+ _ windowBounds: WindowTargetBounds
+ ) -> HotLoopRect? {
+ let minX = max(elementBounds.origin.x, windowBounds.x)
+ let minY = max(elementBounds.origin.y, windowBounds.y)
+ let maxX = min(
+ elementBounds.origin.x + elementBounds.size.width,
+ windowBounds.x + windowBounds.width
+ )
+ let maxY = min(
+ elementBounds.origin.y + elementBounds.size.height,
+ windowBounds.y + windowBounds.height
+ )
+ let width = maxX - minX
+ let height = maxY - minY
+ guard width > 0, height > 0 else {
+ return nil
+ }
+ return HotLoopRect(
+ x: minX,
+ y: minY,
+ width: width,
+ height: height,
+ space: elementBounds.space
+ )
+ }
+
+ static func nearlyEqual(
+ _ lhs: HotLoopRect,
+ _ rhs: HotLoopRect
+ ) -> Bool {
+ lhs.space == rhs.space
+ && abs(lhs.origin.x - rhs.origin.x) <= 0.001
+ && abs(lhs.origin.y - rhs.origin.y) <= 0.001
+ && abs(lhs.size.width - rhs.size.width) <= 0.001
+ && abs(lhs.size.height - rhs.size.height) <= 0.001
+ }
+
+ static func contains(
+ _ windowBounds: WindowTargetBounds,
+ _ elementBounds: HotLoopRect,
+ tolerance: Double
+ ) -> Bool {
+ let minX = windowBounds.x - tolerance
+ let minY = windowBounds.y - tolerance
+ let maxX = windowBounds.x + windowBounds.width + tolerance
+ let maxY = windowBounds.y + windowBounds.height + tolerance
+ return elementBounds.origin.x >= minX
+ && elementBounds.origin.y >= minY
+ && elementBounds.origin.x + elementBounds.size.width <= maxX
+ && elementBounds.origin.y + elementBounds.size.height <= maxY
+ }
+
+ static func substantialOverlap(
+ _ elementBounds: HotLoopRect,
+ _ windowBounds: WindowTargetBounds
+ ) -> Bool {
+ guard let intersection = intersection(elementBounds, windowBounds) else {
+ return false
+ }
+ let overlap = intersection.size.width * intersection.size.height
+ let area = elementBounds.size.width * elementBounds.size.height
+ return area > 0 && overlap / area >= 0.72
+ }
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/DebugUIInspectionRuntime.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift
similarity index 76%
rename from apps/Donkey/Sources/DonkeyRuntime/DebugUIInspectionRuntime.swift
rename to apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift
index 9c836145..ab2ae9a8 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/DebugUIInspectionRuntime.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift
@@ -12,19 +12,28 @@ public struct DebugUIOverlayConfiguration: Equatable, Sendable {
public var cadenceSeconds: TimeInterval
public var screenScope: DebugUIInspectionScreenScope
public var minConfidence: Double
+ public var activeWindowOnly: Bool
+ public var targetBundleIdentifiers: [String]
+ public var targetAppNames: [String]
public init(
enabled: Bool = false,
provider: DebugUIInspectionProvider = .accessibility,
cadenceSeconds: TimeInterval = 1.0,
screenScope: DebugUIInspectionScreenScope = .main,
- minConfidence: Double = 0.25
+ minConfidence: Double = 0.25,
+ activeWindowOnly: Bool = false,
+ targetBundleIdentifiers: [String] = [],
+ targetAppNames: [String] = []
) {
self.enabled = enabled
self.provider = provider
self.cadenceSeconds = min(max(cadenceSeconds, 0.25), 10.0)
self.screenScope = screenScope
self.minConfidence = min(max(minConfidence, 0), 1)
+ self.activeWindowOnly = activeWindowOnly
+ self.targetBundleIdentifiers = Self.normalizedList(targetBundleIdentifiers)
+ self.targetAppNames = Self.normalizedList(targetAppNames)
}
public static let disabled = DebugUIOverlayConfiguration(enabled: false)
@@ -71,10 +80,24 @@ public struct DebugUIOverlayConfiguration: Equatable, Sendable {
provider: raw.provider.flatMap(DebugUIInspectionProvider.init(rawValue:)) ?? .accessibility,
cadenceSeconds: raw.cadenceSeconds ?? 1.0,
screenScope: raw.screenScope.flatMap(DebugUIInspectionScreenScope.init(rawValue:)) ?? .main,
- minConfidence: raw.minConfidence ?? 0.25
+ minConfidence: raw.minConfidence ?? 0.25,
+ activeWindowOnly: raw.activeWindowOnly ?? false,
+ targetBundleIdentifiers: raw.targetBundleIdentifiers ?? [],
+ targetAppNames: raw.targetAppNames ?? []
)
}
+ private static func normalizedList(_ values: [String]) -> [String] {
+ var seen = Set<String>()
+ return values.compactMap { value in
+ let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return nil }
+ let key = trimmed.lowercased()
+ guard seen.insert(key).inserted else { return nil }
+ return trimmed
+ }
+ }
+
public static func candidateConfigURLs(
fileManager: FileManager = .default,
environment: [String: String] = ProcessInfo.processInfo.environment,
@@ -133,6 +156,9 @@ private struct RawDebugUIOverlayConfiguration: Codable {
var cadenceSeconds: TimeInterval?
var screenScope: String?
var minConfidence: Double?
+ var activeWindowOnly: Bool?
+ var targetBundleIdentifiers: [String]?
+ var targetAppNames: [String]?
}
public struct DebugUIElementTracker: Equatable, Sendable {
@@ -145,9 +171,9 @@ public struct DebugUIElementTracker: Equatable, Sendable {
public mutating func update(with frame: DebugUIInspectionFrame) -> DebugUIInspectionFrame {
var usedPreviousIDs = Set<String>()
let tracked = frame.elements.map { incoming -> DebugUIElement in
- if previousElements.contains(where: { $0.id == incoming.id }) {
+ if let previous = previousElements.first(where: { $0.id == incoming.id }) {
usedPreviousIDs.insert(incoming.id)
- return incoming
+ return stableElement(incoming, matchedTo: previous)
}
guard let match = bestSemanticMatch(
@@ -158,13 +184,45 @@ public struct DebugUIElementTracker: Equatable, Sendable {
}
usedPreviousIDs.insert(match.id)
- return incoming.replacingID(match.id)
+ return stableElement(incoming.replacingID(match.id), matchedTo: match)
}
previousElements = tracked
return DebugUIInspectionFrame(elements: tracked)
}
+ private func stableElement(
+ _ incoming: DebugUIElement,
+ matchedTo previous: DebugUIElement
+ ) -> DebugUIElement {
+ guard shouldReusePreviousBounds(incoming.bbox, previous.bbox) else {
+ return incoming
+ }
+ return DebugUIElement(
+ id: incoming.id,
+ type: incoming.type,
+ label: incoming.label,
+ description: incoming.description,
+ bbox: previous.bbox,
+ confidence: incoming.confidence,
+ visualStyle: incoming.visualStyle,
+ metadata: incoming.metadata
+ )
+ }
+
+ private func shouldReusePreviousBounds(
+ _ incoming: DebugUIBoundingBox,
+ _ previous: DebugUIBoundingBox
+ ) -> Bool {
+ let maximumDelta = max(
+ abs(incoming.x - previous.x),
+ abs(incoming.y - previous.y),
+ abs(incoming.width - previous.width),
+ abs(incoming.height - previous.height)
+ )
+ return maximumDelta <= 2.0 && matchScore(previous, incoming) >= 0.82
+ }
+
private func bestSemanticMatch(
for incoming: DebugUIElement,
usedPreviousIDs: Set<String>
@@ -306,13 +364,16 @@ public struct DebugUIScreenCaptureService: Sendable {
switch scope {
case .main:
guard let screen = NSScreen.main ?? NSScreen.screens.first else {
- throw DebugUIScreenCaptureError.noScreenAvailable
+ return try Self.fallbackDisplayIDs(scope: scope).map(capture)
}
screens = [screen]
case .all:
screens = NSScreen.screens
}
+ if screens.isEmpty {
+ return try Self.fallbackDisplayIDs(scope: scope).map(capture)
+ }
return try screens.map(capture)
}
@@ -356,6 +417,38 @@ public struct DebugUIScreenCaptureService: Sendable {
)
}
+ private func capture(displayID: CGDirectDisplayID) throws -> DebugUIScreenCaptureSnapshot {
+ guard let image = CGDisplayCreateImage(displayID) else {
+ throw DebugUIScreenCaptureError.captureFailed(displayID: displayID)
+ }
+ let inspectionImage = Self.inspectionImage(from: image)
+ guard !Self.isLikelyBlank(inspectionImage) else {
+ throw DebugUIScreenCaptureError.blankCapture(displayID: displayID)
+ }
+ guard let pngData = Self.pngData(from: inspectionImage) else {
+ throw DebugUIScreenCaptureError.pngEncodingFailed(displayID: displayID)
+ }
+
+ let bounds = CGDisplayBounds(displayID)
+ return DebugUIScreenCaptureSnapshot(
+ screenID: displayID,
+ screenFrame: HotLoopRect(
+ x: bounds.origin.x,
+ y: bounds.origin.y,
+ width: bounds.width,
+ height: bounds.height,
+ space: .screen
+ ),
+ pixelSize: HotLoopSize(
+ width: Double(inspectionImage.width),
+ height: Double(inspectionImage.height),
+ space: .screen
+ ),
+ pngData: pngData,
+ fingerprint: Self.fingerprint(for: pngData)
+ )
+ }
+
private static func displayID(for screen: NSScreen) throws -> UInt32 {
let key = NSDeviceDescriptionKey("NSScreenNumber")
guard let value = screen.deviceDescription[key] as? NSNumber else {
@@ -364,6 +457,26 @@ public struct DebugUIScreenCaptureService: Sendable {
return value.uint32Value
}
+ private static func fallbackDisplayIDs(scope: DebugUIInspectionScreenScope) throws -> [CGDirectDisplayID] {
+ switch scope {
+ case .main:
+ let displayID = CGMainDisplayID()
+ guard displayID != 0 else {
+ throw DebugUIScreenCaptureError.noScreenAvailable
+ }
+ return [displayID]
+ case .all:
+ var count: UInt32 = 0
+ CGGetActiveDisplayList(0, nil, &count)
+ guard count > 0 else {
+ throw DebugUIScreenCaptureError.noScreenAvailable
+ }
+ var displays = [CGDirectDisplayID](repeating: 0, count: Int(count))
+ CGGetActiveDisplayList(count, &displays, &count)
+ return Array(displays.prefix(Int(count))).filter { $0 != 0 }
+ }
+ }
+
private static func pngData(from image: CGImage) -> Data? {
let data = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(
@@ -459,3 +572,11 @@ public struct DebugUIScreenCaptureService: Sendable {
SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
}
}
+
+protocol DebugUIScreenCapturing: Sendable {
+ func captureScreens(
+ scope: DebugUIInspectionScreenScope
+ ) throws -> [DebugUIScreenCaptureSnapshot]
+}
+
+extension DebugUIScreenCaptureService: DebugUIScreenCapturing {}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionContracts.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionContracts.swift
new file mode 100644
index 00000000..4793d70e
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionContracts.swift
@@ -0,0 +1,216 @@
+import DonkeyContracts
+import Foundation
+
+public enum LocalUIElementCandidateSource: String, Codable, CaseIterable, Equatable, Sendable {
+ case accessibility
+ case shape
+ case ocr
+ case template
+ case color
+ case connectedComponent
+ case hoverProbe
+ case layout
+}
+
+public enum LocalUIElementSignalKind: String, Codable, CaseIterable, Equatable, Sendable {
+ case accessibilityRole
+ case rectangle
+ case roundedRectangle
+ case text
+ case iconTemplate
+ case colorCluster
+ case connectedComponent
+ case hoverHighlight
+ case rowGrouping
+}
+
+public enum LocalUIElementActionEligibility: String, Codable, Equatable, Sendable {
+ case overlayOnly
+ case readOnlyEvidence
+ case cursorVisualization
+ case guardedAction
+}
+
+public struct LocalUIElementCandidate: Codable, Equatable, Sendable, Identifiable {
+ public var id: String
+ public var source: LocalUIElementCandidateSource
+ public var signalKind: LocalUIElementSignalKind
+ public var typeHint: DebugUIElementType?
+ public var label: String?
+ public var role: String?
+ public var bounds: HotLoopRect
+ public var confidence: Double
+ public var actions: [String]
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ source: LocalUIElementCandidateSource,
+ signalKind: LocalUIElementSignalKind,
+ typeHint: DebugUIElementType? = nil,
+ label: String? = nil,
+ role: String? = nil,
+ bounds: HotLoopRect,
+ confidence: Double,
+ actions: [String] = [],
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.source = source
+ self.signalKind = signalKind
+ self.typeHint = typeHint
+ self.label = label
+ self.role = role
+ self.bounds = bounds
+ self.confidence = min(max(confidence, 0), 1)
+ self.actions = actions
+ self.metadata = metadata
+ }
+}
+
+public struct LocalUIElementSuppressedCandidate: Codable, Equatable, Sendable, Identifiable {
+ public var id: String
+ public var candidate: LocalUIElementCandidate
+ public var reason: String
+ public var mergedIntoElementID: String?
+
+ public init(
+ candidate: LocalUIElementCandidate,
+ reason: String,
+ mergedIntoElementID: String? = nil
+ ) {
+ self.id = "\(candidate.id)-suppressed-\(reason)"
+ self.candidate = candidate
+ self.reason = reason
+ self.mergedIntoElementID = mergedIntoElementID
+ }
+}
+
+public struct LocalUIElement: Codable, Equatable, Sendable, Identifiable {
+ public var id: String
+ public var type: DebugUIElementType
+ public var label: String
+ public var bounds: HotLoopRect
+ public var confidence: Double
+ public var sources: [LocalUIElementCandidateSource]
+ public var reasonCodes: [String]
+ public var actionEligibility: LocalUIElementActionEligibility
+ public var sourceCandidateIDs: [String]
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ type: DebugUIElementType,
+ label: String,
+ bounds: HotLoopRect,
+ confidence: Double,
+ sources: [LocalUIElementCandidateSource],
+ reasonCodes: [String],
+ actionEligibility: LocalUIElementActionEligibility,
+ sourceCandidateIDs: [String],
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.type = type
+ self.label = label
+ self.bounds = bounds
+ self.confidence = min(max(confidence, 0), 1)
+ self.sources = Array(Set(sources)).sorted { $0.rawValue < $1.rawValue }
+ self.reasonCodes = Array(Set(reasonCodes)).sorted()
+ self.actionEligibility = actionEligibility
+ self.sourceCandidateIDs = sourceCandidateIDs
+ self.metadata = metadata
+ }
+
+ public var isGuardedActionEligible: Bool {
+ actionEligibility == .guardedAction
+ }
+}
+
+public struct LocalUIElementDetectionMetrics: Codable, Equatable, Sendable {
+ public var sourceCounts: [String: Int]
+ public var candidateCount: Int
+ public var elementCount: Int
+ public var suppressedCount: Int
+ public var duplicateCount: Int
+ public var cvOnlyElementCount: Int
+ public var minConfidence: Double
+ public var latencyMS: [String: Double]
+
+ public init(
+ sourceCounts: [String: Int] = [:],
+ candidateCount: Int = 0,
+ elementCount: Int = 0,
+ suppressedCount: Int = 0,
+ duplicateCount: Int = 0,
+ cvOnlyElementCount: Int = 0,
+ minConfidence: Double = 0,
+ latencyMS: [String: Double] = [:]
+ ) {
+ self.sourceCounts = sourceCounts
+ self.candidateCount = candidateCount
+ self.elementCount = elementCount
+ self.suppressedCount = suppressedCount
+ self.duplicateCount = duplicateCount
+ self.cvOnlyElementCount = cvOnlyElementCount
+ self.minConfidence = min(max(minConfidence, 0), 1)
+ self.latencyMS = latencyMS
+ }
+}
+
+public struct LocalUIElementDetectionTrace: Codable, Equatable, Sendable {
+ public var traceID: String
+ public var candidates: [LocalUIElementCandidate]
+ public var elements: [LocalUIElement]
+ public var suppressedCandidates: [LocalUIElementSuppressedCandidate]
+ public var metrics: LocalUIElementDetectionMetrics
+ public var metadata: [String: String]
+
+ public init(
+ traceID: String,
+ candidates: [LocalUIElementCandidate],
+ elements: [LocalUIElement],
+ suppressedCandidates: [LocalUIElementSuppressedCandidate],
+ metrics: LocalUIElementDetectionMetrics,
+ metadata: [String: String] = [:]
+ ) {
+ self.traceID = traceID
+ self.candidates = candidates
+ self.elements = elements
+ self.suppressedCandidates = suppressedCandidates
+ self.metrics = metrics
+ self.metadata = metadata
+ }
+}
+
+public struct LocalUIElementDetectionRequest: Equatable, Sendable {
+ public var traceID: String
+ public var screenshotPNGData: Data?
+ public var pixelSize: HotLoopSize
+ public var accessibilityCandidates: [LocalUIElementCandidate]
+ public var hoverProbeCandidates: [LocalUIElementCandidate]
+ public var minConfidence: Double
+ public var metadata: [String: String]
+
+ public init(
+ traceID: String,
+ screenshotPNGData: Data? = nil,
+ pixelSize: HotLoopSize,
+ accessibilityCandidates: [LocalUIElementCandidate] = [],
+ hoverProbeCandidates: [LocalUIElementCandidate] = [],
+ minConfidence: Double = 0.25,
+ metadata: [String: String] = [:]
+ ) {
+ self.traceID = traceID
+ self.screenshotPNGData = screenshotPNGData
+ self.pixelSize = pixelSize
+ self.accessibilityCandidates = accessibilityCandidates
+ self.hoverProbeCandidates = hoverProbeCandidates
+ self.minConfidence = min(max(minConfidence, 0), 1)
+ self.metadata = metadata
+ }
+}
+
+public protocol LocalUIElementDetecting: Sendable {
+ func detect(_ request: LocalUIElementDetectionRequest) -> LocalUIElementDetectionTrace
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionService.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionService.swift
new file mode 100644
index 00000000..c959a287
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionService.swift
@@ -0,0 +1,583 @@
+import DonkeyContracts
+import Foundation
+
+public struct LocalUIElementDetectionService: LocalUIElementDetecting {
+ public var nativeVisualDetector: LocalUIElementNativeVisualDetector
+
+ public init(
+ nativeVisualDetector: LocalUIElementNativeVisualDetector = LocalUIElementNativeVisualDetector()
+ ) {
+ self.nativeVisualDetector = nativeVisualDetector
+ }
+
+ public func detect(_ request: LocalUIElementDetectionRequest) -> LocalUIElementDetectionTrace {
+ let startedAt = ProcessInfo.processInfo.systemUptime
+ let nativeResult = nativeVisualDetector.candidates(
+ fromPNGData: request.screenshotPNGData,
+ pixelSize: request.pixelSize
+ )
+ let rowCandidates = rowLayoutCandidates(
+ from: nativeResult.candidates,
+ pixelSize: request.pixelSize
+ )
+ let candidates = request.accessibilityCandidates
+ + request.hoverProbeCandidates
+ + nativeResult.candidates
+ + rowCandidates
+
+ let mergeStartedAt = ProcessInfo.processInfo.systemUptime
+ let merged = merge(
+ candidates: candidates.filter { $0.bounds.hasPositiveArea },
+ minConfidence: request.minConfidence
+ )
+ let mergeMS = (ProcessInfo.processInfo.systemUptime - mergeStartedAt) * 1_000
+ let totalMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
+ var latency = nativeResult.latencyMS
+ latency["mergeClassifyLabel"] = mergeMS
+ latency["total"] = totalMS
+
+ let metrics = metrics(
+ candidates: candidates,
+ elements: merged.elements,
+ suppressed: merged.suppressed,
+ minConfidence: request.minConfidence,
+ latencyMS: latency
+ )
+
+ return LocalUIElementDetectionTrace(
+ traceID: request.traceID,
+ candidates: candidates,
+ elements: merged.elements,
+ suppressedCandidates: merged.suppressed,
+ metrics: metrics,
+ metadata: request.metadata.merging(nativeResult.metadata) { current, _ in current }.merging([
+ "service": "local-ui-element-detection",
+ "rawPixelsPersisted": "false",
+ "visibleSystemA11yToggled": "false"
+ ]) { current, _ in current }
+ )
+ }
+
+ public func debugInspectionFrame(
+ from trace: LocalUIElementDetectionTrace
+ ) -> DebugUIInspectionFrame {
+ DebugUIInspectionFrame(
+ elements: trace.elements.map(Self.debugElement)
+ )
+ }
+
+ public func localUIUnderstandingResult(
+ from trace: LocalUIElementDetectionTrace
+ ) -> LocalUIUnderstandingResult {
+ var visibleText: [String: String] = [:]
+ var controls: [LocalUIUnderstandingControl] = []
+
+ for element in trace.elements {
+ let normalizedControlID = Self.controlID(for: element)
+ if !element.label.isEmpty {
+ visibleText[element.id] = element.label
+ }
+ controls.append(
+ LocalUIUnderstandingControl(
+ id: element.id,
+ label: element.label,
+ kind: Self.localAppKind(for: element),
+ frame: element.bounds,
+ confidence: element.confidence,
+ metadata: element.metadata.merging([
+ "controlID": normalizedControlID,
+ "localUIElement.type": element.type.rawValue,
+ "localUIElement.sources": element.sources.map(\.rawValue).joined(separator: ","),
+ "localUIElement.reasonCodes": element.reasonCodes.joined(separator: ","),
+ "localUIElement.actionEligibility": element.actionEligibility.rawValue,
+ "directInputActionsAllowed": String(element.isGuardedActionEligible)
+ ]) { current, _ in current }
+ )
+ )
+ }
+
+ return LocalUIUnderstandingResult(
+ visibleText: visibleText,
+ controls: controls,
+ formFields: [],
+ confidence: trace.elements.map(\.confidence).max() ?? 0,
+ metadata: trace.metadata.merging(Self.metricsMetadata(trace.metrics)) { current, _ in current }
+ .merging([
+ "understander": "local-ui-element-detection-service",
+ "directInputActionsAllowed": "false"
+ ]) { current, _ in current }
+ )
+ }
+
+ public static func debugElement(from element: LocalUIElement) -> DebugUIElement {
+ DebugUIElement(
+ id: element.id,
+ type: element.type,
+ label: element.label,
+ description: [
+ element.type.rawValue,
+ element.sources.map(\.rawValue).joined(separator: "+"),
+ element.actionEligibility.rawValue
+ ].filter { !$0.isEmpty }.joined(separator: " "),
+ bbox: DebugUIBoundingBox(
+ x: element.bounds.origin.x,
+ y: element.bounds.origin.y,
+ width: element.bounds.size.width,
+ height: element.bounds.size.height
+ ),
+ confidence: element.confidence,
+ metadata: element.metadata.merging([
+ "localUIElement.sources": element.sources.map(\.rawValue).joined(separator: ","),
+ "localUIElement.reasonCodes": element.reasonCodes.joined(separator: ","),
+ "localUIElement.actionEligibility": element.actionEligibility.rawValue
+ ]) { current, _ in current }
+ )
+ }
+
+ private func merge(
+ candidates: [LocalUIElementCandidate],
+ minConfidence: Double
+ ) -> (elements: [LocalUIElement], suppressed: [LocalUIElementSuppressedCandidate]) {
+ var groups: [[LocalUIElementCandidate]] = []
+ var suppressed: [LocalUIElementSuppressedCandidate] = []
+
+ for candidate in candidates.sorted(by: Self.candidateSort) {
+ guard candidate.confidence >= minConfidence else {
+ suppressed.append(LocalUIElementSuppressedCandidate(candidate: candidate, reason: "lowConfidence"))
+ continue
+ }
+
+ if let index = groups.firstIndex(where: { group in
+ group.contains { Self.shouldMerge(candidate, $0) }
+ }) {
+ groups[index].append(candidate)
+ } else {
+ groups.append([candidate])
+ }
+ }
+
+ let elements = groups.enumerated().compactMap { index, group -> LocalUIElement? in
+ guard let element = element(from: group, index: index) else {
+ for candidate in group {
+ suppressed.append(LocalUIElementSuppressedCandidate(candidate: candidate, reason: "unclassifiable"))
+ }
+ return nil
+ }
+ for candidate in group.dropFirst() {
+ suppressed.append(
+ LocalUIElementSuppressedCandidate(
+ candidate: candidate,
+ reason: "mergedDuplicate",
+ mergedIntoElementID: element.id
+ )
+ )
+ }
+ return element
+ }
+
+ return (
+ elements.sorted { lhs, rhs in
+ if lhs.bounds.origin.y != rhs.bounds.origin.y { return lhs.bounds.origin.y < rhs.bounds.origin.y }
+ if lhs.bounds.origin.x != rhs.bounds.origin.x { return lhs.bounds.origin.x < rhs.bounds.origin.x }
+ return lhs.id < rhs.id
+ },
+ suppressed
+ )
+ }
+
+ private func element(
+ from group: [LocalUIElementCandidate],
+ index: Int
+ ) -> LocalUIElement? {
+ guard let primary = group.sorted(by: Self.candidateSort).first else { return nil }
+ let type = classify(group: group)
+ let label = label(group: group, type: type)
+ let bounds = bestBounds(group: group)
+ let sources = group.map(\.source)
+ let confidence = min(1, group.map(\.confidence).max() ?? primary.confidence)
+ let eligibility = actionEligibility(for: group, type: type)
+ let reasonCodes = reasonCodes(for: group, type: type, label: label, eligibility: eligibility)
+ let id = stableElementID(primary: primary, type: type, label: label, index: index)
+
+ return LocalUIElement(
+ id: id,
+ type: type,
+ label: label,
+ bounds: bounds,
+ confidence: confidence,
+ sources: sources,
+ reasonCodes: reasonCodes,
+ actionEligibility: eligibility,
+ sourceCandidateIDs: group.map(\.id),
+ metadata: group.reduce(into: [:]) { result, candidate in
+ for (key, value) in candidate.metadata {
+ result["candidate.\(candidate.id).\(key)"] = value
+ }
+ }.merging([
+ "primaryCandidateID": primary.id,
+ "source.count": String(Set(sources).count)
+ ]) { current, _ in current }
+ )
+ }
+
+ private func classify(group: [LocalUIElementCandidate]) -> DebugUIElementType {
+ if let ax = group.first(where: { $0.source == .accessibility }),
+ let typeHint = ax.typeHint {
+ return typeHint
+ }
+ if let template = group.first(where: { $0.source == .template }),
+ let typeHint = template.typeHint {
+ return typeHint
+ }
+ if let explicit = group.first(where: { $0.typeHint != nil })?.typeHint {
+ return explicit
+ }
+
+ let textCandidate = group.first { $0.source == .ocr }
+ let shapeCandidate = group.first { $0.source == .shape }
+ if textCandidate != nil, let shapeCandidate {
+ let aspect = shapeCandidate.bounds.size.width / max(1, shapeCandidate.bounds.size.height)
+ return aspect > 3.6 ? .input : .button
+ }
+ if group.contains(where: { $0.source == .connectedComponent }) {
+ return .toolbarIcon
+ }
+ return .other
+ }
+
+ private func label(
+ group: [LocalUIElementCandidate],
+ type: DebugUIElementType
+ ) -> String {
+ let axLabel = bestLabel(group: group.filter { $0.source == .accessibility })
+ if let axLabel,
+ !Self.isGenericLabel(axLabel, type: type) {
+ return axLabel
+ }
+ if let insideText = bestLabel(group: group.filter { $0.source == .ocr }) {
+ return insideText
+ }
+ if let axLabel {
+ return axLabel
+ }
+ if let templateLabel = bestLabel(group: group.filter { $0.source == .template }) {
+ return templateLabel
+ }
+ if let hinted = bestLabel(group: group) {
+ return hinted
+ }
+ return type.rawValue.replacingOccurrences(of: "_", with: " ")
+ }
+
+ private func bestLabel(group: [LocalUIElementCandidate]) -> String? {
+ group
+ .compactMap { $0.label?.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .first { !$0.isEmpty }
+ }
+
+ private func bestBounds(group: [LocalUIElementCandidate]) -> HotLoopRect {
+ if let accessibility = group.first(where: { $0.source == .accessibility }) {
+ return accessibility.bounds
+ }
+ if let shape = group.first(where: { $0.source == .shape }) {
+ return shape.bounds
+ }
+ return group.sorted(by: Self.candidateSort).first?.bounds
+ ?? HotLoopRect(x: 0, y: 0, width: 1, height: 1, space: .screen)
+ }
+
+ private func actionEligibility(
+ for group: [LocalUIElementCandidate],
+ type: DebugUIElementType
+ ) -> LocalUIElementActionEligibility {
+ if group.contains(where: { candidate in
+ candidate.source == .accessibility
+ && candidate.actions.contains { action in action == "AXPress" || action == "AXSetValue" }
+ }) {
+ return .guardedAction
+ }
+ if [.button, .input, .link, .checkbox, .toggle, .dropdown, .menuItem, .toolbarIcon, .sidebarItem, .listItem].contains(type) {
+ return .cursorVisualization
+ }
+ return .readOnlyEvidence
+ }
+
+ private func reasonCodes(
+ for group: [LocalUIElementCandidate],
+ type: DebugUIElementType,
+ label: String,
+ eligibility: LocalUIElementActionEligibility
+ ) -> [String] {
+ var reasons = Set(group.map { "\($0.source.rawValue).\($0.signalKind.rawValue)" })
+ if group.contains(where: { $0.source == .accessibility }) {
+ reasons.insert("axWinsSemantics")
+ }
+ if group.contains(where: { $0.source == .ocr }), !label.isEmpty {
+ reasons.insert("ocrContributesLabel")
+ }
+ if group.count > 1 {
+ reasons.insert("mergedOverlappingCandidates")
+ }
+ reasons.insert("classifiedAs.\(type.rawValue)")
+ reasons.insert("eligibility.\(eligibility.rawValue)")
+ return Array(reasons).sorted()
+ }
+
+ private func stableElementID(
+ primary: LocalUIElementCandidate,
+ type: DebugUIElementType,
+ label: String,
+ index: Int
+ ) -> String {
+ if primary.source == .accessibility {
+ return primary.id
+ }
+ let labelSlug = Self.slug(label.isEmpty ? type.rawValue : label)
+ return "local-ui-\(type.rawValue)-\(labelSlug)-\(index)"
+ }
+
+ private func metrics(
+ candidates: [LocalUIElementCandidate],
+ elements: [LocalUIElement],
+ suppressed: [LocalUIElementSuppressedCandidate],
+ minConfidence: Double,
+ latencyMS: [String: Double]
+ ) -> LocalUIElementDetectionMetrics {
+ let sourceCounts = Dictionary(
+ grouping: candidates,
+ by: { $0.source.rawValue }
+ ).mapValues(\.count)
+ let cvOnlyCount = elements.filter { element in
+ !element.sources.contains(.accessibility)
+ }.count
+ return LocalUIElementDetectionMetrics(
+ sourceCounts: sourceCounts,
+ candidateCount: candidates.count,
+ elementCount: elements.count,
+ suppressedCount: suppressed.count,
+ duplicateCount: suppressed.filter { $0.reason == "mergedDuplicate" }.count,
+ cvOnlyElementCount: cvOnlyCount,
+ minConfidence: minConfidence,
+ latencyMS: latencyMS
+ )
+ }
+
+ private static func shouldMerge(
+ _ lhs: LocalUIElementCandidate,
+ _ rhs: LocalUIElementCandidate
+ ) -> Bool {
+ if isStructuralContainer(lhs) != isStructuralContainer(rhs) {
+ return false
+ }
+
+ let iou = intersectionOverUnion(lhs.bounds, rhs.bounds)
+ if iou >= 0.30 { return true }
+ if contains(lhs.bounds, rhs.bounds) || contains(rhs.bounds, lhs.bounds) {
+ return true
+ }
+ if lhs.source == .ocr || rhs.source == .ocr {
+ return center(lhs.bounds, inside: rhs.bounds) || center(rhs.bounds, inside: lhs.bounds)
+ }
+ return false
+ }
+
+ private static func isStructuralContainer(_ candidate: LocalUIElementCandidate) -> Bool {
+ candidate.typeHint == .draggable
+ || candidate.role == "AXWindow"
+ || candidate.role == "AXSheet"
+ || candidate.metadata["element.kind"] == "window"
+ }
+
+ private static func candidateSort(_ lhs: LocalUIElementCandidate, _ rhs: LocalUIElementCandidate) -> Bool {
+ if sourcePriority(lhs.source) != sourcePriority(rhs.source) {
+ return sourcePriority(lhs.source) < sourcePriority(rhs.source)
+ }
+ if lhs.confidence != rhs.confidence {
+ return lhs.confidence > rhs.confidence
+ }
+ return lhs.id < rhs.id
+ }
+
+ private static func sourcePriority(_ source: LocalUIElementCandidateSource) -> Int {
+ switch source {
+ case .accessibility: return 0
+ case .hoverProbe: return 1
+ case .template: return 2
+ case .layout: return 3
+ case .shape: return 4
+ case .ocr: return 5
+ case .color: return 6
+ case .connectedComponent: return 7
+ }
+ }
+
+ private func rowLayoutCandidates(
+ from candidates: [LocalUIElementCandidate],
+ pixelSize: HotLoopSize
+ ) -> [LocalUIElementCandidate] {
+ let textCandidates = candidates
+ .filter { $0.source == .ocr && $0.bounds.size.height >= 8 }
+ .sorted { lhs, rhs in
+ if lhs.bounds.origin.y != rhs.bounds.origin.y {
+ return lhs.bounds.origin.y < rhs.bounds.origin.y
+ }
+ return lhs.bounds.origin.x < rhs.bounds.origin.x
+ }
+ guard textCandidates.count >= 3,
+ pixelSize.width > 0,
+ pixelSize.height > 0
+ else {
+ return []
+ }
+
+ let medianHeight = Self.median(textCandidates.map(\.bounds.size.height))
+ let rowHeight = min(max(medianHeight * 2.35, 28), 58)
+ let leftEdge = max(0, (textCandidates.map(\.bounds.origin.x).min() ?? 0) - 18)
+ let rightTextEdge = textCandidates
+ .map { $0.bounds.origin.x + $0.bounds.size.width }
+ .max() ?? pixelSize.width
+ let rightEdge = min(pixelSize.width, max(rightTextEdge + 28, pixelSize.width - 34))
+ let width = max(1, rightEdge - leftEdge)
+
+ var rows: [LocalUIElementCandidate] = []
+ for (index, text) in textCandidates.enumerated() {
+ let centerY = text.bounds.origin.y + text.bounds.size.height / 2
+ if rows.contains(where: { existing in
+ abs((existing.bounds.origin.y + existing.bounds.size.height / 2) - centerY) < rowHeight * 0.45
+ }) {
+ continue
+ }
+
+ let y = min(max(centerY - rowHeight / 2, 0), max(0, pixelSize.height - rowHeight))
+ rows.append(
+ LocalUIElementCandidate(
+ id: "layout-row-\(index)-\(Self.slug(text.label ?? "row"))",
+ source: .layout,
+ signalKind: .rowGrouping,
+ typeHint: .listItem,
+ label: text.label,
+ bounds: HotLoopRect(
+ x: leftEdge,
+ y: y,
+ width: width,
+ height: rowHeight,
+ space: pixelSize.space
+ ),
+ confidence: 0.58,
+ metadata: [
+ "detector": "local-row-layout",
+ "classification.reason": "ocrRepeatedVerticalListRhythm",
+ "row.height": String(format: "%.1f", rowHeight)
+ ]
+ )
+ )
+ }
+ return rows
+ }
+
+ private static func intersectionOverUnion(_ lhs: HotLoopRect, _ rhs: HotLoopRect) -> Double {
+ let overlap = intersectionArea(lhs, rhs)
+ let union = lhs.size.width * lhs.size.height + rhs.size.width * rhs.size.height - overlap
+ return union > 0 ? overlap / union : 0
+ }
+
+ private static func intersectionArea(_ lhs: HotLoopRect, _ rhs: HotLoopRect) -> Double {
+ let minX = max(lhs.origin.x, rhs.origin.x)
+ let minY = max(lhs.origin.y, rhs.origin.y)
+ let maxX = min(lhs.origin.x + lhs.size.width, rhs.origin.x + rhs.size.width)
+ let maxY = min(lhs.origin.y + lhs.size.height, rhs.origin.y + rhs.size.height)
+ return max(0, maxX - minX) * max(0, maxY - minY)
+ }
+
+ private static func contains(_ outer: HotLoopRect, _ inner: HotLoopRect) -> Bool {
+ guard outer.space == inner.space else { return false }
+ let innerArea = inner.size.width * inner.size.height
+ guard innerArea > 0 else { return false }
+ return intersectionArea(outer, inner) / innerArea >= 0.78
+ }
+
+ private static func center(_ rect: HotLoopRect, inside other: HotLoopRect) -> Bool {
+ guard rect.space == other.space else { return false }
+ let centerX = rect.origin.x + rect.size.width / 2
+ let centerY = rect.origin.y + rect.size.height / 2
+ return centerX >= other.origin.x
+ && centerX <= other.origin.x + other.size.width
+ && centerY >= other.origin.y
+ && centerY <= other.origin.y + other.size.height
+ }
+
+ private static func controlID(for element: LocalUIElement) -> String {
+ slug(element.label.isEmpty ? element.id : element.label)
+ }
+
+ private static func median(_ values: [Double]) -> Double {
+ guard !values.isEmpty else { return 0 }
+ let sorted = values.sorted()
+ let middle = sorted.count / 2
+ if sorted.count % 2 == 0 {
+ return (sorted[middle - 1] + sorted[middle]) / 2
+ }
+ return sorted[middle]
+ }
+
+ private static func localAppKind(for element: LocalUIElement) -> LocalAppControlKind {
+ switch element.type {
+ case .button, .toolbarIcon, .tab, .toggle, .dropdown, .windowControl:
+ return .button
+ case .input:
+ return .textField
+ case .checkbox:
+ return .checkbox
+ case .link:
+ return .link
+ case .menuItem, .sidebarItem:
+ return .menuItem
+ case .listItem:
+ return .listItem
+ case .slider, .draggable, .other:
+ return .unknown
+ }
+ }
+
+ public static func metricsMetadata(_ metrics: LocalUIElementDetectionMetrics) -> [String: String] {
+ var metadata: [String: String] = [
+ "localUIElement.candidateCount": String(metrics.candidateCount),
+ "localUIElement.elementCount": String(metrics.elementCount),
+ "localUIElement.suppressedCount": String(metrics.suppressedCount),
+ "localUIElement.duplicateCount": String(metrics.duplicateCount),
+ "localUIElement.cvOnlyElementCount": String(metrics.cvOnlyElementCount),
+ "localUIElement.minConfidence": String(metrics.minConfidence)
+ ]
+ for (source, count) in metrics.sourceCounts {
+ metadata["localUIElement.source.\(source).count"] = String(count)
+ }
+ for (name, latency) in metrics.latencyMS {
+ metadata["latency.localUIElement.\(name)MS"] = String(format: "%.3f", latency)
+ }
+ return metadata
+ }
+
+ private static func slug(_ value: String) -> String {
+ let normalized = value
+ .lowercased()
+ .split { !$0.isLetter && !$0.isNumber }
+ .prefix(6)
+ .joined(separator: "-")
+ return normalized.isEmpty ? "element" : normalized
+ }
+
+ private static func isGenericLabel(_ label: String, type: DebugUIElementType) -> Bool {
+ let normalized = label
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ .lowercased()
+ .replacingOccurrences(of: "_", with: " ")
+ return normalized.isEmpty
+ || normalized == type.rawValue.replacingOccurrences(of: "_", with: " ")
+ || normalized == "list item"
+ || normalized == "button"
+ || normalized == "checkbox"
+ || normalized == "input"
+ || normalized == "link"
+ || normalized == "other"
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift
new file mode 100644
index 00000000..50caf169
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift
@@ -0,0 +1,528 @@
+import CoreGraphics
+import DonkeyContracts
+import Foundation
+import ImageIO
+@preconcurrency import Vision
+
+public struct LocalUIElementNativeVisualDetector: Sendable {
+ public var maxAnalysisDimension: Int
+
+ public init(maxAnalysisDimension: Int = 900) {
+ self.maxAnalysisDimension = max(120, maxAnalysisDimension)
+ }
+
+ public func candidates(
+ fromPNGData data: Data?,
+ pixelSize: HotLoopSize
+ ) -> (candidates: [LocalUIElementCandidate], latencyMS: [String: Double], metadata: [String: String]) {
+ guard let data,
+ !data.isEmpty,
+ let image = Self.image(from: data)
+ else {
+ return ([], [:], ["nativeVisual.status": "missingImage"])
+ }
+
+ let startedAt = ProcessInfo.processInfo.systemUptime
+ let shapeStartedAt = ProcessInfo.processInfo.systemUptime
+ let shapeCandidates = shapeCandidates(from: image, pixelSize: pixelSize)
+ let shapeMS = (ProcessInfo.processInfo.systemUptime - shapeStartedAt) * 1_000
+
+ let ocrStartedAt = ProcessInfo.processInfo.systemUptime
+ let ocrImage = Self.inspectionImage(from: image, maxDimension: maxAnalysisDimension)
+ let ocrResult = textCandidates(from: ocrImage, pixelSize: pixelSize)
+ let ocrMS = (ProcessInfo.processInfo.systemUptime - ocrStartedAt) * 1_000
+
+ let totalMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
+ return (
+ shapeCandidates + ocrResult.candidates,
+ [
+ "nativeVisual.total": totalMS,
+ "nativeVisual.shape": shapeMS,
+ "nativeVisual.ocr": ocrMS
+ ],
+ [
+ "nativeVisual.status": "completed",
+ "nativeVisual.ocr.status": ocrResult.error == nil ? "completed" : "failed",
+ "nativeVisual.ocr.error": ocrResult.error ?? "",
+ "nativeVisual.ocr.count": String(ocrResult.candidates.count),
+ "nativeVisual.shape.count": String(shapeCandidates.count)
+ ]
+ )
+ }
+
+ private func textCandidates(
+ from image: CGImage,
+ pixelSize: HotLoopSize
+ ) -> (candidates: [LocalUIElementCandidate], error: String?) {
+ let request = VNRecognizeTextRequest()
+ request.recognitionLevel = .fast
+ request.usesLanguageCorrection = true
+ request.recognitionLanguages = ["en-US"]
+
+ let handler = VNImageRequestHandler(cgImage: image, orientation: .up)
+ do {
+ try handler.perform([request])
+ } catch {
+ return ([], String(describing: error))
+ }
+
+ return ((request.results ?? []).enumerated().compactMap { index, observation in
+ guard let candidate = observation.topCandidates(1).first else { return nil }
+ let text = candidate.string.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !text.isEmpty else { return nil }
+
+ let box = observation.boundingBox
+ let bounds = HotLoopRect(
+ x: box.minX * pixelSize.width,
+ y: (1 - box.maxY) * pixelSize.height,
+ width: box.width * pixelSize.width,
+ height: box.height * pixelSize.height,
+ space: pixelSize.space
+ )
+ guard bounds.hasPositiveArea else { return nil }
+
+ return LocalUIElementCandidate(
+ id: "ocr-\(index)-\(Self.slug(text))",
+ source: .ocr,
+ signalKind: .text,
+ label: text,
+ bounds: bounds,
+ confidence: Double(candidate.confidence),
+ metadata: [
+ "detector": "apple-vision-text",
+ "text.length": String(text.count)
+ ]
+ )
+ }, nil)
+ }
+
+ private func shapeCandidates(
+ from image: CGImage,
+ pixelSize: HotLoopSize
+ ) -> [LocalUIElementCandidate] {
+ guard let raster = RasterizedImage(image: image, maxDimension: maxAnalysisDimension) else {
+ return []
+ }
+
+ let components = connectedComponents(in: raster)
+ let scaleX = pixelSize.width / Double(raster.width)
+ let scaleY = pixelSize.height / Double(raster.height)
+ var candidates: [LocalUIElementCandidate] = []
+
+ for (index, component) in components.prefix(180).enumerated() {
+ guard let candidate = candidate(
+ for: component,
+ index: index,
+ scaleX: scaleX,
+ scaleY: scaleY,
+ outputSpace: pixelSize.space,
+ rasterWidth: raster.width,
+ rasterHeight: raster.height
+ ) else {
+ continue
+ }
+ candidates.append(candidate)
+ }
+
+ return candidates
+ }
+
+ private func candidate(
+ for component: PixelComponent,
+ index: Int,
+ scaleX: Double,
+ scaleY: Double,
+ outputSpace: HotLoopCoordinateSpace,
+ rasterWidth: Int,
+ rasterHeight: Int
+ ) -> LocalUIElementCandidate? {
+ let width = Double(component.maxX - component.minX + 1)
+ let height = Double(component.maxY - component.minY + 1)
+ guard width >= 6, height >= 6 else { return nil }
+ guard width <= Double(rasterWidth) * 0.76,
+ height <= Double(rasterHeight) * 0.40
+ else {
+ return nil
+ }
+
+ let area = width * height
+ let fillRatio = Double(component.pixelCount) / max(1, area)
+ let aspect = width / max(1, height)
+ let bounds = HotLoopRect(
+ x: Double(component.minX) * scaleX,
+ y: Double(component.minY) * scaleY,
+ width: width * scaleX,
+ height: height * scaleY,
+ space: outputSpace
+ )
+ let average = component.averageColor
+
+ if let trafficLight = trafficLightCandidate(
+ component: component,
+ bounds: bounds,
+ width: width,
+ height: height,
+ fillRatio: fillRatio,
+ average: average
+ ) {
+ return trafficLight
+ }
+
+ guard component.minY > 2 else {
+ return nil
+ }
+
+ if isBlue(average), width >= 24, height <= 34 {
+ return LocalUIElementCandidate(
+ id: "color-link-\(index)",
+ source: .color,
+ signalKind: .colorCluster,
+ typeHint: .link,
+ label: "link",
+ bounds: bounds,
+ confidence: min(0.78, 0.45 + fillRatio),
+ metadata: [
+ "detector": "native-color-cluster",
+ "color.hint": "blue",
+ "classification.reason": "blueControlOrLink"
+ ]
+ )
+ }
+
+ if width >= 10, width <= 34, height >= 10, height <= 34, aspect >= 0.65, aspect <= 1.45 {
+ return LocalUIElementCandidate(
+ id: "shape-checkbox-\(index)",
+ source: .shape,
+ signalKind: .rectangle,
+ typeHint: .checkbox,
+ bounds: bounds,
+ confidence: 0.64,
+ metadata: [
+ "detector": "native-connected-component",
+ "shape": "square",
+ "classification.reason": "smallSquareControl"
+ ]
+ )
+ }
+
+ if width >= 26, height >= 12, height <= 40, aspect >= 1.7, aspect <= 3.4, fillRatio >= 0.30 {
+ return LocalUIElementCandidate(
+ id: "shape-toggle-\(index)",
+ source: .shape,
+ signalKind: .roundedRectangle,
+ typeHint: .toggle,
+ bounds: bounds,
+ confidence: 0.66,
+ metadata: [
+ "detector": "native-connected-component",
+ "shape": "toggleLike",
+ "classification.reason": "pillControlCluster"
+ ]
+ )
+ }
+
+ guard width >= 34, height >= 16, height <= 76 else {
+ if width >= 10, width <= 52, height >= 10, height <= 52 {
+ return LocalUIElementCandidate(
+ id: "component-icon-\(index)",
+ source: .connectedComponent,
+ signalKind: .connectedComponent,
+ typeHint: .toolbarIcon,
+ bounds: bounds,
+ confidence: 0.42,
+ metadata: [
+ "detector": "native-connected-component",
+ "classification.reason": "smallIconCluster"
+ ]
+ )
+ }
+ return nil
+ }
+
+ let rounded = fillRatio > 0.35 || aspect > 2.6
+ let typeHint: DebugUIElementType = aspect > 3.6 && width >= 140 ? .input : .button
+ return LocalUIElementCandidate(
+ id: "shape-control-\(index)",
+ source: .shape,
+ signalKind: rounded ? .roundedRectangle : .rectangle,
+ typeHint: typeHint,
+ bounds: bounds,
+ confidence: rounded ? 0.62 : 0.56,
+ metadata: [
+ "detector": "native-connected-component",
+ "shape": rounded ? "roundedRectangle" : "rectangle",
+ "shape.fillRatio": String(format: "%.3f", fillRatio),
+ "classification.reason": typeHint == .input ? "wideRoundedControl" : "rectangularControl"
+ ]
+ )
+ }
+
+ private func trafficLightCandidate(
+ component: PixelComponent,
+ bounds: HotLoopRect,
+ width: Double,
+ height: Double,
+ fillRatio: Double,
+ average: AverageColor
+ ) -> LocalUIElementCandidate? {
+ guard width >= 8, width <= 26,
+ height >= 8, height <= 26,
+ width / max(1, height) >= 0.75,
+ width / max(1, height) <= 1.35,
+ fillRatio >= 0.45
+ else {
+ return nil
+ }
+
+ let label: String
+ if average.red > 160, average.green < 120, average.blue < 120 {
+ label = "close"
+ } else if average.red > 150, average.green > 115, average.blue < 80 {
+ label = "minimize"
+ } else if average.green > 130, average.red < 130, average.blue < 130 {
+ label = "zoom"
+ } else {
+ return nil
+ }
+
+ return LocalUIElementCandidate(
+ id: "template-window-control-\(label)-\(component.minX)-\(component.minY)",
+ source: .template,
+ signalKind: .iconTemplate,
+ typeHint: .windowControl,
+ label: label,
+ bounds: bounds,
+ confidence: 0.86,
+ metadata: [
+ "detector": "native-template",
+ "templateID": "macos-traffic-light-\(label)",
+ "classification.reason": "trafficLightColorCluster"
+ ]
+ )
+ }
+
+ private func connectedComponents(in raster: RasterizedImage) -> [PixelComponent] {
+ var visited = [Bool](repeating: false, count: raster.width * raster.height)
+ var components: [PixelComponent] = []
+ let imageArea = raster.width * raster.height
+
+ for y in 0..<raster.height {
+ for x in 0..<raster.width {
+ let index = y * raster.width + x
+ guard !visited[index], raster.isInterestingPixel(x: x, y: y) else {
+ visited[index] = true
+ continue
+ }
+
+ let component = floodFill(
+ startX: x,
+ startY: y,
+ raster: raster,
+ visited: &visited
+ )
+ guard component.pixelCount >= 18,
+ component.pixelCount <= imageArea / 3
+ else {
+ continue
+ }
+ components.append(component)
+ }
+ }
+
+ return components.sorted { lhs, rhs in
+ if lhs.minY != rhs.minY { return lhs.minY < rhs.minY }
+ if lhs.minX != rhs.minX { return lhs.minX < rhs.minX }
+ return lhs.pixelCount > rhs.pixelCount
+ }
+ }
+
+ private func floodFill(
+ startX: Int,
+ startY: Int,
+ raster: RasterizedImage,
+ visited: inout [Bool]
+ ) -> PixelComponent {
+ var stack = [(startX, startY)]
+ var component = PixelComponent(minX: startX, minY: startY, maxX: startX, maxY: startY)
+ visited[startY * raster.width + startX] = true
+
+ while let (x, y) = stack.popLast() {
+ component.add(pixel: raster.pixel(x: x, y: y), x: x, y: y)
+
+ for ny in max(0, y - 1)...min(raster.height - 1, y + 1) {
+ for nx in max(0, x - 1)...min(raster.width - 1, x + 1) {
+ let neighborIndex = ny * raster.width + nx
+ guard !visited[neighborIndex] else { continue }
+ visited[neighborIndex] = true
+ guard raster.isInterestingPixel(x: nx, y: ny) else { continue }
+ stack.append((nx, ny))
+ }
+ }
+ }
+
+ return component
+ }
+
+ private static func image(from data: Data) -> CGImage? {
+ guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
+ return nil
+ }
+ return CGImageSourceCreateImageAtIndex(source, 0, nil)
+ }
+
+ private static func inspectionImage(from image: CGImage, maxDimension: Int) -> CGImage {
+ let longestEdge = max(image.width, image.height)
+ guard longestEdge > maxDimension else {
+ return image
+ }
+
+ let scale = Double(maxDimension) / Double(longestEdge)
+ let width = max(1, Int((Double(image.width) * scale).rounded()))
+ let height = max(1, Int((Double(image.height) * scale).rounded()))
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
+ let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
+ guard let context = CGContext(
+ data: nil,
+ width: width,
+ height: height,
+ bitsPerComponent: 8,
+ bytesPerRow: 0,
+ space: colorSpace,
+ bitmapInfo: bitmapInfo
+ ) else {
+ return image
+ }
+ context.interpolationQuality = .medium
+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
+ return context.makeImage() ?? image
+ }
+
+ private func isBlue(_ color: AverageColor) -> Bool {
+ color.blue > 130 && color.blue > color.red * 1.25 && color.blue > color.green * 1.05
+ }
+
+ private static func slug(_ value: String) -> String {
+ value
+ .lowercased()
+ .split { !$0.isLetter && !$0.isNumber }
+ .prefix(4)
+ .joined(separator: "-")
+ }
+}
+
+private struct RasterizedImage {
+ var width: Int
+ var height: Int
+ var pixels: [UInt8]
+
+ init?(image: CGImage, maxDimension: Int) {
+ let longestEdge = max(image.width, image.height)
+ let scale = longestEdge > maxDimension ? Double(maxDimension) / Double(longestEdge) : 1
+ let width = max(1, Int((Double(image.width) * scale).rounded()))
+ let height = max(1, Int((Double(image.height) * scale).rounded()))
+ let bytesPerPixel = 4
+ let bytesPerRow = width * bytesPerPixel
+ var pixels = [UInt8](repeating: 0, count: height * bytesPerRow)
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
+ let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
+
+ guard let context = CGContext(
+ data: &pixels,
+ width: width,
+ height: height,
+ bitsPerComponent: 8,
+ bytesPerRow: bytesPerRow,
+ space: colorSpace,
+ bitmapInfo: bitmapInfo
+ ) else {
+ return nil
+ }
+ context.interpolationQuality = .medium
+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
+
+ self.width = width
+ self.height = height
+ self.pixels = pixels
+ }
+
+ func pixel(x: Int, y: Int) -> Pixel {
+ let offset = (y * width + x) * 4
+ return Pixel(
+ red: pixels[offset],
+ green: pixels[offset + 1],
+ blue: pixels[offset + 2],
+ alpha: pixels[offset + 3]
+ )
+ }
+
+ func isInterestingPixel(x: Int, y: Int) -> Bool {
+ let pixel = pixel(x: x, y: y)
+ guard pixel.alpha > 28 else { return false }
+ let luminance = pixel.luminance
+ return luminance > 88 || pixel.saturation > 0.28
+ }
+}
+
+private struct Pixel {
+ var red: UInt8
+ var green: UInt8
+ var blue: UInt8
+ var alpha: UInt8
+
+ var luminance: Double {
+ (0.2126 * Double(red) + 0.7152 * Double(green) + 0.0722 * Double(blue))
+ }
+
+ var saturation: Double {
+ let maxChannel = Double(max(red, max(green, blue)))
+ let minChannel = Double(min(red, min(green, blue)))
+ guard maxChannel > 0 else { return 0 }
+ return (maxChannel - minChannel) / maxChannel
+ }
+}
+
+private struct AverageColor: Equatable {
+ var red: Double
+ var green: Double
+ var blue: Double
+}
+
+private struct PixelComponent {
+ var minX: Int
+ var minY: Int
+ var maxX: Int
+ var maxY: Int
+ var pixelCount: Int = 0
+ private var redTotal: Int = 0
+ private var greenTotal: Int = 0
+ private var blueTotal: Int = 0
+
+ init(minX: Int, minY: Int, maxX: Int, maxY: Int) {
+ self.minX = minX
+ self.minY = minY
+ self.maxX = maxX
+ self.maxY = maxY
+ }
+
+ mutating func add(pixel: Pixel, x: Int, y: Int) {
+ minX = min(minX, x)
+ minY = min(minY, y)
+ maxX = max(maxX, x)
+ maxY = max(maxY, y)
+ pixelCount += 1
+ redTotal += Int(pixel.red)
+ greenTotal += Int(pixel.green)
+ blueTotal += Int(pixel.blue)
+ }
+
+ var averageColor: AverageColor {
+ guard pixelCount > 0 else {
+ return AverageColor(red: 0, green: 0, blue: 0)
+ }
+ return AverageColor(
+ red: Double(redTotal) / Double(pixelCount),
+ green: Double(greenTotal) / Double(pixelCount),
+ blue: Double(blueTotal) / Double(pixelCount)
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyUIUnderstandingSidecar/main.swift b/apps/Donkey/Sources/DonkeyUIUnderstandingSidecar/main.swift
index fb7f650e..4b9c31ea 100644
--- a/apps/Donkey/Sources/DonkeyUIUnderstandingSidecar/main.swift
+++ b/apps/Donkey/Sources/DonkeyUIUnderstandingSidecar/main.swift
@@ -2,6 +2,8 @@ import AppKit
import DonkeyContracts
import DonkeyRuntime
import Foundation
+import ImageIO
+import UniformTypeIdentifiers
@preconcurrency import Vision
private struct SidecarRequest: Codable {
@@ -15,6 +17,7 @@ private struct SidecarRequest: Codable {
var targetID: String?
var imagePath: String?
var artifactURL: String?
+ var outputDirectory: String?
var cropBounds: HotLoopRect?
var pixelSize: HotLoopSize?
var metadata: [String: String]?
@@ -44,6 +47,23 @@ private struct ErrorResponse: Codable {
var metadata: [String: String]
}
+private struct DebugInspectionArtifactResponse: Codable {
+ var status: String
+ var runtimeID: String
+ var modelID: String
+ var artifacts: [DebugInspectionArtifact]
+ var metadata: [String: String]
+}
+
+private struct DebugInspectionArtifact: Codable {
+ var screenID: UInt32
+ var screenshotPath: String
+ var annotatedPath: String
+ var framePath: String
+ var elementCount: Int
+ var metadata: [String: String]
+}
+
private let runtimeID = ProcessInfo.processInfo.environment["DONKEY_RUNTIME_ID"] ?? "ui-understander"
private let runtimeVersion = ProcessInfo.processInfo.environment["DONKEY_RUNTIME_VERSION"] ?? "0.3.0-runner"
private let modelID = ProcessInfo.processInfo.environment["DONKEY_MODEL_ID"] ?? "apple-vision-text-recognition"
@@ -60,6 +80,8 @@ struct DonkeyUIUnderstandingSidecar {
output = try JSONEncoder().encode(health())
case "prepareModelWeights":
output = try JSONEncoder().encode(prepared(cacheDirectory: request.cacheDirectory))
+ case "debugInspectAccessibility":
+ output = try JSONEncoder().encode(try debugInspectAccessibility(request))
default:
output = try JSONEncoder().encode(try understand(request))
}
@@ -110,6 +132,77 @@ struct DonkeyUIUnderstandingSidecar {
)
}
+ private static func debugInspectAccessibility(_ request: SidecarRequest) throws -> DebugInspectionArtifactResponse {
+ let outputDirectory = URL(
+ fileURLWithPath: request.outputDirectory
+ ?? request.artifactURL
+ ?? FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-debug-ui-inspection", isDirectory: true)
+ .path,
+ isDirectory: true
+ )
+ try FileManager.default.createDirectory(at: outputDirectory, withIntermediateDirectories: true)
+
+ let minConfidence = Double(request.metadata?["minConfidence"] ?? "") ?? 0.25
+ let startedAt = ProcessInfo.processInfo.systemUptime
+ let results = try DebugUIAccessibilityInspectionService().inspect(
+ scope: DebugUIInspectionScreenScope(rawValue: request.metadata?["screenScope"] ?? "") ?? .main,
+ minConfidence: minConfidence,
+ frontmostOnly: request.metadata?["frontmostOnly"] == "true",
+ focusedOnly: request.metadata?["focusedOnly"] == "true",
+ targetBundleIdentifiers: commaSeparatedList(request.metadata?["targetBundleIdentifiers"]),
+ targetAppNames: commaSeparatedList(request.metadata?["targetAppNames"])
+ )
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+
+ let prefix = slug(request.traceID ?? request.targetID ?? "debug-ui")
+ let artifacts = try results.map { result in
+ let screenSlug = "\(prefix)-screen-\(result.snapshot.screenID)"
+ let screenshotURL = outputDirectory.appendingPathComponent("\(screenSlug).png")
+ let frameURL = outputDirectory.appendingPathComponent("\(screenSlug).frame.json")
+ let annotatedURL = outputDirectory.appendingPathComponent("\(screenSlug).annotated.png")
+
+ try result.snapshot.pngData.write(to: screenshotURL, options: .atomic)
+ try encoder.encode(result.frame).write(to: frameURL, options: .atomic)
+ let annotated = annotatedPNGData(
+ screenshotPNGData: result.snapshot.pngData,
+ frame: result.frame
+ ) ?? result.snapshot.pngData
+ try annotated.write(to: annotatedURL, options: .atomic)
+
+ return DebugInspectionArtifact(
+ screenID: result.snapshot.screenID,
+ screenshotPath: screenshotURL.path,
+ annotatedPath: annotatedURL.path,
+ framePath: frameURL.path,
+ elementCount: result.frame.elements.count,
+ metadata: [
+ "snapshot.fingerprint": result.snapshot.fingerprint,
+ "pixel.width": String(result.snapshot.pixelSize.width),
+ "pixel.height": String(result.snapshot.pixelSize.height)
+ ]
+ )
+ }
+ let elapsedMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
+ return DebugInspectionArtifactResponse(
+ status: "ok",
+ runtimeID: runtimeID,
+ modelID: modelID,
+ artifacts: artifacts,
+ metadata: [
+ "runtime.backend": "accessibility-native-ui-detection",
+ "targetID": request.targetID ?? "",
+ "traceID": request.traceID ?? "",
+ "artifact.count": String(artifacts.count),
+ "element.count": String(artifacts.map(\.elementCount).reduce(0, +)),
+ "latency.debugInspectAccessibilityMS": String(format: "%.3f", elapsedMS),
+ "visibleSystemA11yToggled": "false",
+ "rawPixelsPersisted": "true"
+ ]
+ )
+ }
+
private static func understand(_ request: SidecarRequest) throws -> LocalUIUnderstandingResult {
guard let imagePath = request.imagePath, !imagePath.isEmpty else {
return LocalUIUnderstandingResult(
@@ -122,47 +215,49 @@ struct DonkeyUIUnderstandingSidecar {
}
let imageURL = URL(fileURLWithPath: imagePath)
+ let imageData = try Data(contentsOf: imageURL)
+ let pixelSize = request.pixelSize ?? imagePixelSize(from: imageData)
let startedAt = ProcessInfo.processInfo.systemUptime
- let observations = try recognizedText(in: imageURL)
- let elapsedMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
- var visibleText: [String: String] = [:]
- var controls: [LocalUIUnderstandingControl] = []
- var totalConfidence = 0.0
-
- for (index, item) in observations.enumerated() {
- let id = "vision-text-\(index)"
- visibleText[id] = item.text
- totalConfidence += item.confidence
- controls.append(
- LocalUIUnderstandingControl(
- id: id,
- label: item.text,
- kind: .unknown,
- frame: item.frame,
- confidence: item.confidence,
- metadata: [
- "controlID": id,
- "source": "apple-vision-text-recognition"
- ]
- )
+ let trace = LocalUIElementDetectionService().detect(
+ LocalUIElementDetectionRequest(
+ traceID: request.traceID ?? "ui-understanding-\(UUID().uuidString)",
+ screenshotPNGData: imageData,
+ pixelSize: pixelSize,
+ minConfidence: Double(request.metadata?["minConfidence"] ?? "") ?? 0.25,
+ metadata: [
+ "runtime.backend": "apple-vision-native-ui-detection",
+ "targetID": request.targetID ?? ""
+ ].merging(request.metadata ?? [:]) { current, _ in current }
)
- }
-
- let averageConfidence = observations.isEmpty ? 0 : totalConfidence / Double(observations.count)
+ )
+ let elapsedMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
+ let result = LocalUIElementDetectionService().localUIUnderstandingResult(from: trace)
return LocalUIUnderstandingResult(
- visibleText: visibleText,
- controls: controls,
- formFields: [],
- confidence: averageConfidence,
- metadata: [
- "runtime.backend": "apple-vision",
- "recognition.count": String(observations.count),
- "latency.appleVisionTextMS": String(format: "%.3f", elapsedMS),
+ visibleText: result.visibleText,
+ controls: result.controls,
+ formFields: result.formFields,
+ confidence: result.confidence,
+ metadata: result.metadata.merging([
+ "runtime.backend": "apple-vision-native-ui-detection",
+ "recognition.count": String(trace.candidates.filter { $0.source == .ocr }.count),
+ "latency.appleVisionTextMS": String(format: "%.3f", trace.metrics.latencyMS["nativeVisual.ocr"] ?? 0),
+ "latency.localUIElementSidecarMS": String(format: "%.3f", elapsedMS),
"directInputActionsAllowed": "false"
- ]
+ ]) { current, _ in current }
)
}
+ private static func imagePixelSize(from data: Data) -> HotLoopSize {
+ guard let source = CGImageSourceCreateWithData(data as CFData, nil),
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
+ let width = properties[kCGImagePropertyPixelWidth] as? NSNumber,
+ let height = properties[kCGImagePropertyPixelHeight] as? NSNumber
+ else {
+ return HotLoopSize(width: 1, height: 1, space: .screen)
+ }
+ return HotLoopSize(width: width.doubleValue, height: height.doubleValue, space: .screen)
+ }
+
private static func recognizedText(in imageURL: URL) throws -> [(text: String, confidence: Double, frame: HotLoopRect)] {
let request = VNRecognizeTextRequest()
request.recognitionLevel = .fast
@@ -192,4 +287,153 @@ struct DonkeyUIUnderstandingSidecar {
)
}
}
+
+ private static func annotatedPNGData(
+ screenshotPNGData: Data,
+ frame: DebugUIInspectionFrame
+ ) -> Data? {
+ guard let source = CGImageSourceCreateWithData(screenshotPNGData as CFData, nil),
+ let image = CGImageSourceCreateImageAtIndex(source, 0, nil)
+ else {
+ return nil
+ }
+
+ let width = image.width
+ let height = image.height
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
+ let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
+ guard let context = CGContext(
+ data: nil,
+ width: width,
+ height: height,
+ bitsPerComponent: 8,
+ bytesPerRow: 0,
+ space: colorSpace,
+ bitmapInfo: bitmapInfo
+ ) else {
+ return nil
+ }
+
+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
+ context.setLineWidth(2)
+ for element in frame.elements {
+ let rect = CGRect(
+ x: element.bbox.x,
+ y: Double(height) - element.bbox.y - element.bbox.height,
+ width: element.bbox.width,
+ height: element.bbox.height
+ ).integral
+ guard rect.width > 1, rect.height > 1 else { continue }
+
+ let border = nsColor(hex: element.visualStyle.borderColor) ?? .systemBlue
+ context.setStrokeColor(border.cgColor)
+ context.setFillColor(border.withAlphaComponent(0.13).cgColor)
+ context.fill(rect)
+ context.stroke(rect)
+
+ let label = annotationLabel(for: element)
+ guard !label.isEmpty else { continue }
+ let labelHeight: CGFloat = 18
+ let labelWidth = min(
+ CGFloat(width) - rect.minX - 4,
+ max(44, CGFloat(label.count) * 6.7 + 10)
+ )
+ let labelY = min(CGFloat(height) - labelHeight - 2, max(2, rect.maxY - labelHeight))
+ let labelRect = CGRect(
+ x: rect.minX,
+ y: labelY,
+ width: labelWidth,
+ height: labelHeight
+ )
+ context.setFillColor(border.withAlphaComponent(0.82).cgColor)
+ context.fill(labelRect)
+
+ let nsContext = NSGraphicsContext(cgContext: context, flipped: false)
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = nsContext
+ (label as NSString).draw(
+ in: labelRect.insetBy(dx: 4, dy: 2),
+ withAttributes: [
+ .foregroundColor: NSColor.white,
+ .font: NSFont.systemFont(ofSize: 10, weight: .semibold)
+ ]
+ )
+ NSGraphicsContext.restoreGraphicsState()
+ }
+
+ guard let output = context.makeImage() else {
+ return nil
+ }
+ let data = NSMutableData()
+ guard let destination = CGImageDestinationCreateWithData(
+ data,
+ UTType.png.identifier as CFString,
+ 1,
+ nil
+ ) else {
+ return nil
+ }
+ CGImageDestinationAddImage(destination, output, nil)
+ guard CGImageDestinationFinalize(destination) else {
+ return nil
+ }
+ return data as Data
+ }
+
+ private static func annotationLabel(for element: DebugUIElement) -> String {
+ let sources = (element.metadata["localUIElement.sources"] ?? "")
+ .split(separator: ",")
+ .map(sourceBadge)
+ .filter { !$0.isEmpty }
+ .joined(separator: "+")
+ let label = element.label.trimmingCharacters(in: .whitespacesAndNewlines)
+ let title = label.isEmpty ? element.type.rawValue : label
+ let cappedTitle = title.count > 34 ? "\(title.prefix(31))..." : title
+ return sources.isEmpty ? cappedTitle : "[\(sources)] \(cappedTitle)"
+ }
+
+ private static func sourceBadge(_ source: Substring) -> String {
+ switch source {
+ case "accessibility": return "AX"
+ case "ocr": return "OCR"
+ case "shape": return "SHAPE"
+ case "template": return "TPL"
+ case "color": return "COLOR"
+ case "connectedComponent": return "CC"
+ case "hoverProbe": return "HOVER"
+ case "layout": return "LAYOUT"
+ default: return String(source).uppercased()
+ }
+ }
+
+ private static func nsColor(hex: String) -> NSColor? {
+ let trimmed = hex.trimmingCharacters(in: CharacterSet(charactersIn: "#"))
+ guard trimmed.count == 6,
+ let value = Int(trimmed, radix: 16)
+ else {
+ return nil
+ }
+ return NSColor(
+ calibratedRed: CGFloat((value >> 16) & 0xFF) / 255,
+ green: CGFloat((value >> 8) & 0xFF) / 255,
+ blue: CGFloat(value & 0xFF) / 255,
+ alpha: 1
+ )
+ }
+
+ private static func slug(_ value: String) -> String {
+ let slug = value
+ .lowercased()
+ .split { !$0.isLetter && !$0.isNumber }
+ .prefix(8)
+ .joined(separator: "-")
+ return slug.isEmpty ? "debug-ui" : slug
+ }
+
+ private static func commaSeparatedList(_ value: String?) -> [String] {
+ (value ?? "")
+ .split(separator: ",")
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ }
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift
index 412555cf..2b6700ea 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift
@@ -45,6 +45,32 @@ struct DebugUIInspectionTests {
#expect(config.cadenceSeconds == 1.0)
#expect(config.screenScope == .main)
#expect(config.minConfidence == 0.25)
+ #expect(config.activeWindowOnly == false)
+ #expect(config.targetBundleIdentifiers.isEmpty)
+ #expect(config.targetAppNames.isEmpty)
+ }
+
+ @Test
+ func configLoadsTargetFilters() throws {
+ let url = temporaryDirectory()
+ .appendingPathComponent("targeted-dev-overlay.json", isDirectory: false)
+ try Data(
+ """
+ {
+ "enabled": true,
+ "activeWindowOnly": true,
+ "targetBundleIdentifiers": ["com.apple.Music", " com.apple.Music "],
+ "targetAppNames": ["Music"]
+ }
+ """.utf8
+ ).write(to: url, options: .atomic)
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ let config = DebugUIOverlayConfiguration.load(fileURL: url)
+
+ #expect(config.targetBundleIdentifiers == ["com.apple.Music"])
+ #expect(config.targetAppNames == ["Music"])
+ #expect(config.activeWindowOnly == true)
}
@Test
@@ -156,6 +182,20 @@ struct DebugUIInspectionTests {
#expect(updated.elements.first?.id == "button-1")
}
+ @Test
+ func trackerFreezesTinyBoundingBoxJitter() {
+ var tracker = DebugUIElementTracker()
+ _ = tracker.update(with: DebugUIInspectionFrame(elements: [
+ element(id: "button-1", label: "Save", x: 10, y: 20)
+ ]))
+
+ let updated = tracker.update(with: DebugUIInspectionFrame(elements: [
+ element(id: "button-1", label: "Save", x: 11.4, y: 20.8)
+ ]))
+
+ #expect(updated.elements.first?.bbox == DebugUIBoundingBox(x: 10, y: 20, width: 80, height: 30))
+ }
+
@Test
func geometryConvertsScreenshotPixelsToAppKitPoints() {
let frame = DebugUIOverlayGeometry.appKitFrame(
@@ -266,11 +306,14 @@ struct DebugUIInspectionTests {
#expect(capturer.capturedWindowIDs == [11])
#expect(results.map(\.snapshot.screenID) == [3])
- #expect(results.first?.frame.elements.count == 1)
- let element = results.first?.frame.elements.first
- #expect(element?.id == "window-11")
- #expect(element?.label == "Notes")
- #expect(element?.bbox == DebugUIBoundingBox(x: 100, y: 200, width: 500, height: 300))
+ #expect(results.first?.frame.elements.map(\.id) == ["window-11", "ax-11-ax-1.1"])
+ let window = results.first?.frame.elements.first
+ #expect(window?.label == "Notes")
+ #expect(window?.bbox == DebugUIBoundingBox(x: 100, y: 200, width: 500, height: 300))
+ let button = results.first?.frame.elements.last
+ #expect(button?.type == .button)
+ #expect(button?.label == "Save")
+ #expect(button?.bbox == DebugUIBoundingBox(x: 120, y: 230, width: 80, height: 30))
}
@Test
@@ -303,7 +346,227 @@ struct DebugUIInspectionTests {
let results = try service.inspect(scope: .main, minConfidence: 0.25)
#expect(capturer.capturedWindowIDs.isEmpty)
- #expect(results.first?.frame.elements.isEmpty == true)
+ #expect(results.isEmpty)
+ }
+
+ @Test
+ func accessibilityInspectionCanTargetMusicOnly() throws {
+ let screen = DebugUIScreenMetadata(
+ screenID: 1,
+ appKitFrame: HotLoopRect(x: 0, y: 0, width: 1000, height: 800, space: .screen),
+ captureFrame: WindowTargetBounds(x: 0, y: 0, width: 1000, height: 800)
+ )
+ let capturer = DebugUIFakeAccessibilityCapturer(
+ treesByWindowID: [
+ 1: MacAccessibilitySnapshotTreeBuilder.build(
+ root: RawMacAccessibilitySnapshotNode(
+ role: "AXWindow",
+ title: "Music",
+ frame: WindowTargetBounds(x: 0, y: 0, width: 500, height: 400),
+ children: [
+ RawMacAccessibilitySnapshotNode(
+ role: "AXButton",
+ title: "Play",
+ frame: WindowTargetBounds(x: 40, y: 60, width: 80, height: 34),
+ isEnabled: true,
+ actions: ["AXPress"]
+ )
+ ]
+ ),
+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)
+ ),
+ 2: MacAccessibilitySnapshotTreeBuilder.build(
+ root: RawMacAccessibilitySnapshotNode(
+ role: "AXWindow",
+ title: "Notes",
+ frame: WindowTargetBounds(x: 500, y: 0, width: 500, height: 400),
+ children: [
+ RawMacAccessibilitySnapshotNode(
+ role: "AXButton",
+ title: "New Note",
+ frame: WindowTargetBounds(x: 520, y: 60, width: 100, height: 34),
+ isEnabled: true,
+ actions: ["AXPress"]
+ )
+ ]
+ ),
+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)
+ )
+ ]
+ )
+ let service = DebugUIAccessibilityInspectionService(
+ windowResolver: MacWindowResolver(
+ provider: DebugUIFixtureWindowProvider(
+ windows: [
+ MacWindowProviderWindow(
+ windowID: 1,
+ processID: 100,
+ appName: "Music",
+ bundleIdentifier: "com.apple.Music",
+ bounds: WindowTargetBounds(x: 0, y: 0, width: 500, height: 400)
+ ),
+ MacWindowProviderWindow(
+ windowID: 2,
+ processID: 200,
+ appName: "Notes",
+ bundleIdentifier: "com.apple.Notes",
+ bounds: WindowTargetBounds(x: 500, y: 0, width: 500, height: 400)
+ )
+ ],
+ frontmostProcessID: 100
+ )
+ ),
+ capturer: capturer,
+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),
+ currentProcessID: 999
+ )
+
+ let results = try service.inspect(
+ scope: .main,
+ minConfidence: 0.25,
+ targetBundleIdentifiers: ["com.apple.Music"],
+ targetAppNames: ["Music"]
+ )
+
+ #expect(capturer.capturedWindowIDs == [1])
+ #expect(results.first?.frame.elements.map(\.label).contains("Music") == true)
+ #expect(results.first?.frame.elements.map(\.label).contains("Play") == true)
+ #expect(results.first?.frame.elements.map(\.label).contains("Notes") == false)
+ #expect(results.first?.frame.elements.map(\.label).contains("New Note") == false)
+ }
+
+ @Test
+ func accessibilityInspectionRequiresFocusedMusicWhenRequested() throws {
+ let screen = DebugUIScreenMetadata(
+ screenID: 1,
+ appKitFrame: HotLoopRect(x: 0, y: 0, width: 1000, height: 800, space: .screen),
+ captureFrame: WindowTargetBounds(x: 0, y: 0, width: 1000, height: 800)
+ )
+ let capturer = DebugUIFakeAccessibilityCapturer(
+ treesByWindowID: [
+ 1: MacAccessibilitySnapshotTreeBuilder.build(
+ root: RawMacAccessibilitySnapshotNode(
+ role: "AXWindow",
+ title: "Music",
+ frame: WindowTargetBounds(x: 0, y: 0, width: 500, height: 400),
+ children: [
+ RawMacAccessibilitySnapshotNode(
+ role: "AXButton",
+ title: "Play",
+ frame: WindowTargetBounds(x: 40, y: 60, width: 80, height: 34),
+ isEnabled: true,
+ actions: ["AXPress"]
+ )
+ ]
+ ),
+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)
+ )
+ ]
+ )
+ let service = DebugUIAccessibilityInspectionService(
+ windowResolver: MacWindowResolver(
+ provider: DebugUIFixtureWindowProvider(
+ windows: [
+ MacWindowProviderWindow(
+ windowID: 1,
+ processID: 100,
+ appName: "Music",
+ bundleIdentifier: "com.apple.Music",
+ bounds: WindowTargetBounds(x: 0, y: 0, width: 500, height: 400)
+ ),
+ MacWindowProviderWindow(
+ windowID: 2,
+ processID: 200,
+ appName: "Notes",
+ bundleIdentifier: "com.apple.Notes",
+ bounds: WindowTargetBounds(x: 500, y: 0, width: 500, height: 400)
+ )
+ ],
+ frontmostProcessID: 200,
+ focusedWindowID: 2
+ )
+ ),
+ capturer: capturer,
+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),
+ currentProcessID: 999
+ )
+
+ let results = try service.inspect(
+ scope: .main,
+ minConfidence: 0.25,
+ frontmostOnly: true,
+ focusedOnly: true,
+ targetBundleIdentifiers: ["com.apple.Music"],
+ targetAppNames: ["Music"]
+ )
+
+ #expect(results.isEmpty)
+ #expect(capturer.capturedWindowIDs.isEmpty)
+ }
+
+ @Test
+ func accessibilityInspectionScalesAXBoxesToDownsampledScreenshotPixels() throws {
+ let screen = DebugUIScreenMetadata(
+ screenID: 1,
+ appKitFrame: HotLoopRect(x: 0, y: 0, width: 1000, height: 800, space: .screen),
+ captureFrame: WindowTargetBounds(x: 0, y: 0, width: 1000, height: 800)
+ )
+ let capturer = DebugUIFakeAccessibilityCapturer(
+ tree: MacAccessibilitySnapshotTreeBuilder.build(
+ root: RawMacAccessibilitySnapshotNode(
+ role: "AXWindow",
+ title: "Music",
+ frame: WindowTargetBounds(x: 100, y: 200, width: 500, height: 300),
+ children: [
+ RawMacAccessibilitySnapshotNode(
+ role: "AXButton",
+ title: "Play",
+ frame: WindowTargetBounds(x: 120, y: 240, width: 80, height: 32),
+ isEnabled: true,
+ actions: ["AXPress"]
+ )
+ ]
+ ),
+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)
+ )
+ )
+ let service = DebugUIAccessibilityInspectionService(
+ windowResolver: MacWindowResolver(
+ provider: DebugUIFixtureWindowProvider(
+ windows: [
+ MacWindowProviderWindow(
+ windowID: 1,
+ processID: 100,
+ appName: "Music",
+ bundleIdentifier: "com.apple.Music",
+ bounds: WindowTargetBounds(x: 100, y: 200, width: 500, height: 300)
+ )
+ ],
+ frontmostProcessID: 100
+ )
+ ),
+ capturer: capturer,
+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),
+ screenCapturer: DebugUIFixtureScreenCapturer(
+ snapshots: [
+ DebugUIScreenCaptureSnapshot(
+ screenID: 1,
+ screenFrame: screen.appKitFrame,
+ pixelSize: HotLoopSize(width: 500, height: 400, space: .screen),
+ pngData: Data(),
+ fingerprint: "downsampled"
+ )
+ ]
+ ),
+ currentProcessID: 999
+ )
+
+ let results = try service.inspect(scope: .main, minConfidence: 0.25)
+ let window = try #require(results.first?.frame.elements.first { $0.id == "window-1" })
+ let play = try #require(results.first?.frame.elements.first { $0.label == "Play" })
+
+ #expect(window.bbox == DebugUIBoundingBox(x: 50, y: 100, width: 250, height: 150))
+ #expect(play.bbox == DebugUIBoundingBox(x: 60, y: 120, width: 40, height: 16))
}
@Test
@@ -379,8 +642,8 @@ struct DebugUIInspectionTests {
let results = try service.inspect(scope: .main, minConfidence: 0.25)
#expect(capturer.capturedWindowIDs == [1, 2])
- #expect(results.first?.frame.elements.map(\.id) == ["window-1"])
- #expect(results.first?.frame.elements.map(\.label) == ["Front"])
+ #expect(results.first?.frame.elements.map(\.id) == ["window-1", "ax-1-ax-1.1"])
+ #expect(results.first?.frame.elements.map(\.label) == ["Front", "Visible"])
}
@Test
@@ -444,7 +707,7 @@ struct DebugUIInspectionTests {
}
@Test
- func accessibilityInspectionIgnoresChildElementsWhenDrawingWindowFramesOnly() throws {
+ func accessibilityInspectionFiltersLargeTextAreasButKeepsUsableInputs() throws {
let screen = DebugUIScreenMetadata(
screenID: 1,
appKitFrame: HotLoopRect(x: 0, y: 0, width: 1000, height: 800, space: .screen),
@@ -496,7 +759,9 @@ struct DebugUIInspectionTests {
let results = try service.inspect(scope: .main, minConfidence: 0.25)
#expect(capturer.capturedWindowIDs == [1])
- #expect(results.first?.frame.elements.map(\.id) == ["window-1"])
+ #expect(results.first?.frame.elements.map(\.id) == ["window-1", "ax-1-ax-1.2"])
+ #expect(results.first?.frame.elements.last?.type == .input)
+ #expect(results.first?.frame.elements.last?.label == "Search")
#expect(results.first?.frame.elements.first?.bbox == DebugUIBoundingBox(
x: 0,
y: 0,
@@ -506,7 +771,7 @@ struct DebugUIInspectionTests {
}
@Test
- func accessibilityInspectionDrawsMusicWindowFrameOnly() throws {
+ func accessibilityInspectionDrawsMusicWindowAndClickableCardTile() throws {
let screen = DebugUIScreenMetadata(
screenID: 1,
appKitFrame: HotLoopRect(x: 0, y: 0, width: 1800, height: 1400, space: .screen),
@@ -552,16 +817,25 @@ struct DebugUIInspectionTests {
let results = try service.inspect(scope: .main, minConfidence: 0.25)
+ #expect(results.first?.frame.elements.map(\.id) == ["window-1", "ax-1-ax-1.1"])
#expect(results.first?.frame.elements.first?.bbox == DebugUIBoundingBox(
x: 50,
y: 253,
width: 1530,
height: 930
))
+ #expect(results.first?.frame.elements.last?.type == .button)
+ #expect(results.first?.frame.elements.last?.label == "K-Pop Hits")
+ #expect(results.first?.frame.elements.last?.bbox == DebugUIBoundingBox(
+ x: 436,
+ y: 370,
+ width: 160,
+ height: 240
+ ))
}
@Test
- func accessibilityInspectionDrawsMovedMusicWindowFrameOnly() throws {
+ func accessibilityInspectionDrawsMovedMusicWindowAndClickableCardTile() throws {
let screen = DebugUIScreenMetadata(
screenID: 1,
appKitFrame: HotLoopRect(x: 0, y: 0, width: 1800, height: 1400, space: .screen),
@@ -607,7 +881,16 @@ struct DebugUIInspectionTests {
let results = try service.inspect(scope: .main, minConfidence: 0.25)
+ #expect(results.first?.frame.elements.map(\.id) == ["ax-1-ax-1.1", "window-1"])
+ #expect(results.first?.frame.elements.first?.type == .button)
+ #expect(results.first?.frame.elements.first?.label == "K-Pop Hits")
#expect(results.first?.frame.elements.first?.bbox == DebugUIBoundingBox(
+ x: 436,
+ y: 370,
+ width: 160,
+ height: 240
+ ))
+ #expect(results.first?.frame.elements.last?.bbox == DebugUIBoundingBox(
x: 80,
y: 400,
width: 1530,
@@ -615,6 +898,69 @@ struct DebugUIInspectionTests {
))
}
+ @Test
+ func accessibilityInspectionDrawsWholeSidebarRowsFromDescendantText() throws {
+ let screen = DebugUIScreenMetadata(
+ screenID: 1,
+ appKitFrame: HotLoopRect(x: 0, y: 0, width: 800, height: 700, space: .screen),
+ captureFrame: WindowTargetBounds(x: 0, y: 0, width: 800, height: 700)
+ )
+ let capturer = DebugUIFakeAccessibilityCapturer(
+ tree: MacAccessibilitySnapshotTreeBuilder.build(
+ root: RawMacAccessibilitySnapshotNode(
+ role: "AXWindow",
+ title: "Notes",
+ frame: WindowTargetBounds(x: 0, y: 0, width: 800, height: 700),
+ children: [
+ RawMacAccessibilitySnapshotNode(
+ role: "AXRow",
+ frame: WindowTargetBounds(x: 10, y: 240, width: 190, height: 52),
+ isEnabled: true,
+ actions: ["AXPress"],
+ children: [
+ RawMacAccessibilitySnapshotNode(
+ role: "AXStaticText",
+ valueSummary: "Improve UI element detection",
+ frame: WindowTargetBounds(x: 32, y: 252, width: 140, height: 18)
+ ),
+ RawMacAccessibilitySnapshotNode(
+ role: "AXStaticText",
+ valueSummary: "10:07 AM",
+ frame: WindowTargetBounds(x: 32, y: 272, width: 70, height: 16)
+ )
+ ]
+ )
+ ]
+ ),
+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)
+ )
+ )
+ let service = DebugUIAccessibilityInspectionService(
+ windowResolver: MacWindowResolver(
+ provider: DebugUIFixtureWindowProvider(
+ windows: [
+ MacWindowProviderWindow(
+ windowID: 7,
+ processID: 100,
+ appName: "Notes",
+ bounds: WindowTargetBounds(x: 0, y: 0, width: 800, height: 700)
+ )
+ ],
+ frontmostProcessID: 100
+ )
+ ),
+ capturer: capturer,
+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),
+ currentProcessID: 999
+ )
+
+ let results = try service.inspect(scope: .main, minConfidence: 0.25)
+ let row = try #require(results.first?.frame.elements.first { $0.type == .listItem })
+
+ #expect(row.label == "Improve UI element detection 10:07 AM")
+ #expect(row.bbox == DebugUIBoundingBox(x: 10, y: 240, width: 190, height: 52))
+ }
+
private func element(
id: String,
label: String,
@@ -683,6 +1029,21 @@ private struct DebugUIFixtureScreenProvider: DebugUIScreenMetadataProviding {
}
}
+private struct DebugUIFixtureScreenCapturer: DebugUIScreenCapturing {
+ var snapshots: [DebugUIScreenCaptureSnapshot]
+
+ func captureScreens(
+ scope: DebugUIInspectionScreenScope
+ ) throws -> [DebugUIScreenCaptureSnapshot] {
+ switch scope {
+ case .main:
+ return snapshots.prefix(1).map { $0 }
+ case .all:
+ return snapshots
+ }
+ }
+}
+
private struct DebugUIFixtureWindowProvider: MacWindowMetadataProviding {
var fixtureWindows: [MacWindowProviderWindow]
var frontmostProcessID: Int32?
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/LocalUIElementDetection/.gitkeep b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/LocalUIElementDetection/.gitkeep
new file mode 100644
index 00000000..0c83ca5b
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/LocalUIElementDetection/.gitkeep
@@ -0,0 +1 @@
+Keep local UI element detection fixture directories available for tests without committing private screenshots.
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalUIElementDetectionServiceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalUIElementDetectionServiceTests.swift
new file mode 100644
index 00000000..0687a050
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalUIElementDetectionServiceTests.swift
@@ -0,0 +1,150 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct LocalUIElementDetectionServiceTests {
+ @Test
+ func accessibilityCandidateWinsSemanticsAndAllowsGuardedActionEvidence() throws {
+ let trace = LocalUIElementDetectionService().detect(
+ LocalUIElementDetectionRequest(
+ traceID: "trace-ax-wins",
+ pixelSize: HotLoopSize(width: 400, height: 300, space: .screen),
+ accessibilityCandidates: [
+ LocalUIElementCandidate(
+ id: "ax-save",
+ source: .accessibility,
+ signalKind: .accessibilityRole,
+ typeHint: .button,
+ label: "Save",
+ role: "AXButton",
+ bounds: HotLoopRect(x: 20, y: 40, width: 96, height: 32, space: .screen),
+ confidence: 1,
+ actions: ["AXPress"]
+ )
+ ],
+ hoverProbeCandidates: [
+ LocalUIElementCandidate(
+ id: "hover-save",
+ source: .hoverProbe,
+ signalKind: .hoverHighlight,
+ typeHint: .listItem,
+ label: "Wrong hover label",
+ bounds: HotLoopRect(x: 12, y: 34, width: 160, height: 44, space: .screen),
+ confidence: 0.92
+ )
+ ],
+ minConfidence: 0.25
+ )
+ )
+
+ let element = try #require(trace.elements.first)
+ #expect(trace.elements.count == 1)
+ #expect(element.id == "ax-save")
+ #expect(element.type == .button)
+ #expect(element.label == "Save")
+ #expect(element.sources.contains(.accessibility))
+ #expect(element.sources.contains(.hoverProbe))
+ #expect(element.actionEligibility == .guardedAction)
+ #expect(element.reasonCodes.contains("axWinsSemantics"))
+ }
+
+ @Test
+ func visualOnlyCandidatesRemainReadOnlyForInputEvenWhenTheyLookClickable() throws {
+ let trace = LocalUIElementDetectionService().detect(
+ LocalUIElementDetectionRequest(
+ traceID: "trace-visual-only",
+ pixelSize: HotLoopSize(width: 700, height: 900, space: .screen),
+ hoverProbeCandidates: [
+ LocalUIElementCandidate(
+ id: "hover-row",
+ source: .hoverProbe,
+ signalKind: .hoverHighlight,
+ typeHint: .listItem,
+ label: "Improve UI element detection",
+ bounds: HotLoopRect(x: 16, y: 480, width: 660, height: 48, space: .screen),
+ confidence: 0.88
+ )
+ ],
+ minConfidence: 0.25
+ )
+ )
+
+ let element = try #require(trace.elements.first)
+ let result = LocalUIElementDetectionService().localUIUnderstandingResult(from: trace)
+ let control = try #require(result.controls.first)
+
+ #expect(element.type == .listItem)
+ #expect(element.actionEligibility == .cursorVisualization)
+ #expect(control.metadata["directInputActionsAllowed"] == "false")
+ #expect(result.metadata["directInputActionsAllowed"] == "false")
+ }
+
+ @Test
+ func lowConfidenceCandidatesAreSuppressedWithReasonCodes() {
+ let trace = LocalUIElementDetectionService().detect(
+ LocalUIElementDetectionRequest(
+ traceID: "trace-low-confidence",
+ pixelSize: HotLoopSize(width: 400, height: 300, space: .screen),
+ hoverProbeCandidates: [
+ LocalUIElementCandidate(
+ id: "hover-noise",
+ source: .hoverProbe,
+ signalKind: .hoverHighlight,
+ typeHint: .button,
+ label: "Noise",
+ bounds: HotLoopRect(x: 10, y: 10, width: 80, height: 22, space: .screen),
+ confidence: 0.12
+ )
+ ],
+ minConfidence: 0.25
+ )
+ )
+
+ #expect(trace.elements.isEmpty)
+ #expect(trace.suppressedCandidates.map(\.reason) == ["lowConfidence"])
+ #expect(trace.metrics.suppressedCount == 1)
+ }
+
+ @Test
+ func structuralWindowDoesNotSwallowChildControls() throws {
+ let trace = LocalUIElementDetectionService().detect(
+ LocalUIElementDetectionRequest(
+ traceID: "trace-window-child",
+ pixelSize: HotLoopSize(width: 800, height: 600, space: .screen),
+ accessibilityCandidates: [
+ LocalUIElementCandidate(
+ id: "ax-window",
+ source: .accessibility,
+ signalKind: .accessibilityRole,
+ typeHint: .draggable,
+ label: "Music",
+ role: "AXWindow",
+ bounds: HotLoopRect(x: 0, y: 0, width: 800, height: 600, space: .screen),
+ confidence: 0.65,
+ metadata: ["element.kind": "window"]
+ ),
+ LocalUIElementCandidate(
+ id: "ax-search",
+ source: .accessibility,
+ signalKind: .accessibilityRole,
+ typeHint: .input,
+ label: "Search",
+ role: "AXTextField",
+ bounds: HotLoopRect(x: 32, y: 92, width: 240, height: 36, space: .screen),
+ confidence: 1,
+ actions: ["AXSetValue"]
+ )
+ ],
+ minConfidence: 0.25
+ )
+ )
+
+ #expect(trace.elements.map(\.id).sorted() == ["ax-search", "ax-window"])
+ let search = try #require(trace.elements.first { $0.id == "ax-search" })
+ #expect(search.type == .input)
+ #expect(search.actionEligibility == .guardedAction)
+ #expect(search.sourceCandidateIDs == ["ax-search"])
+ }
+}
diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.md
index a936bc73..1a58cb3e 100644
--- a/docs/guides/agent-harness.md
+++ b/docs/guides/agent-harness.md
@@ -304,8 +304,14 @@ bug, even if the script happens to work on one machine.
Observation prefers Accessibility and app/window metadata. Bounded screenshots
are fallback observation context only; they do not emit direct input actions.
-Captured screenshots, Accessibility snapshots, and manual capture artifacts are
-trace evidence, not a general live vision loop.
+The local UI element detection service keeps this boundary explicit: it merges
+invisible Accessibility candidates with native screenshot signals such as OCR,
+shape/layout grouping, color/icon hints, and optional hover-probe evidence, then
+marks each element as overlay-only, read-only evidence, cursor-visualization
+evidence, or guarded-action eligible. CV-only and hover-only elements can guide
+debug overlays or visualization, but they do not authorize live clicks or text
+entry. Captured screenshots, Accessibility snapshots, and manual capture
+artifacts are trace evidence, not a general live vision loop.
Verification and screenshot fallback behavior should be derived from task
metadata and runtime item metadata, not one-off branches for individual apps.
@@ -330,11 +336,15 @@ tool-output feedback.
The developer UI inspection overlay is not an action workflow. It is enabled by
the repo-tracked `apps/Donkey/dev-overlay.json` during debug runs or by a local
`dev-overlay.json` file under Donkey's Application Support directory. Production
-builds do not bundle the repo config. The overlay sends screenshots to the
-hosted read-only inspection route only while a config explicitly enables it, and
-accepts strict JSON element metadata only. If a provider returns a
-computer/function action for this route, the client rejects the frame and
-performs no interaction.
+builds do not bundle the repo config. The `accessibility` provider runs the
+local AX-primary UI element detection service and renders merged source badges.
+The local provider only inspects safe visible windows on the selected screen;
+optional target filters can narrow it to matching apps, and
+`"activeWindowOnly": true` can keep it blank unless a matching app owns the
+focused frontmost window. Hosted providers send screenshots to the read-only
+inspection route only while a config explicitly enables them, and accept strict
+JSON element metadata only. If a provider returns a computer/function action for
+this route, the client rejects the frame and performs no interaction.
## State And Observability
diff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.md
index 0cb1a689..b07c4d19 100644
--- a/docs/guides/pointer-prompt-overlay.md
+++ b/docs/guides/pointer-prompt-overlay.md
@@ -32,14 +32,22 @@ quick local-app actions:
`~/Library/Application Support/Donkey/dev-overlay.json`. Production builds do
not bundle the repo config and only honor the Application Support path. When
no config exists, the config is invalid, or `"enabled": false`, the debug
- overlay is fully disabled. When enabled, it captures screenshots, asks the
- hosted read-only inspection route for strict JSON element metadata, and draws
- click-through boxes beneath Donkey's own prompt/status/spawn UI.
+ overlay is fully disabled. When enabled with `"provider": "accessibility"`,
+ it uses the local UI element detection service: invisible Accessibility reads
+ are merged with native screenshot OCR, shape/layout, color/icon, and optional
+ hover-probe evidence, then drawn as click-through boxes with source badges
+ beneath Donkey's own prompt/status/spawn UI. The local Accessibility provider
+ only inspects safe visible windows on the selected screen. Optional target
+ filters such as `"targetBundleIdentifiers"` and `"targetAppNames"` can narrow
+ the overlay to matching apps, and `"activeWindowOnly": true` can suppress
+ rendering unless the matching app owns the focused frontmost window. Hosted
+ `openai` and `gemini` providers still use the read-only inspection route and
+ strict JSON element metadata.
```json
{
"enabled": true,
- "provider": "openai",
+ "provider": "accessibility",
"cadenceSeconds": 1.0,
"screenScope": "main",
"minConfidence": 0.25
@@ -69,9 +77,11 @@ quick local-app actions:
- The developer UI inspection overlay is separate from agent visualization. It
is a transparent, non-activating, click-through, keyboard-pass-through AppKit
panel at a lower window level than Donkey's interactive UI. It renders
- CALayer rectangles and labels from model-returned JSON only; provider action
- calls such as click, type, scroll, drag, navigation, `computer_call`, or
- `function_call` are rejected instead of executed.
+ CALayer rectangles and labels from local detector output or model-returned
+ JSON only; provider action calls such as click, type, scroll, drag,
+ navigation, `computer_call`, or `function_call` are rejected instead of
+ executed. CV-only and hover-only detections are visualization/read-only
+ evidence and must not become live input authority.
- Task actions in the notch, including follow-up submission and pause/resume, must cross the model/controller command boundary with the selected task ID.
- Pointer prompt command handling should emit actionable `com.donkey.app` route/result logs for submitted commands, routing decisions, intent resolution, local action traces, unsupported requests, unavailable apps, and final task status. Action trace logs should state the backend, input mode, whether an element click happened, the control or bounds target, and that the overlay pointer is visual-only.