Skip to content

Open source CapCut alternative.

TypeScript

Add Donkey Vision screenshot parsing

David Leaca0f22e3255
diff --git a/apps/Donkey/Sources/Donkey/DocumentFormFillReviewWindowController.swift b/apps/Donkey/Sources/Donkey/DocumentFormFillReviewWindowController.swift
index 952edf21..0e0390c7 100644
--- a/apps/Donkey/Sources/Donkey/DocumentFormFillReviewWindowController.swift
+++ b/apps/Donkey/Sources/Donkey/DocumentFormFillReviewWindowController.swift
@@ -1,4 +1,5 @@
import AppKit
+import DonkeyAI
import DonkeyRuntime
import SwiftUI
@@ -53,6 +54,9 @@ private final class DocumentFormFillReviewViewModel: ObservableObject {
request: DocumentFormFillReviewRequest,
close: @escaping @MainActor () -> Void,
runner: DocumentFormFillApprovalLiveRunner = DocumentFormFillApprovalLiveRunner(
+ appController: MacLocalAppTaskController(
+ uiUnderstandingRunner: DonkeyUIUnderstandingRunnerFactory.defaultRunner()
+ ),
coordinator: RunCoordinator()
)
) {
diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift
index a0ea16f9..effe3ef2 100644
--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift
+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift
@@ -1,9 +1,12 @@
import AppKit
+import CryptoKit
import DonkeyAI
import DonkeyContracts
import DonkeyRuntime
import Foundation
+import ImageIO
import OSLog
+import UniformTypeIdentifiers
private enum DebugUIInspectionLog {
static let overlay = Logger(subsystem: "com.donkey.app", category: "debug-ui-inspection")
@@ -14,6 +17,8 @@ final class DebugUIInspectionCoordinator {
private let overlayController = DebugUIInspectionOverlayController()
private let captureService = DebugUIScreenCaptureService()
private let accessibilityInspectionService = DebugUIAccessibilityInspectionService()
+ private let windowResolver = MacWindowResolver()
+ private let windowScreenshotCapturer = ScreenCaptureKitWindowScreenshotCapturer()
private let configURL: URL?
private var analyzer: (any DebugUIInspectionAnalyzing)?
private var trackers: [UInt32: DebugUIElementTracker] = [:]
@@ -89,16 +94,16 @@ final class DebugUIInspectionCoordinator {
let cadenceChanged = newConfig.cadenceSeconds != currentConfig.cadenceSeconds
let enablementChanged = newConfig.enabled != currentConfig.enabled
let scopeChanged = newConfig.screenScope != currentConfig.screenScope
- let providerChanged = newConfig.provider != currentConfig.provider
+ let modeChanged = newConfig.mode != currentConfig.mode
let confidenceChanged = newConfig.minConfidence != currentConfig.minConfidence
let activeWindowChanged = newConfig.activeWindowOnly != currentConfig.activeWindowOnly
let targetFilterChanged = newConfig.targetBundleIdentifiers != currentConfig.targetBundleIdentifiers
|| newConfig.targetAppNames != currentConfig.targetAppNames
currentConfig = newConfig
- if force || enablementChanged || scopeChanged || providerChanged || confidenceChanged || activeWindowChanged || targetFilterChanged {
+ if force || enablementChanged || scopeChanged || modeChanged || confidenceChanged || activeWindowChanged || targetFilterChanged {
DebugUIInspectionLog.overlay.info(
- "debug inspection config enabled=\(String(newConfig.enabled), privacy: .public) provider=\(newConfig.provider.rawValue, privacy: .public) cadence=\(newConfig.cadenceSeconds, privacy: .public) scope=\(newConfig.screenScope.rawValue, privacy: .public) minConfidence=\(newConfig.minConfidence, privacy: .public) activeWindowOnly=\(String(newConfig.activeWindowOnly), privacy: .public) targetBundles=\(newConfig.targetBundleIdentifiers.joined(separator: ","), privacy: .public) targetApps=\(newConfig.targetAppNames.joined(separator: ","), privacy: .public)"
+ "debug inspection config enabled=\(String(newConfig.enabled), privacy: .public) mode=\(newConfig.mode, privacy: .public) cadence=\(newConfig.cadenceSeconds, privacy: .public) scope=\(newConfig.screenScope.rawValue, privacy: .public) minConfidence=\(newConfig.minConfidence, privacy: .public) activeWindowOnly=\(String(newConfig.activeWindowOnly), privacy: .public) targetBundles=\(newConfig.targetBundleIdentifiers.joined(separator: ","), privacy: .public) targetApps=\(newConfig.targetAppNames.joined(separator: ","), privacy: .public)"
)
}
@@ -113,7 +118,7 @@ final class DebugUIInspectionCoordinator {
RunLoop.main.add(newTimer, forMode: .common)
}
- if enablementChanged || scopeChanged || providerChanged || confidenceChanged || activeWindowChanged || targetFilterChanged {
+ if enablementChanged || scopeChanged || modeChanged || confidenceChanged || activeWindowChanged || targetFilterChanged {
lastFingerprints.removeAll()
trackers.removeAll()
lastRenderedFrames.removeAll()
@@ -151,55 +156,319 @@ final class DebugUIInspectionCoordinator {
}
private func analyzeVisibleScreens(force: Bool) async throws {
- if currentConfig.provider == .accessibility {
- try analyzeAccessibilityScreens(force: force)
+ try await analyzeGeminiWindowScreens(force: force)
+ }
+
+ private func needsTrackerWarmup(screenID: UInt32) -> Bool {
+ lastRenderedFrames[screenID]?.elements.isEmpty == true
+ }
+
+ private func renderFastLocalFrames(
+ screens: [DebugUIScreenSurface],
+ frames: [UInt32: DebugUIInspectionFrame],
+ stage: String,
+ force: Bool
+ ) {
+ for screen in screens {
+ guard let frame = frames[screen.screenID],
+ !frame.elements.isEmpty
+ else {
+ continue
+ }
+ let fingerprint = Self.fingerprint(
+ screenID: screen.screenID,
+ captures: [],
+ accessibilityFrame: frame
+ )
+ renderFastLocalFrame(
+ screen: screen,
+ frame: frame,
+ fingerprint: "\(fingerprint)-\(stage)",
+ stage: stage,
+ force: force
+ )
+ }
+ }
+
+ private func renderFastLocalFrame(
+ screen: DebugUIScreenSurface,
+ frame: DebugUIInspectionFrame,
+ fingerprint: String,
+ stage: String,
+ force: Bool
+ ) {
+ guard force || lastFingerprints[screen.screenID] != fingerprint || needsTrackerWarmup(screenID: screen.screenID) else {
return
}
- let snapshots = try captureService.captureScreens(scope: currentConfig.screenScope)
- DebugUIInspectionLog.overlay.debug(
- "debug inspection captured screens=\(snapshots.count, privacy: .public) force=\(String(force), privacy: .public)"
+ var tracker = trackers[screen.screenID] ?? DebugUIElementTracker()
+ let trackedFrame = tracker.update(with: frame)
+ trackers[screen.screenID] = tracker
+ guard force
+ || lastRenderedFrames[screen.screenID]?.isOverlayRenderEquivalent(to: trackedFrame) != true
+ else {
+ return
+ }
+
+ let snapshot = Self.screenPointSnapshot(screen: screen, fingerprint: fingerprint)
+ DebugUIInspectionLog.overlay.info(
+ "debug inspection rendering source=\(stage, privacy: .public) screenID=\(screen.screenID, privacy: .public) elements=\(trackedFrame.elements.count, privacy: .public)"
)
- let activeScreenIDs = Set(snapshots.map(\.screenID))
+ lastFingerprints[screen.screenID] = fingerprint
+ lastRenderedFrames[screen.screenID] = trackedFrame
+ lastSnapshots[screen.screenID] = snapshot
+ overlayController.render(frame: trackedFrame, snapshot: snapshot)
+ }
+
+ private func analyzeGeminiWindowScreens(force: Bool) async throws {
+ let screens = try screenSurfaces(scope: currentConfig.screenScope)
+ let activeScreenIDs = Set(screens.map(\.screenID))
overlayController.closeScreens(except: activeScreenIDs)
lastRenderedFrames = lastRenderedFrames.filter { activeScreenIDs.contains($0.key) }
- let analyzer = try analyzerInstance()
+ let accessibilityFrames = accessibilityFramesForGeminiFusion()
+ renderFastLocalFrames(
+ screens: screens,
+ frames: accessibilityFrames,
+ stage: "accessibility",
+ force: force
+ )
+
+ let targets = visibleOverlayTargets(on: screens)
+ guard !targets.isEmpty else {
+ ageMissingGeminiScreens(activeScreenIDs: Set(accessibilityFrames.keys))
+ for screen in screens where accessibilityFrames[screen.screenID] != nil {
+ let accessibilityFrame = accessibilityFrames[screen.screenID] ?? DebugUIInspectionFrame()
+ let fingerprint = Self.fingerprint(
+ screenID: screen.screenID,
+ captures: [],
+ accessibilityFrame: accessibilityFrame
+ )
+ guard force || lastFingerprints[screen.screenID] != fingerprint || needsTrackerWarmup(screenID: screen.screenID) else {
+ continue
+ }
+ lastFingerprints[screen.screenID] = fingerprint
+ var tracker = trackers[screen.screenID] ?? DebugUIElementTracker()
+ let trackedFrame = tracker.update(with: accessibilityFrame)
+ trackers[screen.screenID] = tracker
+ let snapshot = Self.screenPointSnapshot(screen: screen, fingerprint: fingerprint)
+ lastRenderedFrames[screen.screenID] = trackedFrame
+ lastSnapshots[screen.screenID] = snapshot
+ overlayController.render(frame: trackedFrame, snapshot: snapshot)
+ }
+ return
+ }
+
+ let client = try backendInferenceClient()
+ var captures: [DebugUIWindowCapture] = []
+ for target in targets {
+ do {
+ let screenshot = try await windowScreenshotCapturer.capture(target: target)
+ let compressed = Self.compressedGeminiImage(from: screenshot)
+ captures.append(
+ DebugUIWindowCapture(
+ target: target,
+ screenshot: screenshot,
+ parseImageData: compressed.data,
+ parseContentType: compressed.contentType,
+ parsePixelSize: compressed.pixelSize
+ )
+ )
+ } catch {
+ DebugUIInspectionLog.overlay.error(
+ "debug inspection skipped gemini windowID=\(target.windowID, privacy: .public) error=\(String(describing: error), privacy: .public)"
+ )
+ }
+ }
+
+ let renderedScreenIDs = Set(captures.flatMap { capture in
+ screens.filter { Self.intersects(capture.target.bounds, Self.windowBounds(from: $0.appKitFrame)) }.map(\.screenID)
+ }).union(accessibilityFrames.keys)
+ ageMissingGeminiScreens(activeScreenIDs: renderedScreenIDs)
- for snapshot in snapshots {
- guard force || lastFingerprints[snapshot.screenID] != snapshot.fingerprint else {
+ for screen in screens where renderedScreenIDs.contains(screen.screenID) {
+ let screenBounds = Self.windowBounds(from: screen.appKitFrame)
+ let screenCaptures = captures.filter { Self.intersects($0.target.bounds, screenBounds) }
+ let accessibilityFrame = accessibilityFrames[screen.screenID] ?? DebugUIInspectionFrame()
+ let fingerprint = Self.fingerprint(
+ screenID: screen.screenID,
+ captures: screenCaptures,
+ accessibilityFrame: accessibilityFrame
+ )
+ guard force || lastFingerprints[screen.screenID] != fingerprint || needsTrackerWarmup(screenID: screen.screenID) else {
DebugUIInspectionLog.overlay.debug(
- "debug inspection skipped unchanged screenID=\(snapshot.screenID, privacy: .public)"
+ "debug inspection skipped unchanged gemini screenID=\(screen.screenID, privacy: .public)"
)
continue
}
- lastFingerprints[snapshot.screenID] = snapshot.fingerprint
- DebugUIInspectionLog.overlay.info(
- "debug inspection analyzing screenID=\(snapshot.screenID, privacy: .public) pixels=\(snapshot.pixelSize.width, privacy: .public)x\(snapshot.pixelSize.height, privacy: .public)"
- )
- let frame = try await analyzer.inspect(
- DebugUIInspectionRequest(
- provider: currentConfig.provider,
- screenshotBase64: snapshot.base64PNG,
- pixelSize: snapshot.pixelSize,
- minConfidence: currentConfig.minConfidence,
+ lastFingerprints[screen.screenID] = fingerprint
+
+ let localEvidenceFrame = accessibilityFrame
+
+ var elements: [DebugUIElement] = []
+ for capture in screenCaptures {
+ let capturePixelSize = HotLoopSize(
+ width: capture.parsePixelSize.width,
+ height: capture.parsePixelSize.height,
+ space: .window
+ )
+ let request = LocalUIUnderstandingRequest(
+ traceID: "debug-ui-gemini-\(screen.screenID)-\(capture.target.windowID)-\(fingerprint)",
+ targetID: "window-\(capture.target.windowID)",
+ imageFileURL: nil,
+ cropBounds: HotLoopRect(
+ x: 0,
+ y: 0,
+ width: capturePixelSize.width,
+ height: capturePixelSize.height,
+ space: .window
+ ),
+ pixelSize: capturePixelSize,
metadata: [
- "screen.id": String(snapshot.screenID),
- "screen.scope": currentConfig.screenScope.rawValue
+ "source": "debug-ui-inspection-overlay",
+ "donkeyVision.ai": "gemini",
+ "screenshot.scope": "targetWindow",
+ "screenshot.desktopCaptureAllowed": "false",
+ "target.windowID": String(capture.target.windowID),
+ "target.processID": String(capture.target.processID),
+ "target.appName": capture.target.appName ?? "",
+ "target.bundleIdentifier": capture.target.bundleIdentifier ?? "",
+ "target.title": capture.target.title ?? "",
+ "target.bounds.x": String(capture.target.bounds.x),
+ "target.bounds.y": String(capture.target.bounds.y),
+ "target.bounds.width": String(capture.target.bounds.width),
+ "target.bounds.height": String(capture.target.bounds.height),
+ "capture.method": capture.screenshot.captureMethod.rawValue,
+ "capture.coordinateSpace": capture.screenshot.coordinateSpace,
+ "capture.originalBytes": String(capture.screenshot.pngData.count),
+ "capture.parseBytes": String(capture.parseImageData.count),
+ "capture.parseContentType": capture.parseContentType,
+ "capture.parseWidth": String(Int(capture.parsePixelSize.width.rounded())),
+ "capture.parseHeight": String(Int(capture.parsePixelSize.height.rounded()))
]
)
+ do {
+ let result = try await client.parseScreenshot(
+ request,
+ imageData: capture.parseImageData,
+ contentType: capture.parseContentType
+ )
+ elements += ScreenshotParseDebugUIOverlayMapper.frame(
+ from: result,
+ target: capture.target,
+ capturePixelSize: capturePixelSize,
+ screenFrame: screenBounds,
+ minConfidence: currentConfig.minConfidence
+ ).elements
+ } catch {
+ DebugUIInspectionLog.overlay.error(
+ "debug inspection gemini parse failed windowID=\(capture.target.windowID, privacy: .public) error=\(String(describing: error), privacy: .public)"
+ )
+ }
+ }
+
+ var tracker = trackers[screen.screenID] ?? DebugUIElementTracker()
+ let geminiFrame = DebugUIInspectionFrame(elements: elements)
+ let fusedFrame = DebugUIInspectionFrameFusion.fused(
+ accessibilityFrame: localEvidenceFrame,
+ geminiFrame: geminiFrame
)
- var tracker = trackers[snapshot.screenID] ?? DebugUIElementTracker()
- let trackedFrame = tracker.update(with: frame)
- trackers[snapshot.screenID] = tracker
+ let trackedFrame = tracker.update(
+ with: fusedFrame,
+ renderNewElementsImmediately: true
+ )
+ trackers[screen.screenID] = tracker
+ if !force,
+ let previousFrame = lastRenderedFrames[screen.screenID],
+ trackedFrame.isOverlayRenderEquivalent(to: previousFrame) {
+ DebugUIInspectionLog.overlay.debug(
+ "debug inspection skipped stable gemini render screenID=\(screen.screenID, privacy: .public)"
+ )
+ continue
+ }
+
+ let snapshot = Self.screenPointSnapshot(screen: screen, fingerprint: fingerprint)
DebugUIInspectionLog.overlay.info(
- "debug inspection rendering screenID=\(snapshot.screenID, privacy: .public) elements=\(trackedFrame.elements.count, privacy: .public)"
+ "debug inspection rendering source=gemini-fused screenID=\(screen.screenID, privacy: .public) windows=\(screenCaptures.count, privacy: .public) localEvidenceElements=\(localEvidenceFrame.elements.count, privacy: .public) geminiElements=\(geminiFrame.elements.count, privacy: .public) elements=\(trackedFrame.elements.count, privacy: .public)"
)
logSampleMappings(frame: trackedFrame, snapshot: snapshot)
- lastRenderedFrames[snapshot.screenID] = trackedFrame
+ lastRenderedFrames[screen.screenID] = trackedFrame
+ lastSnapshots[screen.screenID] = snapshot
overlayController.render(frame: trackedFrame, snapshot: snapshot)
}
}
+ private func accessibilityFramesForGeminiFusion() -> [UInt32: DebugUIInspectionFrame] {
+ do {
+ let results = try accessibilityInspectionService.inspect(
+ scope: currentConfig.screenScope,
+ minConfidence: currentConfig.minConfidence,
+ frontmostOnly: currentConfig.activeWindowOnly,
+ focusedOnly: currentConfig.activeWindowOnly,
+ targetBundleIdentifiers: currentConfig.targetBundleIdentifiers,
+ targetAppNames: currentConfig.targetAppNames
+ )
+ return Dictionary(
+ uniqueKeysWithValues: results.map { result in
+ (
+ result.snapshot.screenID,
+ Self.frameInScreenPointSpace(
+ result.frame,
+ snapshot: result.snapshot
+ )
+ )
+ }
+ )
+ } catch {
+ DebugUIInspectionLog.overlay.info(
+ "debug inspection skipped accessibility fusion error=\(String(describing: error), privacy: .public)"
+ )
+ return [:]
+ }
+ }
+
+ private static func frameInScreenPointSpace(
+ _ frame: DebugUIInspectionFrame,
+ snapshot: DebugUIScreenCaptureSnapshot
+ ) -> DebugUIInspectionFrame {
+ guard snapshot.pixelSize.width > 0,
+ snapshot.pixelSize.height > 0,
+ snapshot.screenFrame.size.width > 0,
+ snapshot.screenFrame.size.height > 0
+ else {
+ return frame
+ }
+
+ let scaleX = snapshot.screenFrame.size.width / snapshot.pixelSize.width
+ let scaleY = snapshot.screenFrame.size.height / snapshot.pixelSize.height
+ guard abs(scaleX - 1) > 0.0001 || abs(scaleY - 1) > 0.0001 else {
+ return frame
+ }
+
+ return DebugUIInspectionFrame(
+ elements: frame.elements.map { element in
+ DebugUIElement(
+ id: element.id,
+ type: element.type,
+ label: element.label,
+ description: element.description,
+ bbox: DebugUIBoundingBox(
+ x: element.bbox.x * scaleX,
+ y: element.bbox.y * scaleY,
+ width: element.bbox.width * scaleX,
+ height: element.bbox.height * scaleY
+ ),
+ confidence: element.confidence,
+ visualStyle: element.visualStyle,
+ metadata: element.metadata.merging([
+ "coordinate.fusionSpace": "screenPoints",
+ "coordinate.fusionScaleX": String(format: "%.6f", scaleX),
+ "coordinate.fusionScaleY": String(format: "%.6f", scaleY)
+ ]) { current, _ in current }
+ )
+ }
+ )
+ }
+
private func analyzeAccessibilityScreens(force: Bool) throws {
let results = try accessibilityInspectionService.inspect(
scope: currentConfig.screenScope,
@@ -252,6 +521,14 @@ final class DebugUIInspectionCoordinator {
}
private func ageMissingAccessibilityScreens(activeScreenIDs: Set<UInt32>) {
+ ageMissingScreens(activeScreenIDs: activeScreenIDs)
+ }
+
+ private func ageMissingGeminiScreens(activeScreenIDs: Set<UInt32>) {
+ ageMissingScreens(activeScreenIDs: activeScreenIDs)
+ }
+
+ private func ageMissingScreens(activeScreenIDs: Set<UInt32>) {
let missingScreenIDs = Set(lastRenderedFrames.keys).subtracting(activeScreenIDs)
for screenID in missingScreenIDs {
var tracker = trackers[screenID] ?? DebugUIElementTracker()
@@ -275,6 +552,70 @@ final class DebugUIInspectionCoordinator {
}
}
+ private func screenSurfaces(scope: DebugUIInspectionScreenScope) throws -> [DebugUIScreenSurface] {
+ let screens: [NSScreen]
+ switch scope {
+ case .main:
+ guard let screen = NSScreen.main ?? NSScreen.screens.first else {
+ return [Self.fallbackScreenSurface(displayID: CGMainDisplayID())]
+ .filter { $0.screenID != 0 }
+ }
+ screens = [screen]
+ case .all:
+ screens = NSScreen.screens
+ }
+
+ if screens.isEmpty {
+ var count: UInt32 = 0
+ CGGetActiveDisplayList(0, nil, &count)
+ var displays = [CGDirectDisplayID](repeating: 0, count: Int(count))
+ CGGetActiveDisplayList(count, &displays, &count)
+ return displays.filter { $0 != 0 }.map(Self.fallbackScreenSurface)
+ }
+
+ return try screens.map { screen in
+ let displayID = try Self.displayID(for: screen)
+ let appKitFrame = screen.frame
+ let captureFrame = CGDisplayBounds(displayID)
+ return DebugUIScreenSurface(
+ screenID: displayID,
+ appKitFrame: HotLoopRect(
+ x: appKitFrame.origin.x,
+ y: appKitFrame.origin.y,
+ width: appKitFrame.width,
+ height: appKitFrame.height,
+ space: .screen
+ ),
+ captureFrame: WindowTargetBounds(
+ x: captureFrame.origin.x,
+ y: captureFrame.origin.y,
+ width: captureFrame.width,
+ height: captureFrame.height
+ )
+ )
+ }
+ }
+
+ private func visibleOverlayTargets(on screens: [DebugUIScreenSurface]) -> [MacWindowTargetCandidate] {
+ let bundleFilters = Set(currentConfig.targetBundleIdentifiers.map(Self.normalizedTargetFilter))
+ let appNameFilters = Set(currentConfig.targetAppNames.map(Self.normalizedTargetFilter))
+ return windowResolver.enumerateCandidates().filter { target in
+ target.isVisible
+ && target.isOnScreen
+ && (!currentConfig.activeWindowOnly || target.isFrontmost)
+ && (!currentConfig.activeWindowOnly || target.isFocused)
+ && target.safetyAssessment.status == .allowed
+ && !target.isIPhoneMirroring
+ && target.processID != ProcessInfo.processInfo.processIdentifier
+ && Self.matchesTargetFilter(
+ target,
+ bundleFilters: bundleFilters,
+ appNameFilters: appNameFilters
+ )
+ && screens.contains { Self.intersects(target.bounds, Self.windowBounds(from: $0.appKitFrame)) }
+ }
+ }
+
private func logSampleMappings(
frame: DebugUIInspectionFrame,
snapshot: DebugUIScreenCaptureSnapshot
@@ -335,4 +676,211 @@ final class DebugUIInspectionCoordinator {
analyzer = created
return created
}
+
+ private func backendInferenceClient() throws -> DonkeyBackendInferenceClient {
+ let configuration = try DonkeyBackendInferenceConfiguration.fromEnvironment()
+ return DonkeyBackendInferenceClient(configuration: configuration)
+ }
+
+ private static func displayID(for screen: NSScreen) throws -> UInt32 {
+ let key = NSDeviceDescriptionKey("NSScreenNumber")
+ guard let value = screen.deviceDescription[key] as? NSNumber else {
+ throw DebugUIScreenCaptureError.missingDisplayIdentifier
+ }
+ return value.uint32Value
+ }
+
+ private static func fallbackScreenSurface(displayID: CGDirectDisplayID) -> DebugUIScreenSurface {
+ let bounds = CGDisplayBounds(displayID)
+ return DebugUIScreenSurface(
+ screenID: displayID,
+ appKitFrame: HotLoopRect(
+ x: bounds.origin.x,
+ y: bounds.origin.y,
+ width: bounds.width,
+ height: bounds.height,
+ space: .screen
+ ),
+ captureFrame: WindowTargetBounds(
+ x: bounds.origin.x,
+ y: bounds.origin.y,
+ width: bounds.width,
+ height: bounds.height
+ )
+ )
+ }
+
+ private static func matchesTargetFilter(
+ _ target: MacWindowTargetCandidate,
+ bundleFilters: Set<String>,
+ appNameFilters: Set<String>
+ ) -> Bool {
+ guard !bundleFilters.isEmpty || !appNameFilters.isEmpty else {
+ return true
+ }
+ if let bundleIdentifier = target.bundleIdentifier,
+ bundleFilters.contains(normalizedTargetFilter(bundleIdentifier)) {
+ return true
+ }
+ if let appName = target.appName,
+ appNameFilters.contains(normalizedTargetFilter(appName)) {
+ return true
+ }
+ return false
+ }
+
+ private static func normalizedTargetFilter(_ value: String) -> String {
+ value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ }
+
+ private static func intersects(
+ _ lhs: WindowTargetBounds,
+ _ rhs: WindowTargetBounds
+ ) -> Bool {
+ lhs.x < rhs.x + rhs.width
+ && lhs.x + lhs.width > rhs.x
+ && lhs.y < rhs.y + rhs.height
+ && lhs.y + lhs.height > rhs.y
+ }
+
+ private static func windowBounds(from rect: HotLoopRect) -> WindowTargetBounds {
+ WindowTargetBounds(
+ x: rect.origin.x,
+ y: rect.origin.y,
+ width: rect.size.width,
+ height: rect.size.height
+ )
+ }
+
+ private static func fingerprint(
+ screenID: UInt32,
+ captures: [DebugUIWindowCapture],
+ accessibilityFrame: DebugUIInspectionFrame? = nil
+ ) -> String {
+ let input = captures.map { capture in
+ [
+ String(screenID),
+ String(capture.target.windowID),
+ String(capture.target.bounds.x),
+ String(capture.target.bounds.y),
+ String(capture.target.bounds.width),
+ String(capture.target.bounds.height),
+ SHA256.hash(data: capture.parseImageData).map { String(format: "%02x", $0) }.joined()
+ ].joined(separator: ":")
+ }.joined(separator: "|")
+ let accessibilityInput = (accessibilityFrame?.elements ?? []).map { element in
+ [
+ element.id,
+ element.type.rawValue,
+ element.label,
+ String(format: "%.2f", element.bbox.x),
+ String(format: "%.2f", element.bbox.y),
+ String(format: "%.2f", element.bbox.width),
+ String(format: "%.2f", element.bbox.height),
+ String(format: "%.3f", element.confidence)
+ ].joined(separator: ":")
+ }.joined(separator: "|")
+ let combinedInput = [input, accessibilityInput]
+ .filter { !$0.isEmpty }
+ .joined(separator: "||")
+ return SHA256.hash(data: Data(combinedInput.utf8)).map { String(format: "%02x", $0) }.joined()
+ }
+
+ private static func screenPointSnapshot(
+ screen: DebugUIScreenSurface,
+ fingerprint: String
+ ) -> DebugUIScreenCaptureSnapshot {
+ DebugUIScreenCaptureSnapshot(
+ screenID: screen.screenID,
+ screenFrame: screen.appKitFrame,
+ pixelSize: HotLoopSize(
+ width: screen.appKitFrame.size.width,
+ height: screen.appKitFrame.size.height,
+ space: .screen
+ ),
+ pngData: Data(),
+ fingerprint: fingerprint
+ )
+ }
+
+ private static func compressedGeminiImage(
+ from screenshot: CapturedWindowScreenshot
+ ) -> DebugUICompressedImage {
+ let fallbackSize = HotLoopSize(
+ width: Double(screenshot.imageWidth),
+ height: Double(screenshot.imageHeight),
+ space: .window
+ )
+ guard let source = CGImageSourceCreateWithData(screenshot.pngData as CFData, nil) else {
+ return DebugUICompressedImage(
+ data: screenshot.pngData,
+ contentType: "image/png",
+ pixelSize: fallbackSize
+ )
+ }
+
+ let maxPixelDimension = 896
+ let thumbnailOptions: [CFString: Any] = [
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceShouldCacheImmediately: true,
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceThumbnailMaxPixelSize: maxPixelDimension
+ ]
+ guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, thumbnailOptions as CFDictionary),
+ let encoded = NSMutableData() as CFMutableData?,
+ let destination = CGImageDestinationCreateWithData(
+ encoded,
+ UTType.jpeg.identifier as CFString,
+ 1,
+ nil
+ )
+ else {
+ return DebugUICompressedImage(
+ data: screenshot.pngData,
+ contentType: "image/png",
+ pixelSize: fallbackSize
+ )
+ }
+
+ CGImageDestinationAddImage(destination, image, [
+ kCGImageDestinationLossyCompressionQuality: 0.48
+ ] as CFDictionary)
+ guard CGImageDestinationFinalize(destination) else {
+ return DebugUICompressedImage(
+ data: screenshot.pngData,
+ contentType: "image/png",
+ pixelSize: fallbackSize
+ )
+ }
+
+ return DebugUICompressedImage(
+ data: encoded as Data,
+ contentType: "image/jpeg",
+ pixelSize: HotLoopSize(
+ width: Double(image.width),
+ height: Double(image.height),
+ space: .window
+ )
+ )
+ }
+}
+
+private struct DebugUIScreenSurface: Equatable, Sendable {
+ var screenID: UInt32
+ var appKitFrame: HotLoopRect
+ var captureFrame: WindowTargetBounds
+}
+
+private struct DebugUIWindowCapture: Sendable {
+ var target: MacWindowTargetCandidate
+ var screenshot: CapturedWindowScreenshot
+ var parseImageData: Data
+ var parseContentType: String
+ var parsePixelSize: HotLoopSize
+}
+
+private struct DebugUICompressedImage: Sendable {
+ var data: Data
+ var contentType: String
+ var pixelSize: HotLoopSize
}
diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift
index 074f9f79..c8a263b7 100644
--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift
+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift
@@ -142,7 +142,7 @@ private final class DebugUIInspectionSurface {
let boxLayer = CAShapeLayer()
boxLayer.name = "debug-ui-box-\(element.id)"
boxLayer.fillColor = fillColor(for: element)
- boxLayer.strokeColor = nsColor(hex: element.visualStyle.borderColor, alpha: 0.95).cgColor
+ boxLayer.strokeColor = strokeColor(for: element)
boxLayer.lineWidth = 2
boxLayer.opacity = 0
@@ -182,7 +182,9 @@ private final class DebugUIInspectionSurface {
layers.box.frame = boxFrame
layers.box.path = path
layers.box.fillColor = fillColor(for: element)
- layers.box.strokeColor = nsColor(hex: element.visualStyle.borderColor, alpha: 0.95).cgColor
+ layers.box.strokeColor = strokeColor(for: element)
+ layers.box.lineDashPattern = lineDashPattern(for: element)
+ layers.box.lineWidth = lineWidth(for: element)
let title = labelText(for: element)
let labelFrame = DebugUIOverlayGeometry.stableLabelFrame(
@@ -192,25 +194,96 @@ private final class DebugUIInspectionSurface {
)
layers.label.string = title
layers.label.foregroundColor = nsColor(hex: element.visualStyle.labelColor, alpha: 1).cgColor
- layers.label.backgroundColor = nsColor(hex: element.visualStyle.overlayColor, alpha: 0.92).cgColor
+ layers.label.backgroundColor = labelBackgroundColor(for: element)
layers.label.frame = labelFrame
}
private func labelText(for element: DebugUIElement) -> String {
let label = element.label.trimmingCharacters(in: .whitespacesAndNewlines)
- if label.isEmpty {
- return element.type.rawValue.replacingOccurrences(of: "_", with: " ")
+ let base = label.isEmpty
+ ? element.type.rawValue.replacingOccurrences(of: "_", with: " ")
+ : label
+ if let badge = sourceBadge(for: element) {
+ return "\(badge) \(base)"
}
- return label
+ return base
}
private func fillColor(for element: DebugUIElement) -> CGColor {
if element.id.hasPrefix("window-") {
return NSColor.clear.cgColor
}
+ if sourceKind(for: element) == .ai {
+ return nsColor(hex: "#FF2D55", alpha: 0.16).cgColor
+ }
+ if sourceKind(for: element) == .nativeVisual {
+ return nsColor(hex: "#00C7BE", alpha: 0.13).cgColor
+ }
return nsColor(hex: element.visualStyle.overlayColor, alpha: 0.14).cgColor
}
+ private func strokeColor(for element: DebugUIElement) -> CGColor {
+ switch sourceKind(for: element) {
+ case .ai:
+ return nsColor(hex: "#FF2D55", alpha: 0.98).cgColor
+ case .nativeVisual:
+ return nsColor(hex: "#00C7BE", alpha: 0.95).cgColor
+ case .accessibility:
+ return nsColor(hex: "#34D399", alpha: 0.95).cgColor
+ case .other:
+ return nsColor(hex: element.visualStyle.borderColor, alpha: 0.95).cgColor
+ }
+ }
+
+ private func labelBackgroundColor(for element: DebugUIElement) -> CGColor {
+ switch sourceKind(for: element) {
+ case .ai:
+ return nsColor(hex: "#FF2D55", alpha: 0.94).cgColor
+ case .nativeVisual:
+ return nsColor(hex: "#00C7BE", alpha: 0.92).cgColor
+ case .accessibility:
+ return nsColor(hex: "#34D399", alpha: 0.92).cgColor
+ case .other:
+ return nsColor(hex: element.visualStyle.overlayColor, alpha: 0.92).cgColor
+ }
+ }
+
+ private func lineDashPattern(for element: DebugUIElement) -> [NSNumber]? {
+ sourceKind(for: element) == .ai ? [6, 4] : nil
+ }
+
+ private func lineWidth(for element: DebugUIElement) -> CGFloat {
+ sourceKind(for: element) == .ai ? 2.5 : 2
+ }
+
+ private func sourceBadge(for element: DebugUIElement) -> String? {
+ switch sourceKind(for: element) {
+ case .ai:
+ return "AI"
+ case .nativeVisual:
+ return "CV"
+ case .accessibility:
+ return "AX"
+ case .other:
+ return nil
+ }
+ }
+
+ private func sourceKind(for element: DebugUIElement) -> DebugUIInspectionSourceKind {
+ let fusionSource = element.metadata["debugUIFusion.source"] ?? ""
+ let sources = element.metadata["localUIElement.sources"] ?? ""
+ if fusionSource == "gemini" || sources.contains("gemini") || element.id.hasPrefix("gemini-") {
+ return .ai
+ }
+ if fusionSource == "native-visual" || sources.contains("shape") || sources.contains("ocr") || sources.contains("layout") || element.id.hasPrefix("native-visual-") {
+ return .nativeVisual
+ }
+ if sources.contains("accessibility") || element.id.hasPrefix("ax-") || sources.contains("window-chrome-geometry") {
+ return .accessibility
+ }
+ return .other
+ }
+
private func fadeIn(_ layers: DebugUIInspectionElementLayers) {
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = 0
@@ -258,6 +331,13 @@ private struct DebugUIInspectionElementLayers {
var label: CATextLayer
}
+private enum DebugUIInspectionSourceKind {
+ case accessibility
+ case nativeVisual
+ case ai
+ case other
+}
+
private final class DebugUIInspectionPanel: NSPanel {
override var canBecomeKey: Bool { false }
override var canBecomeMain: Bool { false }
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
index b15e61fd..144cf884 100644
--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
@@ -88,7 +88,12 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
self.appHarnessRouter = AppHarnessTurnRouter(catalog: catalog)
self.coordinatorRegistry = coordinatorRegistry
self.localModelResolver = localModelResolver ?? LocalModelTaskIntentResolver(catalog: catalog)
- self.liveRunner = liveRunner ?? LocalAppTaskLiveRunner(catalog: catalog)
+ self.liveRunner = liveRunner ?? LocalAppTaskLiveRunner(
+ catalog: catalog,
+ appController: MacLocalAppTaskController(
+ uiUnderstandingRunner: DonkeyUIUnderstandingRunnerFactory.defaultRunner()
+ )
+ )
self.redactor = redactor
self.memoryRetriever = memoryRetriever
self.memoryStore = memoryStore
diff --git a/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionFrameFusion.swift b/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionFrameFusion.swift
new file mode 100644
index 00000000..338af40a
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionFrameFusion.swift
@@ -0,0 +1,129 @@
+import DonkeyContracts
+import Foundation
+
+public enum DebugUIInspectionFrameFusion {
+ public static func fused(
+ accessibilityFrame: DebugUIInspectionFrame,
+ geminiFrame: DebugUIInspectionFrame
+ ) -> DebugUIInspectionFrame {
+ let accessibilityElements = accessibilityFrame.elements
+ let accessibilityDeduplicationBase = accessibilityElements.filter { $0.type != .draggable }
+ let geminiOnlyElements = geminiFrame.elements.filter { geminiElement in
+ !accessibilityDeduplicationBase.contains { accessibilityElement in
+ isDuplicate(geminiElement, of: accessibilityElement)
+ }
+ }.map(annotatedGeminiElement)
+
+ return DebugUIInspectionFrame(
+ elements: (accessibilityElements + geminiOnlyElements).sorted(by: elementSort)
+ )
+ }
+
+ private static func isDuplicate(
+ _ geminiElement: DebugUIElement,
+ of accessibilityElement: DebugUIElement
+ ) -> Bool {
+ let smallerArea = min(area(geminiElement.bbox), area(accessibilityElement.bbox))
+ guard smallerArea > 0 else { return false }
+
+ let geminiLabel = normalized(geminiElement.label)
+ let accessibilityLabel = normalized(accessibilityElement.label)
+ if !geminiLabel.isEmpty,
+ geminiLabel == accessibilityLabel,
+ centerDistance(geminiElement.bbox, accessibilityElement.bbox) <= 32 {
+ return true
+ }
+
+ guard areCompatibleTypes(geminiElement.type, accessibilityElement.type) else {
+ return false
+ }
+
+ let accessibilityArea = area(accessibilityElement.bbox)
+ let geminiArea = area(geminiElement.bbox)
+ let areaRatio = smallerArea / max(accessibilityArea, geminiArea)
+ guard areaRatio >= 0.25 else {
+ return false
+ }
+
+ let containmentScore = intersectionArea(geminiElement.bbox, accessibilityElement.bbox) / smallerArea
+ return containmentScore >= 0.62
+ }
+
+ private static func annotatedGeminiElement(_ element: DebugUIElement) -> DebugUIElement {
+ DebugUIElement(
+ id: element.id,
+ type: element.type,
+ label: element.label,
+ description: element.description,
+ bbox: element.bbox,
+ confidence: element.confidence,
+ visualStyle: element.visualStyle,
+ metadata: element.metadata.merging([
+ "debugUIFusion.source": "gemini",
+ "localUIElement.actionEligibility": "readOnlyEvidence",
+ "directInputActionsAllowed": "false"
+ ]) { current, _ in current }
+ )
+ }
+
+ private static func elementSort(_ lhs: DebugUIElement, _ rhs: DebugUIElement) -> Bool {
+ if lhs.bbox.y != rhs.bbox.y { return lhs.bbox.y < rhs.bbox.y }
+ if lhs.bbox.x != rhs.bbox.x { return lhs.bbox.x < rhs.bbox.x }
+ return lhs.id < rhs.id
+ }
+
+ private static func area(_ box: DebugUIBoundingBox) -> Double {
+ max(0, box.width) * max(0, box.height)
+ }
+
+ private static func intersectionArea(
+ _ lhs: DebugUIBoundingBox,
+ _ rhs: DebugUIBoundingBox
+ ) -> Double {
+ let minX = max(lhs.x, rhs.x)
+ let minY = max(lhs.y, rhs.y)
+ let maxX = min(lhs.x + lhs.width, rhs.x + rhs.width)
+ let maxY = min(lhs.y + lhs.height, rhs.y + rhs.height)
+ return max(0, maxX - minX) * max(0, maxY - minY)
+ }
+
+ private static func centerDistance(
+ _ lhs: DebugUIBoundingBox,
+ _ rhs: DebugUIBoundingBox
+ ) -> Double {
+ hypot(
+ (lhs.x + lhs.width / 2) - (rhs.x + rhs.width / 2),
+ (lhs.y + lhs.height / 2) - (rhs.y + rhs.height / 2)
+ )
+ }
+
+ private static func areCompatibleTypes(
+ _ lhs: DebugUIElementType,
+ _ rhs: DebugUIElementType
+ ) -> Bool {
+ if lhs == rhs { return true }
+
+ let buttonLike: Set<DebugUIElementType> = [
+ .button,
+ .toolbarIcon,
+ .windowControl,
+ .menuItem,
+ .tab,
+ .sidebarItem,
+ .listItem
+ ]
+ let textLike: Set<DebugUIElementType> = [
+ .input,
+ .dropdown
+ ]
+ return buttonLike.contains(lhs) && buttonLike.contains(rhs)
+ || textLike.contains(lhs) && textLike.contains(rhs)
+ }
+
+ private static func normalized(_ value: String) -> String {
+ value
+ .lowercased()
+ .split { !$0.isLetter && !$0.isNumber }
+ .joined(separator: " ")
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
index d9819ab2..5a622abf 100644
--- a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
@@ -1,4 +1,5 @@
import DonkeyContracts
+import DonkeyRuntime
import Foundation
public enum DonkeyBackendInferenceClientError: Error, Equatable, Sendable {
@@ -127,6 +128,39 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {
return try JSONDecoder().decode(RemoteInferenceJSONValue.self, from: data)
}
+ public func parseScreenshot(
+ _ understandingRequest: LocalUIUnderstandingRequest,
+ imageData: Data? = nil,
+ contentType: String = "image/png"
+ ) async throws -> LocalUIUnderstandingResult {
+ guard let imageData = try imageData ?? understandingRequest.imageFileURL.map({ try Data(contentsOf: $0) }) else {
+ throw DonkeyBackendInferenceClientError.missingDownloadPayload("screenshot")
+ }
+
+ var request = makeRequest(path: "/api/inference/screenshots/parse/")
+ request.httpMethod = "POST"
+ var metadata = understandingRequest.metadata
+ metadata["screenshot.scope"] = metadata["screenshot.scope"] ?? "targetWindow"
+ metadata["screenshot.desktopCaptureAllowed"] = "false"
+ request.httpBody = try JSONEncoder().encode(
+ RemoteScreenshotParseRequest(
+ imageBase64: imageData.base64EncodedString(),
+ contentType: contentType,
+ pixelSize: understandingRequest.pixelSize ?? HotLoopSize(
+ width: 1,
+ height: 1,
+ space: .window
+ ),
+ traceID: understandingRequest.traceID,
+ targetID: understandingRequest.targetID,
+ cropBounds: understandingRequest.cropBounds,
+ metadata: metadata
+ )
+ )
+ let data = try await send(request)
+ return try JSONDecoder().decode(LocalUIUnderstandingResult.self, from: data)
+ }
+
public func makeStreamingChatRequest(
_ completionRequest: RemoteInferenceChatCompletionRequest
) throws -> URLRequest {
@@ -366,3 +400,13 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {
return cleaned.isEmpty ? "asset" : String(cleaned.prefix(160))
}
}
+
+private struct RemoteScreenshotParseRequest: Encodable {
+ var imageBase64: String
+ var contentType: String
+ var pixelSize: HotLoopSize
+ var traceID: String
+ var targetID: String
+ var cropBounds: HotLoopRect?
+ var metadata: [String: String]
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/RemoteScreenshotParsingUIUnderstandingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/RemoteScreenshotParsingUIUnderstandingAdapter.swift
new file mode 100644
index 00000000..b08d2473
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/RemoteScreenshotParsingUIUnderstandingAdapter.swift
@@ -0,0 +1,183 @@
+import CryptoKit
+import DonkeyContracts
+import DonkeyRuntime
+import Foundation
+
+public actor RemoteScreenshotParsingThrottle {
+ private struct Entry {
+ var fingerprint: String
+ var timestamp: Date
+ }
+
+ private var entries: [String: Entry] = [:]
+ private let minimumInterval: TimeInterval
+
+ public init(minimumInterval: TimeInterval = 8) {
+ self.minimumInterval = max(0, minimumInterval)
+ }
+
+ public func shouldAllow(
+ targetID: String,
+ imageFingerprint: String,
+ now: Date = Date()
+ ) -> Bool {
+ if let existing = entries[targetID] {
+ if existing.fingerprint == imageFingerprint {
+ return false
+ }
+ if now.timeIntervalSince(existing.timestamp) < minimumInterval {
+ return false
+ }
+ }
+
+ entries[targetID] = Entry(fingerprint: imageFingerprint, timestamp: now)
+ return true
+ }
+}
+
+public struct RemoteScreenshotParsingLocalUIUnderstandingAdapter: LocalUIUnderstandingRunning {
+ public var client: DonkeyBackendInferenceClient
+
+ public init(client: DonkeyBackendInferenceClient) {
+ self.client = client
+ }
+
+ public func understand(_ request: LocalUIUnderstandingRequest) async throws -> LocalUIUnderstandingResult {
+ try await client.parseScreenshot(request)
+ }
+
+ func understand(
+ _ request: LocalUIUnderstandingRequest,
+ imageData: Data
+ ) async throws -> LocalUIUnderstandingResult {
+ try await client.parseScreenshot(request, imageData: imageData)
+ }
+}
+
+public struct RemoteFallbackLocalUIUnderstandingAdapter: LocalUIUnderstandingRunning {
+ public var primary: any LocalUIUnderstandingRunning
+ public var remote: RemoteScreenshotParsingLocalUIUnderstandingAdapter
+ public var throttle: RemoteScreenshotParsingThrottle
+ public var minimumPrimaryConfidence: Double
+
+ public init(
+ primary: any LocalUIUnderstandingRunning = ProcessBackedLocalUIUnderstandingAdapter(),
+ remote: RemoteScreenshotParsingLocalUIUnderstandingAdapter,
+ throttle: RemoteScreenshotParsingThrottle = RemoteScreenshotParsingThrottle(),
+ minimumPrimaryConfidence: Double = 0.75
+ ) {
+ self.primary = primary
+ self.remote = remote
+ self.throttle = throttle
+ self.minimumPrimaryConfidence = min(max(minimumPrimaryConfidence, 0), 1)
+ }
+
+ public func understand(_ request: LocalUIUnderstandingRequest) async throws -> LocalUIUnderstandingResult {
+ let primaryResult = try? await primary.understand(request)
+ if let primaryResult, primaryEvidenceIsGood(primaryResult) {
+ return primaryResult
+ }
+
+ guard let imageFileURL = request.imageFileURL else {
+ if let primaryResult {
+ return primaryResult
+ }
+ throw LocalUIUnderstandingError.unavailable("missingImagePath")
+ }
+
+ let imageData: Data
+ do {
+ imageData = try Data(contentsOf: imageFileURL)
+ } catch {
+ if let primaryResult {
+ return primaryResult
+ }
+ throw LocalUIUnderstandingError.unavailable("missingImageData")
+ }
+
+ let fingerprint = Self.fingerprint(for: imageData)
+ let allowed = await throttle.shouldAllow(
+ targetID: request.targetID,
+ imageFingerprint: fingerprint
+ )
+ guard allowed else {
+ if let primaryResult {
+ return annotatedPrimaryResult(primaryResult, status: "throttled")
+ }
+ throw LocalUIUnderstandingError.unavailable("remoteScreenshotParsingThrottled")
+ }
+
+ do {
+ var remoteResult = try await remote.understand(request, imageData: imageData)
+ remoteResult.metadata = remoteResult.metadata.merging([
+ "remoteScreenshotParsing.status": "used",
+ "remoteScreenshotParsing.fingerprint": fingerprint
+ ]) { current, _ in current }
+ return bestResult(primary: primaryResult, remote: remoteResult)
+ } catch {
+ if let primaryResult {
+ return annotatedPrimaryResult(primaryResult, status: "failed")
+ }
+ throw error
+ }
+ }
+
+ private func primaryEvidenceIsGood(_ result: LocalUIUnderstandingResult) -> Bool {
+ result.confidence >= minimumPrimaryConfidence
+ && (!result.controls.isEmpty || !result.visibleText.isEmpty || !result.formFields.isEmpty)
+ }
+
+ private func bestResult(
+ primary: LocalUIUnderstandingResult?,
+ remote: LocalUIUnderstandingResult
+ ) -> LocalUIUnderstandingResult {
+ guard let primary else {
+ return remote
+ }
+
+ if remote.confidence >= primary.confidence || primary.controls.isEmpty {
+ return remote
+ }
+
+ return annotatedPrimaryResult(primary, status: "primaryPreferred")
+ }
+
+ private func annotatedPrimaryResult(
+ _ result: LocalUIUnderstandingResult,
+ status: String
+ ) -> LocalUIUnderstandingResult {
+ LocalUIUnderstandingResult(
+ visibleText: result.visibleText,
+ controls: result.controls,
+ formFields: result.formFields,
+ confidence: result.confidence,
+ metadata: result.metadata.merging([
+ "remoteScreenshotParsing.status": status
+ ]) { current, _ in current }
+ )
+ }
+
+ private static func fingerprint(for data: Data) -> String {
+ SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
+ }
+}
+
+public enum DonkeyUIUnderstandingRunnerFactory {
+ public static func defaultRunner(
+ environment: [String: String] = ProcessInfo.processInfo.environment,
+ bundle: Bundle = .main
+ ) -> any LocalUIUnderstandingRunning {
+ guard let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment(
+ environment,
+ bundle: bundle
+ ) else {
+ return ProcessBackedLocalUIUnderstandingAdapter()
+ }
+
+ return RemoteFallbackLocalUIUnderstandingAdapter(
+ remote: RemoteScreenshotParsingLocalUIUnderstandingAdapter(
+ client: DonkeyBackendInferenceClient(configuration: configuration)
+ )
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift b/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift
new file mode 100644
index 00000000..2520851b
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift
@@ -0,0 +1,231 @@
+import DonkeyContracts
+import DonkeyRuntime
+import Foundation
+
+public enum ScreenshotParseDebugUIOverlayMapper {
+ public static func frame(
+ from result: LocalUIUnderstandingResult,
+ target: MacWindowTargetCandidate,
+ capturePixelSize: HotLoopSize,
+ screenFrame: WindowTargetBounds,
+ minConfidence: Double
+ ) -> DebugUIInspectionFrame {
+ let threshold = min(max(minConfidence, 0), 1)
+ let windowControls = macWindowControlElements(
+ target: target,
+ screenFrame: screenFrame
+ )
+ return DebugUIInspectionFrame(
+ elements: windowControls + result.controls.compactMap { control in
+ guard !isMacWindowControl(control) else {
+ return nil
+ }
+ guard control.confidence >= threshold,
+ let frame = control.frame,
+ let bbox = overlayBoundingBox(
+ for: frame,
+ target: target,
+ capturePixelSize: capturePixelSize,
+ screenFrame: screenFrame,
+ flipWindowY: true
+ )
+ else {
+ return nil
+ }
+
+ return DebugUIElement(
+ id: "gemini-\(target.windowID)-\(control.id)",
+ type: elementType(for: control.kind),
+ label: control.label,
+ description: [
+ "gemini screenshot parser",
+ control.kind.rawValue
+ ].joined(separator: " "),
+ bbox: bbox,
+ confidence: control.confidence,
+ metadata: control.metadata.merging([
+ "localUIElement.sources": "gemini-screenshot-parser",
+ "localUIElement.actionEligibility": LocalUIElementActionEligibility.readOnlyEvidence.rawValue,
+ "remoteScreenshotParsing.status": result.metadata["remoteScreenshotParsing.status"] ?? "used",
+ "remoteScreenshotParsing.provider": result.metadata["parserProvider"] ?? result.metadata["runtime.backend"] ?? "gemini-screenshot-parser",
+ "target.windowID": String(target.windowID),
+ "target.appName": target.appName ?? "",
+ "target.bundleIdentifier": target.bundleIdentifier ?? "",
+ "target.title": target.title ?? "",
+ "coordinate.sourceSpace": frame.space.rawValue,
+ "directInputActionsAllowed": "false"
+ ]) { current, _ in current }
+ )
+ }
+ ).validated(minConfidence: threshold)
+ }
+
+ private static func macWindowControlElements(
+ target: MacWindowTargetCandidate,
+ screenFrame: WindowTargetBounds
+ ) -> [DebugUIElement] {
+ guard target.bounds.hasPositiveArea,
+ target.bounds.width >= 120,
+ target.bounds.height >= 44
+ else {
+ return []
+ }
+
+ let controls: [(id: String, label: String, centerX: Double)] = [
+ ("close", "Close", 23),
+ ("minimize", "Minimize", 46),
+ ("zoom", "Zoom", 69)
+ ]
+ let diameter = 14.0
+ let centerY = 23.0
+
+ return controls.compactMap { control in
+ let bounds = WindowTargetBounds(
+ x: target.bounds.x + control.centerX - diameter / 2,
+ y: target.bounds.y + centerY - diameter / 2,
+ width: diameter,
+ height: diameter
+ )
+ guard let bbox = clippedBoundingBox(bounds, screenFrame: screenFrame) else {
+ return nil
+ }
+ return DebugUIElement(
+ id: "window-chrome-\(target.windowID)-\(control.id)",
+ type: .windowControl,
+ label: control.label,
+ description: "macOS window chrome",
+ bbox: bbox,
+ confidence: 1,
+ metadata: [
+ "localUIElement.sources": "window-chrome-geometry",
+ "localUIElement.actionEligibility": LocalUIElementActionEligibility.readOnlyEvidence.rawValue,
+ "target.windowID": String(target.windowID),
+ "target.appName": target.appName ?? "",
+ "target.bundleIdentifier": target.bundleIdentifier ?? "",
+ "target.title": target.title ?? "",
+ "coordinate.sourceSpace": "windowChromeGeometry",
+ "directInputActionsAllowed": "false"
+ ]
+ )
+ }
+ }
+
+ private static func isMacWindowControl(_ control: LocalUIUnderstandingControl) -> Bool {
+ let label = control.label
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ .lowercased()
+ return ["close", "minimize", "zoom", "fullscreen", "full screen"].contains(label)
+ }
+
+ public static func overlayBoundingBox(
+ for rect: HotLoopRect,
+ target: MacWindowTargetCandidate,
+ capturePixelSize: HotLoopSize,
+ screenFrame: WindowTargetBounds,
+ flipWindowY: Bool = false
+ ) -> DebugUIBoundingBox? {
+ guard rect.hasPositiveArea,
+ target.bounds.hasPositiveArea,
+ screenFrame.hasPositiveArea,
+ capturePixelSize.width > 0,
+ capturePixelSize.height > 0
+ else {
+ return nil
+ }
+
+ let localRect: WindowTargetBounds
+ switch rect.space {
+ case .window, .crop:
+ localRect = WindowTargetBounds(
+ x: rect.origin.x / capturePixelSize.width * target.bounds.width,
+ y: rect.origin.y / capturePixelSize.height * target.bounds.height,
+ width: rect.size.width / capturePixelSize.width * target.bounds.width,
+ height: rect.size.height / capturePixelSize.height * target.bounds.height
+ )
+ case .normalizedTarget:
+ localRect = WindowTargetBounds(
+ x: rect.origin.x * target.bounds.width,
+ y: rect.origin.y * target.bounds.height,
+ width: rect.size.width * target.bounds.width,
+ height: rect.size.height * target.bounds.height
+ )
+ case .screen:
+ return clippedBoundingBox(
+ WindowTargetBounds(
+ x: rect.origin.x,
+ y: rect.origin.y,
+ width: rect.size.width,
+ height: rect.size.height
+ ),
+ screenFrame: screenFrame
+ )
+ }
+
+ return clippedBoundingBox(
+ WindowTargetBounds(
+ x: target.bounds.x + localRect.x,
+ y: target.bounds.y + mappedWindowY(
+ localRect,
+ targetHeight: target.bounds.height,
+ flipWindowY: flipWindowY
+ ),
+ width: localRect.width,
+ height: localRect.height
+ ),
+ screenFrame: screenFrame
+ )
+ }
+
+ private static func mappedWindowY(
+ _ localRect: WindowTargetBounds,
+ targetHeight: Double,
+ flipWindowY: Bool
+ ) -> Double {
+ guard flipWindowY else {
+ return localRect.y
+ }
+
+ return max(0, targetHeight - localRect.y - localRect.height)
+ }
+
+ private static func clippedBoundingBox(
+ _ bounds: WindowTargetBounds,
+ screenFrame: WindowTargetBounds
+ ) -> DebugUIBoundingBox? {
+ let minX = max(bounds.x, screenFrame.x)
+ let minY = max(bounds.y, screenFrame.y)
+ let maxX = min(bounds.x + bounds.width, screenFrame.x + screenFrame.width)
+ let maxY = min(bounds.y + bounds.height, screenFrame.y + screenFrame.height)
+ let width = maxX - minX
+ let height = maxY - minY
+ guard width > 0, height > 0 else {
+ return nil
+ }
+
+ return DebugUIBoundingBox(
+ x: minX - screenFrame.x,
+ y: minY - screenFrame.y,
+ width: width,
+ height: height
+ )
+ }
+
+ private static func elementType(for kind: LocalAppControlKind) -> DebugUIElementType {
+ switch kind {
+ case .button:
+ return .button
+ case .textField, .searchField:
+ return .input
+ case .checkbox:
+ return .checkbox
+ case .link:
+ return .link
+ case .menuItem:
+ return .menuItem
+ case .listItem:
+ return .listItem
+ case .group, .unknown:
+ return .other
+ }
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
index f4acb247..ec739c6a 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
@@ -1144,6 +1144,8 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
"observer": "mac-local-app-controller",
"observation.source": "screenshot",
"verificationTextKey": verificationKey,
+ "screenshot.scope": "targetWindow",
+ "screenshot.desktopCaptureAllowed": "false",
"target.windowID": String(target.windowID),
"capture.method": screenshot.captureMethod.rawValue
].merging(LocalAppObservationGeometry.targetBoundsMetadata(target.bounds)) { current, _ in current }
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift
index 3a3b91a7..7c7bb883 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift
@@ -112,8 +112,6 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
targets: [MacWindowTargetCandidate],
minConfidence: Double
) -> [DebugUIAccessibilityInspectionResult] {
- let screenshotsByScreenID = (try? screenCapturer.captureScreens(scope: screens.count > 1 ? .all : .main))
- .map { Dictionary(uniqueKeysWithValues: $0.map { ($0.screenID, $0) }) } ?? [:]
let candidatesByScreenID = accessibilityCandidatesByScreen(
screens: screens,
targets: targets
@@ -134,7 +132,7 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
elements: []
)
)
- let snapshot = screenshotsByScreenID[screen.screenID] ?? fallbackSnapshot
+ let snapshot = fallbackSnapshot
let accessibilityCandidates = Self.scaleCandidates(
candidatesByScreenID[screen.screenID] ?? [],
from: screen.captureFrame,
@@ -144,14 +142,14 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
let trace = elementDetectionService.detect(
LocalUIElementDetectionRequest(
traceID: "debug-ui-local-\(screen.screenID)-\(snapshot.fingerprint)",
- screenshotPNGData: snapshot.pngData.isEmpty ? nil : snapshot.pngData,
+ screenshotPNGData: nil,
pixelSize: snapshot.pixelSize,
accessibilityCandidates: accessibilityCandidates,
minConfidence: minConfidence,
metadata: [
"screen.id": String(screen.screenID),
"screen.scope": screens.count > 1 ? "all" : "main",
- "provider": DebugUIInspectionProvider.accessibility.rawValue
+ "donkeyVision.local": "accessibility"
]
)
)
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift
index 15ac33ce..23662b54 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift
@@ -8,7 +8,7 @@ import UniformTypeIdentifiers
public struct DebugUIOverlayConfiguration: Equatable, Sendable {
public var enabled: Bool
- public var provider: DebugUIInspectionProvider
+ public var mode: String
public var cadenceSeconds: TimeInterval
public var screenScope: DebugUIInspectionScreenScope
public var minConfidence: Double
@@ -18,7 +18,7 @@ public struct DebugUIOverlayConfiguration: Equatable, Sendable {
public init(
enabled: Bool = false,
- provider: DebugUIInspectionProvider = .accessibility,
+ mode: String = "donkeyVision",
cadenceSeconds: TimeInterval = 1.0,
screenScope: DebugUIInspectionScreenScope = .main,
minConfidence: Double = 0.25,
@@ -27,7 +27,7 @@ public struct DebugUIOverlayConfiguration: Equatable, Sendable {
targetAppNames: [String] = []
) {
self.enabled = enabled
- self.provider = provider
+ self.mode = mode.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? "donkeyVision" : mode
self.cadenceSeconds = min(max(cadenceSeconds, 0.25), 10.0)
self.screenScope = screenScope
self.minConfidence = min(max(minConfidence, 0), 1)
@@ -75,9 +75,10 @@ public struct DebugUIOverlayConfiguration: Equatable, Sendable {
return .disabled
}
+ let mode = raw.mode?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return DebugUIOverlayConfiguration(
enabled: raw.enabled ?? false,
- provider: raw.provider.flatMap(DebugUIInspectionProvider.init(rawValue:)) ?? .accessibility,
+ mode: mode.isEmpty ? "donkeyVision" : mode,
cadenceSeconds: raw.cadenceSeconds ?? 1.0,
screenScope: raw.screenScope.flatMap(DebugUIInspectionScreenScope.init(rawValue:)) ?? .main,
minConfidence: raw.minConfidence ?? 0.25,
@@ -152,7 +153,7 @@ public struct DebugUIOverlayConfiguration: Equatable, Sendable {
private struct RawDebugUIOverlayConfiguration: Codable {
var enabled: Bool?
- var provider: String?
+ var mode: String?
var cadenceSeconds: TimeInterval?
var screenScope: String?
var minConfidence: Double?
@@ -189,7 +190,11 @@ public struct DebugUIElementTracker: Equatable, Sendable {
self.movementConfirmationSamples = max(1, movementConfirmationSamples)
}
- public mutating func update(with frame: DebugUIInspectionFrame) -> DebugUIInspectionFrame {
+ public mutating func update(
+ with frame: DebugUIInspectionFrame,
+ renderNewElementsImmediately: Bool = false
+ ) -> DebugUIInspectionFrame {
+ let isInitialObservation = previousElements.isEmpty && lastObservedElements.isEmpty
var usedPreviousIDs = Set<String>()
let matchBase = semanticMatchBase()
var trackedCandidates: [DebugUIElement] = []
@@ -223,19 +228,27 @@ public struct DebugUIElementTracker: Equatable, Sendable {
let trackedIDs = Set(trackedCandidates.map(\.id))
var rendered: [DebugUIElement] = []
- for candidate in trackedCandidates {
- if previousElements.contains(where: { $0.id == candidate.id }) {
+ if isInitialObservation {
+ rendered = trackedCandidates
+ for candidate in trackedCandidates {
appearanceCounts[candidate.id] = appearanceThreshold
missingCounts[candidate.id] = nil
- rendered.append(candidate)
- continue
}
+ } else {
+ 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)
+ let count = min(appearanceThreshold, (appearanceCounts[candidate.id] ?? 0) + 1)
+ appearanceCounts[candidate.id] = count
+ missingCounts[candidate.id] = nil
+ if renderNewElementsImmediately || count >= appearanceThreshold {
+ rendered.append(candidate)
+ }
}
}
@@ -556,7 +569,7 @@ public enum DebugUIOverlayGeometry {
let scaleY = screenPointSize.height / screenshotPixelSize.height
return CGRect(
x: bbox.x * scaleX,
- y: screenPointSize.height - (bbox.y + bbox.height) * scaleY,
+ y: bbox.y * scaleY,
width: bbox.width * scaleX,
height: bbox.height * scaleY
)
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/GenericBorderUIDetector.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/GenericBorderUIDetector.swift
new file mode 100644
index 00000000..f47ff20e
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/GenericBorderUIDetector.swift
@@ -0,0 +1,972 @@
+import Foundation
+
+struct GenericBorderUIBox: Codable, Equatable, Sendable {
+ var id: Int
+ var x1: Int
+ var y1: Int
+ var x2: Int
+ var y2: Int
+ var text: String
+ var kind: String
+ var confidence: Double
+ var source: String
+ var borderStrength: Double
+ var fillDensity: Double
+ var childCount: Int
+ var textCount: Int
+
+ var width: Int { max(0, x2 - x1) }
+ var height: Int { max(0, y2 - y1) }
+ var area: Int { width * height }
+}
+
+struct GenericBorderUIDetectionResult: Equatable, Sendable {
+ var boxes: [GenericBorderUIBox]
+ var summary: String
+}
+
+struct GenericBorderUIDetector: Sendable {
+ private var magickPath: String?
+ private var tesseractPath: String?
+ private var useOCR: Bool
+ private var inferRowsInsideContainers: Bool
+ private var maxBoxes: Int
+
+ init(
+ magickPath: String? = nil,
+ tesseractPath: String? = nil,
+ useOCR: Bool = true,
+ inferRowsInsideContainers: Bool = true,
+ maxBoxes: Int = 350
+ ) {
+ self.magickPath = magickPath
+ self.tesseractPath = tesseractPath
+ self.useOCR = useOCR
+ self.inferRowsInsideContainers = inferRowsInsideContainers
+ self.maxBoxes = maxBoxes
+ }
+
+ func detect(
+ inputURL: URL,
+ outputDirectory: URL
+ ) throws -> GenericBorderUIDetectionResult {
+ guard FileManager.default.fileExists(atPath: inputURL.path) else {
+ throw GenericBorderUIDetectorError.noFile(inputURL.path)
+ }
+ try FileManager.default.createDirectory(at: outputDirectory, withIntermediateDirectories: true)
+
+ let size = try readPNGSize(inputURL)
+ let magick = executablePath(
+ preferred: magickPath ?? "magick",
+ env: "DONKEY_MAGICK_PATH",
+ fallbacks: ["/opt/homebrew/bin/magick", "/usr/local/bin/magick", "/opt/imagemagick/bin/magick"]
+ )
+ let preprocessed = try preprocess(input: inputURL, outDir: outputDirectory, magick: magick)
+ let words = runOCRIfAvailable(input: inputURL)
+
+ var boxes = extractVisualCandidates(
+ gray: preprocessed.gray,
+ edge: preprocessed.edge,
+ size: size,
+ minBoxArea: 36
+ )
+ boxes = attachTextAndCounts(boxes: boxes, words: words)
+ boxes = computeChildCounts(boxes)
+ boxes = classifyBoxes(boxes: boxes, size: size)
+
+ if inferRowsInsideContainers {
+ let rowBoxes = inferRowsInsideContainers(boxes: boxes, words: words, size: size)
+ boxes.append(contentsOf: rowBoxes)
+ boxes = attachTextAndCounts(boxes: boxes, words: words)
+ boxes = computeChildCounts(boxes)
+ boxes = classifyBoxes(boxes: boxes, size: size)
+ }
+
+ boxes = dedupeAndPrune(boxes, size: size, maxBoxes: maxBoxes)
+
+ let jsonURL = outputDirectory.appendingPathComponent("border_boxes.json")
+ let csvURL = outputDirectory.appendingPathComponent("border_boxes.csv")
+ let svgURL = outputDirectory.appendingPathComponent("border_overlay.svg")
+ try writeJSON(boxes, jsonURL)
+ try writeCSV(boxes, csvURL)
+ try writeSVG(input: inputURL, size: size, boxes: boxes, to: svgURL)
+
+ return GenericBorderUIDetectionResult(
+ boxes: boxes,
+ summary: [
+ "status=ok",
+ "image=\(size.width)x\(size.height)",
+ "boxes=\(boxes.count)",
+ "json=\(jsonURL.path)",
+ "csv=\(csvURL.path)",
+ "svg=\(svgURL.path)",
+ "preprocessed=\(preprocessed.highContrastURL.path)"
+ ].joined(separator: "\n")
+ )
+ }
+
+ private func executablePath(
+ preferred: String,
+ env: String,
+ fallbacks: [String]
+ ) -> String {
+ let fm = FileManager.default
+ if let override = ProcessInfo.processInfo.environment[env],
+ fm.isExecutableFile(atPath: override) {
+ return override
+ }
+ if preferred.contains("/"), fm.isExecutableFile(atPath: preferred) {
+ return preferred
+ }
+ if !preferred.contains("/") {
+ for prefix in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"] {
+ let candidate = "\(prefix)/\(preferred)"
+ if fm.isExecutableFile(atPath: candidate) {
+ return candidate
+ }
+ }
+ }
+ for fallback in fallbacks where fm.isExecutableFile(atPath: fallback) {
+ return fallback
+ }
+ return preferred
+ }
+
+ private func shell(_ executable: String, _ args: [String]) throws -> String {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: executable)
+ process.arguments = args
+ let outPipe = Pipe()
+ let errPipe = Pipe()
+ process.standardOutput = outPipe
+ process.standardError = errPipe
+ try process.run()
+ process.waitUntilExit()
+
+ let stdout = String(data: outPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
+ let stderr = String(data: errPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
+ if process.terminationStatus != 0 {
+ throw GenericBorderUIDetectorError.commandFailed(
+ ([executable] + args).joined(separator: " "),
+ process.terminationStatus,
+ stderr
+ )
+ }
+ return stdout
+ }
+
+ private func readPNGSize(_ url: URL) throws -> BorderImageSize {
+ let data = try Data(contentsOf: url)
+ guard data.count >= 24 && Array(data[0..<8]) == [137, 80, 78, 71, 13, 10, 26, 10] else {
+ throw GenericBorderUIDetectorError.badPNG(url.path)
+ }
+ func be32(_ i: Int) -> UInt32 {
+ (UInt32(data[i]) << 24)
+ | (UInt32(data[i + 1]) << 16)
+ | (UInt32(data[i + 2]) << 8)
+ | UInt32(data[i + 3])
+ }
+ return BorderImageSize(width: Int(be32(16)), height: Int(be32(20)))
+ }
+
+ private func parsePGM(_ url: URL) throws -> BorderPixelImage {
+ let data = try Data(contentsOf: url)
+ var i = 0
+ func isASCIIWhitespace(_ b: UInt8) -> Bool {
+ b == 9 || b == 10 || b == 11 || b == 12 || b == 13 || b == 32
+ }
+ func nextToken() -> String? {
+ while i < data.count {
+ if data[i] == 35 {
+ while i < data.count && data[i] != 10 { i += 1 }
+ continue
+ }
+ if isASCIIWhitespace(data[i]) {
+ i += 1
+ continue
+ }
+ break
+ }
+ guard i < data.count else { return nil }
+ let start = i
+ while i < data.count && !isASCIIWhitespace(data[i]) { i += 1 }
+ return String(data: data[start..<i], encoding: .ascii)
+ }
+
+ guard nextToken() == "P5",
+ let widthToken = nextToken(),
+ let heightToken = nextToken(),
+ let maxToken = nextToken(),
+ let width = Int(widthToken),
+ let height = Int(heightToken),
+ let maxValue = Int(maxToken),
+ maxValue <= 255
+ else {
+ throw GenericBorderUIDetectorError.badPGM(url.path)
+ }
+
+ if i < data.count && isASCIIWhitespace(data[i]) { i += 1 }
+ let expected = width * height
+ guard data.count - i >= expected else {
+ throw GenericBorderUIDetectorError.badPGM(url.path)
+ }
+ return BorderPixelImage(width: width, height: height, pixels: Array(data[i..<(i + expected)]))
+ }
+
+ private func preprocess(
+ input: URL,
+ outDir: URL,
+ magick: String
+ ) throws -> (gray: BorderPixelImage, edge: BorderPixelImage, highContrastURL: URL) {
+ let grayPGM = outDir.appendingPathComponent("border_gray.pgm")
+ let edgePGM = outDir.appendingPathComponent("border_edges.pgm")
+ let highContrast = outDir.appendingPathComponent("border_preprocessed_high_contrast.png")
+
+ _ = try shell(magick, [input.path, "-colorspace", "Gray", "-depth", "8", grayPGM.path])
+ _ = try shell(magick, [
+ input.path,
+ "-colorspace", "Gray",
+ "-contrast-stretch", "1%x1%",
+ "-sharpen", "0x0.8",
+ highContrast.path
+ ])
+ _ = try shell(magick, [
+ input.path,
+ "-colorspace", "Gray",
+ "-contrast-stretch", "1%x1%",
+ "-blur", "0x0.6",
+ "-edge", "1",
+ "-negate",
+ "-threshold", "70%",
+ "-morphology", "Dilate", "Rectangle:2x2",
+ "-morphology", "Close", "Rectangle:5x3",
+ "-depth", "8",
+ edgePGM.path
+ ])
+
+ return (try parsePGM(grayPGM), try parsePGM(edgePGM), highContrast)
+ }
+
+ private func runOCRIfAvailable(input: URL) -> [BorderOCRWord] {
+ guard useOCR else { return [] }
+ let tesseract = executablePath(
+ preferred: tesseractPath ?? "tesseract",
+ env: "DONKEY_TESSERACT_PATH",
+ fallbacks: ["/opt/homebrew/bin/tesseract", "/usr/local/bin/tesseract", "/usr/bin/tesseract"]
+ )
+ guard FileManager.default.isExecutableFile(atPath: tesseract) else { return [] }
+ do {
+ let tsv = try shell(tesseract, [input.path, "stdout", "--psm", "11", "tsv"])
+ return parseTesseractTSV(tsv)
+ } catch {
+ return []
+ }
+ }
+
+ private func parseTesseractTSV(_ tsv: String) -> [BorderOCRWord] {
+ var words: [BorderOCRWord] = []
+ for (lineIndex, rawLine) in tsv.split(separator: "\n", omittingEmptySubsequences: false).enumerated() {
+ if lineIndex == 0 { continue }
+ let cols = rawLine.split(separator: "\t", omittingEmptySubsequences: false).map(String.init)
+ if cols.count < 12 { continue }
+ guard cols[0] == "5",
+ let x = Int(cols[6]),
+ let y = Int(cols[7]),
+ let w = Int(cols[8]),
+ let h = Int(cols[9]),
+ let conf = Double(cols[10])
+ else { continue }
+ let text = cols[11].trimmingCharacters(in: .whitespacesAndNewlines)
+ if text.isEmpty || conf < 20 || w <= 0 || h <= 0 { continue }
+ words.append(BorderOCRWord(text: text, confidence: conf / 100.0, x: x, y: y, w: w, h: h))
+ }
+ return words
+ }
+
+ private func connectedComponents(
+ image: BorderPixelImage,
+ predicate: (UInt8) -> Bool,
+ minArea: Int
+ ) -> [BorderConnectedComponent] {
+ let width = image.width
+ let height = image.height
+ var visited = Array(repeating: false, count: width * height)
+ var result: [BorderConnectedComponent] = []
+ let dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
+
+ for y in 0..<height {
+ for x in 0..<width {
+ let startIndex = y * width + x
+ if visited[startIndex] || !predicate(image.pixels[startIndex]) { continue }
+
+ var queue: [(Int, Int)] = [(x, y)]
+ var head = 0
+ visited[startIndex] = true
+ var minX = x, maxX = x, minY = y, maxY = y, area = 0
+
+ while head < queue.count {
+ let (cx, cy) = queue[head]
+ head += 1
+ area += 1
+ minX = min(minX, cx); maxX = max(maxX, cx)
+ minY = min(minY, cy); maxY = max(maxY, cy)
+
+ for (dx, dy) in dirs {
+ let nx = cx + dx
+ let ny = cy + dy
+ if nx < 0 || ny < 0 || nx >= width || ny >= height { continue }
+ let ni = ny * width + nx
+ if visited[ni] || !predicate(image.pixels[ni]) { continue }
+ visited[ni] = true
+ queue.append((nx, ny))
+ }
+ }
+
+ if area >= minArea {
+ result.append(
+ BorderConnectedComponent(
+ x: minX,
+ y: minY,
+ w: maxX - minX + 1,
+ h: maxY - minY + 1,
+ area: area
+ )
+ )
+ }
+ }
+ }
+
+ return result
+ }
+
+ private func extractVisualCandidates(
+ gray: BorderPixelImage,
+ edge: BorderPixelImage,
+ size: BorderImageSize,
+ minBoxArea: Int
+ ) -> [GenericBorderUIBox] {
+ var boxes: [GenericBorderUIBox] = []
+
+ let edgeComponents = connectedComponents(image: edge, predicate: { $0 > 160 }, minArea: minBoxArea)
+ for component in edgeComponents {
+ if let box = componentToBox(component, source: "edgeComponent", size: size, edge: edge, gray: gray) {
+ boxes.append(box)
+ }
+ }
+
+ let bands: [(UInt8, UInt8)] = [
+ (0, 24), (25, 48), (49, 72), (73, 96), (97, 124),
+ (125, 154), (155, 184), (185, 214), (215, 255)
+ ]
+ for (low, high) in bands {
+ let components = connectedComponents(
+ image: gray,
+ predicate: { $0 >= low && $0 <= high },
+ minArea: max(minBoxArea, 80)
+ )
+ for component in components {
+ if let box = componentToBox(component, source: "filledSurface", size: size, edge: edge, gray: gray) {
+ boxes.append(box)
+ }
+ }
+ }
+
+ return boxes
+ }
+
+ private func componentToBox(
+ _ component: BorderConnectedComponent,
+ source: String,
+ size: BorderImageSize,
+ edge: BorderPixelImage,
+ gray: BorderPixelImage
+ ) -> GenericBorderUIBox? {
+ let area = component.w * component.h
+ if component.w < 4 || component.h < 4 { return nil }
+ if area < 36 { return nil }
+ if component.w > Int(Double(size.width) * 0.985) && component.h > Int(Double(size.height) * 0.90) { return nil }
+ if area > Int(Double(size.width * size.height) * 0.72) { return nil }
+
+ let aspect = Double(component.w) / Double(max(1, component.h))
+ if aspect > 45 || aspect < 0.025 { return nil }
+
+ var box = GenericBorderUIBox(
+ id: 0,
+ x1: component.x,
+ y1: component.y,
+ x2: component.x2,
+ y2: component.y2,
+ text: "",
+ kind: "unknownControl",
+ confidence: 0.35,
+ source: source,
+ borderStrength: 0,
+ fillDensity: component.density,
+ childCount: 0,
+ textCount: 0
+ )
+
+ box = expanded(box, by: source == "edgeComponent" ? 2 : 1, size: size)
+ box.borderStrength = perimeterEdgeStrength(box: box, edge: edge)
+ let contrast = surroundingContrast(box: box, gray: gray)
+ let screenArea = Double(size.width * size.height)
+ let areaRatio = Double(box.area) / screenArea
+ let smallSquareish = box.width >= 8
+ && box.width <= max(80, size.width / 18)
+ && box.height >= 8
+ && box.height <= max(80, size.height / 18)
+ && aspect > 0.55
+ && aspect < 1.8
+ let controlLike = box.height >= max(12, size.height / 160)
+ && box.height <= max(96, size.height / 12)
+ && box.width >= 8
+ let surfaceLooksReal = source == "filledSurface"
+ && component.density >= 0.52
+ && (contrast > 0.025 || areaRatio > 0.002)
+ let edgeLooksReal = source == "edgeComponent"
+ && (box.borderStrength > 0.08 || smallSquareish)
+
+ if !surfaceLooksReal && !edgeLooksReal { return nil }
+ if areaRatio < 0.000004 && !smallSquareish { return nil }
+ if !controlLike && areaRatio < 0.00008 { return nil }
+
+ box.confidence = min(0.95, 0.30 + box.borderStrength * 0.8 + contrast * 0.6 + min(0.2, component.density * 0.15))
+ return box
+ }
+
+ private func attachTextAndCounts(
+ boxes: [GenericBorderUIBox],
+ words: [BorderOCRWord]
+ ) -> [GenericBorderUIBox] {
+ var out = boxes
+ for index in out.indices {
+ let inside = textInside(out[index], words: words)
+ out[index].textCount = inside.count
+ if out[index].text.isEmpty {
+ out[index].text = labelForBox(out[index], words: words)
+ }
+ }
+ return out
+ }
+
+ private func computeChildCounts(_ boxes: [GenericBorderUIBox]) -> [GenericBorderUIBox] {
+ var out = boxes
+ for i in out.indices {
+ var count = 0
+ for j in out.indices where i != j {
+ if out[j].area < out[i].area && contains(out[i], out[j], padding: 3) {
+ if Double(out[j].area) / Double(max(1, out[i].area)) < 0.80 {
+ count += 1
+ }
+ }
+ }
+ out[i].childCount = count
+ }
+ return out
+ }
+
+ private func classifyBoxes(
+ boxes: [GenericBorderUIBox],
+ size: BorderImageSize
+ ) -> [GenericBorderUIBox] {
+ let screenArea = Double(size.width * size.height)
+ let W = Double(size.width)
+ let H = Double(size.height)
+
+ return boxes.map { original in
+ var box = original
+ let areaRatio = Double(box.area) / screenArea
+ let aspect = Double(box.width) / Double(max(1, box.height))
+ let h = Double(box.height)
+ let w = Double(box.width)
+ let isSmallSquareish = aspect >= 0.55
+ && aspect <= 1.85
+ && w >= 8
+ && h >= 8
+ && w <= max(88, W * 0.055)
+ && h <= max(88, H * 0.070)
+ let isControlHeight = h >= max(12, H * 0.010) && h <= max(96, H * 0.075)
+ let isWideControl = isControlHeight && aspect >= 1.7
+ let hasText = box.textCount > 0 || !box.text.isEmpty
+ let hasChildren = box.childCount >= 2
+ let strongBorder = box.borderStrength > 0.13
+ let filledSurface = box.source == "filledSurface" && box.fillDensity > 0.52
+
+ if areaRatio > 0.075 && hasChildren {
+ box.kind = "section"
+ box.confidence = max(box.confidence, 0.72)
+ } else if areaRatio > 0.018 && (hasChildren || filledSurface) {
+ box.kind = "panel"
+ box.confidence = max(box.confidence, 0.68)
+ } else if areaRatio > 0.0045 && (hasChildren || hasText) && aspect < 12 {
+ box.kind = "card"
+ box.confidence = max(box.confidence, 0.62)
+ } else if isSmallSquareish && (strongBorder || filledSurface || box.source == "edgeComponent") {
+ box.kind = "iconButton"
+ box.confidence = max(box.confidence, 0.58)
+ } else if isWideControl && aspect >= 4.0 && (strongBorder || filledSurface) && hasText {
+ box.kind = "textField"
+ box.confidence = max(box.confidence, 0.64)
+ } else if isWideControl && aspect >= 1.35 && aspect <= 12.0 && (strongBorder || filledSurface) {
+ box.kind = hasText ? "button" : "unknownControl"
+ box.confidence = max(box.confidence, hasText ? 0.62 : 0.46)
+ } else if aspect >= 3.0 && h <= max(72, H * 0.065) && hasText {
+ box.kind = "row"
+ box.confidence = max(box.confidence, 0.56)
+ } else if hasChildren {
+ box.kind = "controlGroup"
+ box.confidence = max(box.confidence, 0.55)
+ } else {
+ box.kind = "unknownControl"
+ }
+ return box
+ }
+ }
+
+ private func inferRowsInsideContainers(
+ boxes: [GenericBorderUIBox],
+ words: [BorderOCRWord],
+ size: BorderImageSize
+ ) -> [GenericBorderUIBox] {
+ if words.isEmpty { return [] }
+
+ let visualContainers = boxes.filter { box in
+ ["section", "panel", "card", "controlGroup"].contains(box.kind)
+ && box.area > Int(Double(size.width * size.height) * 0.002)
+ }
+ var inferred: [GenericBorderUIBox] = []
+
+ for container in visualContainers {
+ let localWords = words.filter { word in
+ containsPoint(container, x: word.cx, y: word.cy, padding: -2)
+ }
+ if localWords.count < 2 { continue }
+
+ let rows = groupWordsIntoRows(localWords)
+ for rowWords in rows {
+ if rowWords.isEmpty { continue }
+ let x1 = rowWords.map(\.x).min() ?? 0
+ let y1 = rowWords.map(\.y).min() ?? 0
+ let x2 = rowWords.map(\.x2).max() ?? 0
+ let y2 = rowWords.map(\.y2).max() ?? 0
+ let text = rowWords.sorted { $0.x < $1.x }.map(\.text).joined(separator: " ")
+ let height = y2 - y1
+ let width = x2 - x1
+ if text.count < 2 || height < 8 || width < 12 { continue }
+
+ let padX = max(8, min(28, container.width / 24))
+ let padY = max(5, min(12, container.height / 50))
+ let rowBox = GenericBorderUIBox(
+ id: 0,
+ x1: max(container.x1 + 1, x1 - padX),
+ y1: max(container.y1 + 1, y1 - padY),
+ x2: min(container.x2 - 1, x2 + padX),
+ y2: min(container.y2 - 1, y2 + padY),
+ text: String(text.prefix(140)),
+ kind: "row",
+ confidence: min(0.86, 0.45 + rowWords.map(\.confidence).reduce(0, +) / Double(max(1, rowWords.count)) * 0.35),
+ source: "containerRowInference",
+ borderStrength: 0,
+ fillDensity: 0,
+ childCount: 0,
+ textCount: rowWords.count
+ )
+
+ if Double(rowBox.area) / Double(max(1, container.area)) > 0.75 { continue }
+ if rowBox.height > max(80, container.height / 3) { continue }
+ inferred.append(rowBox)
+ }
+ }
+
+ return inferred
+ }
+
+ private func groupWordsIntoRows(
+ _ words: [BorderOCRWord],
+ rowTolerance: Int = 10,
+ maxGap: Int = 48
+ ) -> [[BorderOCRWord]] {
+ let sorted = words.sorted {
+ if abs($0.cy - $1.cy) > rowTolerance { return $0.cy < $1.cy }
+ return $0.x < $1.x
+ }
+
+ var rows: [[BorderOCRWord]] = []
+ for word in sorted {
+ if rows.isEmpty {
+ rows.append([word])
+ continue
+ }
+ let lastIndex = rows.count - 1
+ let center = rows[lastIndex].map(\.cy).reduce(0, +) / max(1, rows[lastIndex].count)
+ let medianH = rows[lastIndex].map(\.h).sorted()[rows[lastIndex].count / 2]
+ let tolerance = max(rowTolerance, medianH / 2 + 4)
+ if abs(word.cy - center) <= tolerance {
+ rows[lastIndex].append(word)
+ } else {
+ rows.append([word])
+ }
+ }
+
+ var splitRows: [[BorderOCRWord]] = []
+ for row in rows {
+ let sortedRow = row.sorted { $0.x < $1.x }
+ var current: [BorderOCRWord] = []
+ for word in sortedRow {
+ if current.isEmpty {
+ current.append(word)
+ continue
+ }
+ let previous = current.last!
+ let gap = word.x - previous.x2
+ let localMaxGap = max(maxGap, max(previous.h, word.h) * 3)
+ if gap > localMaxGap {
+ splitRows.append(current)
+ current = [word]
+ } else {
+ current.append(word)
+ }
+ }
+ if !current.isEmpty { splitRows.append(current) }
+ }
+ return splitRows
+ }
+
+ private func dedupeAndPrune(
+ _ input: [GenericBorderUIBox],
+ size: BorderImageSize,
+ maxBoxes: Int
+ ) -> [GenericBorderUIBox] {
+ func priority(_ box: GenericBorderUIBox) -> Int {
+ switch box.kind {
+ case "section": return 20
+ case "panel": return 19
+ case "card": return 18
+ case "textField": return 17
+ case "button": return 16
+ case "iconButton": return 15
+ case "row": return 14
+ case "controlGroup": return 10
+ case "menuItem": return 9
+ default: return 1
+ }
+ }
+
+ let sorted = input
+ .filter { $0.area >= 24 && !isLikelyGlyphFragment($0) }
+ .sorted {
+ if priority($0) != priority($1) { return priority($0) > priority($1) }
+ if abs($0.confidence - $1.confidence) > 0.001 { return $0.confidence > $1.confidence }
+ return $0.area > $1.area
+ }
+
+ var kept: [GenericBorderUIBox] = []
+ for candidate in sorted {
+ var suppress = false
+ for existing in kept {
+ let overlap = iou(candidate, existing)
+ let contained = contains(existing, candidate, padding: 3)
+ let containsExisting = contains(candidate, existing, padding: 3)
+ if overlap > 0.78 {
+ suppress = true
+ break
+ }
+ if contained {
+ if shouldPreserveNested(candidate) {
+ suppress = false
+ continue
+ }
+ if candidate.kind == existing.kind || isLikelyGlyphFragment(candidate) {
+ suppress = true
+ break
+ }
+ }
+ if containsExisting && shouldPreserveNested(existing) && candidate.kind == "unknownControl" {
+ suppress = true
+ break
+ }
+ }
+ if !suppress {
+ kept.append(candidate)
+ if kept.count >= maxBoxes { break }
+ }
+ }
+
+ var final = kept.sorted {
+ if $0.y1 == $1.y1 { return $0.x1 < $1.x1 }
+ return $0.y1 < $1.y1
+ }
+ for index in final.indices { final[index].id = index + 1 }
+ return final
+ }
+
+ private func iou(_ a: GenericBorderUIBox, _ b: GenericBorderUIBox) -> Double {
+ let ix1 = max(a.x1, b.x1)
+ let iy1 = max(a.y1, b.y1)
+ let ix2 = min(a.x2, b.x2)
+ let iy2 = min(a.y2, b.y2)
+ let inter = max(0, ix2 - ix1) * max(0, iy2 - iy1)
+ let union = a.area + b.area - inter
+ return union > 0 ? Double(inter) / Double(union) : 0
+ }
+
+ private func contains(_ outer: GenericBorderUIBox, _ inner: GenericBorderUIBox, padding: Int = 0) -> Bool {
+ outer.x1 - padding <= inner.x1
+ && outer.y1 - padding <= inner.y1
+ && outer.x2 + padding >= inner.x2
+ && outer.y2 + padding >= inner.y2
+ }
+
+ private func containsPoint(_ box: GenericBorderUIBox, x: Int, y: Int, padding: Int = 0) -> Bool {
+ x >= box.x1 - padding && x <= box.x2 + padding && y >= box.y1 - padding && y <= box.y2 + padding
+ }
+
+ private func expanded(_ box: GenericBorderUIBox, by pad: Int, size: BorderImageSize) -> GenericBorderUIBox {
+ var out = box
+ out.x1 = clamp(box.x1 - pad, 0, size.width)
+ out.y1 = clamp(box.y1 - pad, 0, size.height)
+ out.x2 = clamp(box.x2 + pad, 0, size.width)
+ out.y2 = clamp(box.y2 + pad, 0, size.height)
+ return out
+ }
+
+ private func perimeterEdgeStrength(box: GenericBorderUIBox, edge: BorderPixelImage) -> Double {
+ if box.width <= 1 || box.height <= 1 { return 0 }
+ let x1 = clamp(box.x1, 0, edge.width - 1)
+ let y1 = clamp(box.y1, 0, edge.height - 1)
+ let x2 = clamp(box.x2 - 1, 0, edge.width - 1)
+ let y2 = clamp(box.y2 - 1, 0, edge.height - 1)
+ if x2 <= x1 || y2 <= y1 { return 0 }
+
+ var hits = 0
+ var total = 0
+ func sample(_ x: Int, _ y: Int) {
+ total += 1
+ if edge.value(x: x, y: y) > 160 { hits += 1 }
+ }
+ for x in x1...x2 {
+ sample(x, y1)
+ sample(x, y2)
+ }
+ for y in y1...y2 {
+ sample(x1, y)
+ sample(x2, y)
+ }
+ return total > 0 ? Double(hits) / Double(total) : 0
+ }
+
+ private func surroundingContrast(box: GenericBorderUIBox, gray: BorderPixelImage, padding: Int = 4) -> Double {
+ let innerX1 = clamp(box.x1, 0, gray.width - 1)
+ let innerY1 = clamp(box.y1, 0, gray.height - 1)
+ let innerX2 = clamp(box.x2, 0, gray.width)
+ let innerY2 = clamp(box.y2, 0, gray.height)
+ if innerX2 <= innerX1 || innerY2 <= innerY1 { return 0 }
+
+ var insideSum = 0
+ var insideN = 0
+ let stepX = max(1, (innerX2 - innerX1) / 20)
+ let stepY = max(1, (innerY2 - innerY1) / 20)
+ var y = innerY1
+ while y < innerY2 {
+ var x = innerX1
+ while x < innerX2 {
+ insideSum += Int(gray.value(x: x, y: y))
+ insideN += 1
+ x += stepX
+ }
+ y += stepY
+ }
+
+ let outerX1 = clamp(box.x1 - padding, 0, gray.width - 1)
+ let outerY1 = clamp(box.y1 - padding, 0, gray.height - 1)
+ let outerX2 = clamp(box.x2 + padding, 0, gray.width)
+ let outerY2 = clamp(box.y2 + padding, 0, gray.height)
+ var outsideSum = 0
+ var outsideN = 0
+
+ for x in outerX1..<outerX2 {
+ for yy in [outerY1, outerY2 - 1] where yy >= 0 && yy < gray.height {
+ outsideSum += Int(gray.value(x: x, y: yy))
+ outsideN += 1
+ }
+ }
+ for yy in outerY1..<outerY2 {
+ for x in [outerX1, outerX2 - 1] where x >= 0 && x < gray.width {
+ outsideSum += Int(gray.value(x: x, y: yy))
+ outsideN += 1
+ }
+ }
+
+ guard insideN > 0, outsideN > 0 else { return 0 }
+ let insideMean = Double(insideSum) / Double(insideN)
+ let outsideMean = Double(outsideSum) / Double(outsideN)
+ return abs(insideMean - outsideMean) / 255.0
+ }
+
+ private func textInside(_ box: GenericBorderUIBox, words: [BorderOCRWord]) -> [BorderOCRWord] {
+ words.filter { containsPoint(box, x: $0.cx, y: $0.cy, padding: 2) }
+ }
+
+ private func labelForBox(_ box: GenericBorderUIBox, words: [BorderOCRWord]) -> String {
+ let inside = textInside(box, words: words)
+ if inside.isEmpty { return "" }
+ let sorted = inside.sorted {
+ if abs($0.cy - $1.cy) > 8 { return $0.cy < $1.cy }
+ return $0.x < $1.x
+ }
+ let text = sorted.map(\.text).joined(separator: " ")
+ return text.count > 140 ? String(text.prefix(137)) + "..." : text
+ }
+
+ private func shouldPreserveNested(_ box: GenericBorderUIBox) -> Bool {
+ ["button", "iconButton", "textField", "row", "menuItem"].contains(box.kind)
+ }
+
+ private func isLikelyGlyphFragment(_ box: GenericBorderUIBox) -> Bool {
+ if box.kind == "iconButton" { return false }
+ if box.area < 80 { return true }
+ if box.width < 6 || box.height < 6 { return true }
+ if box.fillDensity < 0.20 && box.borderStrength < 0.05 && box.textCount == 0 { return true }
+ return false
+ }
+
+ private func clamp(_ value: Int, _ low: Int, _ high: Int) -> Int {
+ max(low, min(high, value))
+ }
+
+ private func color(_ kind: String) -> String {
+ switch kind {
+ case "section": return "#00C7BE"
+ case "panel": return "#64D2FF"
+ case "card": return "#FFD60A"
+ case "row": return "#34C759"
+ case "button": return "#FF9500"
+ case "iconButton": return "#FF2D55"
+ case "textField": return "#BF5AF2"
+ case "controlGroup": return "#5E5CE6"
+ case "menuItem": return "#0A84FF"
+ default: return "#8E8E93"
+ }
+ }
+
+ private func xml(_ string: String) -> String {
+ string
+ .replacingOccurrences(of: "&", with: "&amp;")
+ .replacingOccurrences(of: "<", with: "&lt;")
+ .replacingOccurrences(of: ">", with: "&gt;")
+ .replacingOccurrences(of: "\"", with: "&quot;")
+ }
+
+ private func writeJSON(_ boxes: [GenericBorderUIBox], _ url: URL) throws {
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ try encoder.encode(boxes).write(to: url)
+ }
+
+ private func writeCSV(_ boxes: [GenericBorderUIBox], _ url: URL) throws {
+ var lines = ["id,x1,y1,x2,y2,kind,confidence,text,source,borderStrength,fillDensity,childCount,textCount"]
+ for box in boxes {
+ let escaped = box.text.replacingOccurrences(of: "\"", with: "\"\"")
+ lines.append([
+ String(box.id),
+ String(box.x1),
+ String(box.y1),
+ String(box.x2),
+ String(box.y2),
+ box.kind,
+ String(format: "%.3f", box.confidence),
+ "\"\(escaped)\"",
+ box.source,
+ String(format: "%.3f", box.borderStrength),
+ String(format: "%.3f", box.fillDensity),
+ String(box.childCount),
+ String(box.textCount)
+ ].joined(separator: ","))
+ }
+ try lines.joined(separator: "\n").write(to: url, atomically: true, encoding: .utf8)
+ }
+
+ private func writeSVG(input: URL, size: BorderImageSize, boxes: [GenericBorderUIBox], to url: URL) throws {
+ let base64 = try Data(contentsOf: input).base64EncodedString()
+ var svg = """
+ <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"\(size.width)\" height=\"\(size.height)\" viewBox=\"0 0 \(size.width) \(size.height)\">
+ <image href=\"data:image/png;base64,\(base64)\" x=\"0\" y=\"0\" width=\"\(size.width)\" height=\"\(size.height)\" preserveAspectRatio=\"none\"/>
+ """
+ for box in boxes {
+ let color = color(box.kind)
+ let label = "\(box.id) \(box.kind)"
+ let title = "#\(box.id) \(box.kind) [\(box.x1),\(box.y1),\(box.x2),\(box.y2)] \(box.text)"
+ svg += "\n <g>"
+ svg += "\n <rect x=\"\(box.x1)\" y=\"\(box.y1)\" width=\"\(box.width)\" height=\"\(box.height)\" fill=\"none\" stroke=\"\(color)\" stroke-width=\"2\"/>"
+ svg += "\n <rect x=\"\(box.x1)\" y=\"\(max(0, box.y1 - 16))\" width=\"\(max(38, label.count * 7))\" height=\"14\" fill=\"#000000AA\"/>"
+ svg += "\n <text x=\"\(box.x1 + 2)\" y=\"\(max(11, box.y1 - 5))\" font-family=\"Arial, sans-serif\" font-size=\"11\" fill=\"\(color)\">\(xml(label))</text>"
+ svg += "\n <title>\(xml(title))</title>"
+ svg += "\n </g>"
+ }
+ svg += "\n</svg>\n"
+ try svg.write(to: url, atomically: true, encoding: .utf8)
+ }
+}
+
+private struct BorderImageSize: Equatable, Sendable {
+ var width: Int
+ var height: Int
+}
+
+private struct BorderPixelImage: Equatable, Sendable {
+ var width: Int
+ var height: Int
+ var pixels: [UInt8]
+
+ func value(x: Int, y: Int) -> UInt8 {
+ if x < 0 || y < 0 || x >= width || y >= height { return 0 }
+ return pixels[y * width + x]
+ }
+}
+
+private struct BorderConnectedComponent: Equatable, Sendable {
+ var x: Int
+ var y: Int
+ var w: Int
+ var h: Int
+ var area: Int
+
+ var x2: Int { x + w }
+ var y2: Int { y + h }
+ var bboxArea: Int { max(1, w * h) }
+ var density: Double { Double(area) / Double(bboxArea) }
+}
+
+private struct BorderOCRWord: Equatable, Sendable {
+ var text: String
+ var confidence: Double
+ var x: Int
+ var y: Int
+ var w: Int
+ var h: Int
+
+ var x2: Int { x + w }
+ var y2: Int { y + h }
+ var cx: Int { x + w / 2 }
+ var cy: Int { y + h / 2 }
+}
+
+private enum GenericBorderUIDetectorError: Error, CustomStringConvertible {
+ case noFile(String)
+ case commandFailed(String, Int32, String)
+ case badPNG(String)
+ case badPGM(String)
+
+ var description: String {
+ switch self {
+ case .noFile(let path):
+ return "File not found: \(path)"
+ case .commandFailed(let command, let code, let stderr):
+ return "Command failed (\(code)): \(command)\n\(stderr)"
+ case .badPNG(let path):
+ return "Could not parse PNG size: \(path)"
+ case .badPGM(let path):
+ return "Could not parse PGM: \(path)"
+ }
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/GenericInteractableDetector.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/GenericInteractableDetector.swift
new file mode 100644
index 00000000..1d06e559
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/GenericInteractableDetector.swift
@@ -0,0 +1,644 @@
+import Foundation
+
+struct GenericInteractableBox: Codable, Equatable, Sendable {
+ var id: Int
+ var x1: Int
+ var y1: Int
+ var x2: Int
+ var y2: Int
+ var text: String
+ var kind: String
+ var confidence: Double
+ var source: String
+ var width: Int { max(0, x2 - x1) }
+ var height: Int { max(0, y2 - y1) }
+ var area: Int { width * height }
+}
+
+struct GenericInteractableDetectionResult: Equatable, Sendable {
+ var boxes: [GenericInteractableBox]
+ var summary: String
+}
+
+struct GenericInteractableDetector: Sendable {
+ private var magickPath: String?
+ private var tesseractPath: String?
+
+ init(
+ magickPath: String? = nil,
+ tesseractPath: String? = nil
+ ) {
+ self.magickPath = magickPath
+ self.tesseractPath = tesseractPath
+ }
+
+ func detect(
+ inputURL: URL,
+ outputDirectory: URL
+ ) throws -> GenericInteractableDetectionResult {
+ guard FileManager.default.fileExists(atPath: inputURL.path) else {
+ throw GenericInteractableDetectorError.noFile(inputURL.path)
+ }
+ try FileManager.default.createDirectory(at: outputDirectory, withIntermediateDirectories: true)
+ let size = try readPNGSize(inputURL)
+
+ let preprocessed = outputDirectory.appendingPathComponent("swift_preprocessed_high_contrast.png")
+ let pgm = outputDirectory.appendingPathComponent("swift_gray.pgm")
+ let originalPGM = outputDirectory.appendingPathComponent("swift_original_gray.pgm")
+ let magick = executablePath(
+ preferred: magickPath ?? "/opt/imagemagick/bin/magick",
+ env: "DONKEY_MAGICK_PATH",
+ fallbacks: ["/opt/homebrew/bin/magick", "/usr/local/bin/magick"]
+ )
+ let tesseract = executablePath(
+ preferred: tesseractPath ?? "/usr/bin/tesseract",
+ env: "DONKEY_TESSERACT_PATH",
+ fallbacks: ["/opt/homebrew/bin/tesseract", "/usr/local/bin/tesseract"]
+ )
+
+ _ = try shell(magick, [inputURL.path, "-colorspace", "Gray", "-contrast-stretch", "2%x2%", "-sharpen", "0x1", preprocessed.path])
+ _ = try shell(magick, [preprocessed.path, "-depth", "8", pgm.path])
+ _ = try shell(magick, [inputURL.path, "-colorspace", "Gray", "-depth", "8", originalPGM.path])
+
+ let tsv = try shell(tesseract, [inputURL.path, "stdout", "--psm", "11", "tsv"])
+ let words = parseTesseractTSV(tsv)
+
+ let globalRows = groupWordsIntoRows(words)
+ var boxes = globalRows.compactMap { classifyOCRRow($0, size: size) }
+
+ let pgmData = try parsePGM(pgm)
+ let comps = connectedComponentsForeground(pixels: pgmData.pixels, w: pgmData.w, h: pgmData.h, threshold: 175)
+ boxes += comps.compactMap { classifyComponent($0, size: size) }
+
+ let originalGray = try parsePGM(originalPGM)
+ let midtone = connectedComponentsRange(pixels: originalGray.pixels, w: originalGray.w, h: originalGray.h, low: 28, high: 70)
+ let containers = midtone.compactMap { classifyMidtoneContainer($0, size: size) }
+ boxes += containers
+
+ boxes += inferRowsInsideContainers(from: words, containers: containers, size: size)
+ boxes = filterComponentDuplicates(boxes)
+ boxes = clampBoxes(boxes, size: size)
+ boxes += addInferredContainers(from: boxes, size: size)
+ boxes = dedupe(boxes)
+
+ let jsonURL = outputDirectory.appendingPathComponent("swift_boxes.json")
+ let csvURL = outputDirectory.appendingPathComponent("swift_boxes.csv")
+ let svg = outputDirectory.appendingPathComponent("swift_overlay.svg")
+ try writeJSON(boxes, jsonURL)
+ try writeCSV(boxes, csvURL)
+ try writeSVG(input: inputURL, size: size, boxes: boxes, to: svg)
+
+ return GenericInteractableDetectionResult(
+ boxes: boxes,
+ summary: [
+ "image=\(size.width)x\(size.height)",
+ "boxes=\(boxes.count)",
+ "preprocessed=\(preprocessed.path)",
+ "json=\(jsonURL.path)",
+ "csv=\(csvURL.path)",
+ "svg=\(svg.path)"
+ ].joined(separator: "\n")
+ )
+ }
+
+ private func shell(_ executable: String, _ args: [String]) throws -> String {
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: executable)
+ p.arguments = args
+ let out = Pipe(); let err = Pipe()
+ p.standardOutput = out; p.standardError = err
+ try p.run(); p.waitUntilExit()
+ let stdout = String(data: out.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
+ let stderr = String(data: err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
+ if p.terminationStatus != 0 {
+ throw GenericInteractableDetectorError.commandFailed(
+ ([executable] + args).joined(separator: " "),
+ p.terminationStatus,
+ stderr
+ )
+ }
+ return stdout
+ }
+
+ private func executablePath(
+ preferred: String,
+ env: String,
+ fallbacks: [String]
+ ) -> String {
+ let fm = FileManager.default
+ if let override = ProcessInfo.processInfo.environment[env],
+ fm.isExecutableFile(atPath: override) {
+ return override
+ }
+ if fm.isExecutableFile(atPath: preferred) {
+ return preferred
+ }
+ for fallback in fallbacks where fm.isExecutableFile(atPath: fallback) {
+ return fallback
+ }
+ return preferred
+ }
+
+ private func readPNGSize(_ url: URL) throws -> PNGSize {
+ let d = try Data(contentsOf: url)
+ guard d.count >= 24 && Array(d[0..<8]) == [137,80,78,71,13,10,26,10] else {
+ throw GenericInteractableDetectorError.badPNG(url.path)
+ }
+ func be32(_ i: Int) -> UInt32 { (UInt32(d[i]) << 24) | (UInt32(d[i+1]) << 16) | (UInt32(d[i+2]) << 8) | UInt32(d[i+3]) }
+ return PNGSize(width: Int(be32(16)), height: Int(be32(20)))
+ }
+
+ private func parseTesseractTSV(_ s: String) -> [OCRWord] {
+ var words: [OCRWord] = []
+ for (idx, line) in s.split(separator: "\n", omittingEmptySubsequences: false).enumerated() {
+ if idx == 0 { continue }
+ let cols = line.split(separator: "\t", omittingEmptySubsequences: false).map(String.init)
+ if cols.count < 12 { continue }
+ guard cols[0] == "5",
+ let block = Int(cols[2]), let par = Int(cols[3]), let ln = Int(cols[4]),
+ let left = Int(cols[6]), let top = Int(cols[7]), let width = Int(cols[8]), let height = Int(cols[9]),
+ let conf = Double(cols[10]) else { continue }
+ var text = cols[11].trimmingCharacters(in: .whitespacesAndNewlines)
+ text = text.trimmingCharacters(in: CharacterSet(charactersIn: "\"\u{201C}\u{201D}\u{2018}\u{2019}`"))
+ if text.isEmpty || conf < 20 { continue }
+ words.append(OCRWord(text: text, conf: conf, x: left, y: top, w: width, h: height, block: block, par: par, line: ln))
+ }
+ return words
+ }
+
+ private func avg(_ xs: [Double]) -> Double { xs.isEmpty ? 0 : xs.reduce(0,+) / Double(xs.count) }
+ private func medianInt(_ xs: [Int]) -> Int {
+ if xs.isEmpty { return 0 }
+ let s = xs.sorted()
+ return s[s.count/2]
+ }
+
+ private func contains(_ a: GenericInteractableBox, _ b: GenericInteractableBox, pad: Int = 0) -> Bool {
+ a.x1 - pad <= b.x1 && a.y1 - pad <= b.y1 && a.x2 + pad >= b.x2 && a.y2 + pad >= b.y2
+ }
+
+ private func wordInside(_ w: OCRWord, _ r: GenericInteractableBox, pad: Int = 0) -> Bool {
+ let cx = w.x + w.w / 2
+ let cy = w.y + w.h / 2
+ return cx >= r.x1 - pad && cx <= r.x2 + pad && cy >= r.y1 - pad && cy <= r.y2 + pad
+ }
+
+ private func groupWordsIntoRows(_ words: [OCRWord], region: GenericInteractableBox? = nil, maxGap: Int = 42, rowTol: Int = 11) -> [GenericInteractableBox] {
+ let ws = words.filter { w in
+ if let r = region { return wordInside(w, r, pad: 6) }
+ return true
+ }
+ if ws.isEmpty { return [] }
+
+ let sorted = ws.sorted { a, b in
+ let acy = a.y + a.h / 2
+ let bcy = b.y + b.h / 2
+ if abs(acy - bcy) > rowTol { return acy < bcy }
+ return a.x < b.x
+ }
+
+ var rows: [[OCRWord]] = []
+ for w in sorted {
+ let cy = w.y + w.h / 2
+ if let last = rows.last {
+ let lastCenter = Int(avg(last.map { Double($0.y + $0.h / 2) }))
+ let tol = max(rowTol, medianInt(last.map { $0.h }) / 2)
+ if abs(cy - lastCenter) <= tol {
+ rows[rows.count - 1].append(w)
+ } else {
+ rows.append([w])
+ }
+ } else {
+ rows.append([w])
+ }
+ }
+
+ var segments: [GenericInteractableBox] = []
+ for row in rows {
+ let rowWords = row.sorted { $0.x < $1.x }
+ var current: [OCRWord] = []
+ for w in rowWords {
+ if current.isEmpty {
+ current.append(w)
+ continue
+ }
+ let prev = current.last!
+ let gap = w.x - (prev.x + prev.w)
+ let localTol = max(maxGap, max(prev.h, w.h) * 2)
+ if gap > localTol {
+ let box = rowSegmentToBox(current)
+ if let b = box { segments.append(b) }
+ current = [w]
+ } else {
+ current.append(w)
+ }
+ }
+ if let b = rowSegmentToBox(current) { segments.append(b) }
+ }
+
+ return segments.sorted { $0.y1 == $1.y1 ? $0.x1 < $1.x1 : $0.y1 < $1.y1 }
+ }
+
+ private func rowSegmentToBox(_ ws: [OCRWord]) -> GenericInteractableBox? {
+ guard !ws.isEmpty else { return nil }
+ let sorted = ws.sorted { $0.x < $1.x }
+ let text = sorted.map { $0.text }.joined(separator: " ").trimmingCharacters(in: .whitespacesAndNewlines)
+ if text.count < 1 { return nil }
+ let x1 = sorted.map { $0.x }.min() ?? 0
+ let y1 = sorted.map { $0.y }.min() ?? 0
+ let x2 = sorted.map { $0.x + $0.w }.max() ?? 0
+ let y2 = sorted.map { $0.y + $0.h }.max() ?? 0
+ let conf = avg(sorted.map { $0.conf }) / 100.0
+ return GenericInteractableBox(id: 0, x1: x1, y1: y1, x2: x2, y2: y2, text: text, kind: "ocr_row", confidence: min(0.99, max(0.2, conf)), source: "tesseract_rows")
+ }
+
+ private func isMostlyText(_ s: String) -> Bool {
+ s.rangeOfCharacter(from: .letters) != nil || s.rangeOfCharacter(from: .decimalDigits) != nil
+ }
+
+ private func classifyOCRRow(_ b: GenericInteractableBox, size: PNGSize) -> GenericInteractableBox? {
+ let w = Double(size.width), h = Double(size.height)
+ let cx = Double(b.x1 + b.x2) / 2.0
+ let lower = b.text.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
+ let isShort = b.text.count <= 40
+ if !isMostlyText(b.text) { return nil }
+ if lower.count <= 3 && Double(b.y1) > h * 0.05 { return nil }
+
+ var out = b
+ out.source = "ocr+geometry"
+
+ if Double(b.y1) < h * 0.040 {
+ out.kind = cx < w * 0.38 ? "menu_bar_item" : "menu_bar_status"
+ out.confidence = max(out.confidence, 0.72)
+ out.x1 = max(0, b.x1 - 8); out.x2 = min(size.width, b.x2 + 8)
+ out.y1 = max(0, b.y1 - 8); out.y2 = min(size.height, b.y2 + 8)
+ return out
+ }
+
+ if Double(b.x1) < w * 0.20 && isShort {
+ if ["pinned", "projects"].contains(lower) { return nil }
+ out.kind = "left_nav_row"
+ out.confidence = max(out.confidence, 0.80)
+ out.x1 = max(0, Int(Double(b.x1) - w * 0.015)); out.x2 = min(size.width, Int(Double(b.x2) + w * 0.035))
+ out.y1 = max(0, b.y1 - 8); out.y2 = min(size.height, b.y2 + 8)
+ return out
+ }
+
+ if Double(b.x1) > w * 0.72 && Double(b.y1) > h * 0.09 && Double(b.y1) < h * 0.45 && isShort {
+ if ["environment", "sources"].contains(lower) { return nil }
+ out.kind = "right_panel_row"
+ out.confidence = max(out.confidence, 0.78)
+ out.x1 = max(0, b.x1 - 28); out.x2 = min(size.width, b.x2 + 28)
+ out.y1 = max(0, b.y1 - 8); out.y2 = min(size.height, b.y2 + 8)
+ return out
+ }
+
+ if Double(b.y1) > h * 0.84 && Double(b.x1) > w * 0.25 && Double(b.x1) < w * 0.82 && isShort {
+ if lower.contains("auto-review") {
+ out.kind = "composer_control"
+ } else if lower.contains("review") || lower.contains("files changed") || lower.contains("changed") {
+ out.kind = "review_button_or_status"
+ } else if lower.contains("ask") || lower.contains("follow") || lower.contains("chang") {
+ out.kind = "text_input_placeholder"
+ } else {
+ out.kind = "composer_control"
+ }
+ out.confidence = max(out.confidence, 0.82)
+ out.x1 = max(0, b.x1 - 14); out.x2 = min(size.width, b.x2 + 16)
+ out.y1 = max(0, b.y1 - 10); out.y2 = min(size.height, b.y2 + 10)
+ return out
+ }
+
+ if isShort && b.width < Int(w * 0.25) {
+ let buttonWords = ["review", "commit", "pull", "changes", "local", "main", "settings", "search", "new chat", "auto-review"]
+ if buttonWords.contains(where: { lower.contains($0) }) {
+ out.kind = "text_button_or_row"
+ out.confidence = max(out.confidence, 0.70)
+ out.x1 = max(0, b.x1 - 12); out.x2 = min(size.width, b.x2 + 12)
+ out.y1 = max(0, b.y1 - 8); out.y2 = min(size.height, b.y2 + 8)
+ return out
+ }
+ }
+
+ return nil
+ }
+
+ private func parsePGM(_ url: URL) throws -> (w: Int, h: Int, pixels: [UInt8]) {
+ let data = try Data(contentsOf: url)
+ var idx = 0
+ func nextToken() -> String? {
+ while idx < data.count {
+ let c = data[idx]
+ if c == 35 { while idx < data.count && data[idx] != 10 { idx += 1 } }
+ if idx < data.count && data[idx] <= 32 { idx += 1; continue }
+ break
+ }
+ if idx >= data.count { return nil }
+ let start = idx
+ while idx < data.count && data[idx] > 32 { idx += 1 }
+ return String(data: data[start..<idx], encoding: .ascii)
+ }
+ guard nextToken() == "P5", let sw = nextToken(), let sh = nextToken(), let sm = nextToken(), let w = Int(sw), let h = Int(sh), Int(sm) != nil else {
+ throw GenericInteractableDetectorError.badPGM(url.path)
+ }
+ if idx < data.count && data[idx] <= 32 { idx += 1 }
+ let expected = w * h
+ guard data.count - idx >= expected else { throw GenericInteractableDetectorError.badPGM(url.path) }
+ return (w, h, Array(data[idx..<(idx+expected)]))
+ }
+
+ private func connectedComponentsForeground(pixels: [UInt8], w: Int, h: Int, threshold: UInt8 = 175) -> [CC] {
+ var visited = Array(repeating: false, count: w*h)
+ var comps: [CC] = []
+ let dirs = [(1,0),(-1,0),(0,1),(0,-1)]
+ for y in 0..<h {
+ for x in 0..<w {
+ let start = y*w+x
+ if visited[start] || pixels[start] < threshold { continue }
+ var q = [(x,y)], head = 0
+ visited[start] = true
+ var minX = x, maxX = x, minY = y, maxY = y, area = 0
+ while head < q.count {
+ let (cx,cy) = q[head]; head += 1; area += 1
+ minX = min(minX,cx); maxX = max(maxX,cx); minY = min(minY,cy); maxY = max(maxY,cy)
+ for (dx,dy) in dirs {
+ let nx = cx + dx, ny = cy + dy
+ if nx < 0 || ny < 0 || nx >= w || ny >= h { continue }
+ let ni = ny*w + nx
+ if visited[ni] || pixels[ni] < threshold { continue }
+ visited[ni] = true; q.append((nx,ny))
+ }
+ }
+ comps.append(CC(x: minX, y: minY, w: maxX-minX+1, h: maxY-minY+1, area: area))
+ }
+ }
+ return comps
+ }
+
+ private func connectedComponentsRange(pixels: [UInt8], w: Int, h: Int, low: UInt8, high: UInt8) -> [CC] {
+ var visited = Array(repeating: false, count: w*h)
+ var comps: [CC] = []
+ let dirs = [(1,0),(-1,0),(0,1),(0,-1)]
+ for y in 0..<h {
+ for x in 0..<w {
+ let start = y*w+x
+ let v = pixels[start]
+ if visited[start] || v < low || v > high { continue }
+ var q = [(x,y)], head = 0
+ visited[start] = true
+ var minX = x, maxX = x, minY = y, maxY = y, area = 0
+ while head < q.count {
+ let (cx,cy) = q[head]; head += 1; area += 1
+ minX = min(minX,cx); maxX = max(maxX,cx); minY = min(minY,cy); maxY = max(maxY,cy)
+ for (dx,dy) in dirs {
+ let nx = cx + dx, ny = cy + dy
+ if nx < 0 || ny < 0 || nx >= w || ny >= h { continue }
+ let ni = ny*w + nx
+ let nv = pixels[ni]
+ if visited[ni] || nv < low || nv > high { continue }
+ visited[ni] = true; q.append((nx,ny))
+ }
+ }
+ comps.append(CC(x: minX, y: minY, w: maxX-minX+1, h: maxY-minY+1, area: area))
+ }
+ }
+ return comps
+ }
+
+ private func classifyMidtoneContainer(_ c: CC, size: PNGSize) -> GenericInteractableBox? {
+ let W = Double(size.width), H = Double(size.height)
+ if c.area < 800 || c.w < 70 || c.h < 20 { return nil }
+ if c.w > Int(W * 0.98) && c.h > Int(H * 0.8) { return nil }
+
+ let inComposer = Double(c.y) > H * 0.80 && Double(c.x) > W * 0.20 && Double(c.x) < W * 0.82
+ let inRightFloatingPanel = Double(c.x) > W * 0.70 && Double(c.y) > H * 0.06 && Double(c.y) < H * 0.55
+ let inMessageBubble = Double(c.x) > W * 0.25 && Double(c.x) < W * 0.82 && c.w < Int(W * 0.45) && c.h < 80
+
+ if inComposer && c.w > Int(W * 0.20) {
+ return GenericInteractableBox(id: 0, x1: c.x, y1: c.y, x2: c.x + c.w, y2: c.y + c.h, text: "bottom input/composer container", kind: "text_input_container", confidence: 0.70, source: "midtone_component")
+ }
+ if inRightFloatingPanel && c.w > Int(W * 0.10) && c.h > 80 {
+ return GenericInteractableBox(id: 0, x1: c.x, y1: c.y, x2: c.x + c.w, y2: c.y + c.h, text: "floating side panel", kind: "panel_container", confidence: 0.68, source: "midtone_component")
+ }
+ if inMessageBubble {
+ return GenericInteractableBox(id: 0, x1: c.x, y1: c.y, x2: c.x + c.w, y2: c.y + c.h, text: "button/bubble-like container", kind: "visual_container", confidence: 0.50, source: "midtone_component")
+ }
+ return nil
+ }
+
+ private func classifyComponent(_ c: CC, size: PNGSize) -> GenericInteractableBox? {
+ let W = Double(size.width), H = Double(size.height)
+ let aspect = Double(c.w) / Double(max(1, c.h))
+ if c.area < 12 || c.w < 4 || c.h < 4 { return nil }
+ if aspect > 18 || aspect < 0.12 { return nil }
+ if c.w > Int(W * 0.35) || c.h > Int(H * 0.20) { return nil }
+
+ let inTopChrome = Double(c.y) < H * 0.09
+ let inLeftRail = Double(c.x) < W * 0.20
+ let inRightPanel = Double(c.x) > W * 0.75 && Double(c.y) > H * 0.08 && Double(c.y) < H * 0.45
+ let inComposer = Double(c.y) > H * 0.86 && Double(c.x) > W * 0.25 && Double(c.x) < W * 0.78
+
+ if c.w <= 42 && c.h <= 42 && (inTopChrome || inLeftRail || inRightPanel || inComposer) {
+ let kind = inComposer ? "composer_icon_button" : "icon_button"
+ return GenericInteractableBox(id: 0, x1: max(0,c.x - 4), y1: max(0,c.y - 4), x2: c.x + c.w + 4, y2: c.y + c.h + 4, text: kind, kind: kind, confidence: 0.56, source: "connected_component")
+ }
+
+ if c.w >= 40 && c.w <= Int(W * 0.30) && c.h >= 16 && c.h <= 62 && (inComposer || inRightPanel || inLeftRail) {
+ return GenericInteractableBox(id: 0, x1: max(0,c.x - 6), y1: max(0,c.y - 6), x2: c.x + c.w + 6, y2: c.y + c.h + 6, text: "visual control", kind: "visual_control", confidence: 0.45, source: "connected_component")
+ }
+ return nil
+ }
+
+ private func iou(_ a: GenericInteractableBox, _ b: GenericInteractableBox) -> Double {
+ let ix1 = max(a.x1,b.x1), iy1 = max(a.y1,b.y1), ix2 = min(a.x2,b.x2), iy2 = min(a.y2,b.y2)
+ let inter = max(0, ix2-ix1) * max(0, iy2-iy1)
+ let u = a.area + b.area - inter
+ return u > 0 ? Double(inter) / Double(u) : 0
+ }
+
+ private func shouldKeepNested(_ b: GenericInteractableBox) -> Bool {
+ ["icon_button","composer_icon_button","composer_control","text_input_placeholder","composer_dropdown","model_selector","review_button_or_status","right_panel_row","left_nav_row"].contains(b.kind)
+ }
+
+ private func clampBoxes(_ boxes: [GenericInteractableBox], size: PNGSize) -> [GenericInteractableBox] {
+ boxes.map { b in
+ GenericInteractableBox(id: b.id,
+ x1: max(0, min(size.width, b.x1)),
+ y1: max(0, min(size.height, b.y1)),
+ x2: max(0, min(size.width, b.x2)),
+ y2: max(0, min(size.height, b.y2)),
+ text: b.text, kind: b.kind, confidence: b.confidence, source: b.source)
+ }.filter { $0.x2 > $0.x1 && $0.y2 > $0.y1 }
+ }
+
+ private func filterComponentDuplicates(_ boxes: [GenericInteractableBox]) -> [GenericInteractableBox] {
+ let textish = boxes.filter { $0.source.contains("ocr") }
+ return boxes.filter { b in
+ if !b.source.contains("connected_component") { return true }
+ let cx = (b.x1 + b.x2) / 2
+ let cy = (b.y1 + b.y2) / 2
+ for t in textish {
+ if cx >= t.x1 - 8 && cx <= t.x2 + 8 && cy >= t.y1 - 8 && cy <= t.y2 + 8 {
+ return false
+ }
+ }
+ return true
+ }
+ }
+
+ private func addInferredContainers(from boxes: [GenericInteractableBox], size: PNGSize) -> [GenericInteractableBox] {
+ var out: [GenericInteractableBox] = []
+ let composerKids = boxes.filter { ($0.kind.contains("composer") || $0.kind == "text_input_placeholder") && !$0.kind.contains("review") }
+ if composerKids.count >= 2 {
+ let x1 = max(0, (composerKids.map{$0.x1}.min() ?? 0) - Int(Double(size.width)*0.02))
+ let x2 = min(size.width, (composerKids.map{$0.x2}.max() ?? 0) + Int(Double(size.width)*0.02))
+ let y1 = max(0, (composerKids.map{$0.y1}.min() ?? 0) - Int(Double(size.height)*0.015))
+ let y2 = min(size.height, (composerKids.map{$0.y2}.max() ?? 0) + Int(Double(size.height)*0.015))
+ out.append(GenericInteractableBox(id: 0, x1: x1, y1: y1, x2: x2, y2: y2, text: "composer/input container", kind: "text_input_container", confidence: 0.62, source: "inferred_from_children"))
+ }
+ return out
+ }
+
+ private func inferRowsInsideContainers(from words: [OCRWord], containers: [GenericInteractableBox], size: PNGSize) -> [GenericInteractableBox] {
+ var out: [GenericInteractableBox] = []
+ for c in containers {
+ let rows = groupWordsIntoRows(words, region: c, maxGap: 32, rowTol: 10)
+ for r0 in rows {
+ var r = r0
+ let lower = r.text.lowercased()
+ if lower.isEmpty || lower.count <= 2 { continue }
+ if c.kind == "panel_container" {
+ if ["environment", "sources"].contains(lower) { continue }
+ if lower.contains("no sources yet") { continue }
+ r.kind = "right_panel_row"
+ r.source = "panel_row_inference"
+ r.confidence = max(r.confidence, 0.86)
+ r.x1 = max(c.x1, r.x1 - 38)
+ r.x2 = min(c.x2, r.x2 + 18)
+ r.y1 = max(c.y1, r.y1 - 8)
+ r.y2 = min(c.y2, r.y2 + 8)
+ out.append(r)
+ } else if c.kind == "text_input_container" {
+ if lower.contains("ask") || lower.contains("follow") || lower.contains("chang") {
+ r.kind = "text_input_placeholder"
+ } else {
+ r.kind = "composer_control"
+ }
+ r.source = "container_child_inference"
+ r.confidence = max(r.confidence, 0.84)
+ r.x1 = max(c.x1, r.x1 - 10)
+ r.x2 = min(c.x2, r.x2 + 12)
+ r.y1 = max(c.y1, r.y1 - 8)
+ r.y2 = min(c.y2, r.y2 + 8)
+ out.append(r)
+ }
+ }
+ }
+ return out
+ }
+
+ private func dedupe(_ boxes: [GenericInteractableBox]) -> [GenericInteractableBox] {
+ func priority(_ b: GenericInteractableBox) -> Int {
+ if b.kind == "right_panel_row" || b.kind == "left_nav_row" || b.kind == "composer_control" || b.kind == "text_input_placeholder" { return 4 }
+ if b.kind.contains("container") { return 1 }
+ if b.source.contains("ocr") || b.source.contains("inference") { return 3 }
+ if b.source.contains("connected_component") { return 2 }
+ return 0
+ }
+ let sorted = boxes.sorted { a,b in
+ if priority(a) != priority(b) { return priority(a) > priority(b) }
+ if abs(a.confidence - b.confidence) > 0.001 { return a.confidence > b.confidence }
+ return a.area > b.area
+ }
+ var kept: [GenericInteractableBox] = []
+ for b in sorted {
+ var suppress = false
+ for e in kept {
+ let overlap = iou(b,e)
+ if overlap > 0.76 { suppress = true; break }
+ if b.source.contains("connected_component") && e.source.contains("connected_component") {
+ if contains(e,b,pad:3) || (overlap > 0.35) {
+ suppress = true; break
+ }
+ let sameBand = abs((b.y1+b.y2)/2 - (e.y1+e.y2)/2) <= 8
+ let near = abs(b.x1 - e.x1) <= 6 && abs(b.x2 - e.x2) <= 6
+ if sameBand && near { suppress = true; break }
+ }
+ if contains(e,b,pad:3) && !shouldKeepNested(b) {
+ if b.kind == e.kind || e.kind.contains("container") { suppress = true; break }
+ }
+ }
+ if !suppress { kept.append(b) }
+ }
+ var result = kept.sorted { $0.y1 == $1.y1 ? $0.x1 < $1.x1 : $0.y1 < $1.y1 }
+ for i in result.indices { result[i].id = i + 1 }
+ return result
+ }
+
+ private func color(_ kind: String) -> String {
+ if kind.contains("menu") { return "#50C8FF" }
+ if kind.contains("left") { return "#34C759" }
+ if kind.contains("right") { return "#FFCC00" }
+ if kind.contains("composer") || kind.contains("input") { return "#BF5AF2" }
+ if kind.contains("icon") { return "#FF9500" }
+ if kind.contains("container") { return "#64D2FF" }
+ return "#64D2FF"
+ }
+
+ private func xml(_ s: String) -> String {
+ s.replacingOccurrences(of: "&", with: "&amp;")
+ .replacingOccurrences(of: "<", with: "&lt;")
+ .replacingOccurrences(of: ">", with: "&gt;")
+ .replacingOccurrences(of: "\"", with: "&quot;")
+ }
+
+ private func writeJSON(_ boxes: [GenericInteractableBox], _ url: URL) throws {
+ let enc = JSONEncoder()
+ enc.outputFormatting = [.prettyPrinted,.sortedKeys]
+ try enc.encode(boxes).write(to: url)
+ }
+
+ private func writeCSV(_ boxes: [GenericInteractableBox], _ url: URL) throws {
+ var lines = ["id,x1,y1,x2,y2,text,kind,confidence,source"]
+ for b in boxes { lines.append("\(b.id),\(b.x1),\(b.y1),\(b.x2),\(b.y2),\"\(b.text.replacingOccurrences(of: "\"", with: "\"\""))\",\(b.kind),\(String(format: "%.3f", b.confidence)),\(b.source)") }
+ try lines.joined(separator:"\n").write(to: url, atomically: true, encoding: .utf8)
+ }
+
+ private func writeSVG(input: URL, size: PNGSize, boxes: [GenericInteractableBox], to url: URL) throws {
+ let b64 = try Data(contentsOf: input).base64EncodedString()
+ var s = """
+ <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"\(size.width)\" height=\"\(size.height)\" viewBox=\"0 0 \(size.width) \(size.height)\">
+ <image href=\"data:image/png;base64,\(b64)\" x=\"0\" y=\"0\" width=\"\(size.width)\" height=\"\(size.height)\" preserveAspectRatio=\"none\"/>
+ """
+ for b in boxes {
+ let c = color(b.kind)
+ s += "\n <g>"
+ s += "\n <rect x=\"\(b.x1)\" y=\"\(b.y1)\" width=\"\(b.width)\" height=\"\(b.height)\" fill=\"none\" stroke=\"\(c)\" stroke-width=\"2\"/>"
+ s += "\n <text x=\"\(b.x1)\" y=\"\(max(12,b.y1-4))\" font-family=\"Arial\" font-size=\"12\" fill=\"\(c)\">\(b.id)</text>"
+ s += "\n <title>\(b.id): \(xml(b.text)) - \(xml(b.kind)) [\(b.x1),\(b.y1),\(b.x2),\(b.y2)]</title>"
+ s += "\n </g>"
+ }
+ s += "\n</svg>\n"
+ try s.write(to: url, atomically: true, encoding: .utf8)
+ }
+}
+
+private struct PNGSize: Equatable, Sendable { let width: Int; let height: Int }
+private struct OCRWord: Equatable, Sendable { let text: String; let conf: Double; let x: Int; let y: Int; let w: Int; let h: Int; let block: Int; let par: Int; let line: Int }
+private struct CC: Equatable, Sendable { let x: Int; let y: Int; let w: Int; let h: Int; let area: Int }
+
+private enum GenericInteractableDetectorError: Error, CustomStringConvertible {
+ case noFile(String)
+ case commandFailed(String, Int32, String)
+ case badPNG(String)
+ case badPGM(String)
+
+ var description: String {
+ switch self {
+ case .noFile(let p): return "File not found: \(p)"
+ case .commandFailed(let c, let code, let err): return "Command failed (\(code)): \(c)\n\(err)"
+ case .badPNG(let p): return "Could not read PNG size: \(p)"
+ case .badPGM(let p): return "Could not parse PGM: \(p)"
+ }
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift
index 209d1b8e..1f61746c 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementNativeVisualDetector.swift
@@ -1,26 +1,418 @@
import DonkeyContracts
import Foundation
+public enum NativeVisualDetectionAlgorithm: String, Codable, Equatable, Sendable {
+ case interactablesV2 = "interactables-v2"
+ case borderUI = "border-ui"
+}
+
public struct LocalUIElementNativeVisualDetector: Sendable {
- public init(maxAnalysisDimension: Int = 900) {}
+ private var algorithm: NativeVisualDetectionAlgorithm
+ private var interactableDetector: GenericInteractableDetector
+ private var borderDetector: GenericBorderUIDetector
+
+ public init(
+ maxAnalysisDimension: Int = 900,
+ algorithm: NativeVisualDetectionAlgorithm? = nil,
+ magickPath: String? = nil,
+ tesseractPath: String? = nil
+ ) {
+ _ = maxAnalysisDimension
+ self.algorithm = algorithm ?? Self.algorithmFromEnvironment()
+ self.interactableDetector = GenericInteractableDetector(
+ magickPath: magickPath,
+ tesseractPath: tesseractPath
+ )
+ self.borderDetector = GenericBorderUIDetector(
+ magickPath: magickPath,
+ tesseractPath: tesseractPath
+ )
+ }
public func candidates(
fromPNGData data: Data?,
imagePath: String? = nil,
pixelSize: HotLoopSize
) -> (candidates: [LocalUIElementCandidate], latencyMS: [String: Double], metadata: [String: String]) {
- _ = data
- _ = imagePath
- _ = pixelSize
+ let startedAt = ProcessInfo.processInfo.systemUptime
+
+ let fileManager = FileManager.default
+ let workingDirectory = fileManager.temporaryDirectory
+ .appendingPathComponent("donkey-native-visual-\(UUID().uuidString)", isDirectory: true)
+ do {
+ try fileManager.createDirectory(at: workingDirectory, withIntermediateDirectories: true)
+ defer { try? fileManager.removeItem(at: workingDirectory) }
+
+ let inputURL: URL
+ if let imagePath,
+ !imagePath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ inputURL = URL(fileURLWithPath: imagePath)
+ } else if let data {
+ inputURL = workingDirectory.appendingPathComponent("input.png", isDirectory: false)
+ try data.write(to: inputURL, options: .atomic)
+ } else {
+ return failureResult(
+ reason: "missingScreenshot",
+ startedAt: startedAt
+ )
+ }
+
+ let detectionResult = try detect(
+ inputURL: inputURL,
+ outputDirectory: workingDirectory,
+ pixelSize: pixelSize
+ )
+ let totalMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
+
+ return (
+ detectionResult.candidates,
+ ["nativeVisual.total": totalMS],
+ [
+ "nativeVisual.status": "ok",
+ "nativeVisual.detector": detectionResult.detectorName,
+ "nativeVisual.algorithm": algorithm.rawValue,
+ "nativeVisual.box.count": String(detectionResult.boxCount),
+ "nativeVisual.candidate.count": String(detectionResult.candidates.count),
+ "nativeVisual.output": detectionResult.summary,
+ "nativeVisual.rawPixelsRead": "true",
+ "nativeVisual.rawPixelsPersisted": "false"
+ ]
+ )
+ } catch {
+ return failureResult(
+ reason: String(describing: error),
+ startedAt: startedAt
+ )
+ }
+ }
+
+ private func failureResult(
+ reason: String,
+ startedAt: TimeInterval
+ ) -> (candidates: [LocalUIElementCandidate], latencyMS: [String: Double], metadata: [String: String]) {
+ let totalMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
return (
[],
- [:],
+ ["nativeVisual.total": totalMS],
[
- "nativeVisual.status": "stubbed",
- "nativeVisual.reason": "cvPipelineRemovedPendingReplacement",
- "nativeVisual.rawPixelsRead": "false"
+ "nativeVisual.status": "failed",
+ "nativeVisual.reason": reason,
+ "nativeVisual.detector": detectorName,
+ "nativeVisual.algorithm": algorithm.rawValue,
+ "nativeVisual.rawPixelsRead": "false",
+ "nativeVisual.rawPixelsPersisted": "false"
]
)
}
+
+ private var detectorName: String {
+ switch algorithm {
+ case .interactablesV2:
+ return "detect_interactables_generic_v2"
+ case .borderUI:
+ return "generic_border_ui_detector"
+ }
+ }
+
+ private func detect(
+ inputURL: URL,
+ outputDirectory: URL,
+ pixelSize: HotLoopSize
+ ) throws -> NativeVisualDetectionResult {
+ switch algorithm {
+ case .interactablesV2:
+ let result = try interactableDetector.detect(inputURL: inputURL, outputDirectory: outputDirectory)
+ return NativeVisualDetectionResult(
+ detectorName: "detect_interactables_generic_v2",
+ boxCount: result.boxes.count,
+ candidates: result.boxes.compactMap { Self.candidate(from: $0, pixelSize: pixelSize) },
+ summary: result.summary
+ )
+ case .borderUI:
+ let result = try borderDetector.detect(inputURL: inputURL, outputDirectory: outputDirectory)
+ return NativeVisualDetectionResult(
+ detectorName: "generic_border_ui_detector",
+ boxCount: result.boxes.count,
+ candidates: result.boxes.compactMap { Self.candidate(from: $0, pixelSize: pixelSize) },
+ summary: result.summary
+ )
+ }
+ }
+
+ static func candidate(
+ from box: GenericInteractableBox,
+ pixelSize: HotLoopSize
+ ) -> LocalUIElementCandidate? {
+ let width = max(0, box.x2 - box.x1)
+ let height = max(0, box.y2 - box.y1)
+ guard width > 0, height > 0 else { return nil }
+
+ let role = debugOverlayRole(for: box.kind)
+ var metadata = [
+ "debug.overlayRole": role,
+ "nativeVisual.detector": "detect_interactables_generic_v2",
+ "nativeVisual.scriptID": String(box.id),
+ "nativeVisual.kind": box.kind,
+ "nativeVisual.source": box.source,
+ "classification.reason": "detectInteractablesGenericV2"
+ ]
+ if box.kind.contains("container") {
+ metadata["element.kind"] = "visualContainer"
+ }
+
+ return LocalUIElementCandidate(
+ id: "native-cv-\(box.id)-\(slug(box.kind))",
+ source: candidateSource(for: box.source, kind: box.kind),
+ signalKind: signalKind(for: box.source, kind: box.kind),
+ typeHint: elementType(for: box.kind),
+ label: label(for: box),
+ bounds: HotLoopRect(
+ x: Double(box.x1),
+ y: Double(box.y1),
+ width: Double(width),
+ height: Double(height),
+ space: pixelSize.space
+ ),
+ confidence: box.confidence,
+ actions: [],
+ metadata: metadata
+ )
+ }
+
+ private static func candidateSource(
+ for source: String,
+ kind: String
+ ) -> LocalUIElementCandidateSource {
+ if source.contains("connected_component") {
+ return .connectedComponent
+ }
+ if source.contains("ocr") || source.contains("tesseract") || source.contains("inference") {
+ return .ocr
+ }
+ if kind.contains("container") || source.contains("midtone") {
+ return .layout
+ }
+ return .shape
+ }
+
+ private static func signalKind(
+ for source: String,
+ kind: String
+ ) -> LocalUIElementSignalKind {
+ if source.contains("connected_component") {
+ return .connectedComponent
+ }
+ if source.contains("ocr") || source.contains("tesseract") || source.contains("inference") {
+ return .text
+ }
+ if kind.contains("container") || kind.contains("row") {
+ return .rowGrouping
+ }
+ return .rectangle
+ }
+
+ private static func elementType(for kind: String) -> DebugUIElementType {
+ switch kind {
+ case "menu_bar_item", "menu_bar_status":
+ return .menuItem
+ case "left_nav_row":
+ return .sidebarItem
+ case "right_panel_row":
+ return .listItem
+ case "text_input_container", "text_input_placeholder":
+ return .input
+ case "composer_icon_button", "icon_button":
+ return .toolbarIcon
+ case "composer_control", "review_button_or_status", "text_button_or_row", "visual_control":
+ return .button
+ case "panel_container", "visual_container":
+ return .other
+ default:
+ return .other
+ }
+ }
+
+ private static func debugOverlayRole(for kind: String) -> String {
+ switch kind {
+ case "menu_bar_item", "menu_bar_status":
+ return "menuBarItem"
+ case "left_nav_row":
+ return "sidebarRow"
+ case "right_panel_row":
+ return "panelRow"
+ case "panel_container":
+ return "panel"
+ case "text_input_container":
+ return "bottomInput"
+ case "text_input_placeholder":
+ return "messageInput"
+ case "composer_icon_button", "composer_control":
+ return "bottomInputAccessory"
+ case "review_button_or_status", "text_button_or_row", "visual_control", "icon_button":
+ return "actionButton"
+ case "visual_container":
+ return "userBubble"
+ default:
+ return "actionButton"
+ }
+ }
+
+ private static func label(for box: GenericInteractableBox) -> String {
+ let trimmed = box.text.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !trimmed.isEmpty {
+ return trimmed
+ }
+ return box.kind.replacingOccurrences(of: "_", with: " ")
+ }
+
+ private static func slug(_ value: String) -> String {
+ let normalized = value
+ .lowercased()
+ .split { !$0.isLetter && !$0.isNumber }
+ .prefix(6)
+ .joined(separator: "-")
+ return normalized.isEmpty ? "element" : normalized
+ }
+
+ static func candidate(
+ from box: GenericBorderUIBox,
+ pixelSize: HotLoopSize
+ ) -> LocalUIElementCandidate? {
+ let width = max(0, box.x2 - box.x1)
+ let height = max(0, box.y2 - box.y1)
+ guard width > 0, height > 0 else { return nil }
+
+ var metadata = [
+ "nativeVisual.detector": "generic_border_ui_detector",
+ "nativeVisual.scriptID": String(box.id),
+ "nativeVisual.kind": box.kind,
+ "nativeVisual.source": box.source,
+ "nativeVisual.borderStrength": String(format: "%.3f", box.borderStrength),
+ "nativeVisual.fillDensity": String(format: "%.3f", box.fillDensity),
+ "nativeVisual.childCount": String(box.childCount),
+ "nativeVisual.textCount": String(box.textCount),
+ "classification.reason": "genericBorderUIDetector"
+ ]
+ if let role = borderDebugOverlayRole(for: box.kind) {
+ metadata["debug.overlayRole"] = role
+ }
+
+ return LocalUIElementCandidate(
+ id: "native-border-\(box.id)-\(slug(box.kind))",
+ source: borderCandidateSource(for: box.source, kind: box.kind),
+ signalKind: borderSignalKind(for: box.source, kind: box.kind),
+ typeHint: borderElementType(for: box.kind),
+ label: label(for: box),
+ bounds: HotLoopRect(
+ x: Double(box.x1),
+ y: Double(box.y1),
+ width: Double(width),
+ height: Double(height),
+ space: pixelSize.space
+ ),
+ confidence: box.confidence,
+ actions: [],
+ metadata: metadata
+ )
+ }
+
+ private static func borderCandidateSource(
+ for source: String,
+ kind: String
+ ) -> LocalUIElementCandidateSource {
+ if source == "containerRowInference" {
+ return .ocr
+ }
+ if ["section", "panel", "card", "controlGroup", "row"].contains(kind) {
+ return .layout
+ }
+ if source == "edgeComponent" {
+ return .shape
+ }
+ return .color
+ }
+
+ private static func borderSignalKind(
+ for source: String,
+ kind: String
+ ) -> LocalUIElementSignalKind {
+ if source == "containerRowInference" || kind == "row" {
+ return .rowGrouping
+ }
+ if source == "edgeComponent" {
+ return .rectangle
+ }
+ if ["section", "panel", "card", "controlGroup"].contains(kind) {
+ return .roundedRectangle
+ }
+ return .colorCluster
+ }
+
+ private static func borderElementType(for kind: String) -> DebugUIElementType {
+ switch kind {
+ case "button":
+ return .button
+ case "iconButton":
+ return .toolbarIcon
+ case "textField":
+ return .input
+ case "row":
+ return .listItem
+ case "menuItem":
+ return .menuItem
+ case "section", "panel", "card", "controlGroup", "unknownControl":
+ return .other
+ default:
+ return .other
+ }
+ }
+
+ private static func borderDebugOverlayRole(for kind: String) -> String? {
+ switch kind {
+ case "button", "iconButton":
+ return "actionButton"
+ case "textField":
+ return "messageInput"
+ case "row":
+ return "panelRow"
+ case "panel", "card", "section", "controlGroup":
+ return "panel"
+ case "unknownControl":
+ return nil
+ default:
+ return nil
+ }
+ }
+
+ private static func label(for box: GenericBorderUIBox) -> String {
+ let trimmed = box.text.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !trimmed.isEmpty {
+ return trimmed
+ }
+ return box.kind
+ }
+
+ private static func algorithmFromEnvironment(
+ environment: [String: String] = ProcessInfo.processInfo.environment
+ ) -> NativeVisualDetectionAlgorithm {
+ let value = environment["DONKEY_NATIVE_VISUAL_DETECTOR"]?
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ .lowercased()
+ switch value {
+ case "interactables", "interactables-v2", "generic-interactables", "generic-interactables-v2":
+ return .interactablesV2
+ case "border", "border-ui", "generic-border", "generic-border-ui":
+ return .borderUI
+ default:
+ return .borderUI
+ }
+ }
+}
+
+private struct NativeVisualDetectionResult: Equatable, Sendable {
+ var detectorName: String
+ var boxCount: Int
+ var candidates: [LocalUIElementCandidate]
+ var summary: String
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift
index 2db7a606..ea7f85b4 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift
@@ -57,14 +57,14 @@ public struct WindowScreenshotCaptureResult: Equatable, Sendable {
}
}
-struct CapturedWindowScreenshot: Equatable, Sendable {
- var pngData: Data
- var imageWidth: Int
- var imageHeight: Int
- var captureMethod: WindowScreenshotCaptureMethod
- var coordinateSpace: String
+public struct CapturedWindowScreenshot: Equatable, Sendable {
+ public var pngData: Data
+ public var imageWidth: Int
+ public var imageHeight: Int
+ public var captureMethod: WindowScreenshotCaptureMethod
+ public var coordinateSpace: String
- init(
+ public init(
pngData: Data,
imageWidth: Int,
imageHeight: Int,
@@ -88,12 +88,14 @@ protocol WindowScreenshotCapturing {
) async throws -> CapturedWindowScreenshot
}
-protocol ScreenRecordingPermissionChecking: Sendable {
+public protocol ScreenRecordingPermissionChecking: Sendable {
func hasScreenRecordingAccess() -> Bool
}
-struct CoreGraphicsScreenRecordingPermissionChecker: ScreenRecordingPermissionChecking {
- func hasScreenRecordingAccess() -> Bool {
+public struct CoreGraphicsScreenRecordingPermissionChecker: ScreenRecordingPermissionChecking {
+ public init() {}
+
+ public func hasScreenRecordingAccess() -> Bool {
CGPreflightScreenCaptureAccess()
}
}
@@ -293,22 +295,22 @@ public final class WindowScreenshotCaptureService {
}
}
-final class ScreenCaptureKitWindowScreenshotCapturer: WindowScreenshotCapturing {
+public final class ScreenCaptureKitWindowScreenshotCapturer: WindowScreenshotCapturing, @unchecked Sendable {
private let permissionChecker: any ScreenRecordingPermissionChecking
- init(permissionChecker: any ScreenRecordingPermissionChecking = CoreGraphicsScreenRecordingPermissionChecker()) {
+ public init(permissionChecker: any ScreenRecordingPermissionChecking = CoreGraphicsScreenRecordingPermissionChecker()) {
self.permissionChecker = permissionChecker
}
- var captureMethod: WindowScreenshotCaptureMethod {
+ public var captureMethod: WindowScreenshotCaptureMethod {
.screenCaptureKitDesktopIndependentWindow
}
- var requiresOverlapFreeTarget: Bool {
+ public var requiresOverlapFreeTarget: Bool {
false
}
- func capture(
+ public func capture(
target: MacWindowTargetCandidate
) async throws -> CapturedWindowScreenshot {
guard permissionChecker.hasScreenRecordingAccess() else {
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift
index 55a6e2c7..e4686f1c 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift
@@ -15,7 +15,7 @@ struct DebugUIInspectionTests {
let config = DebugUIOverlayConfiguration.load(fileURL: url)
#expect(config.enabled == false)
- #expect(config.provider == .accessibility)
+ #expect(config.mode == "donkeyVision")
#expect(config.screenScope == .main)
}
@@ -41,7 +41,7 @@ struct DebugUIInspectionTests {
let config = DebugUIOverlayConfiguration.load(fileURL: url)
#expect(config.enabled == true)
- #expect(config.provider == .accessibility)
+ #expect(config.mode == "donkeyVision")
#expect(config.cadenceSeconds == 1.0)
#expect(config.screenScope == .main)
#expect(config.minConfidence == 0.25)
@@ -81,7 +81,6 @@ struct DebugUIInspectionTests {
"""
{
"enabled": false,
- "provider": "gemini",
"cadenceSeconds": 0.05,
"screenScope": "all",
"minConfidence": 2
@@ -93,7 +92,7 @@ struct DebugUIInspectionTests {
let config = DebugUIOverlayConfiguration.load(fileURL: url)
#expect(config.enabled == false)
- #expect(config.provider == .gemini)
+ #expect(config.mode == "donkeyVision")
#expect(config.cadenceSeconds == 0.25)
#expect(config.screenScope == .all)
#expect(config.minConfidence == 1)
@@ -280,18 +279,24 @@ struct DebugUIInspectionTests {
}
@Test
- func trackerRequiresMultipleSamplesBeforeRenderingNewElement() {
+ func trackerRendersInitialElementsImmediatelyThenRequiresMultipleSamplesForNewElements() {
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)
+ let newElementFirstSample = tracker.update(with: DebugUIInspectionFrame(elements: [
+ element(id: "button-1", label: "Save", x: 10, y: 20),
+ element(id: "button-2", label: "Cancel", x: 110, y: 20)
+ ]))
+ let newElementSecondSample = tracker.update(with: DebugUIInspectionFrame(elements: [
+ element(id: "button-1", label: "Save", x: 10, y: 20),
+ element(id: "button-2", label: "Cancel", x: 110, y: 20)
]))
- #expect(first.elements.isEmpty)
- #expect(second.elements.map(\.id) == ["button-1"])
+ #expect(first.elements.map(\.id) == ["button-1"])
+ #expect(newElementFirstSample.elements.map(\.id) == ["button-1"])
+ #expect(newElementSecondSample.elements.map(\.id) == ["button-1", "button-2"])
}
@Test
@@ -332,7 +337,7 @@ struct DebugUIInspectionTests {
screenPointSize: HotLoopSize(width: 1000, height: 500, space: .screen)
)
- #expect(frame == CGRect(x: 100, y: 350, width: 200, height: 100))
+ #expect(frame == CGRect(x: 100, y: 50, width: 200, height: 100))
}
@Test
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
index dc9e1ae6..6de7d03f 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
@@ -1,5 +1,6 @@
import DonkeyAI
import DonkeyContracts
+import DonkeyRuntime
import Foundation
import Testing
@@ -97,6 +98,344 @@ struct DonkeyBackendInferenceClientTests {
#expect(tools.first?["type"] as? String == "donkey_debug_ui_inspection")
}
+ @Test
+ func parseScreenshotUsesBackendProxyAndDecodesLocalUIUnderstandingResult() async throws {
+ let response = LocalUIUnderstandingResult(
+ visibleText: ["visibleText": "Search"],
+ controls: [
+ LocalUIUnderstandingControl(
+ id: "search",
+ label: "Search",
+ kind: .searchField,
+ frame: HotLoopRect(x: 10, y: 20, width: 100, height: 30, space: .window),
+ confidence: 0.84,
+ metadata: ["controlID": "search"]
+ )
+ ],
+ confidence: 0.84,
+ metadata: ["runtime.backend": "gemini-screenshot-parser"]
+ )
+ let httpClient = FixtureHTTPClient(
+ data: try JSONEncoder().encode(response),
+ statusCode: 200
+ )
+ let client = DonkeyBackendInferenceClient(
+ configuration: configuration(),
+ httpClient: httpClient
+ )
+
+ let result = try await client.parseScreenshot(
+ LocalUIUnderstandingRequest(
+ traceID: "trace-1",
+ targetID: "target-1",
+ imageFileURL: nil,
+ cropBounds: HotLoopRect(x: 0, y: 0, width: 200, height: 100, space: .window),
+ pixelSize: HotLoopSize(width: 200, height: 100, space: .window),
+ metadata: ["source": "test"]
+ ),
+ imageData: Data("png".utf8)
+ )
+
+ #expect(result.controls.first?.id == "search")
+ let request = try #require(httpClient.requests.first)
+ #expect(request.value(forHTTPHeaderField: "Authorization") == nil)
+ #expect(request.value(forHTTPHeaderField: "x-donkey-client-id") == "client-1")
+ #expect(request.url?.path == "/api/inference/screenshots/parse/")
+
+ let object = try #require(request.httpBodyJSONObject)
+ #expect(object["imageBase64"] as? String == Data("png".utf8).base64EncodedString())
+ #expect(object["contentType"] as? String == "image/png")
+ #expect(object["traceID"] as? String == "trace-1")
+ #expect(object["targetID"] as? String == "target-1")
+ let pixelSize = try #require(object["pixelSize"] as? [String: Any])
+ #expect(pixelSize["width"] as? Double == 200)
+ #expect(pixelSize["height"] as? Double == 100)
+ let metadata = try #require(object["metadata"] as? [String: Any])
+ #expect(metadata["screenshot.scope"] as? String == "targetWindow")
+ #expect(metadata["screenshot.desktopCaptureAllowed"] as? String == "false")
+ }
+
+ @Test
+ func screenshotParseOverlayMapperConvertsWindowPixelsToScreenOverlayCoordinates() throws {
+ let result = LocalUIUnderstandingResult(
+ controls: [
+ LocalUIUnderstandingControl(
+ id: "review",
+ label: "Review",
+ kind: .button,
+ frame: HotLoopRect(x: 100, y: 50, width: 200, height: 100, space: .window),
+ confidence: 0.91,
+ metadata: ["controlID": "review"]
+ )
+ ],
+ confidence: 0.91,
+ metadata: ["parserProvider": "gemini-flash"]
+ )
+ let target = MacWindowTargetCandidate(
+ windowID: 42,
+ processID: 100,
+ appName: "Codex",
+ bundleIdentifier: "com.openai.codex",
+ title: "Add screenshot parsing endpoint",
+ bounds: WindowTargetBounds(x: 100, y: 200, width: 500, height: 300),
+ isVisible: true,
+ isOnScreen: true,
+ isFrontmost: true,
+ isFocused: true,
+ isIPhoneMirroring: false,
+ safetyAssessment: WindowTargetSafetyAssessment(
+ status: .allowed,
+ summary: "allowed"
+ )
+ )
+
+ let frame = ScreenshotParseDebugUIOverlayMapper.frame(
+ from: result,
+ target: target,
+ capturePixelSize: HotLoopSize(width: 1_000, height: 600, space: .window),
+ screenFrame: WindowTargetBounds(x: 0, y: 0, width: 1_000, height: 800),
+ minConfidence: 0.25
+ )
+
+ let element = try #require(frame.elements.first)
+ #expect(element.id == "gemini-42-review")
+ #expect(element.type == .button)
+ #expect(element.bbox == DebugUIBoundingBox(x: 150, y: 425, width: 100, height: 50))
+ #expect(element.metadata["directInputActionsAllowed"] == "false")
+ #expect(element.metadata["localUIElement.actionEligibility"] == "readOnlyEvidence")
+ }
+
+ @Test
+ func screenshotParseOverlayMapperUsesCompressedImagePixelSpace() throws {
+ let result = LocalUIUnderstandingResult(
+ controls: [
+ LocalUIUnderstandingControl(
+ id: "compressed-review",
+ label: "Review",
+ kind: .button,
+ frame: HotLoopRect(x: 448, y: 320, width: 112, height: 64, space: .window),
+ confidence: 0.91
+ )
+ ],
+ confidence: 0.91
+ )
+ let target = MacWindowTargetCandidate(
+ windowID: 43,
+ processID: 100,
+ appName: "Codex",
+ bundleIdentifier: "com.openai.codex",
+ title: "Add screenshot parsing endpoint",
+ bounds: WindowTargetBounds(x: 1_440, y: 120, width: 756, height: 540),
+ isVisible: true,
+ isOnScreen: true,
+ isFrontmost: true,
+ isFocused: true,
+ isIPhoneMirroring: false,
+ safetyAssessment: WindowTargetSafetyAssessment(
+ status: .allowed,
+ summary: "allowed"
+ )
+ )
+
+ let frame = ScreenshotParseDebugUIOverlayMapper.frame(
+ from: result,
+ target: target,
+ capturePixelSize: HotLoopSize(width: 896, height: 640, space: .window),
+ screenFrame: WindowTargetBounds(x: 1_440, y: 0, width: 1_440, height: 900),
+ minConfidence: 0.25
+ )
+
+ let bbox = try #require(frame.elements.first?.bbox)
+ #expect(abs(bbox.x - 378) < 0.0001)
+ #expect(abs(bbox.y - 336) < 0.0001)
+ #expect(abs(bbox.width - 94.5) < 0.0001)
+ #expect(abs(bbox.height - 54) < 0.0001)
+ }
+
+ @Test
+ func debugUIFusionKeepsAccessibilityGeometryAndAddsGeminiGaps() throws {
+ let accessibilityFrame = DebugUIInspectionFrame(
+ elements: [
+ DebugUIElement(
+ id: "ax-review",
+ type: .button,
+ label: "Review",
+ bbox: DebugUIBoundingBox(x: 100, y: 100, width: 80, height: 30),
+ confidence: 1,
+ metadata: ["localUIElement.sources": "accessibility"]
+ ),
+ DebugUIElement(
+ id: "ax-window",
+ type: .draggable,
+ label: "Window",
+ bbox: DebugUIBoundingBox(x: 0, y: 0, width: 500, height: 400),
+ confidence: 1,
+ metadata: ["localUIElement.sources": "accessibility"]
+ )
+ ]
+ )
+ let geminiFrame = DebugUIInspectionFrame(
+ elements: [
+ DebugUIElement(
+ id: "gemini-review",
+ type: .button,
+ label: "Review",
+ bbox: DebugUIBoundingBox(x: 105, y: 105, width: 60, height: 20),
+ confidence: 0.95,
+ metadata: ["localUIElement.sources": "gemini-screenshot-parser"]
+ ),
+ DebugUIElement(
+ id: "gemini-voice",
+ type: .toolbarIcon,
+ label: "Voice",
+ bbox: DebugUIBoundingBox(x: 220, y: 100, width: 40, height: 30),
+ confidence: 0.9,
+ metadata: ["localUIElement.sources": "gemini-screenshot-parser"]
+ )
+ ]
+ )
+
+ let fused = DebugUIInspectionFrameFusion.fused(
+ accessibilityFrame: accessibilityFrame,
+ geminiFrame: geminiFrame
+ )
+ let ids = fused.elements.map(\.id)
+
+ #expect(ids.contains("ax-review"))
+ #expect(ids.contains("ax-window"))
+ #expect(!ids.contains("gemini-review"))
+ #expect(ids.contains("gemini-voice"))
+ let geminiElement = try #require(fused.elements.first { $0.id == "gemini-voice" })
+ #expect(geminiElement.metadata["debugUIFusion.source"] == "gemini")
+ #expect(geminiElement.metadata["directInputActionsAllowed"] == "false")
+ #expect(geminiElement.metadata["localUIElement.actionEligibility"] == "readOnlyEvidence")
+ }
+
+ @Test
+ func debugUIFusionDoesNotLetLargeAccessibilityContainersHideGeminiControls() throws {
+ let accessibilityFrame = DebugUIInspectionFrame(
+ elements: [
+ DebugUIElement(
+ id: "ax-sidebar-group",
+ type: .listItem,
+ label: "Sidebar",
+ bbox: DebugUIBoundingBox(x: 0, y: 0, width: 260, height: 700),
+ confidence: 0.8,
+ metadata: ["localUIElement.sources": "accessibility"]
+ )
+ ]
+ )
+ let geminiFrame = DebugUIInspectionFrame(
+ elements: [
+ DebugUIElement(
+ id: "gemini-small-icon",
+ type: .toolbarIcon,
+ label: "Search",
+ bbox: DebugUIBoundingBox(x: 18, y: 84, width: 28, height: 28),
+ confidence: 0.88,
+ metadata: ["localUIElement.sources": "gemini-screenshot-parser"]
+ )
+ ]
+ )
+
+ let fused = DebugUIInspectionFrameFusion.fused(
+ accessibilityFrame: accessibilityFrame,
+ geminiFrame: geminiFrame
+ )
+
+ #expect(fused.elements.map(\.id).contains("gemini-small-icon"))
+ }
+
+ @Test
+ func remoteFallbackDoesNotCallBackendWhenPrimaryEvidenceIsGood() async throws {
+ let httpClient = FixtureHTTPClient(
+ data: try JSONEncoder().encode(LocalUIUnderstandingResult(confidence: 0.9)),
+ statusCode: 200
+ )
+ let adapter = RemoteFallbackLocalUIUnderstandingAdapter(
+ primary: StaticUIUnderstandingRunner(
+ result: LocalUIUnderstandingResult(
+ controls: [
+ LocalUIUnderstandingControl(
+ id: "native-search",
+ label: "Search",
+ kind: .searchField,
+ confidence: 0.86
+ )
+ ],
+ confidence: 0.86
+ )
+ ),
+ remote: RemoteScreenshotParsingLocalUIUnderstandingAdapter(
+ client: DonkeyBackendInferenceClient(
+ configuration: configuration(),
+ httpClient: httpClient
+ )
+ )
+ )
+
+ let result = try await adapter.understand(
+ LocalUIUnderstandingRequest(
+ traceID: "trace-good-primary",
+ targetID: "target-1"
+ )
+ )
+
+ #expect(result.controls.first?.id == "native-search")
+ #expect(httpClient.requests.isEmpty)
+ }
+
+ @Test
+ func remoteFallbackThrottlesUnchangedScreenshots() async throws {
+ let imageURL = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-remote-screenshot-\(UUID().uuidString).png")
+ try Data("same-image".utf8).write(to: imageURL)
+ defer {
+ try? FileManager.default.removeItem(at: imageURL)
+ }
+
+ let remoteResult = LocalUIUnderstandingResult(
+ controls: [
+ LocalUIUnderstandingControl(
+ id: "remote-button",
+ label: "Continue",
+ kind: .button,
+ confidence: 0.9
+ )
+ ],
+ confidence: 0.9
+ )
+ let httpClient = FixtureHTTPClient(
+ data: try JSONEncoder().encode(remoteResult),
+ statusCode: 200
+ )
+ let adapter = RemoteFallbackLocalUIUnderstandingAdapter(
+ primary: StaticUIUnderstandingRunner(
+ result: LocalUIUnderstandingResult(confidence: 0.1)
+ ),
+ remote: RemoteScreenshotParsingLocalUIUnderstandingAdapter(
+ client: DonkeyBackendInferenceClient(
+ configuration: configuration(),
+ httpClient: httpClient
+ )
+ ),
+ throttle: RemoteScreenshotParsingThrottle(minimumInterval: 60)
+ )
+ let request = LocalUIUnderstandingRequest(
+ traceID: "trace-throttle",
+ targetID: "target-throttle",
+ imageFileURL: imageURL,
+ pixelSize: HotLoopSize(width: 100, height: 100, space: .window)
+ )
+
+ let first = try await adapter.understand(request)
+ let second = try await adapter.understand(request)
+
+ #expect(first.controls.first?.id == "remote-button")
+ #expect(second.metadata["remoteScreenshotParsing.status"] == "throttled")
+ #expect(httpClient.requests.count == 1)
+ }
+
@Test
func configurationUsesWebBaseEnvironmentURL() throws {
let configuration = try DonkeyBackendInferenceConfiguration.fromEnvironment([
@@ -438,6 +777,14 @@ private final class FixtureHTTPClient: AIHTTPClient, @unchecked Sendable {
}
}
+private struct StaticUIUnderstandingRunner: LocalUIUnderstandingRunning {
+ var result: LocalUIUnderstandingResult
+
+ func understand(_ request: LocalUIUnderstandingRequest) async throws -> LocalUIUnderstandingResult {
+ result
+ }
+}
+
private extension URLRequest {
var httpBodyJSONObject: [String: Any]? {
guard let httpBody,
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalUIElementDetectionServiceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalUIElementDetectionServiceTests.swift
index 0dd55041..fc80faad 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalUIElementDetectionServiceTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalUIElementDetectionServiceTests.swift
@@ -108,10 +108,10 @@ struct LocalUIElementDetectionServiceTests {
}
@Test
- func nativeVisualDetectorIsStubbedUntilReplacementImplementationExists() {
+ func nativeVisualDetectorFailsClosedWhenDetectorCannotReadScreenshot() {
let trace = LocalUIElementDetectionService().detect(
LocalUIElementDetectionRequest(
- traceID: "trace-native-visual-stub",
+ traceID: "trace-native-visual-invalid-png",
screenshotPNGData: Data([0x89, 0x50, 0x4E, 0x47]),
pixelSize: HotLoopSize(width: 400, height: 300, space: .screen),
minConfidence: 0.25
@@ -120,8 +120,147 @@ struct LocalUIElementDetectionServiceTests {
#expect(trace.candidates.isEmpty)
#expect(trace.elements.isEmpty)
- #expect(trace.metadata["nativeVisual.status"] == "stubbed")
- #expect(trace.metadata["nativeVisual.reason"] == "cvPipelineRemovedPendingReplacement")
+ #expect(trace.metadata["nativeVisual.status"] == "failed")
+ #expect(trace.metadata["nativeVisual.detector"] == "generic_border_ui_detector")
+ #expect(trace.metadata["nativeVisual.algorithm"] == "border-ui")
+ #expect(trace.metadata["nativeVisual.rawPixelsPersisted"] == "false")
+ }
+
+ @Test
+ func nativeDetectorBoxesMapToDebugOverlayCandidatesWithoutGuardedActions() throws {
+ let candidate = try #require(
+ LocalUIElementNativeVisualDetector.candidate(
+ from: GenericInteractableBox(
+ id: 7,
+ x1: 16,
+ y1: 42,
+ x2: 180,
+ y2: 76,
+ text: "Settings",
+ kind: "left_nav_row",
+ confidence: 0.83,
+ source: "ocr+geometry"
+ ),
+ pixelSize: HotLoopSize(width: 400, height: 300, space: .screen)
+ )
+ )
+ let trace = LocalUIElementDetectionService().detect(
+ LocalUIElementDetectionRequest(
+ traceID: "trace-native-visual-box",
+ pixelSize: HotLoopSize(width: 400, height: 300, space: .screen),
+ hoverProbeCandidates: [candidate],
+ minConfidence: 0.25
+ )
+ )
+
+ let element = try #require(trace.elements.first)
+ let frame = LocalUIElementDetectionService().debugInspectionFrame(from: trace)
+ let overlayElement = try #require(frame.elements.first)
+
+ #expect(element.type == .sidebarItem)
+ #expect(element.actionEligibility == .cursorVisualization)
+ #expect(element.metadata["candidate.native-cv-7-left-nav-row.debug.overlayRole"] == "sidebarRow")
+ #expect(overlayElement.id == element.id)
+ #expect(overlayElement.label == "Settings")
+ }
+
+ @Test
+ func borderDetectorBoxesMapToSeparateOverlayCandidates() throws {
+ let candidate = try #require(
+ LocalUIElementNativeVisualDetector.candidate(
+ from: GenericBorderUIBox(
+ id: 4,
+ x1: 24,
+ y1: 36,
+ x2: 220,
+ y2: 80,
+ text: "Search",
+ kind: "textField",
+ confidence: 0.91,
+ source: "filledSurface",
+ borderStrength: 0.81,
+ fillDensity: 0.72,
+ childCount: 0,
+ textCount: 1
+ ),
+ pixelSize: HotLoopSize(width: 400, height: 300, space: .screen)
+ )
+ )
+
+ #expect(candidate.id == "native-border-4-textfield")
+ #expect(candidate.source == .color)
+ #expect(candidate.signalKind == .colorCluster)
+ #expect(candidate.typeHint == .input)
+ #expect(candidate.metadata["debug.overlayRole"] == "messageInput")
+ #expect(candidate.metadata["nativeVisual.detector"] == "generic_border_ui_detector")
+ }
+
+ @Test
+ func compiledGenericInteractableDetectorProducesBoxesWhenDependenciesAreInstalled() throws {
+ let fileManager = FileManager.default
+ let magick = ["/opt/imagemagick/bin/magick", "/opt/homebrew/bin/magick", "/usr/local/bin/magick"]
+ .first { fileManager.isExecutableFile(atPath: $0) }
+ let tesseract = ["/usr/bin/tesseract", "/opt/homebrew/bin/tesseract", "/usr/local/bin/tesseract"]
+ .first { fileManager.isExecutableFile(atPath: $0) }
+ guard let magick, let tesseract else {
+ return
+ }
+
+ let packageRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ let input = packageRoot
+ .appendingPathComponent("Sources/Donkey/Resources/google-continue-dark-rounded.png")
+ let output = fileManager.temporaryDirectory
+ .appendingPathComponent("donkey-generic-interactable-test-\(UUID().uuidString)", isDirectory: true)
+ defer { try? fileManager.removeItem(at: output) }
+
+ let result = try GenericInteractableDetector(
+ magickPath: magick,
+ tesseractPath: tesseract
+ ).detect(
+ inputURL: input,
+ outputDirectory: output
+ )
+
+ #expect(!result.boxes.isEmpty)
+ #expect(fileManager.fileExists(atPath: output.appendingPathComponent("swift_boxes.json").path))
+ #expect(fileManager.fileExists(atPath: output.appendingPathComponent("swift_overlay.svg").path))
+ }
+
+ @Test
+ func compiledBorderUIDetectorProducesBoxesWhenDependenciesAreInstalled() throws {
+ let fileManager = FileManager.default
+ let magick = ["/opt/imagemagick/bin/magick", "/opt/homebrew/bin/magick", "/usr/local/bin/magick"]
+ .first { fileManager.isExecutableFile(atPath: $0) }
+ let tesseract = ["/usr/bin/tesseract", "/opt/homebrew/bin/tesseract", "/usr/local/bin/tesseract"]
+ .first { fileManager.isExecutableFile(atPath: $0) }
+ guard let magick, let tesseract else {
+ return
+ }
+
+ let packageRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ let input = packageRoot
+ .appendingPathComponent("Sources/Donkey/Resources/google-continue-dark-rounded.png")
+ let output = fileManager.temporaryDirectory
+ .appendingPathComponent("donkey-generic-border-ui-test-\(UUID().uuidString)", isDirectory: true)
+ defer { try? fileManager.removeItem(at: output) }
+
+ let result = try GenericBorderUIDetector(
+ magickPath: magick,
+ tesseractPath: tesseract
+ ).detect(
+ inputURL: input,
+ outputDirectory: output
+ )
+
+ #expect(!result.boxes.isEmpty)
+ #expect(fileManager.fileExists(atPath: output.appendingPathComponent("border_boxes.json").path))
+ #expect(fileManager.fileExists(atPath: output.appendingPathComponent("border_overlay.svg").path))
}
@Test
diff --git a/apps/Donkey/dev-overlay.json b/apps/Donkey/dev-overlay.json
index 15461158..a204da9e 100644
--- a/apps/Donkey/dev-overlay.json
+++ b/apps/Donkey/dev-overlay.json
@@ -1,6 +1,6 @@
{
"enabled": true,
- "provider": "accessibility",
+ "mode": "donkeyVision",
"cadenceSeconds": 1.0,
"screenScope": "main",
"minConfidence": 0.25,
diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.md
index 8608c35f..72d2dd5e 100644
--- a/docs/guides/agent-harness.md
+++ b/docs/guides/agent-harness.md
@@ -307,13 +307,15 @@ are fallback observation context only; they do not emit direct input actions.
The local UI element detection service keeps this boundary explicit: it merges
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.
+guarded-action eligible. Native screenshot CV remains a local experimental
+detector, but it is not part of the live Donkey Vision overlay pipeline and
+does not authorize live clicks or text entry.
+The off-the-shelf vision pipeline remains stubbed and must not produce OCR,
+shape, color, layout, segmentation, or tap-target candidates until a new
+measured implementation replaces it. 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 task
metadata and runtime item metadata, not one-off branches for individual apps.
@@ -338,18 +340,18 @@ tool-output feedback.
The developer UI inspection overlay is not an action workflow. It is enabled by
the repo-tracked `apps/Donkey/dev-overlay.json` during debug runs or by a local
`dev-overlay.json` file under Donkey's Application Support directory. Production
-builds do not bundle the repo config. The `accessibility` provider runs the
-local AX-primary UI element detection service and renders merged source badges.
-The local provider only inspects safe visible windows on the selected screen;
+builds do not bundle the repo config. When enabled, Donkey Vision always fuses
+local Accessibility evidence with hosted AI enrichment and renders distinct
+source badges. It 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. 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-only
-inspection route only while a config explicitly enables them, and accept strict
-JSON element metadata only. If a provider returns a computer/function action for
-this route, the client rejects the frame and performs no interaction.
+the debugger reflects durable UI changes instead of sampler noise. The hosted AI
+path sends app/window-scoped screenshots to the read-only inspection route and
+accepts strict JSON element metadata only. If hosted AI returns a
+computer/function action for this route, the client rejects the frame and
+performs no interaction.
## State And Observability
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.md
index fd97e9de..37dba895 100644
--- a/docs/guides/backend-apis.md
+++ b/docs/guides/backend-apis.md
@@ -59,6 +59,12 @@ provider names are configuration/data inside private adapters only.
UI inspection uses `donkey_debug_ui_inspection`; adapters route it through
hosted vision/computer-use-capable models but must not forward or execute UI
action calls.
+- Screenshot parsing is available at `POST /api/inference/screenshots/parse/`.
+ It accepts scoped app/window or system-navigation screenshots only, never
+ whole-desktop captures, and returns read-only UI evidence in the Mac app's
+ local UI understanding shape. The default provider is Gemini 2.5 Flash through
+ a dedicated screenshot-parsing module configured with hosted Google
+ credentials or `GEMINI_API_KEY`.
- The Gemini adapter uses the official `@google/genai` Node/TypeScript SDK for
general non-streaming chat, structured Responses calls, and browser
computer-use calls. It uses Vertex AI's global endpoint only when
diff --git a/docs/guides/donkey-vision.md b/docs/guides/donkey-vision.md
new file mode 100644
index 00000000..97788a88
--- /dev/null
+++ b/docs/guides/donkey-vision.md
@@ -0,0 +1,131 @@
+# Donkey Vision
+
+## What It Is
+
+Donkey Vision is the observation layer that helps Donkey understand what is on a
+user's computer screen well enough to reason about it. It is not a single model
+or a single provider. It is a fusion system: local Mac evidence gives Donkey
+grounded geometry, and AI helps interpret what those grounded regions mean.
+
+The practical goal is simple: when Donkey needs to navigate around a user's
+computer, it should know where UI elements are, what they probably are, and how
+confident it should be. The answer should be useful without pretending that a
+vision model's bounding boxes are perfect.
+
+## Why Fusion Exists
+
+No single source is enough.
+
+Accessibility is the best source when an app exposes good native controls. It
+can give precise bounds, roles, labels, and supported actions. But many modern
+desktop apps are web or Electron shells, and their Accessibility trees can be
+sparse, grouped, stale, or missing important icon controls.
+
+Screenshots see what the user sees. Native visual detection can find shapes,
+rows, panels, input surfaces, and icon-like regions from pixels. It is useful for
+geometry, especially when Accessibility is thin, but it does not always know the
+semantic name of a control.
+
+AI can read the scene and recognize likely UI concepts across apps. It can say
+"this looks like a search field", "this row is a project", or "this icon is a
+voice button." But AI bounding boxes are approximate. They can be off by a few
+pixels, too large, shifted to adjacent text, or attached to the wrong nearby
+region. AI boxes are evidence, not authority.
+
+Donkey Vision combines these strengths:
+
+- Accessibility provides trusted local structure when available.
+- AI provides semantic enrichment and fills gaps.
+- Fusion decides which evidence should render or feed downstream reasoning.
+
+## Geometry Rule
+
+Local geometry wins.
+
+If Donkey has a grounded local box from Accessibility or window chrome
+geometry, that box should be preferred over an overlapping AI box. AI may enrich
+the label or explain what the region probably means, but it should not replace
+precise local geometry with a model-estimated rectangle. Native screenshot CV is
+not part of the live Donkey Vision overlay pipeline.
+
+This is especially important for:
+
+- macOS traffic-light controls and titlebar buttons
+- sidebars and navigation rows
+- search fields and command inputs
+- bottom composers and submit controls
+- small icon-only toolbar buttons
+- repeated list rows where nearby text can confuse model localization
+
+AI-only boxes are still useful when no local evidence covers that part of the
+screen. They should be marked as AI/read-only evidence so maintainers can see
+that the position came from the model.
+
+## Safety Boundary
+
+Donkey Vision is observation. It does not authorize live input by itself.
+
+Vision evidence can help Donkey plan, explain, debug, and decide where to look
+next. Live input still has to pass through the guarded action boundary: target
+validation, focus checks, permission policy, action eligibility, and runtime
+verification.
+
+AI-derived evidence is especially constrained:
+
+- AI boxes are read-only evidence.
+- AI output must not enable direct clicks, typing, scrolling, or dragging.
+- Screenshots sent to hosted AI must be scoped to an app/window or a
+ system-navigation surface, never the full desktop.
+- Screenshots are not persisted or logged as general product data.
+
+## Developer Overlay
+
+The developer overlay is a way to see Donkey Vision while debugging. It should
+render multiple evidence sources at the same time, with visible source badges:
+
+- `AX` for Accessibility-backed boxes
+- `AI` for hosted AI boxes
+
+The distinction matters. If an `AI` box is visibly off, that is expected model
+localization error and should not be fixed by adding arbitrary coordinate
+offsets. Prefer improving local geometry, fusion, or the screenshot scope. If an
+`AX` box is off, that is a local coordinate mapping bug and should be fixed in
+the Mac geometry path.
+
+The debug config uses Donkey Vision as the mode:
+
+```json
+{
+ "enabled": true,
+ "mode": "donkeyVision",
+ "cadenceSeconds": 1.0,
+ "screenScope": "main",
+ "minConfidence": 0.25,
+ "activeWindowOnly": true
+}
+```
+
+Do not add a provider field to this config. Donkey Vision is always local AX
+evidence plus hosted AI enrichment; the config controls cadence, scope, and
+filters, not which evidence source runs.
+
+## Source Map
+
+High-signal entry points:
+
+- `apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift`
+- `apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift`
+- `apps/Donkey/Sources/DonkeyAI/DebugUIInspectionFrameFusion.swift`
+- `apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift`
+- `apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionService.swift`
+- `site/src/lib/inference/screenshot-parsing/`
+
+## Maintainer Rules
+
+- Do not treat model boxes as pixel-perfect.
+- Do not add global coordinate offsets to compensate for AI localization.
+- Do not send full-desktop screenshots to hosted AI.
+- Do not make provider selection the UI or config model for Donkey Vision.
+- Prefer app/window-scoped screenshots and local geometry.
+- Keep AI evidence marked and visually distinct.
+- Keep live input authorization separate from visual evidence.
diff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.md
index fb566e15..083fdc73 100644
--- a/docs/guides/pointer-prompt-overlay.md
+++ b/docs/guides/pointer-prompt-overlay.md
@@ -27,27 +27,22 @@ quick local-app actions:
- 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.
-- A developer-only UI inspection overlay can be enabled by editing the
+- A developer-only Donkey Vision overlay can be enabled by editing the
repo-tracked `apps/Donkey/dev-overlay.json` during debug runs, or by creating
`~/Library/Application Support/Donkey/dev-overlay.json`. Production builds do
not bundle the repo config and only honor the Application Support path. When
no config exists, the config is invalid, or `"enabled": false`, the debug
- overlay is fully disabled. When enabled with `"provider": "accessibility"`,
- it uses the local UI element detection service: invisible Accessibility reads
- 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.
+ overlay is fully disabled. When enabled, Donkey Vision fuses Accessibility and
+ hosted AI screenshot parsing. Local geometry wins; AI boxes are read-only
+ evidence and are visually marked as `AI`. The overlay never sends a full
+ desktop screenshot to hosted AI: it captures safe app/window or
+ system-navigation surfaces only. See
+ `docs/guides/donkey-vision.md`.
```json
{
"enabled": true,
- "provider": "accessibility",
+ "mode": "donkeyVision",
"cadenceSeconds": 1.0,
"screenScope": "main",
"minConfidence": 0.25
diff --git a/scripts/run-donkey-dev.sh b/scripts/run-donkey-dev.sh
index 63c2d936..d3ee5698 100755
--- a/scripts/run-donkey-dev.sh
+++ b/scripts/run-donkey-dev.sh
@@ -125,10 +125,10 @@ with open(sys.argv[1], "r", encoding="utf-8") as handle:
config = json.load(handle)
print(
- "enabled={enabled} provider={provider} cadenceSeconds={cadence} "
+ "enabled={enabled} mode={mode} cadenceSeconds={cadence} "
"screenScope={scope} minConfidence={confidence}".format(
enabled=config.get("enabled", False),
- provider=config.get("provider", "accessibility"),
+ mode=config.get("mode", "donkeyVision"),
cadence=config.get("cadenceSeconds", 1.0),
scope=config.get("screenScope", "main"),
confidence=config.get("minConfidence", 0.25),
diff --git a/site/src/app/api/inference/screenshots/parse/route.ts b/site/src/app/api/inference/screenshots/parse/route.ts
new file mode 100644
index 00000000..9b9a4eb4
--- /dev/null
+++ b/site/src/app/api/inference/screenshots/parse/route.ts
@@ -0,0 +1,115 @@
+import { NextResponse } from "next/server";
+
+import {
+ creditUsageHeaders,
+ inferenceUsageRoutes,
+ recordInferenceUsage,
+ requireInferenceCredits,
+} from "@/lib/credits/inference";
+import { withDonkeyAuth } from "@/lib/donkey-api-auth";
+import { InferenceProviderError } from "@/lib/inference/providers";
+import {
+ checkInMemoryRateLimit,
+ rateLimitResponse,
+} from "@/lib/inference/rate-limit";
+import { readLimitedJsonBody } from "@/lib/inference/request-body";
+import {
+ requireInferenceClientId,
+ validationErrorResponse,
+} from "@/lib/inference/responses";
+import {
+ parseScreenshot,
+ screenshotParseModelForRequest,
+} from "@/lib/inference/screenshot-parsing";
+import { screenshotParseRequestSchema } from "@/lib/inference/screenshot-parsing/schema";
+
+export const dynamic = "force-dynamic";
+
+const screenshotParseMaxBodyBytes = 6_250_000;
+const screenshotParseRateLimit = {
+ limit: 4,
+ windowMs: 3_000,
+};
+
+export const POST = withDonkeyAuth(async (request) => {
+ const client = requireInferenceClientId(request.donkey.clientId);
+ if (!client.ok) {
+ return client.response;
+ }
+
+ const rateLimit = checkInMemoryRateLimit({
+ key: `${request.donkey.userId}:${client.clientId}`,
+ ...screenshotParseRateLimit,
+ });
+ if (!rateLimit.ok) {
+ return rateLimitResponse(rateLimit.retryAfterSeconds);
+ }
+
+ const body = await readLimitedJsonBody(request, screenshotParseMaxBodyBytes);
+ if (!body.ok) {
+ return body.response;
+ }
+
+ const parsed = screenshotParseRequestSchema.safeParse(body.json);
+ if (!parsed.success) {
+ return validationErrorResponse(parsed.error);
+ }
+ if (parsed.data.metadata["screenshot.scope"] === "desktop") {
+ return NextResponse.json(
+ {
+ error: "Unsupported screenshot scope",
+ message: "Screenshot parsing accepts app/window or system-navigation screenshots, not full-desktop captures.",
+ },
+ { status: 400 },
+ );
+ }
+
+ const model = screenshotParseModelForRequest(parsed.data);
+ const credits = await requireInferenceCredits({
+ model,
+ provider: "gemini",
+ route: inferenceUsageRoutes.screenshotParse,
+ userId: request.donkey.userId,
+ });
+ if (!credits.ok) {
+ return credits.response;
+ }
+
+ try {
+ const result = await parseScreenshot(parsed.data);
+ const recordedUsage = await recordInferenceUsage({
+ clientId: client.clientId,
+ metadata: {
+ parserProvider: "gemini-flash",
+ },
+ model: result.model,
+ provider: result.provider,
+ requestKind: "screenshot_parse",
+ route: inferenceUsageRoutes.screenshotParse,
+ status: "succeeded",
+ usage: result.usage,
+ userId: request.donkey.userId,
+ });
+
+ return NextResponse.json(result.result, {
+ headers: {
+ "X-Donkey-Inference-Provider": result.provider,
+ "X-Donkey-Inference-Model": result.model,
+ ...creditUsageHeaders(recordedUsage),
+ },
+ });
+ } catch (error) {
+ if (error instanceof InferenceProviderError) {
+ return NextResponse.json(
+ {
+ error: error.code,
+ message: error.message,
+ details: error.details,
+ },
+ { status: error.statusCode },
+ );
+ }
+
+ throw error;
+ }
+});
diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.ts
index 84a5fad7..3521410f 100644
--- a/site/src/lib/credits/inference.ts
+++ b/site/src/lib/credits/inference.ts
@@ -19,6 +19,7 @@ export const inferenceUsageRoutes = {
assetsRefresh: "/api/inference/assets/refresh/",
chatCompletions: "/api/inference/chat/completions/",
responses: "/api/inference/responses/",
+ screenshotParse: "/api/inference/screenshots/parse/",
} as const;
type CreditsDatabase = PrismaClient | Prisma.TransactionClient;
diff --git a/site/src/lib/inference/rate-limit.ts b/site/src/lib/inference/rate-limit.ts
new file mode 100644
index 00000000..37a93433
--- /dev/null
+++ b/site/src/lib/inference/rate-limit.ts
@@ -0,0 +1,90 @@
+import { NextResponse } from "next/server";
+
+type RateLimitBucket = {
+ windowStartedAt: number;
+ count: number;
+};
+
+const globalBucketsKey = "__donkeyInferenceRateLimitBuckets";
+
+type GlobalWithBuckets = typeof globalThis & {
+ [globalBucketsKey]?: Map<string, RateLimitBucket>;
+};
+
+type RateLimitInput = {
+ key: string;
+ limit: number;
+ windowMs: number;
+ now?: number;
+};
+
+export function checkInMemoryRateLimit(input: RateLimitInput) {
+ const now = input.now ?? Date.now();
+ const buckets = rateLimitBuckets();
+ const current = buckets.get(input.key);
+ if (!current || now - current.windowStartedAt >= input.windowMs) {
+ buckets.set(input.key, {
+ windowStartedAt: now,
+ count: 1,
+ });
+ pruneBuckets(buckets, now, input.windowMs);
+ return {
+ ok: true as const,
+ remaining: input.limit - 1,
+ resetAt: now + input.windowMs,
+ };
+ }
+
+ if (current.count >= input.limit) {
+ return {
+ ok: false as const,
+ retryAfterSeconds: Math.max(1, Math.ceil((current.windowStartedAt + input.windowMs - now) / 1000)),
+ resetAt: current.windowStartedAt + input.windowMs,
+ };
+ }
+
+ current.count += 1;
+ return {
+ ok: true as const,
+ remaining: input.limit - current.count,
+ resetAt: current.windowStartedAt + input.windowMs,
+ };
+}
+
+export function rateLimitResponse(retryAfterSeconds: number) {
+ return NextResponse.json(
+ {
+ error: "rate_limited",
+ message: "Too many screenshot parse requests. Please retry shortly.",
+ },
+ {
+ headers: {
+ "Retry-After": String(retryAfterSeconds),
+ },
+ status: 429,
+ },
+ );
+}
+
+function rateLimitBuckets() {
+ const globalWithBuckets = globalThis as GlobalWithBuckets;
+ globalWithBuckets[globalBucketsKey] ??= new Map<string, RateLimitBucket>();
+ return globalWithBuckets[globalBucketsKey];
+}
+
+function pruneBuckets(
+ buckets: Map<string, RateLimitBucket>,
+ now: number,
+ windowMs: number,
+) {
+ if (buckets.size < 1_000) {
+ return;
+ }
+
+ const staleBefore = now - windowMs * 2;
+ for (const [key, bucket] of buckets) {
+ if (bucket.windowStartedAt < staleBefore) {
+ buckets.delete(key);
+ }
+ }
+}
diff --git a/site/src/lib/inference/request-body.ts b/site/src/lib/inference/request-body.ts
new file mode 100644
index 00000000..afd56dd3
--- /dev/null
+++ b/site/src/lib/inference/request-body.ts
@@ -0,0 +1,134 @@
+import { NextResponse } from "next/server";
+
+type LimitedJsonResult =
+ | {
+ ok: true;
+ json: unknown;
+ }
+ | {
+ ok: false;
+ response: Response;
+ };
+
+export async function readLimitedJsonBody(
+ request: Request,
+ maxBytes: number,
+): Promise<LimitedJsonResult> {
+ const contentType = request.headers.get("content-type") ?? "";
+ if (!contentType.toLowerCase().includes("application/json")) {
+ return {
+ ok: false,
+ response: NextResponse.json(
+ {
+ error: "Unsupported media type",
+ message: "Request body must be application/json.",
+ },
+ { status: 415 },
+ ),
+ };
+ }
+
+ const contentLength = contentLengthBytes(request.headers);
+ if (contentLength !== null && contentLength > maxBytes) {
+ return {
+ ok: false,
+ response: payloadTooLargeResponse(maxBytes),
+ };
+ }
+
+ const body = await readTextBody(request, maxBytes);
+ if (!body.ok) {
+ return body;
+ }
+
+ try {
+ return {
+ ok: true,
+ json: JSON.parse(body.text),
+ };
+ } catch {
+ return {
+ ok: false,
+ response: NextResponse.json(
+ {
+ error: "Invalid JSON",
+ message: "Request body must be valid JSON.",
+ },
+ { status: 400 },
+ ),
+ };
+ }
+}
+
+function contentLengthBytes(headers: Headers) {
+ const raw = headers.get("content-length");
+ if (!raw) {
+ return null;
+ }
+
+ const value = Number(raw);
+ return Number.isFinite(value) && value >= 0 ? value : null;
+}
+
+async function readTextBody(
+ request: Request,
+ maxBytes: number,
+): Promise<
+ | {
+ ok: true;
+ text: string;
+ }
+ | {
+ ok: false;
+ response: Response;
+ }
+> {
+ const reader = request.body?.getReader();
+ if (!reader) {
+ return {
+ ok: false,
+ response: NextResponse.json(
+ {
+ error: "Invalid request",
+ message: "Request body is required.",
+ },
+ { status: 400 },
+ ),
+ };
+ }
+
+ const decoder = new TextDecoder();
+ const chunks: string[] = [];
+ let byteCount = 0;
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) {
+ break;
+ }
+ byteCount += value.byteLength;
+ if (byteCount > maxBytes) {
+ return {
+ ok: false,
+ response: payloadTooLargeResponse(maxBytes),
+ };
+ }
+ chunks.push(decoder.decode(value, { stream: true }));
+ }
+
+ chunks.push(decoder.decode());
+ return {
+ ok: true,
+ text: chunks.join(""),
+ };
+}
+
+function payloadTooLargeResponse(maxBytes: number) {
+ return NextResponse.json(
+ {
+ error: "Payload too large",
+ message: `Request body must be ${maxBytes} bytes or smaller.`,
+ },
+ { status: 413 },
+ );
+}
diff --git a/site/src/lib/inference/screenshot-parsing/gemini-flash.ts b/site/src/lib/inference/screenshot-parsing/gemini-flash.ts
new file mode 100644
index 00000000..53e139b2
--- /dev/null
+++ b/site/src/lib/inference/screenshot-parsing/gemini-flash.ts
@@ -0,0 +1,573 @@
+import {
+ ApiError,
+ GoogleGenAI,
+ MediaResolution,
+ Type,
+} from "@google/genai";
+import { JWT, type JWTInput } from "google-auth-library";
+import type {
+ GenerateContentParameters,
+ GoogleGenAIOptions,
+ Schema,
+} from "@google/genai";
+
+import { ensureConfigured } from "@/lib/inference/http";
+import {
+ isJsonObject,
+ toJsonObject,
+ toJsonValue,
+} from "@/lib/inference/json";
+import {
+ InferenceProviderError,
+ type JsonObject,
+ type JsonValue,
+} from "@/lib/inference/providers";
+import {
+ geminiScreenshotParseOutputSchema,
+ type GeminiScreenshotParseOutput,
+ type HotLoopRectJSON,
+ type ScreenshotParseRequest,
+} from "@/lib/inference/screenshot-parsing/schema";
+import type {
+ ScreenshotParserProvider,
+ ScreenshotParserProviderResult,
+ ScreenshotParserResult,
+} from "@/lib/inference/screenshot-parsing/types";
+
+type AdapterEnvironment = Record<string, string | undefined>;
+type GeminiClient = Pick<GoogleGenAI, "models">;
+type GeminiClientFactory = (options: GoogleGenAIOptions) => GeminiClient;
+
+const geminiProviderID = "gemini";
+const screenshotProviderID = "gemini-flash";
+const defaultScreenshotParseModel = "gemini-2.5-flash";
+const defaultDebugOverlayScreenshotParseModel = "gemini-2.5-flash";
+const defaultVertexLocation = "global";
+const vertexAIScope = "https://www.googleapis.com/auth/cloud-platform";
+
+export function createGeminiFlashScreenshotParser(
+ environment: AdapterEnvironment = process.env,
+ clientFactory: GeminiClientFactory = (options) => new GoogleGenAI(options),
+): ScreenshotParserProvider {
+ const config = geminiClientConfig(environment);
+
+ return {
+ configured: config.configured,
+ async parse(request) {
+ ensureConfigured(config.configured);
+ const client = clientFactory(config.options);
+ const model = screenshotParseModelForRequest(request, environment);
+ const startedAt = performance.now();
+
+ let rawResponse: unknown;
+ try {
+ rawResponse = await client.models.generateContent(
+ geminiRequestParameters(request, model),
+ );
+ } catch (error) {
+ throw geminiProviderError(error);
+ }
+
+ const rawBody = toJsonValue(rawResponse);
+ const output = parseGeminiOutput(rawBody);
+ const result = normalizedScreenshotResult(request, output, {
+ provider: geminiProviderID,
+ parserProvider: screenshotProviderID,
+ model,
+ service: config.service,
+ location: config.location,
+ latencyMs: String(Math.round(performance.now() - startedAt)),
+ });
+
+ return {
+ provider: geminiProviderID,
+ model,
+ result,
+ usage: usageFromGeminiResponse(rawBody),
+ metadata: result.metadata,
+ };
+ },
+ };
+}
+
+export function screenshotParseModelForRequest(
+ request: ScreenshotParseRequest,
+ environment: AdapterEnvironment = process.env,
+) {
+ if (isDebugOverlayRequest(request)) {
+ return environment.GEMINI_SCREENSHOT_PARSE_DEBUG_MODEL?.trim()
+ || environment.GEMINI_SCREENSHOT_PARSE_MODEL?.trim()
+ || defaultDebugOverlayScreenshotParseModel;
+ }
+
+ return environment.GEMINI_SCREENSHOT_PARSE_MODEL?.trim()
+ || defaultScreenshotParseModel;
+}
+
+export function normalizedScreenshotResult(
+ request: ScreenshotParseRequest,
+ output: GeminiScreenshotParseOutput,
+ metadata: Record<string, string>,
+): ScreenshotParserResult {
+ const visibleText = output.visibleText.reduce<Record<string, string>>((result, item, index) => {
+ const key = item.id?.trim() || (index === 0 ? "visibleText" : `visibleText.${index + 1}`);
+ result[key] = item.text;
+ return result;
+ }, {});
+
+ const controls = output.controls.map((control, index) => {
+ const id = control.id?.trim() || `gemini-control-${index + 1}`;
+ return {
+ id,
+ label: control.label,
+ kind: control.kind,
+ frame: rectFromGeminiBox(control.box_2d, request.pixelSize.width, request.pixelSize.height),
+ confidence: clamp01(control.confidence),
+ metadata: {
+ controlID: id,
+ source: "gemini-screenshot-parser",
+ boxFormat: "ymin,xmin,ymax,xmax/1000",
+ },
+ };
+ });
+
+ const formFields = output.formFields.map((field, index) => {
+ const id = field.id?.trim() || `gemini-form-field-${index + 1}`;
+ return {
+ id,
+ label: field.label,
+ isRequired: field.isRequired,
+ currentValue: field.currentValue ?? null,
+ metadata: {
+ source: "gemini-screenshot-parser",
+ confidence: String(clamp01(field.confidence)),
+ },
+ };
+ });
+
+ return {
+ visibleText,
+ controls,
+ formFields,
+ confidence: clamp01(output.confidence || controls.map((control) => control.confidence).reduce(
+ (max, value) => Math.max(max, value),
+ 0,
+ )),
+ metadata: toJsonObject({
+ ...metadata,
+ "runtime.backend": "gemini-screenshot-parser",
+ "directInputActionsAllowed": "false",
+ "screenshotParser.controlCount": String(controls.length),
+ "screenshotParser.formFieldCount": String(formFields.length),
+ }),
+ };
+}
+
+function geminiRequestParameters(
+ request: ScreenshotParseRequest,
+ model: string,
+): GenerateContentParameters {
+ const profile = screenshotParseProfile(request);
+ return {
+ model,
+ contents: [
+ {
+ role: "user",
+ parts: [
+ {
+ text: screenshotParsingPrompt(request),
+ },
+ {
+ inlineData: {
+ data: request.imageBase64,
+ mimeType: request.contentType,
+ },
+ },
+ ],
+ },
+ ],
+ config: {
+ mediaResolution: profile.mediaResolution,
+ responseMimeType: "application/json",
+ responseSchema: geminiOutputSchema,
+ temperature: 0,
+ topP: 0.1,
+ candidateCount: 1,
+ maxOutputTokens: profile.maxOutputTokens,
+ thinkingConfig: {
+ thinkingBudget: 0,
+ },
+ },
+ };
+}
+
+function screenshotParsingPrompt(request: ScreenshotParseRequest) {
+ if (isDebugOverlayRequest(request)) {
+ return [
+ "You are a read-only UI screenshot parser for a macOS developer inspection overlay.",
+ "The screenshot is a single app/window capture, never the entire desktop.",
+ "Return compact JSON matching the provided schema.",
+ "For this overlay profile, visibleText must be [] and formFields must be []; put readable names only in control labels.",
+ "Return bounding boxes for the full visible clickable/control region, not just the text glyphs or icon pixels.",
+ "Treat compound controls as one control when a symbol/icon and nearby text visually act together; the box should cover the icon, text, and full hit target.",
+ "Treat standalone symbols/icons as controls when they use standard UI shapes or placement, even if there is no visible text label.",
+ "For nav/sidebar/list/file rows, box the entire row target including icon, label, and selection background when visible.",
+ "Always include macOS titlebar controls and toolbar controls when visible: red/yellow/green traffic lights, sidebar toggle, back/forward arrows, title actions, and top-right toolbar icons.",
+ "Always include bottom composer/input controls when visible: the text input surface, add/attachment button, mode selector, model selector, mic/voice button, and send/stop button.",
+ "Deliberately scan the top edge of the image from left to right for small window chrome controls, navigation icons, segmented controls, menus, status buttons, and titlebar actions.",
+ "Deliberately scan the bottom edge of the image from left to right for composer/input areas, accessory icons, dropdown selectors, microphone controls, submit/stop controls, and other docked toolbars.",
+ "Small circular or icon-only controls near the top or bottom edges should be included even when they have no readable text; infer a concise generic label such as close, minimize, zoom, back, forward, add, voice, submit, or stop when visually supported.",
+ "Prioritize visible controls and selectable regions that are useful to draw debug boxes: buttons, icon buttons, nav/sidebar rows, tabs, menus, file rows, list rows, links, inputs, titlebar controls, and bottom composer controls.",
+ "Do not include decorative backgrounds, separators, or long static prose blocks unless they are clickable/selectable regions.",
+ "Prefer 25-55 high-confidence controls over an exhaustive map.",
+ "Use box_2d as [ymin, xmin, ymax, xmax] normalized to 0-1000 over the full image.",
+ "Use concise labels copied from visible text when possible.",
+ `Image pixel size: ${request.pixelSize.width}x${request.pixelSize.height}.`,
+ `Target ID: ${request.targetID ?? "unknown"}.`,
+ ].join("\n");
+ }
+
+ return [
+ "You are a read-only UI screenshot parser for a macOS app automation system.",
+ "The screenshot is scoped to an app/window or a system-navigation surface, never the entire desktop.",
+ "Extract only visible, grounded UI evidence from that scoped screenshot.",
+ "Do not infer user intent, do not suggest actions, and do not return executable commands.",
+ "Return JSON matching the provided schema.",
+ "Be dense: return all visible navigation rows, sidebar items, tabs, buttons, icon buttons, menus, file/change rows, input fields, checkboxes, links, cards, list items, and important text regions.",
+ "Treat controls as visual affordances, not only text. Many controls are a symbol/icon plus a label, a symbol inside a button shape, or an icon-only target; box the complete hit target rather than only the glyphs.",
+ "Do not stop after the primary content. Include left navigation, right panels, bottom composers/toolbars, title bars, and repeated rows when visible.",
+ "Use kind=listItem for selectable rows or navigation entries, kind=group for non-clickable labeled regions/cards, and kind=unknown only when no better kind fits.",
+ "Prefer returning more grounded UI elements over a sparse summary. Aim for 40-120 controls on a complex desktop app screenshot when that many distinct regions are visible.",
+ "visibleText should contain the most important readable text snippets, including text from controls.",
+ "Use box_2d as [ymin, xmin, ymax, xmax] normalized to 0-1000 over the full image.",
+ "Use concise labels copied from visible text when possible.",
+ `Image pixel size: ${request.pixelSize.width}x${request.pixelSize.height}.`,
+ `Screenshot scope: ${request.metadata["screenshot.scope"] ?? "targetWindow"}.`,
+ `Target ID: ${request.targetID ?? "unknown"}.`,
+ ].join("\n");
+}
+
+function screenshotParseProfile(request: ScreenshotParseRequest) {
+ if (isDebugOverlayRequest(request)) {
+ return {
+ mediaResolution: MediaResolution.MEDIA_RESOLUTION_LOW,
+ maxOutputTokens: 4_096,
+ };
+ }
+
+ return {
+ mediaResolution: MediaResolution.MEDIA_RESOLUTION_HIGH,
+ maxOutputTokens: 16_384,
+ };
+}
+
+function isDebugOverlayRequest(request: ScreenshotParseRequest) {
+ return request.metadata.source === "debug-ui-inspection-overlay"
+ || request.metadata.provider === "gemini";
+}
+
+function parseGeminiOutput(rawBody: JsonValue) {
+ const text = geminiText(rawBody);
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ throw new InferenceProviderError("Gemini returned invalid screenshot parser JSON.", {
+ statusCode: 502,
+ code: "invalid_provider_output",
+ });
+ }
+
+ const output = geminiScreenshotParseOutputSchema.safeParse(parsed);
+ if (!output.success) {
+ throw new InferenceProviderError("Gemini screenshot parser output did not match schema.", {
+ statusCode: 502,
+ code: "invalid_provider_output",
+ details: {
+ issues: output.error.issues.map((issue) => ({
+ path: issue.path.join("."),
+ message: issue.message,
+ })),
+ },
+ });
+ }
+
+ return output.data;
+}
+
+function geminiText(rawBody: JsonValue) {
+ if (isJsonObject(rawBody) && typeof rawBody.text === "string") {
+ return rawBody.text;
+ }
+ const candidates = isJsonObject(rawBody) && Array.isArray(rawBody.candidates)
+ ? rawBody.candidates
+ : [];
+ const first = candidates.find(isJsonObject);
+ const content = first ? first.content : undefined;
+ const parts = content !== undefined && isJsonObject(content) && Array.isArray(content.parts)
+ ? content.parts
+ : [];
+ return parts
+ .filter(isJsonObject)
+ .map((part) => typeof part.text === "string" ? part.text : "")
+ .join("")
+ .trim();
+}
+
+export function rectFromGeminiBox(
+ box: [number, number, number, number],
+ imageWidth: number,
+ imageHeight: number,
+): HotLoopRectJSON | null {
+ const [ymin, xmin, ymax, xmax] = box;
+ const x1 = clamp(xmin, 0, 1000) / 1000 * imageWidth;
+ const y1 = clamp(ymin, 0, 1000) / 1000 * imageHeight;
+ const x2 = clamp(xmax, 0, 1000) / 1000 * imageWidth;
+ const y2 = clamp(ymax, 0, 1000) / 1000 * imageHeight;
+ const width = Math.max(0, x2 - x1);
+ const height = Math.max(0, y2 - y1);
+ if (width <= 0 || height <= 0) {
+ return null;
+ }
+
+ return {
+ origin: {
+ x: x1,
+ y: y1,
+ space: "window",
+ },
+ size: {
+ width,
+ height,
+ space: "window",
+ },
+ };
+}
+
+function usageFromGeminiResponse(rawBody: JsonValue): JsonValue | undefined {
+ if (!isJsonObject(rawBody)) {
+ return undefined;
+ }
+ const usage = rawBody.usageMetadata ?? rawBody.usage;
+ return usage === undefined ? undefined : toJsonValue(usage);
+}
+
+function clamp01(value: number) {
+ return clamp(value, 0, 1);
+}
+
+function clamp(value: number, lower: number, upper: number) {
+ return Math.min(Math.max(value, lower), upper);
+}
+
+const geminiOutputSchema: Schema = {
+ type: Type.OBJECT,
+ required: ["visibleText", "controls", "formFields", "confidence"],
+ properties: {
+ visibleText: {
+ type: Type.ARRAY,
+ items: {
+ type: Type.OBJECT,
+ required: ["text", "confidence"],
+ properties: {
+ id: { type: Type.STRING },
+ text: { type: Type.STRING },
+ confidence: { type: Type.NUMBER, minimum: 0, maximum: 1 },
+ },
+ },
+ },
+ controls: {
+ type: Type.ARRAY,
+ items: {
+ type: Type.OBJECT,
+ required: ["label", "kind", "confidence", "box_2d"],
+ properties: {
+ id: { type: Type.STRING },
+ label: { type: Type.STRING },
+ kind: { type: Type.STRING },
+ confidence: { type: Type.NUMBER, minimum: 0, maximum: 1 },
+ box_2d: {
+ type: Type.ARRAY,
+ items: { type: Type.NUMBER, minimum: 0, maximum: 1000 },
+ },
+ },
+ },
+ },
+ formFields: {
+ type: Type.ARRAY,
+ items: {
+ type: Type.OBJECT,
+ required: ["label", "isRequired", "confidence"],
+ properties: {
+ id: { type: Type.STRING },
+ label: { type: Type.STRING },
+ isRequired: { type: Type.BOOLEAN },
+ currentValue: { type: Type.STRING },
+ confidence: { type: Type.NUMBER, minimum: 0, maximum: 1 },
+ box_2d: {
+ type: Type.ARRAY,
+ items: { type: Type.NUMBER, minimum: 0, maximum: 1000 },
+ },
+ },
+ },
+ },
+ confidence: { type: Type.NUMBER, minimum: 0, maximum: 1 },
+ },
+};
+
+function geminiClientConfig(environment: AdapterEnvironment): {
+ configured: boolean;
+ options: GoogleGenAIOptions;
+ service: "vertex-ai" | "gemini-api";
+ location: string;
+} {
+ const apiVersion = environment.GEMINI_API_VERSION?.trim() || undefined;
+ const timeout = numberFromString(environment.GEMINI_TIMEOUT_MS);
+ const httpOptions: GoogleGenAIOptions["httpOptions"] | undefined =
+ timeout === undefined ? undefined : { timeout };
+ const googleCredentials = googleCredentialsFromEnvironment(environment);
+ const project = googleCredentials?.project_id;
+ const apiKey =
+ environment.GEMINI_API_KEY?.trim()
+ || environment.GOOGLE_API_KEY?.trim()
+ || "";
+
+ if (project) {
+ const location = environment.GEMINI_VERTEX_LOCATION?.trim()
+ || environment.GOOGLE_VERTEX_LOCATION?.trim()
+ || defaultVertexLocation;
+ const options: GoogleGenAIOptions = {
+ vertexai: true,
+ location,
+ project,
+ };
+ if (apiVersion) {
+ options.apiVersion = apiVersion;
+ }
+ if (httpOptions) {
+ options.httpOptions = httpOptions;
+ }
+ if (googleCredentials) {
+ options.googleAuthOptions = {
+ authClient: googleAuthClient(googleCredentials),
+ };
+ }
+ return {
+ configured: true,
+ options,
+ service: "vertex-ai",
+ location,
+ };
+ }
+
+ const options: GoogleGenAIOptions = {};
+ if (apiKey) {
+ options.apiKey = apiKey;
+ }
+ if (apiVersion) {
+ options.apiVersion = apiVersion;
+ }
+ if (httpOptions) {
+ options.httpOptions = httpOptions;
+ }
+
+ return {
+ configured: Boolean(apiKey),
+ options,
+ service: "gemini-api",
+ location: "global",
+ };
+}
+
+function googleCredentialsFromEnvironment(
+ environment: AdapterEnvironment,
+): JWTInput | undefined {
+ const rawCredentials = environment.GOOGLE_APPLICATION_CREDENTIALS_JSON?.trim();
+ if (!rawCredentials) {
+ return undefined;
+ }
+
+ return serviceAccountCredentials(rawCredentials);
+}
+
+function googleAuthClient(credentials: JWTInput) {
+ return new JWT({
+ email: credentials.client_email,
+ key: credentials.private_key,
+ keyId: credentials.private_key_id,
+ scopes: [vertexAIScope],
+ });
+}
+
+function serviceAccountCredentials(rawCredentials: string): JWTInput {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawCredentials);
+ } catch {
+ throw new InferenceProviderError("Google service account JSON is invalid.", {
+ statusCode: 500,
+ code: "invalid_google_service_account_json",
+ });
+ }
+
+ const credentials = toJsonValue(parsed);
+ if (!isJsonObject(credentials)) {
+ throw new InferenceProviderError("Google service account JSON must be an object.", {
+ statusCode: 500,
+ code: "invalid_google_service_account_json",
+ });
+ }
+
+ const clientEmail = stringValue(credentials.client_email);
+ const privateKey = stringValue(credentials.private_key);
+ if (!clientEmail || !privateKey) {
+ throw new InferenceProviderError(
+ "Google service account JSON must include client_email and private_key.",
+ {
+ statusCode: 500,
+ code: "invalid_google_service_account_json",
+ },
+ );
+ }
+
+ return {
+ type: stringValue(credentials.type),
+ project_id: stringValue(credentials.project_id),
+ private_key_id: stringValue(credentials.private_key_id),
+ private_key: privateKey,
+ client_email: clientEmail,
+ client_id: stringValue(credentials.client_id),
+ universe_domain: stringValue(credentials.universe_domain),
+ };
+}
+
+function geminiProviderError(error: unknown) {
+ if (error instanceof ApiError) {
+ return new InferenceProviderError("Gemini screenshot parsing failed.", {
+ statusCode: error.status,
+ code: "provider_error",
+ details: {
+ status: error.status,
+ message: error.message,
+ },
+ });
+ }
+
+ return new InferenceProviderError("Gemini screenshot parsing failed.", {
+ details: {
+ message: error instanceof Error ? error.message : "Unknown error",
+ },
+ });
+}
+
+function stringValue(value: JsonValue | undefined) {
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
+}
+
+function numberFromString(value: string | undefined) {
+ if (!value) {
+ return undefined;
+ }
+ const parsed = Number(value);
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
+}
diff --git a/site/src/lib/inference/screenshot-parsing/index.ts b/site/src/lib/inference/screenshot-parsing/index.ts
new file mode 100644
index 00000000..3298ffaa
--- /dev/null
+++ b/site/src/lib/inference/screenshot-parsing/index.ts
@@ -0,0 +1,33 @@
+import { InferenceProviderError } from "@/lib/inference/providers";
+import {
+ createGeminiFlashScreenshotParser,
+ screenshotParseModelForRequest,
+} from "@/lib/inference/screenshot-parsing/gemini-flash";
+import type {
+ ScreenshotParserProvider,
+ ScreenshotParserProviderResult,
+} from "@/lib/inference/screenshot-parsing/types";
+import type { ScreenshotParseRequest } from "@/lib/inference/screenshot-parsing/schema";
+
+export function createScreenshotParserProvider(): ScreenshotParserProvider {
+ return createGeminiFlashScreenshotParser();
+}
+
+export { screenshotParseModelForRequest };
+
+export async function parseScreenshot(
+ request: ScreenshotParseRequest,
+ provider: ScreenshotParserProvider = createScreenshotParserProvider(),
+): Promise<ScreenshotParserProviderResult> {
+ if (!provider.configured) {
+ throw new InferenceProviderError("Screenshot parser provider is not configured.", {
+ statusCode: 503,
+ code: "missing_provider_credentials",
+ details: {
+ provider: "gemini-flash",
+ },
+ });
+ }
+
+ return provider.parse(request);
+}
diff --git a/site/src/lib/inference/screenshot-parsing/schema.ts b/site/src/lib/inference/screenshot-parsing/schema.ts
new file mode 100644
index 00000000..f7697f64
--- /dev/null
+++ b/site/src/lib/inference/screenshot-parsing/schema.ts
@@ -0,0 +1,147 @@
+import { z } from "zod";
+
+import { toJsonObject } from "@/lib/inference/json";
+
+const metadataSchema = z.record(z.string().min(1).max(64), z.string().max(512));
+const coordinateSpaceSchema = z.enum(["screen", "window", "crop", "normalizedTarget"]);
+const controlKindValues = [
+ "button",
+ "textField",
+ "searchField",
+ "checkbox",
+ "link",
+ "menuItem",
+ "listItem",
+ "group",
+ "unknown",
+] as const;
+const controlKindSchema = z.enum(controlKindValues);
+type ControlKind = z.infer<typeof controlKindSchema>;
+
+export const hotLoopSizeSchema = z.object({
+ width: z.number().positive().max(20_000),
+ height: z.number().positive().max(20_000),
+ space: coordinateSpaceSchema.default("window"),
+});
+
+export const hotLoopRectSchema = z.object({
+ origin: z.object({
+ x: z.number().finite(),
+ y: z.number().finite(),
+ space: coordinateSpaceSchema,
+ }),
+ size: hotLoopSizeSchema,
+});
+
+export const screenshotParseRequestSchema = z.object({
+ imageBase64: z.string().min(1).max(6_000_000),
+ contentType: z.enum(["image/png", "image/jpeg", "image/webp"]).default("image/png"),
+ pixelSize: hotLoopSizeSchema,
+ traceID: z.string().min(1).max(128).optional(),
+ targetID: z.string().min(1).max(256).optional(),
+ cropBounds: hotLoopRectSchema.optional(),
+ metadata: metadataSchema.optional().default({}),
+}).transform((value) => ({
+ ...value,
+ metadata: toJsonObject(value.metadata),
+}));
+
+export const geminiScreenshotTextSchema = z.object({
+ id: clippedString(128).optional(),
+ text: clippedString(2_000),
+ confidence: z.number().min(0).max(1).optional().default(0.5),
+});
+
+export const geminiScreenshotControlSchema = z.object({
+ id: clippedString(128).optional(),
+ label: clippedString(256),
+ kind: z.string().optional().default("unknown").transform(normalizedControlKind),
+ confidence: z.number().min(0).max(1),
+ box_2d: z.tuple([
+ z.number().min(0).max(1000),
+ z.number().min(0).max(1000),
+ z.number().min(0).max(1000),
+ z.number().min(0).max(1000),
+ ]),
+});
+
+export const geminiScreenshotFormFieldSchema = z.object({
+ id: clippedString(128).optional(),
+ label: clippedString(256),
+ isRequired: z.boolean().optional().default(false),
+ currentValue: clippedString(1_000).nullable().optional(),
+ confidence: z.number().min(0).max(1).optional().default(0.5),
+ box_2d: z.tuple([
+ z.number().min(0).max(1000),
+ z.number().min(0).max(1000),
+ z.number().min(0).max(1000),
+ z.number().min(0).max(1000),
+ ]).optional(),
+});
+
+export const geminiScreenshotParseOutputSchema = z.object({
+ visibleText: z.array(geminiScreenshotTextSchema).max(200).default([]),
+ controls: z.array(geminiScreenshotControlSchema).max(200).default([]),
+ formFields: z.array(geminiScreenshotFormFieldSchema).max(80).default([]),
+ confidence: z.number().min(0).max(1).default(0),
+});
+
+export type ScreenshotParseRequest = z.infer<typeof screenshotParseRequestSchema>;
+export type GeminiScreenshotParseOutput = z.infer<typeof geminiScreenshotParseOutputSchema>;
+export type HotLoopRectJSON = z.infer<typeof hotLoopRectSchema>;
+
+function clippedString(maxLength: number) {
+ return z.string()
+ .transform((value) => value.trim().slice(0, maxLength))
+ .pipe(z.string().min(1));
+}
+
+function normalizedControlKind(value: string): ControlKind {
+ const normalized = value.trim().toLowerCase().replace(/[^a-z]/g, "");
+ switch (normalized) {
+ case "button":
+ case "iconbutton":
+ case "toolbarbutton":
+ case "reviewbutton":
+ case "sendbutton":
+ return "button";
+ case "textfield":
+ case "textinput":
+ case "input":
+ case "composer":
+ case "textarea":
+ return "textField";
+ case "searchfield":
+ case "search":
+ case "searchinput":
+ return "searchField";
+ case "checkbox":
+ case "toggle":
+ return "checkbox";
+ case "link":
+ return "link";
+ case "menuitem":
+ case "menu":
+ case "dropdown":
+ return "menuItem";
+ case "listitem":
+ case "navitem":
+ case "navigationitem":
+ case "row":
+ case "filerow":
+ case "changerow":
+ case "threadrow":
+ return "listItem";
+ case "group":
+ case "card":
+ case "panel":
+ case "region":
+ case "label":
+ case "text":
+ case "textregion":
+ case "statictext":
+ return "group";
+ default:
+ return "unknown";
+ }
+}
diff --git a/site/src/lib/inference/screenshot-parsing/types.ts b/site/src/lib/inference/screenshot-parsing/types.ts
new file mode 100644
index 00000000..cdf075cf
--- /dev/null
+++ b/site/src/lib/inference/screenshot-parsing/types.ts
@@ -0,0 +1,43 @@
+import type { JsonObject, JsonValue } from "@/lib/inference/providers";
+import type {
+ HotLoopRectJSON,
+ ScreenshotParseRequest,
+} from "@/lib/inference/screenshot-parsing/schema";
+
+export type ScreenshotParserResult = {
+ visibleText: Record<string, string>;
+ controls: ScreenshotParserControl[];
+ formFields: ScreenshotParserFormField[];
+ confidence: number;
+ metadata: JsonObject;
+};
+
+export type ScreenshotParserControl = {
+ id: string;
+ label: string;
+ kind: string;
+ frame: HotLoopRectJSON | null;
+ confidence: number;
+ metadata: Record<string, string>;
+};
+
+export type ScreenshotParserFormField = {
+ id: string;
+ label: string;
+ isRequired: boolean;
+ currentValue?: string | null;
+ metadata: Record<string, string>;
+};
+
+export type ScreenshotParserProviderResult = {
+ provider: string;
+ model: string;
+ result: ScreenshotParserResult;
+ usage?: JsonValue;
+ metadata: JsonObject;
+};
+
+export type ScreenshotParserProvider = {
+ configured: boolean;
+ parse: (request: ScreenshotParseRequest) => Promise<ScreenshotParserProviderResult>;
+};