Open source CapCut alternative.
TypeScript
Stub screenshot vision pipeline
David Leae30328bb745
diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swiftindex ec7e159f..a0ea16f9 100644--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift@@ -19,6 +19,7 @@ final class DebugUIInspectionCoordinator {private var trackers: [UInt32: DebugUIElementTracker] = [:]private var lastFingerprints: [UInt32: String] = [:]private var lastRenderedFrames: [UInt32: DebugUIInspectionFrame] = [:]+ private var lastSnapshots: [UInt32: DebugUIScreenCaptureSnapshot] = [:]private var timer: Timer?private var notificationObservers: [NSObjectProtocol] = []private var currentConfig: DebugUIOverlayConfiguration = .disabled@@ -50,6 +51,7 @@ final class DebugUIInspectionCoordinator {trackers.removeAll()lastFingerprints.removeAll()lastRenderedFrames.removeAll()+ lastSnapshots.removeAll()isAnalyzing = falsecurrentConfig = .disabled}@@ -115,6 +117,7 @@ final class DebugUIInspectionCoordinator {lastFingerprints.removeAll()trackers.removeAll()lastRenderedFrames.removeAll()+ lastSnapshots.removeAll()if !newConfig.enabled {overlayController.close()}@@ -211,23 +214,29 @@ 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) }+ ageMissingAccessibilityScreens(activeScreenIDs: activeScreenIDs)for result in results {let snapshot = result.snapshot- guard force || lastFingerprints[snapshot.screenID] != snapshot.fingerprint else {+ if !force, lastFingerprints[snapshot.screenID] == snapshot.fingerprint {DebugUIInspectionLog.overlay.debug(- "debug inspection skipped unchanged accessibility screenID=\(snapshot.screenID, privacy: .public)"+ "debug inspection sampling unchanged accessibility screenID=\(snapshot.screenID, privacy: .public)")- continue}lastFingerprints[snapshot.screenID] = snapshot.fingerprint+ lastSnapshots[snapshot.screenID] = snapshotvar tracker = trackers[snapshot.screenID] ?? DebugUIElementTracker()let trackedFrame = tracker.update(with: result.frame)trackers[snapshot.screenID] = tracker+ if !force,+ let previousFrame = lastRenderedFrames[snapshot.screenID],+ trackedFrame.isOverlayRenderEquivalent(to: previousFrame) {+ DebugUIInspectionLog.overlay.debug(+ "debug inspection skipped stable accessibility render screenID=\(snapshot.screenID, privacy: .public)"+ )+ continue+ }DebugUIInspectionLog.overlay.info("debug inspection rendering source=accessibility screenID=\(snapshot.screenID, privacy: .public) elements=\(trackedFrame.elements.count, privacy: .public)")@@ -235,6 +244,35 @@ final class DebugUIInspectionCoordinator {lastRenderedFrames[snapshot.screenID] = trackedFrameoverlayController.render(frame: trackedFrame, snapshot: snapshot)}++ let retainedScreenIDs = Set(lastRenderedFrames.keys).union(activeScreenIDs)+ overlayController.closeScreens(except: retainedScreenIDs)+ lastFingerprints = lastFingerprints.filter { retainedScreenIDs.contains($0.key) }+ lastSnapshots = lastSnapshots.filter { retainedScreenIDs.contains($0.key) }+ }++ private func ageMissingAccessibilityScreens(activeScreenIDs: Set<UInt32>) {+ let missingScreenIDs = Set(lastRenderedFrames.keys).subtracting(activeScreenIDs)+ for screenID in missingScreenIDs {+ var tracker = trackers[screenID] ?? DebugUIElementTracker()+ let trackedFrame = tracker.update(with: DebugUIInspectionFrame())+ trackers[screenID] = tracker+ if trackedFrame.elements.isEmpty {+ lastRenderedFrames.removeValue(forKey: screenID)+ lastFingerprints.removeValue(forKey: screenID)+ lastSnapshots.removeValue(forKey: screenID)+ continue+ }++ if let snapshot = lastSnapshots[screenID] {+ if let previousFrame = lastRenderedFrames[screenID],+ trackedFrame.isOverlayRenderEquivalent(to: previousFrame) {+ continue+ }+ lastRenderedFrames[screenID] = trackedFrame+ overlayController.render(frame: trackedFrame, snapshot: snapshot)+ }+ }}private func logSampleMappings(diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swiftindex caccca0e..074f9f79 100644--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift@@ -23,6 +23,12 @@ final class DebugUIInspectionOverlayController {}}+ func setHidden(_ hidden: Bool) {+ for surface in surfaces.values {+ surface.setHidden(hidden)+ }+ }+func close() {for surface in surfaces.values {surface.close()@@ -124,6 +130,14 @@ private final class DebugUIInspectionSurface {elementLayers.removeAll()}+ func setHidden(_ hidden: Bool) {+ if hidden {+ panel.orderOut(nil)+ } else {+ panel.orderFrontRegardless()+ }+ }+private func makeLayers(for element: DebugUIElement) -> DebugUIInspectionElementLayers {let boxLayer = CAShapeLayer()boxLayer.name = "debug-ui-box-\(element.id)"@@ -171,62 +185,23 @@ private final class DebugUIInspectionSurface {layers.box.strokeColor = nsColor(hex: element.visualStyle.borderColor, alpha: 0.95).cgColorlet title = labelText(for: element)- let labelSize = labelFrameSize(for: title, boxFrame: boxFrame)- let labelY = max(0, boxFrame.minY - labelSize.height - 2)+ let labelFrame = DebugUIOverlayGeometry.stableLabelFrame(+ for: title,+ boxFrame: boxFrame,+ containerSize: rootView.bounds.size+ )layers.label.string = titlelayers.label.foregroundColor = nsColor(hex: element.visualStyle.labelColor, alpha: 1).cgColorlayers.label.backgroundColor = nsColor(hex: element.visualStyle.overlayColor, alpha: 0.92).cgColor- layers.label.frame = CGRect(- x: max(0, min(boxFrame.minX, rootView.bounds.width - labelSize.width)),- y: labelY,- width: labelSize.width,- height: labelSize.height- ).integral+ layers.label.frame = labelFrame}private func labelText(for element: DebugUIElement) -> String {let label = element.label.trimmingCharacters(in: .whitespacesAndNewlines)- let baseLabel: Stringif label.isEmpty {- baseLabel = element.type.rawValue.replacingOccurrences(of: "_", with: " ")- } else {- baseLabel = label- }-- guard let sources = element.metadata["localUIElement.sources"],- !sources.isEmpty- else {- return baseLabel+ return element.type.rawValue.replacingOccurrences(of: "_", with: " ")}- 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()- }- }-- private func labelFrameSize(for text: String, boxFrame: CGRect) -> CGSize {- let characterWidth = 6.5- let width = min(- max(48, Double(text.count) * characterWidth + 14),- max(64, Double(rootView.bounds.width - max(0, boxFrame.minX)))- )- return CGSize(width: width, height: 18)+ return label}private func fillColor(for element: DebugUIElement) -> CGColor {diff --git a/apps/Donkey/Sources/DonkeyContracts/AgentVisualizationContracts.swift b/apps/Donkey/Sources/DonkeyContracts/AgentVisualizationContracts.swiftindex 04b9b6d7..8a3fb087 100644--- a/apps/Donkey/Sources/DonkeyContracts/AgentVisualizationContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/AgentVisualizationContracts.swift@@ -25,7 +25,6 @@ public enum AgentVisualizationGroundingSource: String, Codable, Equatable, Sendacase accessibilitycase windowMetadatacase localUIUnderstanding- case yoloSegmentationcase actionTracecase fallback}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swiftindex 030c9a4b..c920d254 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift@@ -3,7 +3,7 @@ import Foundationpublic enum LocalModelRuntimeID: String, Codable, CaseIterable, Equatable, Sendable {case parakeetTranscriber = "parakeet-transcriber"- case yoloSegmenter = "yolo-segmenter"+ case screenshotSegmentationStub = "screenshot-segmentation-stub"case uiUnderstander = "ui-understander"case localLLM = "local-llm"}@@ -460,8 +460,8 @@ public struct LocalModelRuntimeSetupManager: Sendable {switch runtimeID {case .parakeetTranscriber:return "DONKEY_PARAKEET_RUNTIME_MANIFEST_URL"- case .yoloSegmenter:- return "DONKEY_YOLO_RUNTIME_MANIFEST_URL"+ case .screenshotSegmentationStub:+ return "DONKEY_SCREENSHOT_SEGMENTATION_STUB_RUNTIME_MANIFEST_URL"case .uiUnderstander:return "DONKEY_UI_UNDERSTANDER_RUNTIME_MANIFEST_URL"case .localLLM:diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swiftindex ab2ae9a8..15ac33ce 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift@@ -163,50 +163,184 @@ private struct RawDebugUIOverlayConfiguration: Codable {public struct DebugUIElementTracker: Equatable, Sendable {private var previousElements: [DebugUIElement]+ private var lastObservedElements: [DebugUIElement]+ private var appearanceCounts: [String: Int]+ private var missingCounts: [String: Int]+ private var pendingMovements: [String: PendingTrackedElement]+ private var pendingContent: [String: PendingTrackedElement]+ private var appearanceThreshold: Int+ private var disappearanceTolerance: Int+ private var movementConfirmationSamples: Int- public init(previousElements: [DebugUIElement] = []) {+ public init(+ previousElements: [DebugUIElement] = [],+ appearanceThreshold: Int = 2,+ disappearanceTolerance: Int = 2,+ movementConfirmationSamples: Int = 2+ ) {self.previousElements = previousElements+ self.lastObservedElements = previousElements+ self.appearanceCounts = Dictionary(uniqueKeysWithValues: previousElements.map { ($0.id, appearanceThreshold) })+ self.missingCounts = [:]+ self.pendingMovements = [:]+ self.pendingContent = [:]+ self.appearanceThreshold = max(1, appearanceThreshold)+ self.disappearanceTolerance = max(0, disappearanceTolerance)+ self.movementConfirmationSamples = max(1, movementConfirmationSamples)}public mutating func update(with frame: DebugUIInspectionFrame) -> DebugUIInspectionFrame {var usedPreviousIDs = Set<String>()- let tracked = frame.elements.map { incoming -> DebugUIElement in+ let matchBase = semanticMatchBase()+ var trackedCandidates: [DebugUIElement] = []++ for incoming in frame.elements {if let previous = previousElements.first(where: { $0.id == incoming.id }) {usedPreviousIDs.insert(incoming.id)- return stableElement(incoming, matchedTo: previous)+ trackedCandidates.append(stableElement(incoming, matchedTo: previous))+ continue+ }+ if let observed = lastObservedElements.first(where: { $0.id == incoming.id }) {+ usedPreviousIDs.insert(incoming.id)+ trackedCandidates.append(stableElement(incoming, matchedTo: observed))+ continue}guard let match = bestSemanticMatch(for: incoming,+ in: matchBase,usedPreviousIDs: usedPreviousIDs) else {- return incoming+ trackedCandidates.append(incoming)+ continue}usedPreviousIDs.insert(match.id)- return stableElement(incoming.replacingID(match.id), matchedTo: match)+ trackedCandidates.append(stableElement(incoming.replacingID(match.id), matchedTo: match))+ }++ lastObservedElements = trackedCandidates+ let trackedIDs = Set(trackedCandidates.map(\.id))+ var rendered: [DebugUIElement] = []++ for candidate in trackedCandidates {+ if previousElements.contains(where: { $0.id == candidate.id }) {+ appearanceCounts[candidate.id] = appearanceThreshold+ missingCounts[candidate.id] = nil+ rendered.append(candidate)+ continue+ }++ let count = min(appearanceThreshold, (appearanceCounts[candidate.id] ?? 0) + 1)+ appearanceCounts[candidate.id] = count+ missingCounts[candidate.id] = nil+ if count >= appearanceThreshold {+ rendered.append(candidate)+ }+ }++ for previous in previousElements where !trackedIDs.contains(previous.id) {+ let missingCount = (missingCounts[previous.id] ?? 0) + 1+ if missingCount <= disappearanceTolerance {+ missingCounts[previous.id] = missingCount+ rendered.append(previous)+ } else {+ missingCounts[previous.id] = nil+ appearanceCounts[previous.id] = nil+ }+ }++ let renderedIDs = Set(rendered.map(\.id))+ appearanceCounts = appearanceCounts.filter { trackedIDs.contains($0.key) || renderedIDs.contains($0.key) }+ missingCounts = missingCounts.filter { renderedIDs.contains($0.key) }+ pendingMovements = pendingMovements.filter { trackedIDs.contains($0.key) || renderedIDs.contains($0.key) }+ pendingContent = pendingContent.filter { trackedIDs.contains($0.key) || renderedIDs.contains($0.key) }+ previousElements = rendered+ return DebugUIInspectionFrame(elements: rendered)+ }++ private func semanticMatchBase() -> [DebugUIElement] {+ var seen = Set<String>()+ return (previousElements + lastObservedElements).filter { element in+ guard !seen.contains(element.id) else { return false }+ seen.insert(element.id)+ return true+ }+ }++ private mutating func stableElement(+ _ incoming: DebugUIElement,+ matchedTo previous: DebugUIElement+ ) -> DebugUIElement {+ let geometryStable = stableGeometryElement(incoming, matchedTo: previous)+ return stableContentElement(geometryStable, matchedTo: previous)+ }++ private mutating func stableGeometryElement(+ _ incoming: DebugUIElement,+ matchedTo previous: DebugUIElement+ ) -> DebugUIElement {+ if shouldReusePreviousBounds(incoming.bbox, previous.bbox) {+ pendingMovements[incoming.id] = nil+ return copy(incoming, bbox: previous.bbox)+ }++ if isLargeMovement(from: previous.bbox, to: incoming.bbox) {+ pendingMovements[incoming.id] = nil+ return incoming+ }++ let pending = pendingMovements[incoming.id]+ let nextCount: Int+ if let pending,+ shouldReusePreviousBounds(incoming.bbox, pending.element.bbox) {+ nextCount = min(movementConfirmationSamples, pending.count + 1)+ } else {+ nextCount = 1}- previousElements = tracked- return DebugUIInspectionFrame(elements: tracked)+ if nextCount >= movementConfirmationSamples {+ pendingMovements[incoming.id] = nil+ return incoming+ }++ pendingMovements[incoming.id] = PendingTrackedElement(element: incoming, count: nextCount)+ return copy(incoming, bbox: previous.bbox)}- private func stableElement(+ private mutating func stableContentElement(_ incoming: DebugUIElement,matchedTo previous: DebugUIElement) -> DebugUIElement {- guard shouldReusePreviousBounds(incoming.bbox, previous.bbox) else {+ if hasSameRenderContent(incoming, previous) {+ pendingContent[incoming.id] = nilreturn incoming}++ let pending = pendingContent[incoming.id]+ let nextCount: Int+ if let pending,+ hasSameRenderContent(incoming, pending.element) {+ nextCount = min(movementConfirmationSamples, pending.count + 1)+ } else {+ nextCount = 1+ }++ if nextCount >= movementConfirmationSamples {+ pendingContent[incoming.id] = nil+ return incoming+ }++ pendingContent[incoming.id] = PendingTrackedElement(element: incoming, count: nextCount)return DebugUIElement(id: incoming.id,type: incoming.type,- label: incoming.label,+ label: previous.label,description: incoming.description,- bbox: previous.bbox,+ bbox: incoming.bbox,confidence: incoming.confidence,- visualStyle: incoming.visualStyle,- metadata: incoming.metadata+ visualStyle: previous.visualStyle,+ metadata: stableRenderMetadata(incoming: incoming.metadata, previous: previous.metadata))}@@ -220,14 +354,73 @@ public struct DebugUIElementTracker: Equatable, Sendable {abs(incoming.width - previous.width),abs(incoming.height - previous.height))- return maximumDelta <= 2.0 && matchScore(previous, incoming) >= 0.82+ return maximumDelta <= jitterTolerance(for: previous) && matchScore(previous, incoming) >= 0.70+ }++ private func isLargeMovement(+ from previous: DebugUIBoundingBox,+ to incoming: 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)+ )+ let threshold = max(48.0, max(previous.width, previous.height) * 0.25)+ return maximumDelta >= threshold || matchScore(previous, incoming) < 0.12+ }++ private func jitterTolerance(for bbox: DebugUIBoundingBox) -> Double {+ min(max(6.0, min(bbox.width, bbox.height) * 0.08), 10.0)+ }++ private func hasSameRenderContent(+ _ lhs: DebugUIElement,+ _ rhs: DebugUIElement+ ) -> Bool {+ lhs.type == rhs.type+ && lhs.label.trimmingCharacters(in: .whitespacesAndNewlines)+ == rhs.label.trimmingCharacters(in: .whitespacesAndNewlines)+ && lhs.visualStyle == rhs.visualStyle+ && lhs.metadata["localUIElement.sources"] == rhs.metadata["localUIElement.sources"]+ }++ private func stableRenderMetadata(+ incoming: [String: String],+ previous: [String: String]+ ) -> [String: String] {+ guard let sources = previous["localUIElement.sources"] else {+ return incoming+ }++ var metadata = incoming+ metadata["localUIElement.sources"] = sources+ return metadata+ }++ private func copy(+ _ element: DebugUIElement,+ bbox: DebugUIBoundingBox+ ) -> DebugUIElement {+ DebugUIElement(+ id: element.id,+ type: element.type,+ label: element.label,+ description: element.description,+ bbox: bbox,+ confidence: element.confidence,+ visualStyle: element.visualStyle,+ metadata: element.metadata+ )}private func bestSemanticMatch(for incoming: DebugUIElement,+ in candidates: [DebugUIElement],usedPreviousIDs: Set<String>) -> DebugUIElement? {- previousElements+ candidates.filter { previous in!usedPreviousIDs.contains(previous.id)&& previous.type == incoming.type@@ -269,7 +462,64 @@ public struct DebugUIElementTracker: Equatable, Sendable {}}+private struct PendingTrackedElement: Equatable, Sendable {+ var element: DebugUIElement+ var count: Int+}++public extension DebugUIInspectionFrame {+ func isOverlayRenderEquivalent(to other: DebugUIInspectionFrame) -> Bool {+ guard elements.count == other.elements.count else { return false }++ return zip(elements, other.elements).allSatisfy { lhs, rhs in+ lhs.id == rhs.id+ && lhs.type == rhs.type+ && lhs.label == rhs.label+ && lhs.bbox == rhs.bbox+ && lhs.visualStyle == rhs.visualStyle+ && lhs.metadata["localUIElement.sources"] == rhs.metadata["localUIElement.sources"]+ }+ }+}+public enum DebugUIOverlayGeometry {+ public static func stableLabelFrame(+ for text: String,+ boxFrame: CGRect,+ containerSize: CGSize+ ) -> CGRect {+ let height = 18.0+ let availableWidth = max(64.0, Double(containerSize.width) - max(0, boxFrame.minX))+ let estimatedWidth = Double(text.count) * 6.5 + 14+ let bucketedWidth: Double+ if estimatedWidth <= 96 {+ bucketedWidth = 96+ } else if estimatedWidth <= 160 {+ bucketedWidth = 160+ } else if estimatedWidth <= 240 {+ bucketedWidth = 240+ } else {+ bucketedWidth = 320+ }+ let width = min(bucketedWidth, availableWidth)+ let labelY: Double+ if boxFrame.minY >= height + 2 {+ labelY = boxFrame.minY - height - 2+ } else {+ labelY = min(+ max(0, Double(boxFrame.minY) + 2),+ max(0, Double(containerSize.height) - height)+ )+ }++ return CGRect(+ x: max(0, min(Double(boxFrame.minX), Double(containerSize.width) - width)),+ y: labelY,+ width: width,+ height: height+ ).integral+ }+public static func appKitFrame(for bbox: DebugUIBoundingBox,screenshotPixelSize: HotLoopSize,diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionContracts.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionContracts.swiftindex 4793d70e..d7142a4e 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionContracts.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionContracts.swift@@ -133,7 +133,7 @@ public struct LocalUIElementDetectionMetrics: Codable, Equatable, Sendable {public var elementCount: Intpublic var suppressedCount: Intpublic var duplicateCount: Int- public var cvOnlyElementCount: Int+ public var nonAccessibilityElementCount: Intpublic var minConfidence: Doublepublic var latencyMS: [String: Double]@@ -143,7 +143,7 @@ public struct LocalUIElementDetectionMetrics: Codable, Equatable, Sendable {elementCount: Int = 0,suppressedCount: Int = 0,duplicateCount: Int = 0,- cvOnlyElementCount: Int = 0,+ nonAccessibilityElementCount: Int = 0,minConfidence: Double = 0,latencyMS: [String: Double] = [:]) {@@ -152,7 +152,7 @@ public struct LocalUIElementDetectionMetrics: Codable, Equatable, Sendable {self.elementCount = elementCountself.suppressedCount = suppressedCountself.duplicateCount = duplicateCount- self.cvOnlyElementCount = cvOnlyElementCount+ self.nonAccessibilityElementCount = nonAccessibilityElementCountself.minConfidence = min(max(minConfidence, 0), 1)self.latencyMS = latencyMS}@@ -186,6 +186,7 @@ public struct LocalUIElementDetectionTrace: Codable, Equatable, Sendable {public struct LocalUIElementDetectionRequest: Equatable, Sendable {public var traceID: Stringpublic var screenshotPNGData: Data?+ public var screenshotImagePath: String?public var pixelSize: HotLoopSizepublic var accessibilityCandidates: [LocalUIElementCandidate]public var hoverProbeCandidates: [LocalUIElementCandidate]@@ -195,6 +196,7 @@ public struct LocalUIElementDetectionRequest: Equatable, Sendable {public init(traceID: String,screenshotPNGData: Data? = nil,+ screenshotImagePath: String? = nil,pixelSize: HotLoopSize,accessibilityCandidates: [LocalUIElementCandidate] = [],hoverProbeCandidates: [LocalUIElementCandidate] = [],@@ -203,6 +205,7 @@ public struct LocalUIElementDetectionRequest: Equatable, Sendable {) {self.traceID = traceIDself.screenshotPNGData = screenshotPNGData+ self.screenshotImagePath = screenshotImagePathself.pixelSize = pixelSizeself.accessibilityCandidates = accessibilityCandidatesself.hoverProbeCandidates = hoverProbeCandidatesdiff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionService.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionService.swiftindex c959a287..a92185c4 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionService.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionService.swift@@ -14,16 +14,12 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {let startedAt = ProcessInfo.processInfo.systemUptimelet nativeResult = nativeVisualDetector.candidates(fromPNGData: request.screenshotPNGData,- pixelSize: request.pixelSize- )- let rowCandidates = rowLayoutCandidates(- from: nativeResult.candidates,+ imagePath: request.screenshotImagePath,pixelSize: request.pixelSize)let candidates = request.accessibilityCandidates+ request.hoverProbeCandidates+ nativeResult.candidates- + rowCandidateslet mergeStartedAt = ProcessInfo.processInfo.systemUptimelet merged = merge(@@ -62,10 +58,90 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {from trace: LocalUIElementDetectionTrace) -> DebugUIInspectionFrame {DebugUIInspectionFrame(- elements: trace.elements.map(Self.debugElement)+ elements: trace.elements+ .filter(Self.shouldRenderInDebugOverlay)+ .map(Self.debugElement))}+ private static func shouldRenderInDebugOverlay(_ element: LocalUIElement) -> Bool {+ if isDebugOverlayFeedbackLabel(element.label) {+ return false+ }+ if element.type == .draggable {+ return false+ }++ if let role = debugOverlayRole(for: element) {+ if isStaticDebugOverlayLabel(element.label, role: role) {+ return false+ }+ return true+ }+ if element.sources.contains(.accessibility) {+ return isInspectableAccessibilityElement(element)+ }+ if element.sources.contains(.hoverProbe) {+ return true+ }+ return false+ }++ private static func debugOverlayRole(for element: LocalUIElement) -> String? {+ element.metadata.first { key, _ in+ key == "debug.overlayRole" || key.hasSuffix(".debug.overlayRole")+ }?.value+ }++ private static func isDebugOverlayFeedbackLabel(_ value: String) -> Bool {+ let normalized = value.uppercased()+ let tokens = normalized+ .split { !$0.isLetter && !$0.isNumber }+ .map(String.init)+ if tokens.first == "LAYOUT"+ || tokens.first == "AX" {+ return true+ }+ return normalized.contains("LAYOUT+")+ || normalized.contains("+LAYOUT")+ || normalized.contains("AX]")+ }++ private static func isStaticDebugOverlayLabel(_ value: String, role: String) -> Bool {+ let normalized = cleanDebugOverlayLabel(value)+ .lowercased()+ .trimmingCharacters(in: .whitespacesAndNewlines)+ guard !normalized.isEmpty else { return false }++ if role == "sidebarRow" {+ return ["pinned", "projects", "chats"].contains(normalized)+ }+ if role == "panelRow" {+ return ["environment", "sources", "no sources yet"].contains(normalized)+ }+ return false+ }++ private static func isInspectableAccessibilityElement(_ element: LocalUIElement) -> Bool {+ let width = element.bounds.size.width+ let height = element.bounds.size.height++ switch element.type {+ case .draggable, .other:+ return false+ case .checkbox, .toggle, .toolbarIcon, .windowControl:+ return width <= 160 && height <= 96+ case .menuItem, .tab, .dropdown, .slider:+ return width <= 260 && height <= 80+ case .button, .link:+ return width <= 420 && height <= 100+ case .sidebarItem, .listItem:+ return width <= 460 && height <= 120+ case .input:+ return width <= 920 && height <= 180+ }+ }+public func localUIUnderstandingResult(from trace: LocalUIElementDetectionTrace) -> LocalUIUnderstandingResult {@@ -113,7 +189,7 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {DebugUIElement(id: element.id,type: element.type,- label: element.label,+ label: debugOverlayLabel(for: element),description: [element.type.rawValue,element.sources.map(\.rawValue).joined(separator: "+"),@@ -126,6 +202,7 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {height: element.bounds.size.height),confidence: element.confidence,+ visualStyle: debugOverlayStyle(for: element),metadata: element.metadata.merging(["localUIElement.sources": element.sources.map(\.rawValue).joined(separator: ","),"localUIElement.reasonCodes": element.reasonCodes.joined(separator: ","),@@ -134,6 +211,139 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {)}+ private static func debugOverlayLabel(for element: LocalUIElement) -> String {+ let role = debugOverlayRole(for: element)+ let label = cleanDebugOverlayLabel(element.label)+ let lowercasedLabel = label.lowercased()++ switch role {+ case "panel":+ return "environment panel"+ case "bottomInput", "messageInput":+ return "message input"+ case "bottomInputAccessory":+ if lowercasedLabel.contains("auto-review") {+ return "auto-review selector"+ }+ if lowercasedLabel.contains("5.5") || lowercasedLabel.contains("high") {+ return "model selector"+ }+ if lowercasedLabel.contains("submit") {+ return "send button"+ }+ if lowercasedLabel.contains("add") {+ return "add button"+ }+ if lowercasedLabel.contains("voice") {+ return "voice input button"+ }+ return "composer control"+ case "actionButton":+ if lowercasedLabel.contains("review") {+ return "review changes button"+ }+ return label.isEmpty ? "action button" : label+ case "chatTitle":+ return "chat title"+ case "fileLink":+ return "file link"+ case "userBubble":+ return "user bubble"+ case "commandRow":+ return "run command row"+ case "panelRow", "sidebarRow", "menuBarItem":+ break+ default:+ break+ }++ if !label.isEmpty,+ !isGenericLabel(label, type: element.type),+ label != "panel row",+ label != "sidebar item",+ label != "menu item" {+ return label+ }++ switch element.type {+ case .input:+ return "text input"+ case .button:+ return "button"+ case .toolbarIcon:+ return "toolbar icon"+ case .windowControl:+ return "window control"+ case .menuItem:+ return "menu item"+ case .sidebarItem:+ return "sidebar item"+ case .listItem:+ return "clickable row"+ case .dropdown:+ return "selector"+ case .checkbox:+ return "checkbox"+ case .toggle:+ return "toggle"+ case .link:+ return "link"+ case .tab:+ return "tab"+ case .slider:+ return "slider"+ case .draggable, .other:+ return ""+ }+ }++ private static func cleanDebugOverlayLabel(_ value: String) -> String {+ var label = value.trimmingCharacters(in: .whitespacesAndNewlines)+ label = stripLeadingNoise(from: label)+ let noisyPrefixes = ["O ", "Q ", "00 ", "0 "]+ var changed = true+ while changed {+ changed = false+ for prefix in noisyPrefixes where label.hasPrefix(prefix) {+ label.removeFirst(prefix.count)+ label = label.trimmingCharacters(in: .whitespacesAndNewlines)+ label = stripLeadingNoise(from: label)+ changed = true+ }+ }+ return label+ }++ private static func stripLeadingNoise(from value: String) -> String {+ var label = value.trimmingCharacters(in: .whitespacesAndNewlines)+ while let first = label.first,+ !first.isLetter,+ !first.isNumber {+ label.removeFirst()+ label = label.trimmingCharacters(in: .whitespacesAndNewlines)+ }+ return label+ }++ private static func debugOverlayStyle(for element: LocalUIElement) -> DebugUIOverlayStyle {+ switch debugOverlayRole(for: element) {+ case "menuBarItem":+ return DebugUIOverlayStyle(overlayColor: "#06B6D4", borderColor: "#22D3EE")+ case "sidebarRow":+ return DebugUIOverlayStyle(overlayColor: "#0EA5E9", borderColor: "#38BDF8")+ case "panel", "panelRow":+ return DebugUIOverlayStyle(overlayColor: "#D946EF", borderColor: "#F0ABFC")+ case "bottomInput", "messageInput", "bottomInputAccessory":+ return DebugUIOverlayStyle(overlayColor: "#22C55E", borderColor: "#86EFAC")+ case "actionButton", "chatTitle":+ return DebugUIOverlayStyle(overlayColor: "#EAB308", borderColor: "#FDE047")+ case "fileLink", "userBubble", "commandRow":+ return DebugUIOverlayStyle(overlayColor: "#A855F7", borderColor: "#D8B4FE")+ default:+ return DebugUIOverlayStyle.style(for: element.type)+ }+ }+private func merge(candidates: [LocalUIElementCandidate],minConfidence: Double@@ -225,23 +435,9 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {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}@@ -254,15 +450,15 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {!Self.isGenericLabel(axLabel, type: type) {return axLabel}- if let insideText = bestLabel(group: group.filter { $0.source == .ocr }) {- return insideText+ if let layoutLabel = bestLabel(group: group.filter({ candidate in+ candidate.source == .layout && Self.debugOverlayRole(for: candidate) != nil+ })),+ !Self.isGenericLabel(layoutLabel, type: type) {+ return layoutLabel}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}@@ -279,8 +475,10 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {if let accessibility = group.first(where: { $0.source == .accessibility }) {return accessibility.bounds}- if let shape = group.first(where: { $0.source == .shape }) {- return shape.bounds+ if let layout = group.first(where: { candidate in+ candidate.source == .layout && Self.debugOverlayRole(for: candidate) != nil+ }) {+ return layout.bounds}return group.sorted(by: Self.candidateSort).first?.bounds?? HotLoopRect(x: 0, y: 0, width: 1, height: 1, space: .screen)@@ -312,9 +510,6 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {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")}@@ -347,7 +542,7 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {grouping: candidates,by: { $0.source.rawValue }).mapValues(\.count)- let cvOnlyCount = elements.filter { element in+ let nonAccessibilityCount = elements.filter { element in!element.sources.contains(.accessibility)}.countreturn LocalUIElementDetectionMetrics(@@ -356,7 +551,7 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {elementCount: elements.count,suppressedCount: suppressed.count,duplicateCount: suppressed.filter { $0.reason == "mergedDuplicate" }.count,- cvOnlyElementCount: cvOnlyCount,+ nonAccessibilityElementCount: nonAccessibilityCount,minConfidence: minConfidence,latencyMS: latencyMS)@@ -366,6 +561,27 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {_ lhs: LocalUIElementCandidate,_ rhs: LocalUIElementCandidate) -> Bool {+ if isBottomInputSurface(lhs), isBottomInputAccessory(rhs) {+ return false+ }+ if isBottomInputSurface(rhs), isBottomInputAccessory(lhs) {+ return false+ }+ if isBottomInputAccessory(lhs), isBottomInputAccessory(rhs),+ lhs.source == .layout, rhs.source == .layout {+ return false+ }+ if isBottomInputAccessory(lhs),+ let role = debugOverlayRole(for: rhs),+ role != "bottomInputAccessory" {+ return false+ }+ if isBottomInputAccessory(rhs),+ let role = debugOverlayRole(for: lhs),+ role != "bottomInputAccessory" {+ return false+ }+if isStructuralContainer(lhs) != isStructuralContainer(rhs) {return false}@@ -375,12 +591,24 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {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 debugOverlayRole(for candidate: LocalUIElementCandidate) -> String? {+ candidate.metadata.first { key, _ in+ key == "debug.overlayRole" || key.hasSuffix(".debug.overlayRole")+ }?.value+ }++ private static func isBottomInputSurface(_ candidate: LocalUIElementCandidate) -> Bool {+ let role = debugOverlayRole(for: candidate)+ return role == "bottomInput" || role == "messageInput"+ }++ private static func isBottomInputAccessory(_ candidate: LocalUIElementCandidate) -> Bool {+ debugOverlayRole(for: candidate) == "bottomInputAccessory"+ }+private static func isStructuralContainer(_ candidate: LocalUIElementCandidate) -> Bool {candidate.typeHint == .draggable|| candidate.role == "AXWindow"@@ -411,70 +639,6 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {}}- 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@@ -496,30 +660,10 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {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:@@ -545,7 +689,7 @@ public struct LocalUIElementDetectionService: LocalUIElementDetecting {"localUIElement.elementCount": String(metrics.elementCount),"localUIElement.suppressedCount": String(metrics.suppressedCount),"localUIElement.duplicateCount": String(metrics.duplicateCount),- "localUIElement.cvOnlyElementCount": String(metrics.cvOnlyElementCount),+ "localUIElement.nonAccessibilityElementCount": String(metrics.nonAccessibilityElementCount),"localUIElement.minConfidence": String(metrics.minConfidence)]for (source, count) in metrics.sourceCounts {diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swiftindex 50caf169..209d1b8e 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift@@ -1,528 +1,26 @@-import CoreGraphicsimport DonkeyContractsimport Foundation-import ImageIO-@preconcurrency import Visionpublic struct LocalUIElementNativeVisualDetector: Sendable {- public var maxAnalysisDimension: Int-- public init(maxAnalysisDimension: Int = 900) {- self.maxAnalysisDimension = max(120, maxAnalysisDimension)- }+ public init(maxAnalysisDimension: Int = 900) {}public func candidates(fromPNGData data: Data?,+ imagePath: String? = nil,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+ _ = data+ _ = imagePath+ _ = pixelSize- 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_000return (- 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"+ "nativeVisual.status": "stubbed",+ "nativeVisual.reason": "cvPipelineRemovedPendingReplacement",+ "nativeVisual.rawPixelsRead": "false"])}-- 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/DonkeyRuntime/OffTheShelfVisionPerception.swift b/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfVisionPerception.swiftindex 87afd04b..16159ee8 100644--- a/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfVisionPerception.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfVisionPerception.swift@@ -49,38 +49,35 @@ public struct OffTheShelfVisionModelCandidate: Codable, Equatable, Sendable {}public enum OffTheShelfVisionModelCatalog {- public static let yolo26NanoScreenshotSegmentation = OffTheShelfVisionModelCandidate(- id: "ultralytics-yolo26n-seg-screenshot",- family: "YOLO26",- modelName: "yolo26n-seg.pt",+ public static let stubbedScreenshotSegmentation = OffTheShelfVisionModelCandidate(+ id: "stubbed-screenshot-segmentation",+ family: "stub",+ modelName: "stubbed",signalKind: .segmentation,- preferredInputSource: .crop,- componentID: "screenshot-segmentation-yolo26",- docsURL: URL(string: "https://docs.ultralytics.com/models/yolo26/")!,- lastVerifiedAt: "2026-05-17",+ preferredInputSource: .recorded,+ componentID: "screenshot-segmentation-stub",+ docsURL: URL(string: "https://github.com/dle87/donkey")!,+ lastVerifiedAt: "2026-05-26",metadata: [- "provider": "ultralytics",- "task": "instanceSegmentation",- "latestYOLOFamilyVerified": "YOLO26",- "screenshotUse": "boundedCropFirst",+ "provider": "none",+ "task": "stub",+ "reason": "cvPipelineRemovedPendingReplacement","liveDefault": "false",- "requiresLocalBenchmark": "true",- "docsTaskURL": "https://docs.ultralytics.com/tasks/segment/"+ "rawPixelsRead": "false"])public static var screenshotSegmentationCandidates: [OffTheShelfVisionModelCandidate] {- [yolo26NanoScreenshotSegmentation]+ []}public static func defaultCandidate(signalKind: OffTheShelfVisionSignalKind,inputSource: OffTheShelfVisionInputSource) -> OffTheShelfVisionModelCandidate? {- screenshotSegmentationCandidates.first {- $0.signalKind == signalKind- && ($0.preferredInputSource == inputSource || inputSource == .screenshot)- }+ _ = signalKind+ _ = inputSource+ return nil}}@@ -291,46 +288,8 @@ public struct OffTheShelfVisionPerceptionAdapter: DryRunPerceptionAdapting {}public func perceive(frame: HotLoopFrame) async -> [HotLoopPerceptionSignal] {- let signals = RecordedOffTheShelfVisionMetadataCodec.decode(from: frame.metadata)- return signals.map { signal in- let observedAt = frame.capturedAt.addingMilliseconds(- signal.preprocessMS + signal.modelInferenceMS + signal.adapterOverheadMS- )- return HotLoopPerceptionSignal(- id: signal.id,- traceID: frame.traceID,- frameID: frame.id,- kind: signal.kind.rawValue,- capturedAt: frame.capturedAt,- observedAt: observedAt,- confidence: signal.confidence,- observations: signal.observations.map { observation in- HotLoopPerceptionObservation(- id: observation.id,- label: observation.label,- bounds: observation.bounds,- confidence: observation.confidence,- metadata: observation.metadata.merging([- "vision.componentID": signal.componentID,- "vision.modelID": signal.modelID ?? "",- "vision.cropID": signal.cropID ?? "",- "vision.signalKind": signal.kind.rawValue- ]) { current, _ in current }- )- },- plannerHintID: frame.plannerHintID,- metadata: signal.metadata.merging([- "adapter": adapterName,- "rawPixelsExposed": "false",- "vision.localEvidence": "true",- "vision.componentID": signal.componentID,- "vision.modelID": signal.modelID ?? "",- "vision.cropID": signal.cropID ?? "",- "latency.preprocessMS": String(signal.preprocessMS),- "latency.modelInferenceMS": String(signal.modelInferenceMS)- ]) { current, _ in current }- )- }+ _ = frame+ return []}}@@ -352,48 +311,13 @@ public struct OffTheShelfVisionWorldStateProjector: DryRunWorldStateProjecting {signals: signals,observedAt: observedAt,staleThresholdMS: staleSignalThresholdMS,- actionAffordances: actionAffordances(from: signals),+ actionAffordances: [],metadata: [- "projector": "off-the-shelf-vision-world-state-projector",- "vision.localEvidence": String(!signals.isEmpty),- "rawPixelsExposed": "false"+ "projector": "off-the-shelf-vision-world-state-projector-stub",+ "vision.localEvidence": "false",+ "rawPixelsExposed": "false",+ "reason": "cvPipelineRemovedPendingReplacement"])}-- private func actionAffordances(- from signals: [HotLoopPerceptionSignal]- ) -> [HotLoopActionAffordance] {- signals.flatMap { signal in- signal.observations.compactMap { observation in- guard let bounds = observation.bounds else { return nil }- return HotLoopActionAffordance(- id: "affordance-\(observation.id)",- kind: .tapTarget,- targetBounds: bounds,- confidence: min(signal.confidence, observation.confidence),- sourceSignalID: signal.id,- metadata: [- "vision.label": observation.label,- "vision.signalKind": signal.kind,- "vision.componentID": signal.metadata["vision.componentID"] ?? "",- "vision.modelID": signal.metadata["vision.modelID"] ?? "",- "vision.cropID": signal.metadata["vision.cropID"] ?? "",- "vision.localEvidence": "true"- ].merging(observation.metadata) { current, _ in current }- )- }- }- }-}--private extension RunTraceTimestamp {- func addingMilliseconds(_ milliseconds: Double) -> RunTraceTimestamp {- RunTraceTimestamp(- wallClock: wallClock.addingTimeInterval(milliseconds / 1_000),- monotonicUptimeNanoseconds: UInt64(- max(0, Double(monotonicUptimeNanoseconds) + milliseconds * 1_000_000)- )- )- }}diff --git a/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift b/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swiftindex 70f10597..d66820bc 100644--- a/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift@@ -227,7 +227,6 @@ public enum ReflexLatencyReportBuilder {"accessibilityAction": "latency.accessibilityActionMS","keyboardAction": "latency.keyboardActionMS","verification": "latency.verificationMS",- "yoloSegmentation": "latency.yoloSegmentationMS","uiUnderstanding": "latency.uiUnderstandingMS","parakeetTranscription": "latency.parakeetTranscriptionMS"]diff --git a/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/ScreenshotSegmentationStubRunner.swiftsimilarity index 66%rename from apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swiftrename to apps/Donkey/Sources/DonkeyRuntime/ScreenshotSegmentationStubRunner.swiftindex e3865d7d..cb7a03bb 100644--- a/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/ScreenshotSegmentationStubRunner.swift@@ -123,113 +123,42 @@ public struct UnavailableScreenshotSegmentationBackend: ScreenshotSegmentationBa}public struct ProcessBackedScreenshotSegmentationBackend: ScreenshotSegmentationBackend {- public var sidecarRunner: any LocalJSONSidecarRunning- public var encoder: JSONEncoder- public var decoder: JSONDecoder-public init(sidecarRunner: any LocalJSONSidecarRunning = ProcessBackedLocalJSONSidecarRunner(),encoder: JSONEncoder = JSONEncoder(),decoder: JSONDecoder = JSONDecoder()) {- self.sidecarRunner = sidecarRunner- self.encoder = encoder- self.decoder = decoder+ _ = sidecarRunner+ _ = encoder+ _ = decoder}public func segment(request: ScreenshotSegmentationRequest,model: OffTheShelfVisionModelCandidate) async throws -> ScreenshotSegmentationBackendResult {- let input = YOLOSidecarRequest(- traceID: request.traceID,- frameID: request.frameID,- targetID: request.targetID,- cropID: request.cropID,- cropImagePath: request.cropImageFileURL?.path,- artifactURL: request.artifactURL?.absoluteString,- cropBounds: request.cropBounds,- pixelSize: request.pixelSize,- modelID: model.id,- modelName: model.modelName,- metadata: request.metadata- )- let result = await sidecarRunner.run(- LocalJSONSidecarRequest(- environmentVariableName: "DONKEY_YOLO_SEGMENTER",- inputData: try encoder.encode(input),- timeoutMS: Int(model.metadata["timeoutMS"] ?? "4000") ?? 4_000,- metadata: [- "sidecar.role": "screenshotSegmentation",- "modelID": model.id,- "modelName": model.modelName- ]- )+ _ = request+ _ = model+ return ScreenshotSegmentationBackendResult(+ masks: [],+ preprocessMS: 0,+ modelInferenceMS: 0,+ metadata: [+ "runner": "screenshot-segmentation-stub",+ "reason": "cvPipelineRemovedPendingReplacement",+ "rawPixelsRead": "false"+ ])-- guard result.status == .completed else {- throw ScreenshotSegmentationRunnerError.backendUnavailable(- result.metadata["sidecar.reason"] ?? result.status.rawValue- )- }-- do {- let response = try decoder.decode(YOLOSidecarResponse.self, from: result.outputData)- return ScreenshotSegmentationBackendResult(- masks: response.masks,- preprocessMS: response.preprocessMS,- modelInferenceMS: response.modelInferenceMS,- metadata: result.metadata.merging(response.metadata) { current, _ in current }- .merging([- "latency.yoloSegmentationMS": result.latencyMS.map { String(format: "%.3f", $0) } ?? ""- ]) { current, _ in current }- )- } catch {- throw ScreenshotSegmentationRunnerError.invalidOutput(String(describing: error))- }- }-}--private struct YOLOSidecarRequest: Codable, Equatable, Sendable {- var traceID: String- var frameID: String- var targetID: String- var cropID: String- var cropImagePath: String?- var artifactURL: String?- var cropBounds: HotLoopRect- var pixelSize: HotLoopSize- var modelID: String- var modelName: String- var metadata: [String: String]-}--private struct YOLOSidecarResponse: Codable, Equatable, Sendable {- var masks: [ScreenshotSegmentationMask]- var preprocessMS: Double- var modelInferenceMS: Double- var metadata: [String: String]-- init(- masks: [ScreenshotSegmentationMask] = [],- preprocessMS: Double = 0,- modelInferenceMS: Double = 0,- metadata: [String: String] = [:]- ) {- self.masks = masks- self.preprocessMS = preprocessMS- self.modelInferenceMS = modelInferenceMS- self.metadata = metadata}}-public struct YOLOScreenshotSegmentationRunner: Sendable {+public struct ScreenshotSegmentationStubRunner: Sendable {public var model: OffTheShelfVisionModelCandidatepublic var backend: any ScreenshotSegmentationBackendpublic var now: @Sendable () -> RunTraceTimestamppublic init(- model: OffTheShelfVisionModelCandidate = OffTheShelfVisionModelCatalog.yolo26NanoScreenshotSegmentation,+ model: OffTheShelfVisionModelCandidate = OffTheShelfVisionModelCatalog.stubbedScreenshotSegmentation,backend: any ScreenshotSegmentationBackend = UnavailableScreenshotSegmentationBackend(),now: @escaping @Sendable () -> RunTraceTimestamp = Self.defaultNow) {@@ -240,7 +169,17 @@ public struct YOLOScreenshotSegmentationRunner: Sendable {public func run(_ request: ScreenshotSegmentationRequest) async throws -> ScreenshotSegmentationResult {let startedAt = now()- let backendResult = try await backend.segment(request: request, model: model)+ _ = backend+ let backendResult = ScreenshotSegmentationBackendResult(+ masks: [],+ preprocessMS: 0,+ modelInferenceMS: 0,+ metadata: [+ "runner": "screenshot-segmentation-stub",+ "reason": "cvPipelineRemovedPendingReplacement",+ "rawPixelsRead": "false"+ ]+ )let completedAt = now()let totalMS = startedAt.milliseconds(until: completedAt) ?? 0let adapterOverheadMS = max(0, totalMS - backendResult.preprocessMS - backendResult.modelInferenceMS)@@ -266,12 +205,13 @@ public struct YOLOScreenshotSegmentationRunner: Sendable {modelInferenceMS: backendResult.modelInferenceMS,adapterOverheadMS: adapterOverheadMS,metadata: [- "runner": "yolo-screenshot-segmentation",+ "runner": "screenshot-segmentation-stub","modelFamily": model.family,"modelName": model.modelName,"inputSource": model.preferredInputSource.rawValue,"liveDefault": model.metadata["liveDefault"] ?? "false",- "requiresLocalBenchmark": model.metadata["requiresLocalBenchmark"] ?? "true",+ "reason": "cvPipelineRemovedPendingReplacement",+ "rawPixelsRead": "false","latency.totalMS": String(totalMS)].merging(backendResult.metadata) { current, _ in current })diff --git a/apps/Donkey/Sources/DonkeyUIUnderstandingSidecar/main.swift b/apps/Donkey/Sources/DonkeyUIUnderstandingSidecar/main.swiftindex 4b9c31ea..01ae4f98 100644--- a/apps/Donkey/Sources/DonkeyUIUnderstandingSidecar/main.swift+++ b/apps/Donkey/Sources/DonkeyUIUnderstandingSidecar/main.swift@@ -4,7 +4,6 @@ import DonkeyRuntimeimport Foundationimport ImageIOimport UniformTypeIdentifiers-@preconcurrency import Visionprivate struct SidecarRequest: Codable {var operation: String?@@ -66,7 +65,7 @@ private struct DebugInspectionArtifact: Codable {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"+private let modelID = ProcessInfo.processInfo.environment["DONKEY_MODEL_ID"] ?? "local-ui-understanding-stubbed-visual"@mainstruct DonkeyUIUnderstandingSidecar {@@ -92,7 +91,7 @@ struct DonkeyUIUnderstandingSidecar {runtimeID: runtimeID,modelID: modelID,metadata: [- "runtime.backend": "apple-vision",+ "runtime.backend": "local-ui-understanding-stubbed-visual","reason": "uiUnderstandingSidecarFailed","detail": String(describing: error)]@@ -111,7 +110,7 @@ struct DonkeyUIUnderstandingSidecar {modelID: modelID,protocolVersion: "v1",metadata: [- "runtime.backend": "apple-vision",+ "runtime.backend": "local-ui-understanding-stubbed-visual","modelWeights.status": "notRequired","modelWeights.provider": "system"]@@ -125,7 +124,7 @@ struct DonkeyUIUnderstandingSidecar {modelID: modelID,cacheDirectory: cacheDirectory,metadata: [- "runtime.backend": "apple-vision",+ "runtime.backend": "local-ui-understanding-stubbed-visual","modelWeights.status": "notRequired","modelWeights.provider": "system"]@@ -208,7 +207,7 @@ struct DonkeyUIUnderstandingSidecar {return LocalUIUnderstandingResult(confidence: 0,metadata: [- "runtime.backend": "apple-vision",+ "runtime.backend": "local-ui-understanding-stubbed-visual","reason": "missingImagePath"])@@ -222,31 +221,72 @@ struct DonkeyUIUnderstandingSidecar {LocalUIElementDetectionRequest(traceID: request.traceID ?? "ui-understanding-\(UUID().uuidString)",screenshotPNGData: imageData,+ screenshotImagePath: imageURL.path,pixelSize: pixelSize,minConfidence: Double(request.metadata?["minConfidence"] ?? "") ?? 0.25,metadata: [- "runtime.backend": "apple-vision-native-ui-detection",+ "runtime.backend": "local-ui-element-detection-stubbed-visual","targetID": request.targetID ?? ""].merging(request.metadata ?? [:]) { current, _ in current }))let elapsedMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000- let result = LocalUIElementDetectionService().localUIUnderstandingResult(from: trace)+ let detectionService = LocalUIElementDetectionService()+ let result = detectionService.localUIUnderstandingResult(from: trace)+ let debugFrame = detectionService.debugInspectionFrame(from: trace)+ let annotatedURL = try writeAnnotatedScreenshot(+ request: request,+ imageURL: imageURL,+ screenshotPNGData: imageData,+ frame: debugFrame+ )return LocalUIUnderstandingResult(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),+ "runtime.backend": "local-ui-element-detection-stubbed-visual",+ "nativeVisual.status": trace.metadata["nativeVisual.status"] ?? "unknown","latency.localUIElementSidecarMS": String(format: "%.3f", elapsedMS),+ "debugInspection.element.count": String(debugFrame.elements.count),+ "debugInspection.annotatedPath": annotatedURL?.path ?? "","directInputActionsAllowed": "false"]) { current, _ in current })}+ private static func writeAnnotatedScreenshot(+ request: SidecarRequest,+ imageURL: URL,+ screenshotPNGData: Data,+ frame: DebugUIInspectionFrame+ ) throws -> URL? {+ guard let annotated = annotatedPNGData(+ screenshotPNGData: screenshotPNGData,+ frame: frame+ ) else {+ return nil+ }++ 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 filename = "\(slug(request.traceID ?? imageURL.deletingPathExtension().lastPathComponent)).annotated.png"+ let annotatedURL = outputDirectory.appendingPathComponent(filename)+ try annotated.write(to: annotatedURL, options: .atomic)+ return annotatedURL+ }+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],@@ -258,36 +298,6 @@ struct DonkeyUIUnderstandingSidecar {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- request.usesLanguageCorrection = true- request.recognitionLanguages = ["en-US"]-- let handler = VNImageRequestHandler(url: imageURL)- try handler.perform([request])-- return (request.results ?? []).compactMap { 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- return (- text: text,- confidence: Double(candidate.confidence),- frame: HotLoopRect(- x: box.minX,- y: 1 - box.maxY,- width: box.width,- height: box.height,- space: .normalizedTarget- )- )- }- }-private static func annotatedPNGData(screenshotPNGData: Data,frame: DebugUIInspectionFrame@@ -381,29 +391,10 @@ struct DonkeyUIUnderstandingSidecar {}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 : labellet 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()- }+ return cappedTitle}private static func nsColor(hex: String) -> NSColor? {diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swiftindex 2b6700ea..55a6e2c7 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift@@ -196,6 +196,123 @@ struct DebugUIInspectionTests {#expect(updated.elements.first?.bbox == DebugUIBoundingBox(x: 10, y: 20, width: 80, height: 30))}+ @Test+ func trackerFreezesLargerBoundingBoxJitter() {+ var tracker = DebugUIElementTracker()+ _ = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 10, y: 20)+ ]))+ _ = 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: 15.8, y: 24.9)+ ]))++ #expect(updated.elements.first?.bbox == DebugUIBoundingBox(x: 10, y: 20, width: 80, height: 30))+ }++ @Test+ func trackerRequiresRepeatedSamplesBeforeRenderingModerateMovement() {+ var tracker = DebugUIElementTracker()+ _ = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 10, y: 20)+ ]))+ _ = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 10, y: 20)+ ]))++ let firstMoved = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 28, y: 20)+ ]))+ let secondMoved = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 28.5, y: 20.2)+ ]))++ #expect(firstMoved.elements.first?.bbox == DebugUIBoundingBox(x: 10, y: 20, width: 80, height: 30))+ #expect(secondMoved.elements.first?.bbox == DebugUIBoundingBox(x: 28.5, y: 20.2, width: 80, height: 30))+ }++ @Test+ func trackerAcceptsLargeMovementImmediately() {+ var tracker = DebugUIElementTracker()+ _ = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 10, y: 20)+ ]))+ _ = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 10, y: 20)+ ]))++ let moved = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 95, y: 20)+ ]))++ #expect(moved.elements.first?.bbox == DebugUIBoundingBox(x: 95, y: 20, width: 80, height: 30))+ }++ @Test+ func trackerRequiresRepeatedSamplesBeforeRenderingLabelAndSourceBadgeChanges() {+ var tracker = DebugUIElementTracker()+ let accessibilityElement = element(+ id: "button-1",+ label: "Save",+ x: 10,+ y: 20,+ metadata: ["localUIElement.sources": "accessibility"]+ )+ _ = tracker.update(with: DebugUIInspectionFrame(elements: [accessibilityElement]))+ let rendered = tracker.update(with: DebugUIInspectionFrame(elements: [accessibilityElement]))++ let changed = element(+ id: "button-1",+ label: "Save file",+ x: 10,+ y: 20,+ metadata: ["localUIElement.sources": "accessibility,ocr"]+ )+ let firstChanged = tracker.update(with: DebugUIInspectionFrame(elements: [changed]))+ let secondChanged = tracker.update(with: DebugUIInspectionFrame(elements: [changed]))++ #expect(firstChanged.isOverlayRenderEquivalent(to: rendered))+ #expect(secondChanged.elements.first?.label == "Save file")+ #expect(secondChanged.elements.first?.metadata["localUIElement.sources"] == "accessibility,ocr")+ }++ @Test+ func trackerRequiresMultipleSamplesBeforeRenderingNewElement() {+ var tracker = DebugUIElementTracker()++ let first = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 10, y: 20)+ ]))+ let second = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 10, y: 20)+ ]))++ #expect(first.elements.isEmpty)+ #expect(second.elements.map(\.id) == ["button-1"])+ }++ @Test+ func trackerRetainsMissingElementForAFewSamplesBeforeRemoving() {+ var tracker = DebugUIElementTracker()+ _ = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 10, y: 20)+ ]))+ _ = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 10, y: 20)+ ]))++ let firstMissing = tracker.update(with: DebugUIInspectionFrame())+ let secondMissing = tracker.update(with: DebugUIInspectionFrame())+ let thirdMissing = tracker.update(with: DebugUIInspectionFrame())++ #expect(firstMissing.elements.map(\.id) == ["button-1"])+ #expect(secondMissing.elements.map(\.id) == ["button-1"])+ #expect(thirdMissing.elements.isEmpty)+ }+@Testfunc geometryConvertsScreenshotPixelsToAppKitPoints() {let frame = DebugUIOverlayGeometry.appKitFrame(@@ -218,6 +335,29 @@ struct DebugUIInspectionTests {#expect(frame == CGRect(x: 100, y: 350, width: 200, height: 100))}+ @Test+ func labelGeometryUsesStableWidthBuckets() {+ let short = DebugUIOverlayGeometry.stableLabelFrame(+ for: "Save",+ boxFrame: CGRect(x: 24, y: 80, width: 80, height: 30),+ containerSize: CGSize(width: 500, height: 400)+ )+ let medium = DebugUIOverlayGeometry.stableLabelFrame(+ for: "Save current document",+ boxFrame: CGRect(x: 24, y: 80, width: 80, height: 30),+ containerSize: CGSize(width: 500, height: 400)+ )+ let topEdge = DebugUIOverlayGeometry.stableLabelFrame(+ for: "Toolbar",+ boxFrame: CGRect(x: 24, y: 4, width: 80, height: 30),+ containerSize: CGSize(width: 500, height: 400)+ )++ #expect(short == CGRect(x: 24, y: 60, width: 96, height: 18))+ #expect(medium == CGRect(x: 24, y: 60, width: 160, height: 18))+ #expect(topEdge == CGRect(x: 24, y: 6, width: 96, height: 18))+ }+@Testfunc accessibilityGeometryClipsScreenLocalBounds() {let bbox = DebugUIAccessibilityGeometry.boundingBox(@@ -965,14 +1105,19 @@ struct DebugUIInspectionTests {id: String,label: String,x: Double,- y: Double+ y: Double,+ width: Double = 80,+ height: Double = 30,+ type: DebugUIElementType = .button,+ metadata: [String: String] = [:]) -> DebugUIElement {DebugUIElement(id: id,- type: .button,+ type: type,label: label,- bbox: DebugUIBoundingBox(x: x, y: y, width: 80, height: 30),- confidence: 0.9+ bbox: DebugUIBoundingBox(x: x, y: y, width: width, height: height),+ confidence: 0.9,+ metadata: metadata)}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swiftindex 622b5812..9577baf9 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift@@ -26,21 +26,21 @@ struct LocalModelRuntimeSetupTests {}let executableURL = try makeExecutable(root: download,- relativePath: "bin/donkey-yolo-segmenter"+ relativePath: "bin/donkey-screenshot-segmentation-stub")let manager = try runtimeManager(baseDirectory: root)let installation = try manager.registerDownloadedRuntime(- runtimeID: .yoloSegmenter,+ runtimeID: .screenshotSegmentationStub,downloadedDirectory: download)- let status = try manager.status(for: .yoloSegmenter)+ let status = try manager.status(for: .screenshotSegmentationStub)let environment = try manager.configuredEnvironment()#expect(installation.executablePath == executableURL.path)#expect(status.state == .installed)#expect(status.installation?.downloadedDirectoryPath == download.path)- #expect(environment["DONKEY_YOLO_SEGMENTER"] == executableURL.path)+ #expect(environment["DONKEY_SCREENSHOT_SEGMENTATION_STUB"] == executableURL.path)}@Test@@ -215,14 +215,14 @@ struct LocalModelRuntimeSetupTests {let executableData = Data("#!/bin/sh\necho ok\n".utf8)let privateKey = Curve25519.Signing.PrivateKey()var manifest = LocalModelRuntimePackageManifest(- runtimeID: .yoloSegmenter,+ runtimeID: .screenshotSegmentationStub,runtimeVersion: "1.0.0",- modelID: "ultralytics/yolo26n-seg",- executableRelativePath: "bin/donkey-yolo-segmenter",+ modelID: "stubbed-screenshot-segmentation",+ executableRelativePath: "bin/donkey-screenshot-segmentation-stub",files: [LocalModelRuntimePackageFile(- relativePath: "bin/donkey-yolo-segmenter",- downloadURL: URL(string: "https://example.test/yolo/bin")!,+ relativePath: "bin/donkey-screenshot-segmentation-stub",+ downloadURL: URL(string: "https://example.test/segmentation-stub/bin")!,sha256: LocalModelRuntimeSetupManager.sha256Hex(executableData),isExecutable: true)@@ -240,7 +240,7 @@ struct LocalModelRuntimeSetupTests {_ = try await manager.downloadAndInstall(manifest: manifest,downloader: FakeRuntimeDownloader(files: [- URL(string: "https://example.test/yolo/bin")!: executableData+ URL(string: "https://example.test/segmentation-stub/bin")!: executableData]))}@@ -262,7 +262,7 @@ struct LocalModelRuntimeSetupTests {_ = try await trustedManager.downloadAndInstall(manifest: tampered,downloader: FakeRuntimeDownloader(files: [- URL(string: "https://example.test/yolo/bin")!: executableData+ URL(string: "https://example.test/segmentation-stub/bin")!: executableData]))}@@ -275,14 +275,14 @@ struct LocalModelRuntimeSetupTests {let data = Data("#!/bin/sh\necho ok\n".utf8)let manager = try runtimeManager(baseDirectory: root)let unsigned = LocalModelRuntimePackageManifest(- runtimeID: .yoloSegmenter,+ runtimeID: .screenshotSegmentationStub,runtimeVersion: "1.0.0",- modelID: "ultralytics/yolo26n-seg",- executableRelativePath: "bin/donkey-yolo-segmenter",+ modelID: "stubbed-screenshot-segmentation",+ executableRelativePath: "bin/donkey-screenshot-segmentation-stub",files: [LocalModelRuntimePackageFile(- relativePath: "bin/donkey-yolo-segmenter",- downloadURL: URL(string: "https://example.test/yolo/bin")!,+ relativePath: "bin/donkey-screenshot-segmentation-stub",+ downloadURL: URL(string: "https://example.test/segmentation-stub/bin")!,sha256: LocalModelRuntimeSetupManager.sha256Hex(data),isExecutable: true)@@ -292,19 +292,19 @@ struct LocalModelRuntimeSetupTests {await #expect(throws: LocalModelRuntimeSetupError.manifestMissingSignature) {_ = try await manager.downloadAndInstall(manifest: unsigned,- downloader: FakeRuntimeDownloader(files: [URL(string: "https://example.test/yolo/bin")!: data])+ downloader: FakeRuntimeDownloader(files: [URL(string: "https://example.test/segmentation-stub/bin")!: data]))}let signedWithBadHash = LocalModelRuntimePackageManifest(- runtimeID: .yoloSegmenter,+ runtimeID: .screenshotSegmentationStub,runtimeVersion: "1.0.0",- modelID: "ultralytics/yolo26n-seg",- executableRelativePath: "bin/donkey-yolo-segmenter",+ modelID: "stubbed-screenshot-segmentation",+ executableRelativePath: "bin/donkey-screenshot-segmentation-stub",files: [LocalModelRuntimePackageFile(- relativePath: "bin/donkey-yolo-segmenter",- downloadURL: URL(string: "https://example.test/yolo/bin")!,+ relativePath: "bin/donkey-screenshot-segmentation-stub",+ downloadURL: URL(string: "https://example.test/segmentation-stub/bin")!,sha256: "bad",isExecutable: true)@@ -313,10 +313,10 @@ struct LocalModelRuntimeSetupTests {signingKeyID: "test-key")- await #expect(throws: LocalModelRuntimeSetupError.manifestFileHashMismatch(relativePath: "bin/donkey-yolo-segmenter")) {+ await #expect(throws: LocalModelRuntimeSetupError.manifestFileHashMismatch(relativePath: "bin/donkey-screenshot-segmentation-stub")) {_ = try await manager.downloadAndInstall(manifest: signedWithBadHash,- downloader: FakeRuntimeDownloader(files: [URL(string: "https://example.test/yolo/bin")!: data])+ downloader: FakeRuntimeDownloader(files: [URL(string: "https://example.test/segmentation-stub/bin")!: data]))}}@@ -425,23 +425,23 @@ struct LocalModelRuntimeSetupTests {@Testfunc removeRuntimeClearsRegistryAndManagedFiles() throws {let root = temporaryDirectory()- let download = root.appendingPathComponent("Packages/yolo-segmenter/1.0.0", isDirectory: true)+ let download = root.appendingPathComponent("Packages/screenshot-segmentation-stub/1.0.0", isDirectory: true)defer { try? FileManager.default.removeItem(at: root) }let executable = try makeExecutable(root: download,- relativePath: "bin/donkey-yolo-segmenter"+ relativePath: "bin/donkey-screenshot-segmentation-stub")let manager = try runtimeManager(baseDirectory: root)try manager.registerExecutable(- runtimeID: .yoloSegmenter,+ runtimeID: .screenshotSegmentationStub,executableURL: executable,downloadedDirectory: download,runtimeVersion: "1.0.0",- modelID: "ultralytics/yolo26n-seg"+ modelID: "stubbed-screenshot-segmentation")- let removed = try manager.removeRuntime(runtimeID: .yoloSegmenter)- let status = try manager.status(for: .yoloSegmenter)+ let removed = try manager.removeRuntime(runtimeID: .screenshotSegmentationStub)+ let status = try manager.status(for: .screenshotSegmentationStub)#expect(removed)#expect(status.state == .notInstalled)@@ -489,11 +489,11 @@ struct LocalModelRuntimeSetupTests {installSteps: []),LocalModelRuntimeSpec(- id: .yoloSegmenter,- displayName: "YOLO26 screenshot segmentation",- environmentVariableName: "DONKEY_YOLO_SEGMENTER",- expectedExecutableRelativePath: "bin/donkey-yolo-segmenter",- modelName: "ultralytics/yolo26n-seg",+ id: .screenshotSegmentationStub,+ displayName: "Screenshot segmentation stub",+ environmentVariableName: "DONKEY_SCREENSHOT_SEGMENTATION_STUB",+ expectedExecutableRelativePath: "bin/donkey-screenshot-segmentation-stub",+ modelName: "stubbed-screenshot-segmentation",downloadPageURL: nil,manifestURL: nil,installSteps: []diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalUIElementDetectionServiceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalUIElementDetectionServiceTests.swiftindex 0687a050..0dd55041 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalUIElementDetectionServiceTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalUIElementDetectionServiceTests.swift@@ -107,6 +107,151 @@ struct LocalUIElementDetectionServiceTests {#expect(trace.metrics.suppressedCount == 1)}+ @Test+ func nativeVisualDetectorIsStubbedUntilReplacementImplementationExists() {+ let trace = LocalUIElementDetectionService().detect(+ LocalUIElementDetectionRequest(+ traceID: "trace-native-visual-stub",+ screenshotPNGData: Data([0x89, 0x50, 0x4E, 0x47]),+ pixelSize: HotLoopSize(width: 400, height: 300, space: .screen),+ minConfidence: 0.25+ )+ )++ #expect(trace.candidates.isEmpty)+ #expect(trace.elements.isEmpty)+ #expect(trace.metadata["nativeVisual.status"] == "stubbed")+ #expect(trace.metadata["nativeVisual.reason"] == "cvPipelineRemovedPendingReplacement")+ }++ @Test+ func debugInspectionFrameSuppressesLegacyVisualAndLayoutOnlyFragments() {+ let trace = LocalUIElementDetectionTrace(+ traceID: "trace-debug-frame-filter",+ candidates: [],+ elements: [+ LocalUIElement(+ id: "legacy-visual-copy",+ type: .other,+ label: "Body copy",+ bounds: HotLoopRect(x: 20, y: 40, width: 180, height: 22, space: .screen),+ confidence: 0.9,+ sources: [.ocr],+ reasonCodes: [],+ actionEligibility: .readOnlyEvidence,+ sourceCandidateIDs: ["legacy-visual-copy"]+ ),+ LocalUIElement(+ id: "layout-only-row",+ type: .listItem,+ label: "Improve UI element detection",+ bounds: HotLoopRect(x: 10, y: 80, width: 240, height: 34, space: .screen),+ confidence: 0.72,+ sources: [.layout],+ reasonCodes: [],+ actionEligibility: .cursorVisualization,+ sourceCandidateIDs: ["layout-only-row"]+ ),+ LocalUIElement(+ id: "sidebar-row",+ type: .sidebarItem,+ label: "Stabilize dev layout UI",+ bounds: HotLoopRect(x: 10, y: 120, width: 240, height: 34, space: .screen),+ confidence: 0.72,+ sources: [.layout],+ reasonCodes: [],+ actionEligibility: .cursorVisualization,+ sourceCandidateIDs: ["sidebar-row"],+ metadata: ["candidate.sidebar-row.debug.overlayRole": "sidebarRow"]+ )+ ],+ suppressedCandidates: [],+ metrics: LocalUIElementDetectionMetrics()+ )++ let frame = LocalUIElementDetectionService().debugInspectionFrame(from: trace)++ #expect(frame.elements.map(\.id) == ["sidebar-row"])+ }++ @Test+ func debugInspectionFrameSuppressesLegacyVisionWithoutPromotingAtomicControls() {+ let trace = LocalUIElementDetectionTrace(+ traceID: "trace-debug-large-panel-filter",+ candidates: [],+ elements: [+ LocalUIElement(+ id: "legacy-small-checkbox",+ type: .checkbox,+ label: "Auto-review",+ bounds: HotLoopRect(x: 600, y: 1210, width: 34, height: 34, space: .screen),+ confidence: 0.72,+ sources: [.shape],+ reasonCodes: [],+ actionEligibility: .cursorVisualization,+ sourceCandidateIDs: ["legacy-shape-checkbox"]+ ),+ LocalUIElement(+ id: "hover-row",+ type: .listItem,+ label: "Hover-highlighted row",+ bounds: HotLoopRect(x: 120, y: 80, width: 180, height: 36, space: .screen),+ confidence: 0.74,+ sources: [.hoverProbe],+ reasonCodes: [],+ actionEligibility: .cursorVisualization,+ sourceCandidateIDs: ["hover-row"]+ )+ ],+ suppressedCandidates: [],+ metrics: LocalUIElementDetectionMetrics()+ )++ let frame = LocalUIElementDetectionService().debugInspectionFrame(from: trace)++ #expect(frame.elements.map(\.id) == ["hover-row"])+ }++ @Test+ func bottomComposerAccessoriesDoNotMergeIntoInputSurface() throws {+ let input = LocalUIElementCandidate(+ id: "layout-bottom-input",+ source: .layout,+ signalKind: .rowGrouping,+ typeHint: .input,+ label: "Ask for follow-up changes",+ bounds: HotLoopRect(x: 988, y: 1981, width: 1278, height: 150, space: .screen),+ confidence: 0.70,+ metadata: ["debug.overlayRole": "bottomInput"]+ )+ let accessory = LocalUIElementCandidate(+ id: "layout-bottom-input-plus",+ source: .layout,+ signalKind: .rowGrouping,+ typeHint: .toolbarIcon,+ label: "composer add button",+ bounds: HotLoopRect(x: 1016, y: 2083, width: 38, height: 38, space: .screen),+ confidence: 0.66,+ metadata: ["debug.overlayRole": "bottomInputAccessory"]+ )++ let trace = LocalUIElementDetectionService().detect(+ LocalUIElementDetectionRequest(+ traceID: "trace-bottom-composer-accessory",+ pixelSize: HotLoopSize(width: 2880, height: 2304, space: .screen),+ hoverProbeCandidates: [input, accessory],+ minConfidence: 0.25+ )+ )++ let elements = trace.elements.sorted { $0.bounds.origin.x < $1.bounds.origin.x }+ #expect(elements.count == 2)+ #expect(elements.map(\.type) == [.input, .toolbarIcon])++ let frame = LocalUIElementDetectionService().debugInspectionFrame(from: trace)+ #expect(frame.elements.count == 2)+ }+@Testfunc structuralWindowDoesNotSwallowChildControls() throws {let trace = LocalUIElementDetectionService().detect(@@ -147,4 +292,32 @@ struct LocalUIElementDetectionServiceTests {#expect(search.actionEligibility == .guardedAction)#expect(search.sourceCandidateIDs == ["ax-search"])}++ @Test+ func debugInspectionFrameSuppressesWindowFrames() {+ let trace = LocalUIElementDetectionTrace(+ traceID: "trace-debug-window-frame-filter",+ candidates: [],+ elements: [+ LocalUIElement(+ id: "window-1",+ type: .draggable,+ label: "Codex",+ bounds: HotLoopRect(x: 0, y: 0, width: 1600, height: 1000, space: .screen),+ confidence: 1,+ sources: [.accessibility],+ reasonCodes: [],+ actionEligibility: .readOnlyEvidence,+ sourceCandidateIDs: ["window-1"]+ )+ ],+ suppressedCandidates: [],+ metrics: LocalUIElementDetectionMetrics()+ )++ let frame = LocalUIElementDetectionService().debugInspectionFrame(from: trace)++ #expect(frame.elements.isEmpty)+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swiftindex 3d565c03..cfa12c8a 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift@@ -75,25 +75,25 @@ struct ManualCaptureDebugCommandTests {"Donkey","--install-local-runtime","--runtime-id",- "yolo-segmenter",+ "screenshot-segmentation-stub","--runtime-source",- "/tmp/yolo-runtime"+ "/tmp/segmentation-stub-runtime"])#expect(command == .installLocalRuntime(LocalRuntimeInstallDebugOptions(- runtimeID: .yoloSegmenter,- sourceDirectory: URL(fileURLWithPath: "/tmp/yolo-runtime")+ runtimeID: .screenshotSegmentationStub,+ sourceDirectory: URL(fileURLWithPath: "/tmp/segmentation-stub-runtime"))))#expect(try ManualCaptureDebugCommandParser.parse(- arguments: ["Donkey", "--repair-local-runtime", "--runtime-id", "yolo-segmenter"]- ) == .repairLocalRuntime(.yoloSegmenter))+ arguments: ["Donkey", "--repair-local-runtime", "--runtime-id", "screenshot-segmentation-stub"]+ ) == .repairLocalRuntime(.screenshotSegmentationStub))#expect(try ManualCaptureDebugCommandParser.parse(- arguments: ["Donkey", "--remove-local-runtime", "--runtime-id", "yolo-segmenter"]- ) == .removeLocalRuntime(.yoloSegmenter))+ arguments: ["Donkey", "--remove-local-runtime", "--runtime-id", "screenshot-segmentation-stub"]+ ) == .removeLocalRuntime(.screenshotSegmentationStub))}@Test@@ -207,7 +207,7 @@ struct ManualCaptureDebugCommandTests {#expect(instructionLines.contains("runtime=parakeet-transcriber"))#expect(instructionLines.contains("expectedExecutable=bin/donkey-parakeet-transcriber"))#expect(statusLines.contains("local runtime status"))- #expect(statusLines.contains("runtime=yolo-segmenter | state=notInstalled | env=DONKEY_YOLO_SEGMENTER | executable=- | reason=noRegisteredRuntime"))+ #expect(statusLines.contains("runtime=screenshot-segmentation-stub | state=notInstalled | env=DONKEY_SCREENSHOT_SEGMENTATION_STUB | executable=- | reason=noRegisteredRuntime"))let supportLines = ManualCaptureDebugCommandFormatter.lines(for: try manager.supportSnapshot()diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swiftindex 0f310a63..a8faf967 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift@@ -6,126 +6,101 @@ import Testing@Suitestruct OffTheShelfVisionPerceptionTests {@Test- func modelCatalogIncludesLatestYOLOForScreenshotSegmentation() throws {- let candidate = try #require(OffTheShelfVisionModelCatalog.defaultCandidate(+ func modelCatalogDoesNotExposeRunnableScreenshotSegmentationCandidate() {+ let candidate = OffTheShelfVisionModelCatalog.defaultCandidate(signalKind: .segmentation,inputSource: .screenshot- ))+ )- #expect(candidate.family == "YOLO26")- #expect(candidate.modelName == "yolo26n-seg.pt")- #expect(candidate.signalKind == .segmentation)- #expect(candidate.preferredInputSource == .crop)- #expect(candidate.componentID == "screenshot-segmentation-yolo26")- #expect(candidate.metadata["latestYOLOFamilyVerified"] == "YOLO26")- #expect(candidate.metadata["requiresLocalBenchmark"] == "true")- #expect(candidate.docsURL.absoluteString == "https://docs.ultralytics.com/models/yolo26/")+ #expect(candidate == nil)+ #expect(OffTheShelfVisionModelCatalog.screenshotSegmentationCandidates.isEmpty)+ #expect(OffTheShelfVisionModelCatalog.stubbedScreenshotSegmentation.metadata["reason"] == "cvPipelineRemovedPendingReplacement")}@Test- func metadataCodecRoundTripsLocalVisionEvidence() throws {+ func metadataCodecRemainsReadOnlyTraceCodecForLegacyArtifacts() throws {let metadata = RecordedOffTheShelfVisionMetadataCodec.encode(signals: [- recordedSignal(kind: .detector, id: "detector-signal", modelID: "yolo-nano-local"),- recordedSignal(kind: .ocr, id: "ocr-signal", modelID: "vision-text-local")+ RecordedOffTheShelfVisionSignal(+ id: "legacy-signal",+ kind: .segmentation,+ componentID: "legacy-component",+ modelID: "legacy-model",+ cropID: "legacy-crop",+ confidence: 0.88,+ observations: [+ RecordedOffTheShelfVisionObservation(+ id: "legacy-observation",+ label: "legacy",+ bounds: HotLoopRect(+ x: 0.42,+ y: 0.58,+ width: 0.12,+ height: 0.08,+ space: .normalizedTarget+ ),+ confidence: 0.82+ )+ ]+ )])let signals = RecordedOffTheShelfVisionMetadataCodec.decode(from: metadata)#expect(metadata["vision.offTheShelf.rawPixelsExposed"] == "false")- #expect(signals.map(\.kind) == [.detector, .ocr])- #expect(signals.first?.componentID == "component-detector-signal")- #expect(signals.first?.observations.first?.bounds == HotLoopRect(- x: 0.42,- y: 0.58,- width: 0.12,- height: 0.08,- space: .normalizedTarget- ))+ #expect(signals.first?.kind == .segmentation)+ #expect(signals.first?.observations.first?.bounds?.space == .normalizedTarget)}@Test- func adapterBuildsSignalsFromRecordedOffTheShelfVisionOutput() async throws {- let frame = fixtureFrame(signals: [- recordedSignal(- kind: .template,- id: "template-signal",- modelID: "button-template-v1",- preprocessMS: 2,- modelInferenceMS: 3,- adapterOverheadMS: 1- )- ])-- let signals = await OffTheShelfVisionPerceptionAdapter().perceive(frame: frame)- let signal = try #require(signals.first)- let observation = try #require(signal.observations.first)-- #expect(signal.kind == "template")- #expect(signal.metadata["vision.localEvidence"] == "true")- #expect(signal.metadata["rawPixelsExposed"] == "false")- #expect(signal.metadata["latency.preprocessMS"] == "2.0")- #expect(signal.metadata["latency.modelInferenceMS"] == "3.0")- #expect(signal.sourceAgeMS(at: timestamp(16)) == 6)- #expect(observation.metadata["vision.modelID"] == "button-template-v1")- #expect(observation.bounds?.space == .normalizedTarget)- }-- @Test- func dryRunLoopActsFromLocalVisionEvidenceAndRecordsLatency() async throws {- let coordinator = RunCoordinator()- let frame = fixtureFrame(signals: [- recordedSignal(- kind: .detector,- id: "detector-signal",- modelID: "yolo-nano-local",- preprocessMS: 3,- modelInferenceMS: 7,- adapterOverheadMS: 1- )- ])- let loop = DryRunReflexLoop(- coordinator: coordinator,- frameSource: RecordedFrameSource(frames: [frame]),- perceptionAdapter: OffTheShelfVisionPerceptionAdapter(),- worldStateProjector: OffTheShelfVisionWorldStateProjector(),- controllerPolicy: DeterministicControllerPolicy()+ func adapterIgnoresRecordedVisionMetadataWhilePipelineIsStubbed() async throws {+ let frame = HotLoopFrame(+ id: "frame-local-vision",+ traceID: "trace-local-vision",+ targetID: "target-visual-game",+ capturedAt: timestamp(10),+ sourceKind: .recorded,+ windowBounds: HotLoopRect(x: 0, y: 0, width: 390, height: 844, space: .screen),+ crop: nil,+ pixelSize: HotLoopSize(width: 390, height: 844, space: .window),+ metadata: RecordedOffTheShelfVisionMetadataCodec.encode(signals: [+ RecordedOffTheShelfVisionSignal(+ id: "legacy-signal",+ kind: .segmentation,+ componentID: "legacy-component",+ confidence: 0.88,+ observations: [+ RecordedOffTheShelfVisionObservation(+ id: "legacy-observation",+ label: "legacy",+ bounds: HotLoopRect(x: 0.42, y: 0.58, width: 0.12, height: 0.08, space: .normalizedTarget),+ confidence: 0.82+ )+ ]+ )+ ]))- let result = await loop.run(- session: RunSession(- id: "session-local-vision",- userGoal: "tap detected play button",- targetID: "target-visual-game"- )+ let signals = await OffTheShelfVisionPerceptionAdapter().perceive(frame: frame)+ let state = await OffTheShelfVisionWorldStateProjector().project(+ frame: frame,+ signals: signals,+ observedAt: timestamp(16))- let trace = try #require(await coordinator.latestReflexTrace())- let report = await ReflexLatencyReportBuilder.build(from: coordinator.reflexTraces())-- #expect(result.processedFrameCount == 1)- #expect(result.latestWorldState?.metadata["vision.localEvidence"] == "true")- #expect(result.latestAction?.kind == .tapTarget)- #expect(result.latestAction?.metadata["vision.modelID"] == "yolo-nano-local")- #expect(trace.latencyBreakdown.preprocessMS == 3)- #expect(trace.latencyBreakdown.modelInferenceMS == 7)- #expect(trace.latencyBreakdown.perceptionMS == 11)- #expect(trace.metadata["vision.localEvidence"] == "true")- #expect(trace.metadata["vision.signalKind"] == "detector")- #expect(report.modelInferenceMS.p95 == 7)- #expect(report.decisionMS.p95 == 1)+ #expect(signals.isEmpty)+ #expect(state.actionAffordances.isEmpty)+ #expect(state.metadata["vision.localEvidence"] == "false")+ #expect(state.metadata["reason"] == "cvPipelineRemovedPendingReplacement")}@Test- func yoloScreenshotSegmentationRunnerProducesRecordedLocalEvidence() async throws {- let runner = YOLOScreenshotSegmentationRunner(- backend: FakeScreenshotSegmentationBackend(),- now: fixedClock([100, 118])- )+ func screenshotSegmentationStubRunnerReturnsStubEvidenceOnly() async throws {+ let runner = ScreenshotSegmentationStubRunner(now: fixedClock([100, 118]))let result = try await runner.run(ScreenshotSegmentationRequest(- traceID: "trace-yolo",- frameID: "frame-yolo",- targetID: "target-yolo",+ traceID: "trace-segmentation-stub",+ frameID: "frame-segmentation-stub",+ targetID: "target-segmentation-stub",cropID: "crop-search",cropImageFileURL: URL(fileURLWithPath: "/tmp/crop-search.png"),cropBounds: HotLoopRect(x: 0, y: 0, width: 320, height: 180, space: .window),@@ -135,80 +110,38 @@ struct OffTheShelfVisionPerceptionTests {let decoded = RecordedOffTheShelfVisionMetadataCodec.decode(from: result.metadata)let signal = try #require(decoded.first)- #expect(result.model.id == "ultralytics-yolo26n-seg-screenshot")+ #expect(result.model.id == "stubbed-screenshot-segmentation")#expect(signal.kind == .segmentation)- #expect(signal.modelID == "ultralytics-yolo26n-seg-screenshot")- #expect(signal.cropID == "crop-search")- #expect(signal.preprocessMS == 3)- #expect(signal.modelInferenceMS == 9)- #expect(signal.adapterOverheadMS == 6)- #expect(signal.observations.first?.label == "search-field")- #expect(signal.metadata["requiresLocalBenchmark"] == "true")+ #expect(signal.observations.isEmpty)+ #expect(signal.metadata["reason"] == "cvPipelineRemovedPendingReplacement")+ #expect(signal.metadata["rawPixelsRead"] == "false")}@Test- func processBackedYOLORuntimeDecodesSidecarMasks() async throws {- let backend = ProcessBackedScreenshotSegmentationBackend(- sidecarRunner: FakeSidecarRunner(- result: LocalJSONSidecarResult(- status: .completed,- outputData: Data("""- {"masks":[{"id":"mask-play","label":"play-button","bounds":{"x":0.2,"y":0.3,"width":0.4,"height":0.1,"space":"normalizedTarget"},"confidence":0.88,"pointCount":12,"metadata":{"source":"fake-yolo"}}],"preprocessMS":4,"modelInferenceMS":11,"metadata":{"backend":"fake-sidecar-yolo"}}- """.utf8),- metadata: ["sidecar.reason": "completed"]- )- )- )-+ func processBackedScreenshotSegmentationRuntimeIsStubbed() async throws {+ let backend = ProcessBackedScreenshotSegmentationBackend()let result = try await backend.segment(request: ScreenshotSegmentationRequest(- traceID: "trace-sidecar-yolo",- frameID: "frame-sidecar-yolo",- targetID: "target-sidecar-yolo",+ traceID: "trace-sidecar-segmentation-stub",+ frameID: "frame-sidecar-segmentation-stub",+ targetID: "target-sidecar-segmentation-stub",cropID: "crop-play",- artifactURL: URL(string: "donkey-artifact://crop-play"),cropBounds: HotLoopRect(x: 0, y: 0, width: 100, height: 100, space: .window),pixelSize: HotLoopSize(width: 100, height: 100, space: .crop)),- model: OffTheShelfVisionModelCatalog.yolo26NanoScreenshotSegmentation- )-- #expect(result.masks.first?.label == "play-button")- #expect(result.preprocessMS == 4)- #expect(result.modelInferenceMS == 11)- #expect(result.metadata["backend"] == "fake-sidecar-yolo")- }-- @Test- func processBackedYOLORuntimeFailsClearlyWhenUnavailable() async throws {- let backend = ProcessBackedScreenshotSegmentationBackend(- sidecarRunner: FakeSidecarRunner(- result: LocalJSONSidecarResult(- status: .unavailable,- metadata: ["sidecar.reason": "missingEnvironmentVariable"]- )- )+ model: OffTheShelfVisionModelCatalog.stubbedScreenshotSegmentation)- await #expect(throws: ScreenshotSegmentationRunnerError.backendUnavailable("missingEnvironmentVariable")) {- _ = try await backend.segment(- request: ScreenshotSegmentationRequest(- traceID: "trace-missing-yolo",- frameID: "frame-missing-yolo",- targetID: "target-missing-yolo",- cropID: "crop-missing",- cropBounds: HotLoopRect(x: 0, y: 0, width: 100, height: 100, space: .window),- pixelSize: HotLoopSize(width: 100, height: 100, space: .crop)- ),- model: OffTheShelfVisionModelCatalog.yolo26NanoScreenshotSegmentation- )- }+ #expect(result.masks.isEmpty)+ #expect(result.preprocessMS == 0)+ #expect(result.modelInferenceMS == 0)+ #expect(result.metadata["reason"] == "cvPipelineRemovedPendingReplacement")}@Testfunc localUIUnderstandingSidecarFeedsObservationShape() async throws {let adapter = ProcessBackedLocalUIUnderstandingAdapter(- sidecarRunner: FakeSidecarRunner(+ sidecarRunner: StubbedLocalUIUnderstandingSidecarRunner(result: LocalJSONSidecarResult(status: .completed,outputData: Data("""@@ -233,62 +166,6 @@ struct OffTheShelfVisionPerceptionTests {#expect(observation.metadata["understander"] == "fake-local-llm")}- private func recordedSignal(- kind: OffTheShelfVisionSignalKind,- id: String,- modelID: String,- preprocessMS: Double = 1,- modelInferenceMS: Double = 4,- adapterOverheadMS: Double = 1- ) -> RecordedOffTheShelfVisionSignal {- RecordedOffTheShelfVisionSignal(- id: id,- kind: kind,- componentID: "component-\(id)",- modelID: modelID,- cropID: "gameplay-crop",- confidence: 0.88,- observations: [- RecordedOffTheShelfVisionObservation(- id: "observation-\(id)",- label: "play-button",- bounds: HotLoopRect(- x: 0.42,- y: 0.58,- width: 0.12,- height: 0.08,- space: .normalizedTarget- ),- confidence: 0.82,- metadata: [- "templateID": "play-button-template"- ]- )- ],- preprocessMS: preprocessMS,- modelInferenceMS: modelInferenceMS,- adapterOverheadMS: adapterOverheadMS- )- }-- private func fixtureFrame(signals: [RecordedOffTheShelfVisionSignal]) -> HotLoopFrame {- HotLoopFrame(- id: "frame-local-vision",- traceID: "trace-local-vision",- targetID: "target-visual-game",- capturedAt: timestamp(10),- sourceKind: .recorded,- windowBounds: HotLoopRect(x: 0, y: 0, width: 390, height: 844, space: .screen),- crop: HotLoopCrop(- id: "gameplay-crop",- bounds: HotLoopRect(x: 0, y: 120, width: 390, height: 600, space: .window),- outputSize: HotLoopSize(width: 390, height: 600, space: .crop)- ),- pixelSize: HotLoopSize(width: 390, height: 844, space: .window),- metadata: RecordedOffTheShelfVisionMetadataCodec.encode(signals: signals)- )- }-private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {RunTraceTimestamp(wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),@@ -322,32 +199,11 @@ private final class FixedVisionClock: @unchecked Sendable {}}-private struct FakeScreenshotSegmentationBackend: ScreenshotSegmentationBackend {- func segment(- request: ScreenshotSegmentationRequest,- model: OffTheShelfVisionModelCandidate- ) async throws -> ScreenshotSegmentationBackendResult {- ScreenshotSegmentationBackendResult(- masks: [- ScreenshotSegmentationMask(- id: "mask-search",- label: "search-field",- bounds: HotLoopRect(x: 0.1, y: 0.2, width: 0.5, height: 0.1, space: .normalizedTarget),- confidence: 0.87,- pointCount: 18- )- ],- preprocessMS: 3,- modelInferenceMS: 9,- metadata: ["backend": "fake-yolo"]- )- }-}--private struct FakeSidecarRunner: LocalJSONSidecarRunning {+private struct StubbedLocalUIUnderstandingSidecarRunner: LocalJSONSidecarRunning {var result: LocalJSONSidecarResultfunc run(_ request: LocalJSONSidecarRequest) async -> LocalJSONSidecarResult {- result+ _ = request+ return result}}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swiftindex 09684e6a..fb41490e 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swift@@ -57,7 +57,6 @@ struct ReflexLatencyReportTests {"latency.accessibilityActionMS": "5","latency.keyboardActionMS": "6","latency.verificationMS": "9",- "latency.yoloSegmentationMS": "21","latency.uiUnderstandingMS": "16","latency.parakeetTranscriptionMS": "31"]@@ -75,7 +74,6 @@ struct ReflexLatencyReportTests {#expect(lines.contains("droppedFrameCount=1"))#expect(lines.contains("softwareLoopMS=p50=10.00,p95=10.00,p99=10.00"))#expect(lines.contains("componentLatency.commandParseMS=p50=4.00,p95=4.00,p99=4.00"))- #expect(lines.contains("componentLatency.yoloSegmentationMS=p50=21.00,p95=21.00,p99=21.00"))#expect(lines.contains("componentLatency.parakeetTranscriptionMS=p50=31.00,p95=31.00,p99=31.00"))}diff --git a/apps/Donkey/dev-overlay.json b/apps/Donkey/dev-overlay.jsonindex 527db903..15461158 100644--- a/apps/Donkey/dev-overlay.json+++ b/apps/Donkey/dev-overlay.json@@ -3,5 +3,6 @@"provider": "accessibility","cadenceSeconds": 1.0,"screenScope": "main",- "minConfidence": 0.25+ "minConfidence": 0.25,+ "activeWindowOnly": true}diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 1a58cb3e..8608c35f 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -272,8 +272,8 @@ internal planning, approval/review, guarded execution, and verification.Evidence planning remains a background runtime concern: the handler should notpublish a pre-execution visualization for normal live work. The runner derivesagent visualization steps from observed evidence and action traces, and cursor-playback requires Accessibility, screenshot-understanding, or action-trace-targets. The model can be told about this state, but the runner owns it.+playback requires Accessibility or action-trace targets. The model can be told+about this state, but the runner owns it.Live input remains guarded. The action engine checks permission policy, targetfocus, rate limits, hold duration, and backend evidence before issuing input.@@ -305,13 +305,15 @@ bug, even if the script happens to work on one machine.Observation prefers Accessibility and app/window metadata. Bounded screenshotsare fallback observation context only; they do not emit direct input actions.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.+Accessibility candidates with optional hover-probe evidence, then marks each+element as overlay-only, read-only evidence, cursor-visualization evidence, or+guarded-action eligible. The native screenshot CV detector and off-the-shelf+vision pipeline are stubs and must not produce OCR, shape, color, layout,+segmentation, or tap-target candidates until a new measured implementation+replaces them. Hover-only evidence can guide debug overlays or visualization,+but it does 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 taskmetadata and runtime item metadata, not one-off branches for individual apps.@@ -341,7 +343,10 @@ 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+focused frontmost window. The overlay tracker stabilizes small geometry jitter,+brief disappearances, and one-sample label/source changes before redrawing so+the debugger reflects durable UI changes instead of sampler noise. Hosted+providers send screenshots to the read-onlyinspection route only while a config explicitly enables them, and accept strictJSON element metadata only. If a provider returns a computer/function action forthis route, the client rejects the frame and performs no interaction.diff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.mdindex b07c4d19..fb566e15 100644--- a/docs/guides/pointer-prompt-overlay.md+++ b/docs/guides/pointer-prompt-overlay.md@@ -23,7 +23,7 @@ quick local-app actions:- Keep prompt submissions, voice transcripts, and follow-ups on the same agent-harness path: task-thread routing, context assembly, conversational response, clarification, review, catalog-backed action parsing, task validation, and guarded local-app execution when a turn is actionable.- Resolve model-classified local-item requests against local apps, files, and folders by querying the current Mac with the SQLite-backed agent memory store, Spotlight/`mdfind`, and bounded filesystem fallback. If the requested local item cannot be found, keep the task safe and report that it was not found instead of falling back to a vague clarification.- Handle scriptable app tasks as guarded AppleScript automation when possible. Commands may use task metadata, generated source, or compact templates; completion is verified through generic task verification policy instead of requiring visible result text for every app.-- Visualize agent work with the spawned task cursor when a submitted turn already has one. Normal local-app tasks keep planning in the background and may create a final `AgentVisualizationPlan` only from runtime evidence such as evidence-backed action steps, observations, and action traces. Cursor playback uses only grounded control bounds or action targets, so it does not animate to invented coordinates. Visual-only demonstration turns use the same plan shape without live input. Local-app visualizations use observed Accessibility or screenshot-understanding control bounds when available, convert target-window-normalized element centers into the active overlay screen's pixel coordinates, and only then move the overlay cursor. Donkey moves the overlay cursor along curved paths and shows compact labels next to it while keeping the real mouse untouched. A separate visualization-only cursor is only a fallback when no spawned cursor is available to attach to.+- Visualize agent work with the spawned task cursor when a submitted turn already has one. Normal local-app tasks keep planning in the background and may create a final `AgentVisualizationPlan` only from runtime evidence such as evidence-backed action steps, observations, and action traces. Cursor playback uses only grounded control bounds or action targets, so it does not animate to invented coordinates. Visual-only demonstration turns use the same plan shape without live input. Local-app visualizations use observed Accessibility or action-trace control bounds when available, convert target-window-normalized element centers into the active overlay screen's pixel coordinates, and only then move the overlay cursor. Donkey moves the overlay cursor along curved paths and shows compact labels next to it while keeping the real mouse untouched. A separate visualization-only cursor is only a fallback when no spawned cursor is available to attach to.- Maintain a background agent memory store in Application Support. The store records resolved and missing local-item lookups, prewarms apps, stores runtime task definitions, keeps metadata such as kind/path/bundle ID/source/task/action, indexes records with SQLite FTS5 plus local vectors, and passes a bounded set of matching hints into the agent harness memory section for classifier and model consideration. Protected file folders such as Desktop, Documents, and Downloads stay lazy and are searched only when a user-requested local-item lookup needs them. See `docs/guides/decision-system.md` for how those hints feed typed model decisions and guarded local-app plans.- Persist task threads as searchable Core Data conversations with event history, task assets, and per-run runtime coordination for any action work attached to the thread.- Keep the overlay non-invasive. Permission setup requests Accessibility, screenshot, and microphone access with user-visible reasons, but the overlay itself does not capture the screen or synthesize input directly. Bounded screenshots and Accessibility reads are used only by guarded local-app workflows.@@ -34,15 +34,15 @@ quick local-app actions:no config exists, the config is invalid, or `"enabled": false`, the debugoverlay 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.+ are merged with optional hover-probe evidence, then drawn as+ click-through boxes with source badges beneath Donkey's own+ prompt/status/spawn UI. The native screenshot CV detector is stubbed and does+ not emit OCR, shape, color, layout, segmentation, or tap-target candidates.+ 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.```json{@@ -77,11 +77,11 @@ quick local-app actions:- The developer UI inspection overlay is separate from agent visualization. Itis a transparent, non-activating, click-through, keyboard-pass-through AppKitpanel at a lower window level than Donkey's interactive UI. It renders- CALayer rectangles and labels from local detector output or model-returned- JSON only; provider action calls such as click, type, scroll, drag,+ CALayer rectangles and labels from local Accessibility or hover-probe detector+ output 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.+ executed. 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.@@ -98,7 +98,7 @@ Manually verify:- With multiple spawned cursors visible, clicking a cursor selects it; double-Command still opens the centered prompt, and the submitted typed or voice turn routes to the selected/latest cursor's task without opening the inline label editor.- Open requests for installed apps, files, and folders launch or open the local item; missing local items show a not-found result and log the lookup provider/reason.- LLM-classified visual-only prompts complete as visualization turns and show the animated cursor with typed labels without moving the real pointer.-- Normal local-app tasks can produce final visualization steps for observed, navigated, acted, and verified runtime work. Planning stays in the background. Cursor playback should target observed control centers from Accessibility, screenshot understanding, or action traces when those bounds exist, omit ungrounded steps, and must not claim completion unless the runtime verification state supports it.+- Normal local-app tasks can produce final visualization steps for observed, navigated, acted, and verified runtime work. Planning stays in the background. Cursor playback should target observed control centers from Accessibility or action traces when those bounds exist, omit ungrounded steps, and must not claim completion unless the runtime verification state supports it.- The prompt supports wrapping, Shift-Return newline insertion, Return submission, Escape dismissal, outside-click dismissal, and dragging from non-input areas.- File drops on the notch attach to the active or most recent task.- With `dev-overlay.json` enabled, interact with underlying applications whilediff --git a/scripts/create-dev-runtime-manifests.py b/scripts/create-dev-runtime-manifests.pyindex 2228da86..0314f468 100755--- a/scripts/create-dev-runtime-manifests.py+++ b/scripts/create-dev-runtime-manifests.py@@ -18,7 +18,6 @@ ENV_FILE = Path(os.environ.get("DONKEY_DEV_RUNTIME_ENV_FILE", ROOT_DIR / "dist"RUNTIME_ENV_NAMES = {"parakeet-transcriber": "DONKEY_PARAKEET_RUNTIME_MANIFEST_URL",- "yolo-segmenter": "DONKEY_YOLO_RUNTIME_MANIFEST_URL","ui-understander": "DONKEY_UI_UNDERSTANDER_RUNTIME_MANIFEST_URL","local-llm": "DONKEY_LOCAL_LLM_RUNTIME_MANIFEST_URL",}diff --git a/scripts/local-runtime-runners/donkey_runtime_runner.py b/scripts/local-runtime-runners/donkey_runtime_runner.pyindex 26376e09..e6324473 100644--- a/scripts/local-runtime-runners/donkey_runtime_runner.py+++ b/scripts/local-runtime-runners/donkey_runtime_runner.py@@ -41,10 +41,6 @@ DEFAULT_RUNTIME_REQUIREMENTS: dict[str, list[str]] = {"parakeet-transcriber": ["huggingface_hub>=0.25,<1",],- "yolo-segmenter": [- "ultralytics>=8.3,<9",- "opencv-python-headless>=4.10,<5",- ],}@@ -72,8 +68,8 @@ def main() -> int:if RUNTIME_ID == "parakeet-transcriber":write_json(run_parakeet(request))return 0- if RUNTIME_ID == "yolo-segmenter":- write_json(run_yolo(request))+ if RUNTIME_ID == "screenshot-segmentation-stub":+ write_json(run_screenshot_segmentation_stub(request))return 0if RUNTIME_ID == "ui-understander":write_json(run_ui_understander(request))@@ -275,16 +271,23 @@ def prepare_model_weights(request: dict[str, Any]) -> dict[str, Any]:return prepared(cache_dir, {"modelWeights.status": "cached", "modelWeights.path": str(target_file)})return download_model_file(MODEL_URL, target_file, MODEL_SHA256, cache_dir)- if RUNTIME_ID == "yolo-segmenter":- return prepare_ultralytics_model(cache_dir)+ if RUNTIME_ID == "screenshot-segmentation-stub":+ return prepared(+ cache_dir,+ {+ "modelWeights.status": "notRequired",+ "runtime.backend": "screenshot-segmentation-stub",+ "reason": "cvPipelineRemovedPendingReplacement",+ },+ )if RUNTIME_ID == "ui-understander":return prepared(cache_dir,{"modelWeights.status": "notRequired",- "runtime.backend": "external-ui-understander",- "reason": "uiUnderstandingUsesPackagedAppleVisionSidecar",+ "runtime.backend": "local-ui-understanding-stubbed-visual",+ "reason": "uiUnderstandingVisualPipelineStubbed",},)@@ -339,31 +342,6 @@ def prepare_huggingface_snapshot(cache_dir: str) -> dict[str, Any]:)-def prepare_ultralytics_model(cache_dir: str) -> dict[str, Any]:- try:- from ultralytics import YOLO # type: ignore- except Exception as exc: # noqa: BLE001- return error_payload(- "pythonDependencyUnavailable",- {"cacheDirectory": cache_dir, "dependency": "ultralytics", "detail": str(exc)},- )-- try:- YOLO(MODEL_ID)- return prepared(- cache_dir,- {- "modelWeights.status": "cached",- "modelWeights.provider": "ultralytics",- },- )- except Exception as exc: # noqa: BLE001- return error_payload(- "ultralyticsModelPrepareFailed",- {"cacheDirectory": cache_dir, "detail": str(exc)},- )--def download_model_file(url: str, target_file: Path, expected_sha256: str, cache_dir: str) -> dict[str, Any]:target_file.parent.mkdir(parents=True, exist_ok=True)tmp_file = target_file.with_suffix(target_file.suffix + ".tmp")@@ -1575,65 +1553,19 @@ def transcript_payload(text: str, confidence: float, extra: dict[str, Any] | Non}-def run_yolo(request: dict[str, Any]) -> dict[str, Any]:- external_command = os.environ.get("DONKEY_YOLO_COMMAND")- if external_command:- return run_external_json_command(external_command, request)-- try:- from ultralytics import YOLO # type: ignore- except Exception as exc: # noqa: BLE001- return {"masks": [], "preprocessMS": 0, "modelInferenceMS": 0, "metadata": metadata({"reason": "pythonDependencyUnavailable", "dependency": "ultralytics", "detail": str(exc)})}-- image_path = request.get("cropImagePath")- if not image_path:- return {"masks": [], "preprocessMS": 0, "modelInferenceMS": 0, "metadata": metadata({"reason": "missingCropImagePath"})}-- started = time.monotonic()- try:- model = YOLO(MODEL_ID)- loaded = time.monotonic()- results = model(image_path)- finished = time.monotonic()- masks = yolo_masks(results)- return {- "masks": masks,- "preprocessMS": (loaded - started) * 1000,- "modelInferenceMS": (finished - loaded) * 1000,- "metadata": metadata({"runtime.backend": "ultralytics"}),- }- except Exception as exc: # noqa: BLE001- return {"masks": [], "preprocessMS": 0, "modelInferenceMS": 0, "metadata": metadata({"reason": "yoloSegmentationFailed", "detail": str(exc)})}---def yolo_masks(results: Any) -> list[dict[str, Any]]:- masks: list[dict[str, Any]] = []- first = results[0] if results else None- if first is None or getattr(first, "boxes", None) is None:- return masks- names = getattr(first, "names", {}) or {}- boxes = getattr(first.boxes, "xyxy", []) or []- confidences = getattr(first.boxes, "conf", []) or []- classes = getattr(first.boxes, "cls", []) or []- for index, box in enumerate(boxes):- values = [float(v) for v in box.tolist()]- confidence = float(confidences[index]) if index < len(confidences) else 0- class_id = int(classes[index]) if index < len(classes) else -1- label = str(names.get(class_id, class_id))- masks.append(+def run_screenshot_segmentation_stub(request: dict[str, Any]) -> dict[str, Any]:+ return {+ "masks": [],+ "preprocessMS": 0,+ "modelInferenceMS": 0,+ "metadata": metadata({- "id": f"mask-{index}",- "label": label,- "bounds": {- "origin": {"x": values[0], "y": values[1], "space": "window"},- "size": {"width": max(0, values[2] - values[0]), "height": max(0, values[3] - values[1]), "space": "window"},- },- "confidence": confidence,- "pointCount": 0,- "metadata": {"classID": str(class_id)},+ "runtime.backend": "screenshot-segmentation-stub",+ "reason": "cvPipelineRemovedPendingReplacement",+ "rawPixelsRead": "false",}- )- return masks+ ),+ }def run_ui_understander(request: dict[str, Any]) -> dict[str, Any]:@@ -1645,7 +1577,7 @@ def run_ui_understander(request: dict[str, Any]) -> dict[str, Any]:"controls": [],"formFields": [],"confidence": 0,- "metadata": metadata({"reason": "uiUnderstandingRequiresPackagedAppleVisionSidecar"}),+ "metadata": metadata({"reason": "uiUnderstandingVisualPipelineStubbed", "rawPixelsRead": "false"}),}diff --git a/scripts/setup-dev-local-runtimes.py b/scripts/setup-dev-local-runtimes.pyindex c28c2dd3..6c220ef8 100755--- a/scripts/setup-dev-local-runtimes.py+++ b/scripts/setup-dev-local-runtimes.py@@ -20,14 +20,12 @@ RUNTIME_ENV_NAMES = {"local-llm": "DONKEY_LOCAL_LLM_RUNTIME_MANIFEST_URL","parakeet-transcriber": "DONKEY_PARAKEET_RUNTIME_MANIFEST_URL","ui-understander": "DONKEY_UI_UNDERSTANDER_RUNTIME_MANIFEST_URL",- "yolo-segmenter": "DONKEY_YOLO_RUNTIME_MANIFEST_URL",}RUNTIME_EXECUTABLE_ENV_NAMES = {"local-llm": "DONKEY_LOCAL_LLM_RUNNER","parakeet-transcriber": "DONKEY_PARAKEET_TRANSCRIBER","ui-understander": "DONKEY_UI_UNDERSTANDER",- "yolo-segmenter": "DONKEY_YOLO_SEGMENTER",}DEFAULT_BASE_DIR = (