Open source CapCut alternative.
TypeScript
Add accessibility-backed debug overlay
David Le1966830f1184
diff --git a/apps/Donkey/Sources/Donkey/DebugUIInspectionCoordinator.swift b/apps/Donkey/Sources/Donkey/DebugUIInspectionCoordinator.swiftindex f3726ce8..efbcd68d 100644--- a/apps/Donkey/Sources/Donkey/DebugUIInspectionCoordinator.swift+++ b/apps/Donkey/Sources/Donkey/DebugUIInspectionCoordinator.swift@@ -3,25 +3,35 @@ import DonkeyAIimport DonkeyContractsimport DonkeyRuntimeimport Foundation+import OSLog++private enum DebugUIInspectionLog {+ static let overlay = Logger(subsystem: "com.donkey.app", category: "debug-ui-inspection")+}@MainActorfinal class DebugUIInspectionCoordinator {private let overlayController = DebugUIInspectionOverlayController()private let captureService = DebugUIScreenCaptureService()+ private let accessibilityInspectionService = DebugUIAccessibilityInspectionService()private let configURL: URL?private var analyzer: (any DebugUIInspectionAnalyzing)?private var trackers: [UInt32: DebugUIElementTracker] = [:]private var lastFingerprints: [UInt32: String] = [:]+ private var lastRenderedFrames: [UInt32: DebugUIInspectionFrame] = [:]private var timer: Timer?private var notificationObservers: [NSObjectProtocol] = []private var currentConfig: DebugUIOverlayConfiguration = .disabledprivate var isAnalyzing = false- init(configURL: URL? = DebugUIOverlayConfiguration.defaultConfigURL()) {+ init(configURL: URL? = nil) {self.configURL = configURL}func start() {+ DebugUIInspectionLog.overlay.info(+ "debug inspection starting configURL=\(self.configURL?.path ?? "candidate-search", privacy: .public)"+ )stop()installNotificationObservers()reloadConfigAndReschedule(force: true)@@ -39,6 +49,7 @@ final class DebugUIInspectionCoordinator {overlayController.close()trackers.removeAll()lastFingerprints.removeAll()+ lastRenderedFrames.removeAll()isAnalyzing = falsecurrentConfig = .disabled}@@ -80,6 +91,12 @@ final class DebugUIInspectionCoordinator {let confidenceChanged = newConfig.minConfidence != currentConfig.minConfidencecurrentConfig = newConfig+ if force || enablementChanged || scopeChanged || providerChanged || confidenceChanged {+ 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)"+ )+ }+if cadenceChanged || timer == nil || force {timer?.invalidate()let newTimer = Timer(timeInterval: newConfig.cadenceSeconds, repeats: true) { [weak self] _ in@@ -94,6 +111,7 @@ final class DebugUIInspectionCoordinator {if enablementChanged || scopeChanged || providerChanged || confidenceChanged {lastFingerprints.removeAll()trackers.removeAll()+ lastRenderedFrames.removeAll()if !newConfig.enabled {overlayController.close()}@@ -103,7 +121,10 @@ final class DebugUIInspectionCoordinator {private func refresh(force: Bool = false) {reloadConfigAndReschedule()guard currentConfig.enabled else { return }- guard !isAnalyzing else { return }+ guard !isAnalyzing else {+ DebugUIInspectionLog.overlay.debug("debug inspection skipped refresh because analysis is already running")+ return+ }isAnalyzing = trueTask { @MainActor in@@ -111,24 +132,44 @@ final class DebugUIInspectionCoordinator {do {try await analyzeVisibleScreens(force: force)} catch {- overlayController.close()- lastFingerprints.removeAll()- trackers.removeAll()+ DebugUIInspectionLog.overlay.error(+ "debug inspection failed error=\(String(describing: error), privacy: .public)"+ )+ if lastRenderedFrames.isEmpty {+ overlayController.close()+ lastFingerprints.removeAll()+ trackers.removeAll()+ }}}}private func analyzeVisibleScreens(force: Bool) async throws {+ if currentConfig.provider == .accessibility {+ try analyzeAccessibilityScreens(force: force)+ return+ }+let snapshots = try captureService.captureScreens(scope: currentConfig.screenScope)- overlayController.closeScreens(except: Set(snapshots.map(\.screenID)))+ DebugUIInspectionLog.overlay.debug(+ "debug inspection captured screens=\(snapshots.count, privacy: .public) force=\(String(force), privacy: .public)"+ )+ let activeScreenIDs = Set(snapshots.map(\.screenID))+ overlayController.closeScreens(except: activeScreenIDs)+ lastRenderedFrames = lastRenderedFrames.filter { activeScreenIDs.contains($0.key) }let analyzer = try analyzerInstance()for snapshot in snapshots {guard force || lastFingerprints[snapshot.screenID] != snapshot.fingerprint else {+ DebugUIInspectionLog.overlay.debug(+ "debug inspection skipped unchanged screenID=\(snapshot.screenID, privacy: .public)"+ )continue}lastFingerprints[snapshot.screenID] = snapshot.fingerprint-+ DebugUIInspectionLog.overlay.info(+ "debug inspection analyzing screenID=\(snapshot.screenID, privacy: .public) pixels=\(snapshot.pixelSize.width, privacy: .public)x\(snapshot.pixelSize.height, privacy: .public)"+ )let frame = try await analyzer.inspect(DebugUIInspectionRequest(provider: currentConfig.provider,@@ -144,16 +185,104 @@ final class DebugUIInspectionCoordinator {var tracker = trackers[snapshot.screenID] ?? DebugUIElementTracker()let trackedFrame = tracker.update(with: frame)trackers[snapshot.screenID] = tracker+ DebugUIInspectionLog.overlay.info(+ "debug inspection rendering screenID=\(snapshot.screenID, privacy: .public) elements=\(trackedFrame.elements.count, privacy: .public)"+ )+ logSampleMappings(frame: trackedFrame, snapshot: snapshot)+ lastRenderedFrames[snapshot.screenID] = trackedFrameoverlayController.render(frame: trackedFrame, snapshot: snapshot)}}+ private func analyzeAccessibilityScreens(force: Bool) throws {+ let results = try accessibilityInspectionService.inspect(+ scope: currentConfig.screenScope,+ minConfidence: currentConfig.minConfidence+ )+ DebugUIInspectionLog.overlay.debug(+ "debug inspection accessibility screens=\(results.count, privacy: .public) force=\(String(force), privacy: .public)"+ )++ let activeScreenIDs = Set(results.map(\.snapshot.screenID))+ overlayController.closeScreens(except: activeScreenIDs)+ lastRenderedFrames = lastRenderedFrames.filter { activeScreenIDs.contains($0.key) }++ for result in results {+ let snapshot = result.snapshot+ guard force || lastFingerprints[snapshot.screenID] != snapshot.fingerprint else {+ DebugUIInspectionLog.overlay.debug(+ "debug inspection skipped unchanged accessibility screenID=\(snapshot.screenID, privacy: .public)"+ )+ continue+ }+ lastFingerprints[snapshot.screenID] = snapshot.fingerprint++ var tracker = trackers[snapshot.screenID] ?? DebugUIElementTracker()+ let trackedFrame = tracker.update(with: result.frame)+ trackers[snapshot.screenID] = tracker+ DebugUIInspectionLog.overlay.info(+ "debug inspection rendering source=accessibility screenID=\(snapshot.screenID, privacy: .public) elements=\(trackedFrame.elements.count, privacy: .public)"+ )+ logSampleMappings(frame: trackedFrame, snapshot: snapshot)+ lastRenderedFrames[snapshot.screenID] = trackedFrame+ overlayController.render(frame: trackedFrame, snapshot: snapshot)+ }+ }++ private func logSampleMappings(+ frame: DebugUIInspectionFrame,+ snapshot: DebugUIScreenCaptureSnapshot+ ) {+ let screenPointSize = HotLoopSize(+ width: snapshot.screenFrame.size.width,+ height: snapshot.screenFrame.size.height,+ space: .screen+ )+ for element in frame.elements.prefix(3) {+ let localFrame = DebugUIOverlayGeometry.localLayerFrame(+ for: element.bbox,+ screenshotPixelSize: snapshot.pixelSize,+ screenPointSize: screenPointSize+ )+ DebugUIInspectionLog.overlay.info(+ "debug inspection mapping id=\(element.id, privacy: .public) label=\(element.label, privacy: .public) bbox=\(Self.describe(element.bbox), privacy: .public) local=\(Self.describe(localFrame), privacy: .public) pixels=\(Self.describe(snapshot.pixelSize), privacy: .public) points=\(Self.describe(screenPointSize), privacy: .public)"+ )+ }+ }++ private static func describe(_ box: DebugUIBoundingBox) -> String {+ String(+ format: "x=%.1f y=%.1f w=%.1f h=%.1f",+ box.x,+ box.y,+ box.width,+ box.height+ )+ }++ private static func describe(_ rect: CGRect) -> String {+ String(+ format: "x=%.1f y=%.1f w=%.1f h=%.1f",+ rect.origin.x,+ rect.origin.y,+ rect.size.width,+ rect.size.height+ )+ }++ private static func describe(_ size: HotLoopSize) -> String {+ String(format: "w=%.1f h=%.1f", size.width, size.height)+ }+private func analyzerInstance() throws -> any DebugUIInspectionAnalyzing {if let analyzer {return analyzer}let configuration = try DonkeyBackendInferenceConfiguration.fromEnvironment()+ DebugUIInspectionLog.overlay.info(+ "debug inspection using backend baseURL=\(configuration.baseURL.absoluteString, privacy: .public)"+ )let created = HostedDebugUIInspectionAnalyzer(backend: DonkeyBackendInferenceClient(configuration: configuration))diff --git a/apps/Donkey/Sources/Donkey/DebugUIInspectionOverlayController.swift b/apps/Donkey/Sources/Donkey/DebugUIInspectionOverlayController.swiftindex 0d860fa7..0d774525 100644--- a/apps/Donkey/Sources/Donkey/DebugUIInspectionOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/DebugUIInspectionOverlayController.swift@@ -67,7 +67,7 @@ final class DebugUIInspectionOverlayController {.ignoresCycle,.stationary]- panel.sharingType = .none+ panel.sharingType = .readOnlypanel.orderFrontRegardless()return DebugUIInspectionSurface(panel: panel, rootView: rootView)@@ -127,7 +127,7 @@ private final class DebugUIInspectionSurface {private func makeLayers(for element: DebugUIElement) -> DebugUIInspectionElementLayers {let boxLayer = CAShapeLayer()boxLayer.name = "debug-ui-box-\(element.id)"- boxLayer.fillColor = nsColor(hex: element.visualStyle.overlayColor, alpha: 0.14).cgColor+ boxLayer.fillColor = fillColor(for: element)boxLayer.strokeColor = nsColor(hex: element.visualStyle.borderColor, alpha: 0.95).cgColorboxLayer.lineWidth = 2boxLayer.opacity = 0@@ -167,7 +167,7 @@ private final class DebugUIInspectionSurface {let path = CGPath(rect: CGRect(origin: .zero, size: boxFrame.size), transform: nil)layers.box.frame = boxFramelayers.box.path = path- layers.box.fillColor = nsColor(hex: element.visualStyle.overlayColor, alpha: 0.14).cgColor+ layers.box.fillColor = fillColor(for: element)layers.box.strokeColor = nsColor(hex: element.visualStyle.borderColor, alpha: 0.95).cgColorlet title = labelText(for: element)@@ -201,6 +201,13 @@ private final class DebugUIInspectionSurface {return CGSize(width: width, height: 18)}+ private func fillColor(for element: DebugUIElement) -> CGColor {+ if element.id.hasPrefix("window-") {+ return NSColor.clear.cgColor+ }+ return nsColor(hex: element.visualStyle.overlayColor, alpha: 0.14).cgColor+ }+private func fadeIn(_ layers: DebugUIInspectionElementLayers) {let animation = CABasicAnimation(keyPath: "opacity")animation.fromValue = 0diff --git a/apps/Donkey/Sources/Donkey/DonkeyOverlayWindowLevels.swift b/apps/Donkey/Sources/Donkey/DonkeyOverlayWindowLevels.swiftindex e82ee8af..3c3d76a9 100644--- a/apps/Donkey/Sources/Donkey/DonkeyOverlayWindowLevels.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyOverlayWindowLevels.swift@@ -1,6 +1,6 @@import AppKitenum DonkeyOverlayWindowLevel {- static let debugInspection: NSWindow.Level = .floating+ static let debugInspection = NSWindow.Level(rawValue: NSWindow.Level.statusBar.rawValue - 1)static let pointerPrompt: NSWindow.Level = .statusBar}diff --git a/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionHostedAdapter.swift b/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionHostedAdapter.swiftindex ca458370..45e6a25d 100644--- a/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionHostedAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionHostedAdapter.swift@@ -50,6 +50,7 @@ public struct HostedDebugUIInspectionAnalyzer: DebugUIInspectionAnalyzing {return try DebugUIInspectionResponseDecoder.decode(response,decoder: decoder,+ screenshotPixelSize: request.pixelSize,minConfidence: request.minConfidence)}@@ -65,11 +66,12 @@ public struct HostedDebugUIInspectionAnalyzer: DebugUIInspectionAnalyzing {"content": .array([.object(["type": .string("input_text"),- "text": .string(Self.prompt)+ "text": .string(Self.prompt(for: request.pixelSize))]),.object(["type": .string("input_image"),- "image_url": .string("data:image/png;base64,\(request.screenshotBase64)")+ "image_url": .string("data:image/png;base64,\(request.screenshotBase64)"),+ "detail": .string("original")])])])@@ -94,26 +96,36 @@ public struct HostedDebugUIInspectionAnalyzer: DebugUIInspectionAnalyzing {"screenshot.height": String(request.pixelSize.height)]) { current, _ in current },parameters: [- "temperature": .number(0),+ "reasoning": .object([+ "effort": .string("low")+ ]),"max_output_tokens": .number(8_000)])}- private static let prompt = """- You are a read-only macOS UI inspection model. Analyze the screenshot and return ONLY valid JSON.+ private static func prompt(for pixelSize: HotLoopSize) -> String {+ let width = max(1, Int(pixelSize.width.rounded()))+ let height = max(1, Int(pixelSize.height.rounded()))+ return """+ You are a read-only macOS UI inspection model. Return bounding boxes for visible visual controls that are likely clickable or otherwise user-interactable. Return ONLY valid JSON.- Detect visible user-interactable UI elements. Include window controls, buttons, links, tabs, menu items, dropdowns, text inputs, search fields, checkboxes, radios, toggles, sliders, toolbar icons, sidebar items, Dock items, menu bar items, table rows, list items, tree items, clickable cards, draggable handles, resize handles, scrollbars, split panes, canvas interaction regions, floating action buttons, and icon-only controls. Prefer over-detecting interactable elements over missing them.+ The attached screenshot coordinate space is exactly \(width) pixels wide by \(height) pixels high.++ Find every visible control candidate a person could click, focus, drag, select, or activate. Include macOS window controls, browser toolbar controls, app sidebars, buttons, links, tabs, menu items, dropdowns, text inputs, search fields, checkboxes, radios, toggles, sliders, toolbar icons, sidebar rows, list rows, clickable cards, draggable handles, resize handles, scrollbars, split panes, canvas interaction regions, floating action buttons, and icon-only controls. Prefer over-detecting likely controls over missing them.Do not include static text, decorative graphics, separators, backgrounds, or non-interactable containers unless they are clearly interactive.- Coordinates must be screenshot pixel coordinates with origin at top-left. Bounding boxes must tightly fit the clickable region. If an element is partially obscured, include it with lower confidence. Infer labels for icon-only controls when possible.+ Coordinates must be screenshot pixel coordinates in that \(width)x\(height) coordinate space with origin at top-left. Bounding boxes must tightly fit the clickable region. If you can only report coordinates in a resized internal image coordinate space, set coordinate_space to that image width and height so the client can scale the boxes. If an element is partially obscured, include it with lower confidence. Infer labels for icon-only controls when possible.++ Do not return an empty elements array unless the screenshot is blank or contains no visible UI. For a normal macOS desktop screenshot, return the visible controls you can identify.Do not click, type, scroll, drag, navigate, call tools, or propose actions. This is visual inspection only.Return exactly:- {"elements":[{"id":"stable_unique_id","type":"button","label":"Save","description":"Saves current document","bbox":{"x":120,"y":340,"width":88,"height":32},"confidence":0.98,"visual_style":{"overlay_color":"#3B82F6","border_color":"#60A5FA","label_color":"#FFFFFF"}}]}+ {"coordinate_space":{"width":\(width),"height":\(height)},"elements":[{"id":"stable_unique_id","type":"button","label":"Save","description":"Saves current document","bbox":{"x":120,"y":340,"width":88,"height":32},"confidence":0.98,"visual_style":{"overlay_color":"#3B82F6","border_color":"#60A5FA","label_color":"#FFFFFF"}}]}"""+ }private static let excludedActionNames = ["click",@@ -137,6 +149,7 @@ public struct HostedDebugUIInspectionAnalyzer: DebugUIInspectionAnalyzing {]private static let responseFormat: RemoteInferenceJSONObject = [+ "verbosity": .string("low"),"format": .object(["type": .string("json_schema"),"name": .string("debug_ui_inspection_v1"),@@ -144,8 +157,29 @@ public struct HostedDebugUIInspectionAnalyzer: DebugUIInspectionAnalyzing {"schema": .object(["type": .string("object"),"additionalProperties": .bool(false),- "required": .array([.string("elements")]),+ "required": .array([+ .string("coordinate_space"),+ .string("elements")+ ]),"properties": .object([+ "coordinate_space": .object([+ "type": .string("object"),+ "additionalProperties": .bool(false),+ "required": .array([+ .string("width"),+ .string("height")+ ]),+ "properties": .object([+ "width": .object([+ "type": .string("number"),+ "minimum": .number(1)+ ]),+ "height": .object([+ "type": .string("number"),+ "minimum": .number(1)+ ])+ ])+ ]),"elements": .object(["type": .string("array"),"items": .object([@@ -216,6 +250,7 @@ public enum DebugUIInspectionResponseDecoder {public static func decode(_ response: RemoteInferenceJSONValue,decoder: JSONDecoder = JSONDecoder(),+ screenshotPixelSize: HotLoopSize? = nil,minConfidence: Double = 0.25) throws -> DebugUIInspectionFrame {guard containsActionOutput(response) == false else {@@ -236,7 +271,8 @@ public enum DebugUIInspectionResponseDecoder {}do {- return try decoder.decode(DebugUIInspectionFrame.self, from: frameData)+ let rawFrame = try decoder.decode(RawDebugUIInspectionFrame.self, from: frameData)+ return normalizedFrame(rawFrame, screenshotPixelSize: screenshotPixelSize).validated(minConfidence: minConfidence)} catch {throw DebugUIInspectionHostedAdapterError.invalidJSON(String(describing: error))@@ -306,4 +342,49 @@ public enum DebugUIInspectionResponseDecoder {"\"functionCall\"","\"function_call\""]++ private static func normalizedFrame(+ _ frame: RawDebugUIInspectionFrame,+ screenshotPixelSize: HotLoopSize?+ ) -> DebugUIInspectionFrame {+ guard let screenshotPixelSize,+ screenshotPixelSize.width > 0,+ screenshotPixelSize.height > 0,+ let coordinateSpace = frame.coordinateSpace,+ coordinateSpace.width > 0,+ coordinateSpace.height > 0+ else {+ return DebugUIInspectionFrame(elements: frame.elements)+ }++ let scaleX = screenshotPixelSize.width / coordinateSpace.width+ let scaleY = screenshotPixelSize.height / coordinateSpace.height+ return DebugUIInspectionFrame(+ elements: frame.elements.map { element in+ var adjusted = element+ adjusted.bbox = DebugUIBoundingBox(+ x: adjusted.bbox.x * scaleX,+ y: adjusted.bbox.y * scaleY,+ width: adjusted.bbox.width * scaleX,+ height: adjusted.bbox.height * scaleY+ )+ return adjusted+ }+ )+ }+}++private struct RawDebugUIInspectionFrame: Decodable {+ var coordinateSpace: RawDebugUICoordinateSpace?+ var elements: [DebugUIElement]++ enum CodingKeys: String, CodingKey {+ case coordinateSpace = "coordinate_space"+ case elements+ }+}++private struct RawDebugUICoordinateSpace: Decodable {+ var width: Double+ var height: Double}diff --git a/apps/Donkey/Sources/DonkeyContracts/DebugUIInspectionContracts.swift b/apps/Donkey/Sources/DonkeyContracts/DebugUIInspectionContracts.swiftindex 04d4c344..37b9e10d 100644--- a/apps/Donkey/Sources/DonkeyContracts/DebugUIInspectionContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/DebugUIInspectionContracts.swift@@ -1,6 +1,7 @@import Foundationpublic enum DebugUIInspectionProvider: String, Codable, Equatable, Sendable {+ case accessibilitycase openaicase gemini}diff --git a/apps/Donkey/Sources/DonkeyRuntime/DebugUIAccessibilityInspectionService.swift b/apps/Donkey/Sources/DonkeyRuntime/DebugUIAccessibilityInspectionService.swiftnew file mode 100644index 00000000..26499864--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/DebugUIAccessibilityInspectionService.swift@@ -0,0 +1,673 @@+@preconcurrency import AppKit+import CoreGraphics+import CryptoKit+import DonkeyContracts+import Foundation++public struct DebugUIAccessibilityInspectionResult: Equatable, Sendable {+ public var snapshot: DebugUIScreenCaptureSnapshot+ public var frame: DebugUIInspectionFrame++ public init(+ snapshot: DebugUIScreenCaptureSnapshot,+ frame: DebugUIInspectionFrame+ ) {+ self.snapshot = snapshot+ self.frame = frame+ }+}++public enum DebugUIAccessibilityInspectionError: Error, Equatable, Sendable {+ case noScreenAvailable+ case missingDisplayIdentifier+ case accessibilityNotTrusted+}++struct DebugUIScreenMetadata: Equatable, Sendable {+ var screenID: UInt32+ var appKitFrame: HotLoopRect+ var captureFrame: WindowTargetBounds+}++protocol DebugUIScreenMetadataProviding: Sendable {+ func screens(scope: DebugUIInspectionScreenScope) throws -> [DebugUIScreenMetadata]+}++public struct DebugUIAccessibilityInspectionService: Sendable {+ private let windowResolver: MacWindowResolver+ private let capturer: any MacAccessibilitySnapshotCapturing+ private let controlDiscovery: LocalAppAccessibilityControlDiscovery+ private let screenProvider: any DebugUIScreenMetadataProviding+ private let currentProcessID: Int32++ public init() {+ self.init(+ windowResolver: MacWindowResolver(),+ capturer: ApplicationServicesMacAccessibilitySnapshotCapturer(),+ screenProvider: AppKitDebugUIScreenMetadataProvider(),+ currentProcessID: ProcessInfo.processInfo.processIdentifier+ )+ }++ init(+ windowResolver: MacWindowResolver,+ capturer: any MacAccessibilitySnapshotCapturing,+ controlDiscovery: LocalAppAccessibilityControlDiscovery = LocalAppAccessibilityControlDiscovery(),+ screenProvider: any DebugUIScreenMetadataProviding,+ currentProcessID: Int32+ ) {+ self.windowResolver = windowResolver+ self.capturer = capturer+ self.controlDiscovery = controlDiscovery+ self.screenProvider = screenProvider+ self.currentProcessID = currentProcessID+ }++ public func inspect(+ scope: DebugUIInspectionScreenScope,+ minConfidence: Double+ ) throws -> [DebugUIAccessibilityInspectionResult] {+ let screens = try screenProvider.screens(scope: scope)+ guard !screens.isEmpty else {+ throw DebugUIAccessibilityInspectionError.noScreenAvailable+ }++ let targets = visibleInspectableTargets(on: screens)+ guard capturer.trustStatus() == .trusted else {+ throw DebugUIAccessibilityInspectionError.accessibilityNotTrusted+ }+ return windowFrameResults(+ screens: screens,+ targets: targets,+ minConfidence: minConfidence+ )+ }++ private func accessibilityElementResults(+ screens: [DebugUIScreenMetadata],+ targets: [MacWindowTargetCandidate],+ minConfidence: Double+ ) throws -> [DebugUIAccessibilityInspectionResult] {+ guard capturer.trustStatus() == .trusted else {+ throw DebugUIAccessibilityInspectionError.accessibilityNotTrusted+ }++ var elementsByScreenID = Dictionary(+ uniqueKeysWithValues: screens.map { ($0.screenID, [DebugUIElement]()) }+ )+ let limits = MacAccessibilitySnapshotLimits(+ maxDepth: 6,+ maxChildrenPerNode: 90,+ maxTotalNodes: 600,+ maxTextLength: 120+ )+ var occludingWindowBounds: [WindowTargetBounds] = []++ 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+ let controls = controlDiscovery.discover(in: snapshot).controls+ for control in controls {+ guard let element = debugElement(+ for: control,+ target: target,+ windowBounds: windowBounds,+ screens: screens,+ occludingWindowBounds: occludingWindowBounds+ ) else {+ continue+ }+ elementsByScreenID[element.screenID, default: []].append(element.element)+ }+ occludingWindowBounds.append(windowBounds)+ }++ return screens.map { screen in+ let elements = (elementsByScreenID[screen.screenID] ?? [])+ .sorted(by: Self.elementSort)+ let frame = DebugUIInspectionFrame(elements: elements)+ .validated(minConfidence: minConfidence)+ let fingerprint = Self.fingerprint(for: screen, elements: frame.elements)+ let snapshot = DebugUIScreenCaptureSnapshot(+ screenID: screen.screenID,+ screenFrame: screen.appKitFrame,+ pixelSize: HotLoopSize(+ width: screen.captureFrame.width,+ height: screen.captureFrame.height,+ space: .screen+ ),+ pngData: Data(),+ fingerprint: fingerprint+ )+ return DebugUIAccessibilityInspectionResult(snapshot: snapshot, frame: frame)+ }+ }++ private func windowFrameResults(+ screens: [DebugUIScreenMetadata],+ targets: [MacWindowTargetCandidate],+ minConfidence: Double+ ) -> [DebugUIAccessibilityInspectionResult] {+ var elementsByScreenID = Dictionary(+ uniqueKeysWithValues: screens.map { ($0.screenID, [DebugUIElement]()) }+ )+ let limits = MacAccessibilitySnapshotLimits(+ maxDepth: 0,+ maxChildrenPerNode: 0,+ maxTotalNodes: 1,+ maxTextLength: 120+ )+ var occludingWindowBounds: [WindowTargetBounds] = []+ var visibleWindowIndex = 0++ for target in targets {+ let tree = try? capturer.captureTree(target: target, limits: limits)+ let windowBounds = tree?.root.frame ?? target.bounds+ defer { occludingWindowBounds.append(windowBounds) }++ guard Self.isVisible(windowBounds, occludingWindowBounds: occludingWindowBounds) else {+ continue+ }++ let visualStyle = Self.windowFrameStyle(at: visibleWindowIndex)+ visibleWindowIndex += 1++ for screen in screens where Self.intersects(windowBounds, screen.captureFrame) {+ guard let bbox = DebugUIAccessibilityGeometry.boundingBox(+ for: windowBounds,+ screenFrame: screen.captureFrame+ ) else {+ continue+ }++ let label = Self.windowLabel(for: target)+ elementsByScreenID[screen.screenID, default: []].append(+ DebugUIElement(+ id: "window-\(target.windowID)",+ type: .draggable,+ label: label,+ description: "Window frame \(label)",+ bbox: bbox,+ confidence: 1,+ visualStyle: visualStyle+ )+ )+ }+ }++ return screens.map { screen in+ let elements = (elementsByScreenID[screen.screenID] ?? [])+ .sorted(by: Self.elementSort)+ let frame = DebugUIInspectionFrame(elements: elements)+ .validated(minConfidence: minConfidence)+ let fingerprint = Self.fingerprint(for: screen, elements: frame.elements)+ let snapshot = DebugUIScreenCaptureSnapshot(+ screenID: screen.screenID,+ screenFrame: screen.appKitFrame,+ pixelSize: HotLoopSize(+ width: screen.captureFrame.width,+ height: screen.captureFrame.height,+ space: .screen+ ),+ pngData: Data(),+ fingerprint: fingerprint+ )+ return DebugUIAccessibilityInspectionResult(snapshot: snapshot, frame: frame)+ }+ }++ private func visibleInspectableTargets(+ on screens: [DebugUIScreenMetadata]+ ) -> [MacWindowTargetCandidate] {+ windowResolver.enumerateCandidates()+ .filter { target in+ target.isVisible+ && target.isOnScreen+ && target.safetyAssessment.status == .allowed+ && !target.isIPhoneMirroring+ && target.processID != currentProcessID+ && screens.contains { screen in+ Self.intersects(target.bounds, screen.captureFrame)+ }+ }+ }++ private func debugElement(+ for control: LocalAppDiscoveredControl,+ target: MacWindowTargetCandidate,+ windowBounds: WindowTargetBounds,+ screens: [DebugUIScreenMetadata],+ occludingWindowBounds: [WindowTargetBounds]+ ) -> (screenID: UInt32, element: DebugUIElement)? {+ 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,+ DebugUIElement(+ id: "ax-\(target.windowID)-\(control.id)",+ type: type,+ label: label,+ description: Self.description(for: control, target: target),+ bbox: bbox,+ confidence: 1+ )+ )+ }++ private static func elementType(for control: LocalAppDiscoveredControl) -> DebugUIElementType? {+ switch control.kind {+ case .button:+ if isWindowControl(control) {+ return .windowControl+ }+ return isToolbarControl(control) ? .toolbarIcon : .button+ case .textField, .searchField:+ return .input+ case .checkbox:+ return .checkbox+ case .menuItem:+ return .menuItem+ case .group:+ return control.actions.contains("AXPress") ? .button : nil+ case .unknown:+ return nil+ }+ }++ private static func isWindowControl(_ control: LocalAppDiscoveredControl) -> Bool {+ let label = control.label.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()+ return ["close", "minimize", "zoom", "fullscreen", "full screen"].contains(label)+ }++ 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+ }++ private static func label(+ for control: LocalAppDiscoveredControl,+ type: DebugUIElementType+ ) -> String {+ let trimmed = control.label.trimmingCharacters(in: .whitespacesAndNewlines)+ if !trimmed.isEmpty {+ return trimmed+ }+ return type.rawValue.replacingOccurrences(of: "_", with: " ")+ }++ private static func description(+ for control: LocalAppDiscoveredControl,+ target: MacWindowTargetCandidate+ ) -> String {+ [+ target.appName,+ target.title,+ control.role+ ]+ .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }+ .filter { !$0.isEmpty }+ .joined(separator: " ")+ }++ private static func windowLabel(for target: MacWindowTargetCandidate) -> String {+ [+ target.appName,+ target.title+ ]+ .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }+ .first { !$0.isEmpty } ?? "window \(target.windowID)"+ }++ private static func windowFrameStyle(at index: Int) -> DebugUIOverlayStyle {+ windowFrameStyles[index % windowFrameStyles.count]+ }++ private static let windowFrameStyles: [DebugUIOverlayStyle] = [+ DebugUIOverlayStyle(overlayColor: "#EF4444", borderColor: "#F87171", labelColor: "#FFFFFF"),+ DebugUIOverlayStyle(overlayColor: "#F97316", borderColor: "#FB923C", labelColor: "#FFFFFF"),+ DebugUIOverlayStyle(overlayColor: "#EAB308", borderColor: "#FACC15", labelColor: "#111827"),+ DebugUIOverlayStyle(overlayColor: "#22C55E", borderColor: "#4ADE80", labelColor: "#052E16"),+ DebugUIOverlayStyle(overlayColor: "#06B6D4", borderColor: "#22D3EE", labelColor: "#083344"),+ DebugUIOverlayStyle(overlayColor: "#3B82F6", borderColor: "#60A5FA", labelColor: "#FFFFFF"),+ DebugUIOverlayStyle(overlayColor: "#8B5CF6", borderColor: "#A78BFA", labelColor: "#FFFFFF"),+ DebugUIOverlayStyle(overlayColor: "#EC4899", borderColor: "#F472B6", labelColor: "#FFFFFF"),+ DebugUIOverlayStyle(overlayColor: "#84CC16", borderColor: "#A3E635", labelColor: "#1A2E05"),+ DebugUIOverlayStyle(overlayColor: "#14B8A6", borderColor: "#2DD4BF", labelColor: "#042F2E")+ ]++ private static func shouldRender(+ control: LocalAppDiscoveredControl,+ type: DebugUIElementType,+ bbox: DebugUIBoundingBox,+ screen: DebugUIScreenMetadata+ ) -> Bool {+ guard bbox.width >= 4, bbox.height >= 4 else { return false }++ let screenWidth = screen.captureFrame.width+ let screenHeight = screen.captureFrame.height+ guard screenWidth > 0, screenHeight > 0 else { return false }++ let area = bbox.width * bbox.height+ let screenArea = screenWidth * screenHeight+ let areaFraction = area / screenArea+ let widthFraction = bbox.width / screenWidth+ let heightFraction = bbox.height / screenHeight++ if type == .input {+ return areaFraction <= 0.045+ && heightFraction <= 0.18+ && widthFraction <= 0.65+ }+ if control.kind == .group && areaFraction > 0.08 {+ return false+ }+ if areaFraction > 0.12 {+ return false+ }+ if heightFraction > 0.55 && widthFraction > 0.10 {+ return false+ }+ if widthFraction > 0.85 && heightFraction > 0.05 {+ return false+ }++ return true+ }++ private static func isVisible(+ _ bounds: WindowTargetBounds,+ occludingWindowBounds: [WindowTargetBounds]+ ) -> Bool {+ !visibleFragments(+ of: bounds,+ afterSubtracting: occludingWindowBounds+ ).isEmpty+ }++ private static func intersects(+ _ lhs: WindowTargetBounds,+ _ rhs: WindowTargetBounds+ ) -> Bool {+ lhs.x < rhs.x + rhs.width+ && lhs.x + lhs.width > rhs.x+ && lhs.y < rhs.y + rhs.height+ && lhs.y + lhs.height > rhs.y+ }++ private static func visibleFragments(+ of bounds: WindowTargetBounds,+ afterSubtracting occluders: [WindowTargetBounds]+ ) -> [WindowTargetBounds] {+ guard bounds.hasPositiveArea else { return [] }++ var fragments = [bounds]+ for occluder in occluders where occluder.hasPositiveArea {+ fragments = fragments.flatMap { subtract(occluder, from: $0) }+ if fragments.isEmpty {+ return []+ }+ }++ return fragments+ }++ private static func subtract(+ _ occluder: WindowTargetBounds,+ from fragment: WindowTargetBounds+ ) -> [WindowTargetBounds] {+ guard let overlap = intersection(fragment, occluder) else {+ return [fragment]+ }++ let fragmentMaxX = fragment.x + fragment.width+ let fragmentMaxY = fragment.y + fragment.height+ let overlapMaxX = overlap.x + overlap.width+ let overlapMaxY = overlap.y + overlap.height++ let candidates = [+ WindowTargetBounds(+ x: fragment.x,+ y: fragment.y,+ width: fragment.width,+ height: overlap.y - fragment.y+ ),+ WindowTargetBounds(+ x: fragment.x,+ y: overlapMaxY,+ width: fragment.width,+ height: fragmentMaxY - overlapMaxY+ ),+ WindowTargetBounds(+ x: fragment.x,+ y: overlap.y,+ width: overlap.x - fragment.x,+ height: overlap.height+ ),+ WindowTargetBounds(+ x: overlapMaxX,+ y: overlap.y,+ width: fragmentMaxX - overlapMaxX,+ height: overlap.height+ )+ ]++ return candidates.filter(\.hasPositiveArea)+ }++ private static func intersection(+ _ lhs: WindowTargetBounds,+ _ rhs: WindowTargetBounds+ ) -> WindowTargetBounds? {+ let minX = max(lhs.x, rhs.x)+ let minY = max(lhs.y, rhs.y)+ let maxX = min(lhs.x + lhs.width, rhs.x + rhs.width)+ let maxY = min(lhs.y + lhs.height, rhs.y + rhs.height)+ let width = maxX - minX+ let height = maxY - minY+ guard width > 0, height > 0 else {+ return nil+ }++ return WindowTargetBounds(x: minX, y: minY, width: width, height: height)+ }++ private static func elementSort(_ lhs: DebugUIElement, _ rhs: DebugUIElement) -> Bool {+ if lhs.bbox.y != rhs.bbox.y {+ return lhs.bbox.y < rhs.bbox.y+ }+ if lhs.bbox.x != rhs.bbox.x {+ return lhs.bbox.x < rhs.bbox.x+ }+ return lhs.id < rhs.id+ }++ private static func fingerprint(+ for screen: DebugUIScreenMetadata,+ elements: [DebugUIElement]+ ) -> String {+ let payload = ([String(screen.screenID)] + elements.map { element in+ [+ element.id,+ element.type.rawValue,+ element.label,+ String(format: "%.1f", element.bbox.x),+ String(format: "%.1f", element.bbox.y),+ String(format: "%.1f", element.bbox.width),+ String(format: "%.1f", element.bbox.height)+ ].joined(separator: "|")+ }).joined(separator: "\n")+ return SHA256.hash(data: Data(payload.utf8))+ .map { String(format: "%02x", $0) }+ .joined()+ }+}++public enum DebugUIAccessibilityGeometry {+ static func normalizedBounds(+ for bounds: WindowTargetBounds,+ targetBounds: WindowTargetBounds,+ rootBounds: WindowTargetBounds? = nil+ ) -> WindowTargetBounds? {+ let rootBounds = rootBounds ?? targetBounds+ let grounded = WindowTargetBounds(+ x: normalizedAxisOrigin(+ bounds.x,+ length: bounds.width,+ rootOrigin: rootBounds.x,+ rootLength: rootBounds.width,+ targetOrigin: targetBounds.x+ ),+ y: normalizedAxisOrigin(+ bounds.y,+ length: bounds.height,+ rootOrigin: rootBounds.y,+ rootLength: rootBounds.height,+ targetOrigin: targetBounds.y+ ),+ width: bounds.width,+ height: bounds.height+ )+ return intersection(grounded, targetBounds)+ }++ private static func normalizedAxisOrigin(+ _ origin: Double,+ length: Double,+ rootOrigin: Double,+ rootLength: Double,+ targetOrigin: Double+ ) -> Double {+ let rootMax = rootOrigin + rootLength+ let center = origin + length / 2+ if center >= rootOrigin && center <= rootMax {+ return targetOrigin + (origin - rootOrigin)+ }+ return targetOrigin + origin+ }++ public static func boundingBox(+ for bounds: WindowTargetBounds,+ screenFrame: WindowTargetBounds+ ) -> DebugUIBoundingBox? {+ let minX = max(bounds.x, screenFrame.x)+ let minY = max(bounds.y, screenFrame.y)+ let maxX = min(bounds.x + bounds.width, screenFrame.x + screenFrame.width)+ let maxY = min(bounds.y + bounds.height, screenFrame.y + screenFrame.height)+ let width = maxX - minX+ let height = maxY - minY+ guard width > 0, height > 0 else {+ return nil+ }++ return DebugUIBoundingBox(+ x: minX - screenFrame.x,+ y: minY - screenFrame.y,+ width: width,+ height: height+ )+ }++ private static func intersection(+ _ lhs: WindowTargetBounds,+ _ rhs: WindowTargetBounds+ ) -> WindowTargetBounds? {+ let minX = max(lhs.x, rhs.x)+ let minY = max(lhs.y, rhs.y)+ let maxX = min(lhs.x + lhs.width, rhs.x + rhs.width)+ let maxY = min(lhs.y + lhs.height, rhs.y + rhs.height)+ let width = maxX - minX+ let height = maxY - minY+ guard width > 0, height > 0 else {+ return nil+ }++ return WindowTargetBounds(x: minX, y: minY, width: width, height: height)+ }++}++private struct AppKitDebugUIScreenMetadataProvider: DebugUIScreenMetadataProviding {+ func screens(scope: DebugUIInspectionScreenScope) throws -> [DebugUIScreenMetadata] {+ let screens: [NSScreen]+ switch scope {+ case .main:+ guard let screen = NSScreen.main ?? NSScreen.screens.first else {+ throw DebugUIAccessibilityInspectionError.noScreenAvailable+ }+ screens = [screen]+ case .all:+ screens = NSScreen.screens+ }++ return try screens.map(Self.metadata(for:))+ }++ private static func metadata(for screen: NSScreen) throws -> DebugUIScreenMetadata {+ let displayID = try displayID(for: screen)+ let appKitFrame = screen.frame+ let captureFrame = CGDisplayBounds(displayID)++ return DebugUIScreenMetadata(+ screenID: displayID,+ appKitFrame: HotLoopRect(+ x: appKitFrame.origin.x,+ y: appKitFrame.origin.y,+ width: appKitFrame.width,+ height: appKitFrame.height,+ space: .screen+ ),+ captureFrame: WindowTargetBounds(+ x: captureFrame.origin.x,+ y: captureFrame.origin.y,+ width: captureFrame.width,+ height: captureFrame.height+ )+ )+ }++ private static func displayID(for screen: NSScreen) throws -> UInt32 {+ let key = NSDeviceDescriptionKey("NSScreenNumber")+ guard let value = screen.deviceDescription[key] as? NSNumber else {+ throw DebugUIAccessibilityInspectionError.missingDisplayIdentifier+ }+ return value.uint32Value+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/DebugUIInspectionRuntime.swift b/apps/Donkey/Sources/DonkeyRuntime/DebugUIInspectionRuntime.swiftindex 9d4da06a..9c836145 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DebugUIInspectionRuntime.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DebugUIInspectionRuntime.swift@@ -15,7 +15,7 @@ public struct DebugUIOverlayConfiguration: Equatable, Sendable {public init(enabled: Bool = false,- provider: DebugUIInspectionProvider = .openai,+ provider: DebugUIInspectionProvider = .accessibility,cadenceSeconds: TimeInterval = 1.0,screenScope: DebugUIInspectionScreenScope = .main,minConfidence: Double = 0.25@@ -68,7 +68,7 @@ public struct DebugUIOverlayConfiguration: Equatable, Sendable {return DebugUIOverlayConfiguration(enabled: raw.enabled ?? false,- provider: raw.provider.flatMap(DebugUIInspectionProvider.init(rawValue:)) ?? .openai,+ 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@@ -248,7 +248,7 @@ public enum DebugUIOverlayGeometry {let scaleY = screenPointSize.height / screenshotPixelSize.heightreturn CGRect(x: bbox.x * scaleX,- y: bbox.y * scaleY,+ y: screenPointSize.height - (bbox.y + bbox.height) * scaleY,width: bbox.width * scaleX,height: bbox.height * scaleY)@@ -258,6 +258,8 @@ public enum DebugUIOverlayGeometry {public enum DebugUIScreenCaptureError: Error, Equatable, Sendable {case noScreenAvailablecase missingDisplayIdentifier+ case screenCapturePermissionDenied+ case blankCapture(displayID: UInt32)case captureFailed(displayID: UInt32)case pngEncodingFailed(displayID: UInt32)}@@ -289,11 +291,17 @@ public struct DebugUIScreenCaptureSnapshot: Equatable, Sendable {}public struct DebugUIScreenCaptureService: Sendable {+ private static let maxInspectionPixelDimension = 1_600+public init() {}public func captureScreens(scope: DebugUIInspectionScreenScope) throws -> [DebugUIScreenCaptureSnapshot] {+ guard Self.screenCaptureAccessGranted() else {+ throw DebugUIScreenCaptureError.screenCapturePermissionDenied+ }+let screens: [NSScreen]switch scope {case .main:@@ -308,12 +316,23 @@ public struct DebugUIScreenCaptureService: Sendable {return try screens.map(capture)}+ private static func screenCaptureAccessGranted() -> Bool {+ if CGPreflightScreenCaptureAccess() {+ return true+ }+ return CGRequestScreenCaptureAccess()+ }+private func capture(screen: NSScreen) throws -> DebugUIScreenCaptureSnapshot {let displayID = try Self.displayID(for: screen)guard let image = CGDisplayCreateImage(displayID) else {throw DebugUIScreenCaptureError.captureFailed(displayID: displayID)}- guard let pngData = Self.pngData(from: image) else {+ 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)}@@ -328,8 +347,8 @@ public struct DebugUIScreenCaptureService: Sendable {space: .screen),pixelSize: HotLoopSize(- width: Double(image.width),- height: Double(image.height),+ width: Double(inspectionImage.width),+ height: Double(inspectionImage.height),space: .screen),pngData: pngData,@@ -362,6 +381,80 @@ public struct DebugUIScreenCaptureService: Sendable {return data as Data}+ private static func inspectionImage(from image: CGImage) -> CGImage {+ let longestEdge = max(image.width, image.height)+ guard longestEdge > maxInspectionPixelDimension else {+ return image+ }++ let scale = Double(maxInspectionPixelDimension) / 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 static func isLikelyBlank(_ image: CGImage) -> Bool {+ let width = 32+ let height = 32+ let bytesPerPixel = 4+ let bytesPerRow = width * bytesPerPixel+ var pixels = [UInt8](repeating: 0, count: height * bytesPerRow)+ let colorSpace = CGColorSpaceCreateDeviceRGB()+ let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue++ return pixels.withUnsafeMutableBytes { buffer in+ guard let context = CGContext(+ data: buffer.baseAddress,+ width: width,+ height: height,+ bitsPerComponent: 8,+ bytesPerRow: bytesPerRow,+ space: colorSpace,+ bitmapInfo: bitmapInfo+ ) else {+ return false+ }++ context.interpolationQuality = .low+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))++ let bytes = buffer.bindMemory(to: UInt8.self)+ var luminanceTotal = 0+ var brightPixels = 0+ for offset in stride(from: 0, to: bytes.count, by: bytesPerPixel) {+ let red = Int(bytes[offset])+ let green = Int(bytes[offset + 1])+ let blue = Int(bytes[offset + 2])+ let luminance = (red + green + blue) / 3+ luminanceTotal += luminance+ if luminance > 24 {+ brightPixels += 1+ }+ }++ let pixelCount = width * height+ let averageLuminance = Double(luminanceTotal) / Double(pixelCount * 255)+ let brightFraction = Double(brightPixels) / Double(pixelCount)+ return averageLuminance < 0.02 && brightFraction < 0.01+ }+ }+private static func fingerprint(for data: Data) -> String {SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swiftindex d96c5b00..412555cf 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift@@ -1,6 +1,6 @@import DonkeyAIimport DonkeyContracts-import DonkeyRuntime+@testable import DonkeyRuntimeimport CoreGraphicsimport Foundationimport Testing@@ -15,7 +15,7 @@ struct DebugUIInspectionTests {let config = DebugUIOverlayConfiguration.load(fileURL: url)#expect(config.enabled == false)- #expect(config.provider == .openai)+ #expect(config.provider == .accessibility)#expect(config.screenScope == .main)}@@ -41,7 +41,7 @@ struct DebugUIInspectionTests {let config = DebugUIOverlayConfiguration.load(fileURL: url)#expect(config.enabled == true)- #expect(config.provider == .openai)+ #expect(config.provider == .accessibility)#expect(config.cadenceSeconds == 1.0)#expect(config.screenScope == .main)#expect(config.minConfidence == 0.25)@@ -91,7 +91,7 @@ struct DebugUIInspectionTests {let response = RemoteInferenceJSONValue.object(["output_text": .string("""- {"elements":[+ {"coordinate_space":{"width":1000,"height":500},"elements":[{"id":"save","type":"button","label":"Save","description":"Saves","bbox":{"x":10,"y":20,"width":80,"height":30},"confidence":1.5,"visual_style":{"overlay_color":"#3B82F6","border_color":"#60A5FA","label_color":"#FFFFFF"}},{"id":"low","type":"link","label":"Low","description":"","bbox":{"x":0,"y":0,"width":10,"height":10},"confidence":0.1,"visual_style":{"overlay_color":"#06B6D4","border_color":"#67E8F9","label_color":"#FFFFFF"}}]}@@ -106,6 +106,26 @@ struct DebugUIInspectionTests {#expect(frame.elements.first?.visualStyle == DebugUIOverlayStyle.style(for: .button))}+ @Test+ func inspectionResponseScalesProviderCoordinateSpaceToScreenshotPixels() throws {+ let response = RemoteInferenceJSONValue.object([+ "output_text": .string(+ """+ {"coordinate_space":{"width":960,"height":540},"elements":[+ {"id":"search","type":"input","label":"Search","description":"","bbox":{"x":120,"y":270,"width":240,"height":30},"confidence":0.9,"visual_style":{"overlay_color":"#10B981","border_color":"#6EE7B7","label_color":"#FFFFFF"}}+ ]}+ """+ )+ ])++ let frame = try DebugUIInspectionResponseDecoder.decode(+ response,+ screenshotPixelSize: HotLoopSize(width: 1920, height: 1080, space: .screen)+ )++ #expect(frame.elements.first?.bbox == DebugUIBoundingBox(x: 240, y: 540, width: 480, height: 60))+ }+@Testfunc inspectionResponseRejectsProviderActions() {let response = RemoteInferenceJSONValue.object([@@ -147,6 +167,454 @@ struct DebugUIInspectionTests {#expect(frame == CGRect(x: 100, y: 350, width: 200, height: 100))}+ @Test+ func geometryConvertsTopLeftScreenPixelsToLocalLayerPoints() {+ let frame = DebugUIOverlayGeometry.localLayerFrame(+ for: DebugUIBoundingBox(x: 200, y: 100, width: 400, height: 200),+ screenshotPixelSize: HotLoopSize(width: 2000, height: 1000, space: .screen),+ screenPointSize: HotLoopSize(width: 1000, height: 500, space: .screen)+ )++ #expect(frame == CGRect(x: 100, y: 350, width: 200, height: 100))+ }++ @Test+ func accessibilityGeometryClipsScreenLocalBounds() {+ let bbox = DebugUIAccessibilityGeometry.boundingBox(+ for: WindowTargetBounds(x: 900, y: 750, width: 200, height: 100),+ screenFrame: WindowTargetBounds(x: 0, y: 0, width: 1000, height: 800)+ )++ #expect(bbox == DebugUIBoundingBox(x: 900, y: 750, width: 100, height: 50))+ }++ @Test+ func accessibilityGeometryNormalizesWindowLocalAxisWhenItBetterFitsTarget() {+ let normalized = DebugUIAccessibilityGeometry.normalizedBounds(+ for: WindowTargetBounds(x: 436, y: 117, width: 160, height: 240),+ targetBounds: WindowTargetBounds(x: 50, y: 253, width: 1530, height: 930),+ rootBounds: WindowTargetBounds(x: 50, y: 253, width: 1530, height: 930)+ )++ #expect(normalized == WindowTargetBounds(x: 436, y: 370, width: 160, height: 240))+ }++ @Test+ func accessibilityGeometryGroundsGlobalFrameOnMovedWindowPosition() {+ let normalized = DebugUIAccessibilityGeometry.normalizedBounds(+ for: WindowTargetBounds(x: 436, y: 370, width: 160, height: 240),+ targetBounds: WindowTargetBounds(x: 80, y: 400, width: 1530, height: 930),+ rootBounds: WindowTargetBounds(x: 50, y: 253, width: 1530, height: 930)+ )++ #expect(normalized == WindowTargetBounds(x: 466, y: 517, width: 160, height: 240))+ }++ @Test+ func accessibilityInspectionBuildsScreenLocalWindowFrames() throws {+ let screen = DebugUIScreenMetadata(+ screenID: 3,+ 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: "Window",+ frame: WindowTargetBounds(x: 100, y: 200, width: 500, height: 300),+ children: [+ RawMacAccessibilitySnapshotNode(+ role: "AXButton",+ title: "Save",+ frame: WindowTargetBounds(x: 120, y: 230, width: 80, height: 30),+ isEnabled: true,+ actions: ["AXPress"]+ ),+ RawMacAccessibilitySnapshotNode(+ role: "AXGroup",+ title: "Container",+ frame: WindowTargetBounds(x: 0, y: 0, width: 1000, height: 800),+ isEnabled: true+ )+ ]+ ),+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)+ )+ )+ let service = DebugUIAccessibilityInspectionService(+ windowResolver: MacWindowResolver(+ provider: DebugUIFixtureWindowProvider(+ windows: [+ MacWindowProviderWindow(+ windowID: 11,+ processID: 100,+ appName: "Notes",+ title: "Window",+ bounds: WindowTargetBounds(x: 100, y: 200, width: 500, height: 300)+ )+ ],+ frontmostProcessID: 100+ )+ ),+ capturer: capturer,+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),+ currentProcessID: 999+ )++ let results = try service.inspect(scope: .main, minConfidence: 0.25)++ #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))+ }++ @Test+ func accessibilityInspectionSkipsCurrentProcess() throws {+ let screen = DebugUIScreenMetadata(+ screenID: 1,+ appKitFrame: HotLoopRect(x: 0, y: 0, width: 500, height: 500, space: .screen),+ captureFrame: WindowTargetBounds(x: 0, y: 0, width: 500, height: 500)+ )+ let capturer = DebugUIFakeAccessibilityCapturer()+ let service = DebugUIAccessibilityInspectionService(+ windowResolver: MacWindowResolver(+ provider: DebugUIFixtureWindowProvider(+ windows: [+ MacWindowProviderWindow(+ windowID: 1,+ processID: 42,+ appName: "Donkey Dev",+ bounds: WindowTargetBounds(x: 0, y: 0, width: 200, height: 200)+ )+ ],+ frontmostProcessID: 42+ )+ ),+ capturer: capturer,+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),+ currentProcessID: 42+ )++ let results = try service.inspect(scope: .main, minConfidence: 0.25)++ #expect(capturer.capturedWindowIDs.isEmpty)+ #expect(results.first?.frame.elements.isEmpty == true)+ }++ @Test+ func accessibilityInspectionSkipsFullyCoveredWindowFrame() throws {+ let screen = DebugUIScreenMetadata(+ screenID: 1,+ appKitFrame: HotLoopRect(x: 0, y: 0, width: 500, height: 500, space: .screen),+ captureFrame: WindowTargetBounds(x: 0, y: 0, width: 500, height: 500)+ )+ let capturer = DebugUIFakeAccessibilityCapturer(+ treesByWindowID: [+ 1: MacAccessibilitySnapshotTreeBuilder.build(+ root: RawMacAccessibilitySnapshotNode(+ role: "AXWindow",+ title: "Front",+ frame: WindowTargetBounds(x: 100, y: 100, width: 200, height: 200),+ children: [+ RawMacAccessibilitySnapshotNode(+ role: "AXButton",+ title: "Visible",+ frame: WindowTargetBounds(x: 120, y: 120, width: 80, height: 30),+ isEnabled: true,+ actions: ["AXPress"]+ )+ ]+ ),+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)+ ),+ 2: MacAccessibilitySnapshotTreeBuilder.build(+ root: RawMacAccessibilitySnapshotNode(+ role: "AXWindow",+ title: "Back",+ frame: WindowTargetBounds(x: 100, y: 100, width: 200, height: 200),+ children: [+ RawMacAccessibilitySnapshotNode(+ role: "AXButton",+ title: "Hidden",+ frame: WindowTargetBounds(x: 130, y: 130, width: 80, height: 30),+ isEnabled: true,+ actions: ["AXPress"]+ )+ ]+ ),+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)+ )+ ]+ )+ let service = DebugUIAccessibilityInspectionService(+ windowResolver: MacWindowResolver(+ provider: DebugUIFixtureWindowProvider(+ windows: [+ MacWindowProviderWindow(+ windowID: 1,+ processID: 100,+ appName: "Front",+ bounds: WindowTargetBounds(x: 100, y: 100, width: 200, height: 200)+ ),+ MacWindowProviderWindow(+ windowID: 2,+ processID: 200,+ appName: "Back",+ bounds: WindowTargetBounds(x: 100, y: 100, width: 200, height: 200)+ )+ ],+ frontmostProcessID: 100+ )+ ),+ capturer: capturer,+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),+ currentProcessID: 999+ )++ 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"])+ }++ @Test+ func accessibilityInspectionKeepsPartiallyVisibleWindowFrame() throws {+ let screen = DebugUIScreenMetadata(+ screenID: 1,+ appKitFrame: HotLoopRect(x: 0, y: 0, width: 500, height: 500, space: .screen),+ captureFrame: WindowTargetBounds(x: 0, y: 0, width: 500, height: 500)+ )+ let capturer = DebugUIFakeAccessibilityCapturer(+ treesByWindowID: [+ 1: MacAccessibilitySnapshotTreeBuilder.build(+ root: RawMacAccessibilitySnapshotNode(+ role: "AXWindow",+ title: "Front",+ frame: WindowTargetBounds(x: 100, y: 100, width: 100, height: 100)+ ),+ limits: MacAccessibilitySnapshotLimits(maxDepth: 0)+ ),+ 2: MacAccessibilitySnapshotTreeBuilder.build(+ root: RawMacAccessibilitySnapshotNode(+ role: "AXWindow",+ title: "Back",+ frame: WindowTargetBounds(x: 150, y: 150, width: 200, height: 200)+ ),+ limits: MacAccessibilitySnapshotLimits(maxDepth: 0)+ )+ ]+ )+ let service = DebugUIAccessibilityInspectionService(+ windowResolver: MacWindowResolver(+ provider: DebugUIFixtureWindowProvider(+ windows: [+ MacWindowProviderWindow(+ windowID: 1,+ processID: 100,+ appName: "Front",+ bounds: WindowTargetBounds(x: 100, y: 100, width: 100, height: 100)+ ),+ MacWindowProviderWindow(+ windowID: 2,+ processID: 200,+ appName: "Back",+ bounds: WindowTargetBounds(x: 150, y: 150, width: 200, height: 200)+ )+ ],+ frontmostProcessID: 100+ )+ ),+ capturer: capturer,+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),+ currentProcessID: 999+ )++ let results = try service.inspect(scope: .main, minConfidence: 0.25)++ #expect(capturer.capturedWindowIDs == [1, 2])+ #expect(results.first?.frame.elements.map(\.id) == ["window-1", "window-2"])+ #expect(results.first?.frame.elements.map(\.label) == ["Front", "Back"])+ #expect(results.first?.frame.elements.map(\.visualStyle.borderColor) == ["#F87171", "#FB923C"])+ }++ @Test+ func accessibilityInspectionIgnoresChildElementsWhenDrawingWindowFramesOnly() 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: "Terminal",+ frame: WindowTargetBounds(x: 0, y: 0, width: 1000, height: 800),+ children: [+ RawMacAccessibilitySnapshotNode(+ role: "AXTextArea",+ title: "Terminal output",+ frame: WindowTargetBounds(x: 100, y: 100, width: 700, height: 300),+ isEnabled: true+ ),+ RawMacAccessibilitySnapshotNode(+ role: "AXTextField",+ title: "Search",+ frame: WindowTargetBounds(x: 100, y: 450, width: 300, height: 34),+ isEnabled: true+ )+ ]+ ),+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)+ )+ )+ let service = DebugUIAccessibilityInspectionService(+ windowResolver: MacWindowResolver(+ provider: DebugUIFixtureWindowProvider(+ windows: [+ MacWindowProviderWindow(+ windowID: 1,+ processID: 100,+ appName: "Terminal",+ bounds: WindowTargetBounds(x: 0, y: 0, width: 1000, height: 800)+ )+ ],+ frontmostProcessID: 100+ )+ ),+ capturer: capturer,+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),+ currentProcessID: 999+ )++ 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.first?.bbox == DebugUIBoundingBox(+ x: 0,+ y: 0,+ width: 1000,+ height: 800+ ))+ }++ @Test+ func accessibilityInspectionDrawsMusicWindowFrameOnly() throws {+ let screen = DebugUIScreenMetadata(+ screenID: 1,+ appKitFrame: HotLoopRect(x: 0, y: 0, width: 1800, height: 1400, space: .screen),+ captureFrame: WindowTargetBounds(x: 0, y: 0, width: 1800, height: 1400)+ )+ let capturer = DebugUIFakeAccessibilityCapturer(+ tree: MacAccessibilitySnapshotTreeBuilder.build(+ root: RawMacAccessibilitySnapshotNode(+ role: "AXWindow",+ title: "Music",+ frame: WindowTargetBounds(x: 50, y: 253, width: 1530, height: 930),+ children: [+ RawMacAccessibilitySnapshotNode(+ role: "AXButton",+ title: "K-Pop Hits",+ frame: WindowTargetBounds(x: 436, y: 117, width: 160, height: 240),+ isEnabled: true,+ actions: ["AXPress"]+ )+ ]+ ),+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)+ )+ )+ let service = DebugUIAccessibilityInspectionService(+ windowResolver: MacWindowResolver(+ provider: DebugUIFixtureWindowProvider(+ windows: [+ MacWindowProviderWindow(+ windowID: 1,+ processID: 100,+ appName: "Music",+ bounds: WindowTargetBounds(x: 50, y: 253, width: 1530, height: 930)+ )+ ],+ frontmostProcessID: 100+ )+ ),+ capturer: capturer,+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),+ currentProcessID: 999+ )++ let results = try service.inspect(scope: .main, minConfidence: 0.25)++ #expect(results.first?.frame.elements.first?.bbox == DebugUIBoundingBox(+ x: 50,+ y: 253,+ width: 1530,+ height: 930+ ))+ }++ @Test+ func accessibilityInspectionDrawsMovedMusicWindowFrameOnly() throws {+ let screen = DebugUIScreenMetadata(+ screenID: 1,+ appKitFrame: HotLoopRect(x: 0, y: 0, width: 1800, height: 1400, space: .screen),+ captureFrame: WindowTargetBounds(x: 0, y: 0, width: 1800, height: 1400)+ )+ let capturer = DebugUIFakeAccessibilityCapturer(+ tree: MacAccessibilitySnapshotTreeBuilder.build(+ root: RawMacAccessibilitySnapshotNode(+ role: "AXWindow",+ title: "Music",+ frame: WindowTargetBounds(x: 80, y: 400, width: 1530, height: 930),+ children: [+ RawMacAccessibilitySnapshotNode(+ role: "AXButton",+ title: "K-Pop Hits",+ frame: WindowTargetBounds(x: 436, y: 370, width: 160, height: 240),+ isEnabled: true,+ actions: ["AXPress"]+ )+ ]+ ),+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)+ )+ )+ let service = DebugUIAccessibilityInspectionService(+ windowResolver: MacWindowResolver(+ provider: DebugUIFixtureWindowProvider(+ windows: [+ MacWindowProviderWindow(+ windowID: 1,+ processID: 100,+ appName: "Music",+ bounds: WindowTargetBounds(x: 80, y: 400, width: 1530, height: 930)+ )+ ],+ frontmostProcessID: 100+ )+ ),+ capturer: capturer,+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),+ currentProcessID: 999+ )++ let results = try service.inspect(scope: .main, minConfidence: 0.25)++ #expect(results.first?.frame.elements.first?.bbox == DebugUIBoundingBox(+ x: 80,+ y: 400,+ width: 1530,+ height: 930+ ))+ }+private func element(id: String,label: String,@@ -169,3 +637,76 @@ struct DebugUIInspectionTests {return url}}++private final class DebugUIFakeAccessibilityCapturer: MacAccessibilitySnapshotCapturing, @unchecked Sendable {+ var trust: MacAccessibilityTrustStatus+ var tree: MacAccessibilitySnapshotTree+ var treesByWindowID: [UInt32: MacAccessibilitySnapshotTree]+ var capturedWindowIDs: [UInt32] = []++ init(+ trustStatus: MacAccessibilityTrustStatus = .trusted,+ tree: MacAccessibilitySnapshotTree = MacAccessibilitySnapshotTreeBuilder.build(+ root: RawMacAccessibilitySnapshotNode(role: "AXWindow", title: "Window"),+ limits: .default+ ),+ treesByWindowID: [UInt32: MacAccessibilitySnapshotTree] = [:]+ ) {+ self.trust = trustStatus+ self.tree = tree+ self.treesByWindowID = treesByWindowID+ }++ func trustStatus() -> MacAccessibilityTrustStatus {+ trust+ }++ func captureTree(+ target: MacWindowTargetCandidate,+ limits: MacAccessibilitySnapshotLimits+ ) throws -> MacAccessibilitySnapshotTree {+ capturedWindowIDs.append(target.windowID)+ return treesByWindowID[target.windowID] ?? tree+ }+}++private struct DebugUIFixtureScreenProvider: DebugUIScreenMetadataProviding {+ var screens: [DebugUIScreenMetadata]++ func screens(scope: DebugUIInspectionScreenScope) throws -> [DebugUIScreenMetadata] {+ switch scope {+ case .main:+ return screens.prefix(1).map { $0 }+ case .all:+ return screens+ }+ }+}++private struct DebugUIFixtureWindowProvider: MacWindowMetadataProviding {+ var fixtureWindows: [MacWindowProviderWindow]+ var frontmostProcessID: Int32?+ var focusedWindowID: UInt32?++ init(+ windows: [MacWindowProviderWindow],+ frontmostProcessID: Int32? = nil,+ focusedWindowID: UInt32? = nil+ ) {+ self.fixtureWindows = windows+ self.frontmostProcessID = frontmostProcessID+ self.focusedWindowID = focusedWindowID+ }++ func windows() -> [MacWindowProviderWindow] {+ fixtureWindows+ }++ func frontmostProcessIdentifier() -> Int32? {+ frontmostProcessID+ }++ func focusedWindowIdentifier() -> UInt32? {+ focusedWindowID+ }+}diff --git a/apps/Donkey/dev-overlay.json b/apps/Donkey/dev-overlay.jsonindex 95f5d92d..527db903 100644--- a/apps/Donkey/dev-overlay.json+++ b/apps/Donkey/dev-overlay.json@@ -1,6 +1,6 @@{- "enabled": false,- "provider": "openai",+ "enabled": true,+ "provider": "accessibility","cadenceSeconds": 1.0,"screenScope": "main","minConfidence": 0.25diff --git a/scripts/run-donkey-dev.sh b/scripts/run-donkey-dev.shindex eb4a584e..63c2d936 100755--- a/scripts/run-donkey-dev.sh+++ b/scripts/run-donkey-dev.sh@@ -108,6 +108,43 @@ start_logger() {LOG_PID="$!"}+print_dev_overlay_status() {+ local overlay_config="$APP_DIR/dev-overlay.json"+ if [ ! -f "$overlay_config" ]; then+ echo "Dev overlay config: missing at $overlay_config"+ return+ fi++ local summary+ summary="$(+ python3 - "$overlay_config" <<'PY' 2>/dev/null || true+import json+import sys++with open(sys.argv[1], "r", encoding="utf-8") as handle:+ config = json.load(handle)++print(+ "enabled={enabled} provider={provider} cadenceSeconds={cadence} "+ "screenScope={scope} minConfidence={confidence}".format(+ enabled=config.get("enabled", False),+ provider=config.get("provider", "accessibility"),+ cadence=config.get("cadenceSeconds", 1.0),+ scope=config.get("screenScope", "main"),+ confidence=config.get("minConfidence", 0.25),+ )+)+PY+ )"++ if [ -n "$summary" ]; then+ echo "Dev overlay config: $summary"+ echo "Dev overlay logs: look for 'debug inspection rendering ... elements=N' below."+ else+ echo "Dev overlay config: invalid JSON at $overlay_config"+ fi+}+is_local_web_base_url() {case "$DONKEY_WEB_BASE_URL" inhttp://localhost|http://localhost:*|http://127.0.0.1|http://127.0.0.1:*|http://[::1]|http://[::1]:*)@@ -405,5 +442,6 @@ if [ "$LAUNCH_APP" = "0" ]; thenfiecho "Starting Donkey..."+print_dev_overlay_statusstart_loggeropen -W -n "$DEV_APP_DIR"