Skip to content

Open source CapCut alternative.

TypeScript

Add hosted-vision grounding fallback for sparse-accessibility apps

David Le286d3b18dff1
diff --git a/apps/Donkey/Sources/DonkeyAI/VisionGroundingFlow.swift b/apps/Donkey/Sources/DonkeyAI/VisionGroundingFlow.swift
new file mode 100644
index 00000000..1cb6158a
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/VisionGroundingFlow.swift
@@ -0,0 +1,129 @@
+import CoreGraphics
+import DonkeyContracts
+import DonkeyRuntime
+import Foundation
+
+/// Grounds a target control by VISION when accessibility can't: screenshot the app window, ask the
+/// hosted UI-inspection model for clickable elements, resolve the requested one by text, and map its
+/// screenshot bounding box back to a screen point. This is the fallback for apps whose accessibility
+/// tree is too sparse to ground by text (e.g. Spotify and other Electron apps).
+@MainActor
+public enum VisionGroundingFlow {
+ public struct Outcome: Sendable {
+ public var screenPoint: CGPoint?
+ public var reason: String
+ public var matchedLabel: String?
+ public var resolvedAppName: String?
+
+ public init(screenPoint: CGPoint?, reason: String, matchedLabel: String? = nil, resolvedAppName: String? = nil) {
+ self.screenPoint = screenPoint
+ self.reason = reason
+ self.matchedLabel = matchedLabel
+ self.resolvedAppName = resolvedAppName
+ }
+ }
+
+ public typealias ScreenshotCapture = @Sendable (MacWindowTargetCandidate) async throws -> CapturedWindowScreenshot
+
+ public static func locate(
+ appName: String?,
+ bundleIdentifier: String?,
+ targetQuery: String,
+ analyzer: DebugUIInspectionAnalyzing,
+ minConfidence: Double = 0.25,
+ capture: ScreenshotCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: $0) },
+ windowResolver: MacWindowResolver = MacWindowResolver()
+ ) async -> Outcome {
+ guard let target = AccessibilityObserver.resolveTarget(
+ appName: appName,
+ bundleIdentifier: bundleIdentifier,
+ resolver: windowResolver
+ ) else {
+ return Outcome(screenPoint: nil, reason: "noWindowForApp")
+ }
+
+ let shot: CapturedWindowScreenshot
+ do {
+ shot = try await capture(target)
+ } catch {
+ return Outcome(screenPoint: nil, reason: "screenshotFailed", resolvedAppName: target.appName)
+ }
+ guard shot.imageWidth > 0, shot.imageHeight > 0 else {
+ return Outcome(screenPoint: nil, reason: "emptyScreenshot", resolvedAppName: target.appName)
+ }
+
+ let frame: DebugUIInspectionFrame
+ do {
+ frame = try await analyzer.inspect(
+ DebugUIInspectionRequest(
+ screenshotBase64: shot.pngData.base64EncodedString(),
+ pixelSize: HotLoopSize(width: Double(shot.imageWidth), height: Double(shot.imageHeight), space: .crop),
+ minConfidence: minConfidence
+ )
+ )
+ } catch {
+ return Outcome(screenPoint: nil, reason: "visionInspectionFailed", resolvedAppName: target.appName)
+ }
+
+ guard let element = resolveElement(targetQuery, in: frame.elements) else {
+ return Outcome(screenPoint: nil, reason: "elementNotFound", resolvedAppName: target.appName)
+ }
+ let point = screenPoint(
+ bbox: element.bbox,
+ imageWidth: shot.imageWidth,
+ imageHeight: shot.imageHeight,
+ window: target.bounds
+ )
+ return Outcome(screenPoint: point, reason: "ok", matchedLabel: element.label, resolvedAppName: target.appName)
+ }
+
+ /// Resolves the best inspected element for `query` by text relevance over its label/description/type.
+ nonisolated static func resolveElement(_ query: String, in elements: [DebugUIElement]) -> DebugUIElement? {
+ let normalizedQuery = query.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !normalizedQuery.isEmpty else { return nil }
+ let queryTokens = Set(normalizedQuery.split { !$0.isLetter && !$0.isNumber }.map(String.init))
+
+ var best: (element: DebugUIElement, score: Double)?
+ for element in elements where element.bbox.hasPositiveArea {
+ let candidates = [element.label, element.description, element.type.rawValue]
+ .map { $0.lowercased() }
+ .filter { !$0.isEmpty }
+ var score = 0.0
+ for candidate in candidates {
+ if candidate == normalizedQuery {
+ score = max(score, 1_000)
+ } else if candidate.contains(normalizedQuery) || normalizedQuery.contains(candidate) {
+ score = max(score, 500)
+ } else {
+ let overlap = queryTokens.intersection(Set(candidate.split { !$0.isLetter && !$0.isNumber }.map(String.init))).count
+ if overlap > 0 { score = max(score, Double(overlap)) }
+ }
+ }
+ guard score > 0 else { continue }
+ // Tie-break toward higher model confidence.
+ let composite = score * 1_000 + element.confidence
+ if best == nil || composite > best!.score {
+ best = (element, composite)
+ }
+ }
+ return best?.element
+ }
+
+ /// Maps a screenshot-pixel bounding box center to a screen point, given the window's screen
+ /// bounds and the screenshot pixel size (handles Retina scaling between the two).
+ nonisolated static func screenPoint(
+ bbox: DebugUIBoundingBox,
+ imageWidth: Int,
+ imageHeight: Int,
+ window: WindowTargetBounds
+ ) -> CGPoint {
+ let scaleX = window.width / Double(imageWidth)
+ let scaleY = window.height / Double(imageHeight)
+ let centerX = bbox.x + bbox.width / 2
+ let centerY = bbox.y + bbox.height / 2
+ return CGPoint(
+ x: window.x + centerX * scaleX,
+ y: window.y + centerY * scaleY
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityObserver.swift b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityObserver.swift
index 40cc4e54..1f11a64c 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityObserver.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityObserver.swift
@@ -11,7 +11,7 @@ struct ResolvedAccessibilityObservation {
/// Captures a running app's accessibility tree and discovers its controls. Shared by the guidance
/// overlay and the accessibility action executor so both ground against the same observation.
@MainActor
-enum AccessibilityObserver {
+public enum AccessibilityObserver {
static func observe(
appName: String?,
bundleIdentifier: String?,
@@ -40,10 +40,10 @@ enum AccessibilityObserver {
return ResolvedAccessibilityObservation(target: target, controls: index.controls)
}
- static func resolveTarget(
+ public static func resolveTarget(
appName: String?,
bundleIdentifier: String?,
- resolver: MacWindowResolver
+ resolver: MacWindowResolver = MacWindowResolver()
) -> MacWindowTargetCandidate? {
if appName != nil || bundleIdentifier != nil {
let candidates = resolver.enumerateCandidates()
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionGroundingFlowTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionGroundingFlowTests.swift
new file mode 100644
index 00000000..ec52b3d9
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionGroundingFlowTests.swift
@@ -0,0 +1,58 @@
+@testable import DonkeyAI
+import DonkeyContracts
+import Foundation
+import Testing
+
+@Suite
+struct VisionGroundingFlowTests {
+ private func element(
+ id: String,
+ type: DebugUIElementType,
+ label: String,
+ description: String = "",
+ x: Double, y: Double, width: Double, height: Double,
+ confidence: Double = 0.9
+ ) -> DebugUIElement {
+ DebugUIElement(
+ id: id,
+ type: type,
+ label: label,
+ description: description,
+ bbox: DebugUIBoundingBox(x: x, y: y, width: width, height: height),
+ confidence: confidence,
+ visualStyle: DebugUIOverlayStyle(overlayColor: "#000", borderColor: "#000", labelColor: "#fff"),
+ metadata: [:]
+ )
+ }
+
+ @Test
+ func mapsScreenshotPixelBoxToScreenWithRetinaScaling() {
+ // 2x Retina screenshot (1600x1200) of a 800x600 window at screen (100, 50).
+ let window = WindowTargetBounds(x: 100, y: 50, width: 800, height: 600)
+ let bbox = DebugUIBoundingBox(x: 700, y: 100, width: 200, height: 60) // center (800, 130) in image px
+ let point = VisionGroundingFlow.screenPoint(bbox: bbox, imageWidth: 1600, imageHeight: 1200, window: window)
+ // scaleX=800/1600=0.5, scaleY=600/1200=0.5 → screen (100+400, 50+65) = (500, 115)
+ #expect(point.x == 500)
+ #expect(point.y == 115)
+ }
+
+ @Test
+ func resolvesElementByLabelPreferringExactThenConfidence() {
+ let elements = [
+ element(id: "a", type: .button, label: "Search the web", x: 0, y: 0, width: 10, height: 10, confidence: 0.6),
+ element(id: "b", type: .input, label: "Search", x: 20, y: 0, width: 10, height: 10, confidence: 0.9),
+ element(id: "c", type: .button, label: "Settings", x: 40, y: 0, width: 10, height: 10)
+ ]
+ #expect(VisionGroundingFlow.resolveElement("Search", in: elements)?.id == "b")
+ }
+
+ @Test
+ func ignoresZeroAreaAndUnrelatedElements() {
+ let elements = [
+ element(id: "ghost", type: .input, label: "Search", x: 0, y: 0, width: 0, height: 0),
+ element(id: "other", type: .button, label: "Play", x: 10, y: 10, width: 30, height: 20)
+ ]
+ #expect(VisionGroundingFlow.resolveElement("Search", in: elements) == nil)
+ #expect(VisionGroundingFlow.resolveElement("Play", in: elements)?.id == "other")
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionGroundingLiveSmokeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionGroundingLiveSmokeTests.swift
new file mode 100644
index 00000000..df48a95e
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionGroundingLiveSmokeTests.swift
@@ -0,0 +1,54 @@
+import AppKit
+import DonkeyAI
+import DonkeyContracts
+import DonkeyRuntime
+import Foundation
+import Testing
+
+/// Live, env-gated test that hosted VISION can ground a control AX can't (e.g. Spotify's search
+/// box). Captures the app window, sends it to the hosted UI-inspection model, and maps the located
+/// element to a screen point.
+///
+/// env DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer \
+/// DONKEY_LIVE_SMOKE=1 DONKEY_WEB_BASE_URL=http://localhost:3000 DONKEY_DEV_AUTH_BYPASS=1 \
+/// [DONKEY_GUIDE_APP=Spotify] [DONKEY_GUIDE_TARGET=Search] \
+/// swift test --filter VisionGroundingLiveSmokeTests
+@Suite
+struct VisionGroundingLiveSmokeTests {
+ @Test
+ @MainActor
+ func hostedVisionLocatesAControl() async {
+ let env = ProcessInfo.processInfo.environment
+ guard env["DONKEY_LIVE_SMOKE"] == "1" else { return }
+ guard env["DONKEY_WEB_BASE_URL"]?.isEmpty == false else {
+ Issue.record("DONKEY_WEB_BASE_URL not set")
+ return
+ }
+ guard let config = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {
+ Issue.record("could not load backend configuration")
+ return
+ }
+
+ let app = env["DONKEY_GUIDE_APP"] ?? "Spotify"
+ let target = env["DONKEY_GUIDE_TARGET"] ?? "Search"
+ NSWorkspace.shared.launchApplication(app)
+ try? await Task.sleep(nanoseconds: 1_200_000_000)
+
+ let analyzer = HostedDebugUIInspectionAnalyzer(
+ backend: DonkeyBackendInferenceClient(configuration: config, httpClient: URLSessionAIHTTPClient())
+ )
+ let outcome = await VisionGroundingFlow.locate(
+ appName: app,
+ bundleIdentifier: nil,
+ targetQuery: target,
+ analyzer: analyzer
+ )
+
+ guard let point = outcome.screenPoint else {
+ Issue.record("Hosted vision did not locate '\(target)' in \(app): reason=\(outcome.reason) app=\(outcome.resolvedAppName ?? "nil"). Needs Screen Recording permission + a reachable backend.")
+ return
+ }
+ #expect(point.x > 0 && point.y > 0)
+ #expect(outcome.matchedLabel != nil)
+ }
+}