Open source CapCut alternative.
TypeScript
Wire Donkey Vision overlay parser
David Le9b7693462c28
diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swiftindex 8d865926..bd5f0935 100644--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift@@ -14,6 +14,14 @@ private enum DebugUIInspectionLog {static let overlay = Logger(subsystem: "com.donkey.app", category: "debug-ui-inspection")}+/// Which hosted backend supplies the "AI" evidence rendered on the overlay.+/// `vision` is the active path (RunPod OmniParser V2 via /api/inference/vision).+/// `screenshotParse` is the older streaming parser, kept compiled but disabled.+private enum RemoteAIEngine {+ case vision+ case screenshotParse+}+@MainActorfinal class DebugUIInspectionCoordinator {private let overlayController = DebugUIInspectionOverlayController()@@ -27,6 +35,8 @@ final class DebugUIInspectionCoordinator {private var lastFingerprints: [UInt32: String] = [:]private var lastRenderedFrames: [UInt32: DebugUIInspectionFrame] = [:]private var lastSnapshots: [UInt32: DebugUIScreenCaptureSnapshot] = [:]+ private var lastVisionImageHashes: [UInt32: String] = [:]+ private let remoteAIEngine: RemoteAIEngine = .visionprivate var timer: Timer?private var activeAccessibilityTimer: Timer?private var notificationObservers: [NSObjectProtocol] = []@@ -68,6 +78,7 @@ final class DebugUIInspectionCoordinator {lastFingerprints.removeAll()lastRenderedFrames.removeAll()lastSnapshots.removeAll()+ lastVisionImageHashes.removeAll()isAnalyzing = falseisRefreshingActiveAccessibility = falsecurrentConfig = .disabled@@ -168,6 +179,7 @@ final class DebugUIInspectionCoordinator {trackers.removeAll()lastRenderedFrames.removeAll()lastSnapshots.removeAll()+ lastVisionImageHashes.removeAll()if !newConfig.enabled {overlayController.close()}@@ -574,6 +586,43 @@ final class DebugUIInspectionCoordinator {height: capture.parsePixelSize.height,space: .window)++ if remoteAIEngine == .vision {+ let windowID = capture.target.windowID+ let imageHash = SHA256.hash(data: capture.parseImageData)+ .map { String(format: "%02x", $0) }+ .joined()+ // Skip the network call when this window's pixels are unchanged+ // since the last successful vision parse; its elements are still+ // carried forward in `elements`. Server-side caching comes later.+ if lastVisionImageHashes[windowID] == imageHash {+ DebugUIInspectionLog.overlay.debug(+ "debug inspection skipped unchanged vision windowID=\(windowID, privacy: .public)"+ )+ continue+ }+ do {+ let response = try await client.parseScreenshotVision(+ imageData: capture.parseImageData+ )+ let parsedElements = VisionParseDebugUIOverlayMapper.frame(+ from: response,+ target: capture.target,+ screenFrame: screenBounds,+ minConfidence: currentConfig.minConfidence+ ).elements+ elements.removeAll { Self.windowID(for: $0) == windowID }+ elements += parsedElements+ lastVisionImageHashes[windowID] = imageHash+ renderRemoteAIFrame(stage: "vision", updatesFingerprint: false)+ } catch {+ DebugUIInspectionLog.overlay.error(+ "debug inspection vision parse failed windowID=\(windowID, privacy: .public) error=\(String(describing: error), privacy: .public)"+ )+ }+ continue+ }+let request = LocalUIUnderstandingRequest(traceID: "debug-ui-ai-\(screen.screenID)-\(capture.target.windowID)-\(fingerprint)",targetID: "window-\(capture.target.windowID)",diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swiftindex cc0a6e7f..b04bb377 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift@@ -271,6 +271,26 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {return finalResult}+ /// Parse a screenshot with the hosted vision endpoint (RunPod OmniParser V2).+ /// Single-shot only — the route does not stream. Returns elements with pixel+ /// boxes relative to the uploaded image, origin top-left.+ public func parseScreenshotVision(+ imageData: Data,+ options: RemoteVisionParseOptions? = nil+ ) async throws -> RemoteVisionParseResponse {+ var request = makeRequest(path: "/api/inference/vision")+ request.httpMethod = "POST"+ request.httpBody = try JSONEncoder().encode(+ RemoteVisionParseRequest(+ image: imageData.base64EncodedString(),+ returnElements: true,+ options: options+ )+ )+ let data = try await send(request)+ return try JSONDecoder().decode(RemoteVisionParseResponse.self, from: data)+ }+private static func decodeLocalUIUnderstandingResult(from text: String,decoder: JSONDecoderdiff --git a/apps/Donkey/Sources/DonkeyAI/RemoteVisionParse.swift b/apps/Donkey/Sources/DonkeyAI/RemoteVisionParse.swiftnew file mode 100644index 00000000..a1502670--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/RemoteVisionParse.swift@@ -0,0 +1,70 @@+import Foundation++// Wire models for the hosted vision endpoint (POST /api/inference/vision), which+// fronts the RunPod OmniParser V2 worker. Coordinates in the response are pixels+// relative to the uploaded image, origin top-left. See the contract in+// site/src/lib/inference/vision/schema.ts.++public struct RemoteVisionParseOptions: Codable, Equatable, Sendable {+ public var boxThreshold: Double?+ public var iouThreshold: Double?++ public init(boxThreshold: Double? = nil, iouThreshold: Double? = nil) {+ self.boxThreshold = boxThreshold+ self.iouThreshold = iouThreshold+ }+}++struct RemoteVisionParseRequest: Encodable {+ var image: String+ var returnElements: Bool+ var options: RemoteVisionParseOptions?+}++public struct RemoteVisionParseResponse: Decodable, Equatable, Sendable {+ public struct ImageSize: Decodable, Equatable, Sendable {+ public var width: Double+ public var height: Double+ }++ public struct Box: Decodable, Equatable, Sendable {+ public var x: Double+ public var y: Double+ public var width: Double+ public var height: Double+ }++ public struct Point: Decodable, Equatable, Sendable {+ public var x: Double+ public var y: Double+ }++ public struct Element: Decodable, Equatable, Sendable {+ public var id: String+ public var label: String+ public var kind: String+ public var interactive: Bool+ public var box: Box+ public var point: Point+ public var confidence: Double+ }++ public var image: ImageSize+ public var elements: [Element]++ public init(image: ImageSize, elements: [Element]) {+ self.image = image+ self.elements = elements+ }++ public init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ self.image = try container.decode(ImageSize.self, forKey: .image)+ self.elements = try container.decodeIfPresent([Element].self, forKey: .elements) ?? []+ }++ private enum CodingKeys: String, CodingKey {+ case image+ case elements+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift b/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swiftindex dd9b49e7..70c5aa9b 100644--- a/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift+++ b/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift@@ -74,7 +74,7 @@ public enum ScreenshotParseDebugUIOverlayMapper {).validated(minConfidence: threshold)}- private static func macWindowControlElements(+ static func macWindowControlElements(target: MacWindowTargetCandidate,screenFrame: WindowTargetBounds) -> [DebugUIElement] {@@ -186,7 +186,7 @@ public enum ScreenshotParseDebugUIOverlayMapper {)}- private static func overlayLocalBounds(+ static func overlayLocalBounds(for rect: HotLoopRect,target: MacWindowTargetCandidate,capturePixelSize: HotLoopSizediff --git a/apps/Donkey/Sources/DonkeyAI/VisionParseDebugUIOverlayMapper.swift b/apps/Donkey/Sources/DonkeyAI/VisionParseDebugUIOverlayMapper.swiftnew file mode 100644index 00000000..537294e3--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/VisionParseDebugUIOverlayMapper.swift@@ -0,0 +1,122 @@+#if DONKEY_DEBUG_OVERLAY++import DonkeyContracts+import DonkeyRuntime+import Foundation++// Maps hosted vision results (RunPod OmniParser V2) into overlay elements. Vision+// boxes are pixels relative to the uploaded image, so they normalize against the+// response image size and reuse the same window->screen geometry as the older+// screenshot-parse mapper. Marked as AI evidence so fusion and badges treat them+// the same way the screenshot-parse path did.+public enum VisionParseDebugUIOverlayMapper {+ public static func frame(+ from response: RemoteVisionParseResponse,+ target: MacWindowTargetCandidate,+ screenFrame: WindowTargetBounds,+ minConfidence: Double+ ) -> DebugUIInspectionFrame {+ let threshold = min(max(minConfidence, 0), 1)+ let capturePixelSize = HotLoopSize(+ width: response.image.width,+ height: response.image.height,+ space: .window+ )+ let windowControls = ScreenshotParseDebugUIOverlayMapper.macWindowControlElements(+ target: target,+ screenFrame: screenFrame+ )++ let parsed = response.elements.compactMap { element -> DebugUIElement? in+ guard !isMacWindowControl(label: element.label) else {+ return nil+ }+ let rect = HotLoopRect(+ x: element.box.x,+ y: element.box.y,+ width: element.box.width,+ height: element.box.height,+ space: .window+ )+ guard element.confidence >= threshold,+ let localBounds = ScreenshotParseDebugUIOverlayMapper.overlayLocalBounds(+ for: rect,+ target: target,+ capturePixelSize: capturePixelSize+ ),+ let bbox = ScreenshotParseDebugUIOverlayMapper.overlayBoundingBox(+ for: rect,+ target: target,+ capturePixelSize: capturePixelSize,+ screenFrame: screenFrame+ )+ else {+ return nil+ }++ let metadata = [+ "localUIElement.sources": "remote-vision-parser",+ "localUIElement.actionEligibility": LocalUIElementActionEligibility.guardedAction.rawValue,+ "remoteScreenshotParsing.status": "used",+ "remoteScreenshotParsing.provider": "omniparser-v2",+ "vision.kind": element.kind,+ "vision.interactive": String(element.interactive),+ "target.windowID": String(target.windowID),+ "target.appName": target.appName ?? "",+ "target.bundleIdentifier": target.bundleIdentifier ?? "",+ "target.title": target.title ?? "",+ "coordinate.sourceSpace": rect.space.rawValue,+ "directInputActionsAllowed": "true"+ ]+ .merging(boundsMetadata(prefix: "target.bounds.", bounds: target.bounds)) { current, _ in current }+ .merging(boundsMetadata(prefix: "debugOverlay.localBounds.", bounds: localBounds)) { current, _ in current }++ return DebugUIElement(+ id: "ai-\(target.windowID)-\(element.id)",+ type: elementType(forKind: element.kind, interactive: element.interactive),+ label: element.label,+ description: ["donkey vision", element.kind].joined(separator: " "),+ bbox: bbox,+ confidence: element.confidence,+ metadata: metadata+ )+ }++ return DebugUIInspectionFrame(elements: windowControls + parsed)+ .validated(minConfidence: threshold)+ }++ private static func isMacWindowControl(label: String) -> Bool {+ let normalized = label+ .trimmingCharacters(in: .whitespacesAndNewlines)+ .lowercased()+ return ["close", "minimize", "zoom", "fullscreen", "full screen"].contains(normalized)+ }++ private static func elementType(forKind kind: String, interactive: Bool) -> DebugUIElementType {+ switch kind.lowercased() {+ case "button":+ return .button+ case "text":+ return .other+ case "icon":+ return interactive ? .toolbarIcon : .other+ default:+ return interactive ? .button : .other+ }+ }++ private static func boundsMetadata(+ prefix: String,+ bounds: WindowTargetBounds+ ) -> [String: String] {+ [+ prefix + "x": String(bounds.x),+ prefix + "y": String(bounds.y),+ prefix + "width": String(bounds.width),+ prefix + "height": String(bounds.height)+ ]+ }+}++#endifdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionParseDebugUIOverlayMapperTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionParseDebugUIOverlayMapperTests.swiftnew file mode 100644index 00000000..6b8c7c53--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionParseDebugUIOverlayMapperTests.swift@@ -0,0 +1,142 @@+import DonkeyAI+import DonkeyContracts+import Foundation+import Testing++@Suite+struct VisionParseDebugUIOverlayMapperTests {+ private func target(+ windowID: UInt32 = 11,+ bounds: WindowTargetBounds+ ) -> MacWindowTargetCandidate {+ MacWindowTargetCandidate(+ windowID: windowID,+ processID: 100,+ appName: "Notes",+ bundleIdentifier: "com.apple.Notes",+ title: "Window",+ bounds: bounds,+ isVisible: true,+ isOnScreen: true,+ isFrontmost: true,+ isFocused: true,+ isIPhoneMirroring: false,+ safetyAssessment: WindowTargetSafetyAssessment(+ status: .allowed,+ summary: "allowed"+ )+ )+ }++ private func response(_ json: String) throws -> RemoteVisionParseResponse {+ try JSONDecoder().decode(RemoteVisionParseResponse.self, from: Data(json.utf8))+ }++ @Test+ func mapsPixelBoxIntoScreenLocalBounds() throws {+ // Image size equals the window size, so element pixels map 1:1 into window+ // space, then offset by the window origin and clipped to the screen.+ let parsed = try response(+ """+ {+ "image": { "width": 500, "height": 300 },+ "elements": [+ {+ "id": "abc",+ "label": "Save",+ "kind": "button",+ "interactive": true,+ "box": { "x": 40, "y": 60, "width": 80, "height": 30 },+ "point": { "x": 80, "y": 75 },+ "confidence": 0.5+ }+ ]+ }+ """+ )++ let frame = VisionParseDebugUIOverlayMapper.frame(+ from: parsed,+ target: target(bounds: WindowTargetBounds(x: 100, y: 200, width: 500, height: 300)),+ screenFrame: WindowTargetBounds(x: 0, y: 0, width: 1000, height: 800),+ minConfidence: 0.25+ )++ let element = try #require(frame.elements.first { $0.id.hasPrefix("ai-") })+ #expect(element.id == "ai-11-abc")+ #expect(element.type == .button)+ #expect(element.label == "Save")+ #expect(element.bbox == DebugUIBoundingBox(x: 140, y: 260, width: 80, height: 30))+ #expect(element.metadata["localUIElement.sources"] == "remote-vision-parser")+ #expect(element.metadata["target.windowID"] == "11")+ #expect(element.metadata["debugOverlay.localBounds.x"] == "40.0")+ #expect(element.metadata["debugOverlay.localBounds.y"] == "60.0")+ #expect(element.metadata["debugOverlay.localBounds.width"] == "80.0")+ #expect(element.metadata["debugOverlay.localBounds.height"] == "30.0")+ }++ @Test+ func scalesBoxesWhenImageSizeDiffersFromWindow() throws {+ // Worker saw a 250x150 image but the window is 500x300, so boxes scale 2x.+ let parsed = try response(+ """+ {+ "image": { "width": 250, "height": 150 },+ "elements": [+ {+ "id": "x1",+ "label": "Icon",+ "kind": "icon",+ "interactive": false,+ "box": { "x": 20, "y": 30, "width": 40, "height": 15 },+ "point": { "x": 40, "y": 37 },+ "confidence": 0.5+ }+ ]+ }+ """+ )++ let frame = VisionParseDebugUIOverlayMapper.frame(+ from: parsed,+ target: target(bounds: WindowTargetBounds(x: 0, y: 0, width: 500, height: 300)),+ screenFrame: WindowTargetBounds(x: 0, y: 0, width: 1000, height: 800),+ minConfidence: 0.25+ )++ let element = try #require(frame.elements.first { $0.id.hasPrefix("ai-") })+ #expect(element.type == .other)+ #expect(element.bbox == DebugUIBoundingBox(x: 40, y: 60, width: 80, height: 30))+ }++ @Test+ func dropsElementsBelowConfidenceThreshold() throws {+ let parsed = try response(+ """+ {+ "image": { "width": 500, "height": 300 },+ "elements": [+ {+ "id": "lowconf",+ "label": "Maybe",+ "kind": "button",+ "interactive": true,+ "box": { "x": 10, "y": 10, "width": 20, "height": 20 },+ "point": { "x": 20, "y": 20 },+ "confidence": 0.5+ }+ ]+ }+ """+ )++ let frame = VisionParseDebugUIOverlayMapper.frame(+ from: parsed,+ target: target(bounds: WindowTargetBounds(x: 0, y: 0, width: 500, height: 300)),+ screenFrame: WindowTargetBounds(x: 0, y: 0, width: 1000, height: 800),+ minConfidence: 0.75+ )++ #expect(frame.elements.first { $0.id.hasPrefix("ai-") } == nil)+ }+}diff --git a/docs/guides/donkey-vision.md b/docs/guides/donkey-vision.mdindex a20afa8d..3928ca60 100644--- a/docs/guides/donkey-vision.md+++ b/docs/guides/donkey-vision.md@@ -114,6 +114,16 @@ Do not add a provider field to this config. Donkey Vision is always local AXevidence plus hosted AI enrichment; the config controls cadence, scope, andfilters, not which evidence source runs.+## AI Source++The hosted AI evidence comes from the vision endpoint+(`POST /api/inference/vision`, RunPod OmniParser V2). The overlay coordinator+hashes each window screenshot and only calls the endpoint when that window's+pixels changed since the last successful parse; unchanged windows reuse their+carried-forward boxes. The older streaming screenshot-parse path is kept compiled+but disabled behind `remoteAIEngine` in the coordinator so it can be switched back+while we iterate on vision.+## Source MapHigh-signal entry points:@@ -121,9 +131,10 @@ 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/DonkeyAI/VisionParseDebugUIOverlayMapper.swift` (active AI source)+- `apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift` (retained, disabled)- `apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionService.swift`-- `site/src/lib/inference/screenshot-parsing/`+- `site/src/lib/inference/vision/` and `site/src/lib/inference/screenshot-parsing/`## Maintainer Rulesdiff --git a/plans/master-plan.md b/plans/master-plan.mdindex db7b6e7f..af677b2a 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -21,6 +21,13 @@ even when there are no active tasks.## Current Sequence+- Better Donkey Vision testing UI. Vision (RunPod OmniParser V2) now renders on+ the developer debug overlay (`DONKEY_DEBUG_OVERLAY`, fused with AX, gated behind+ `remoteAIEngine` in `DebugUIInspectionCoordinator`). That overlay is a debugging+ surface, not a real product/testing UI. We need a better way to view and+ evaluate raw vision output (boxes, labels, per-window parse latency, hit/skip on+ the local image-hash cache) while iterating. Scope/shape TBD.+## Invariants- Completed behavior belongs in `docs/`, not in active plans.diff --git a/scripts/run-donkey-dev.sh b/scripts/run-donkey-dev.shindex 0dab04da..62629b7a 100755--- a/scripts/run-donkey-dev.sh+++ b/scripts/run-donkey-dev.sh@@ -29,6 +29,15 @@ LOG_PID=""export DONKEY_WEB_BASE_URL="${DONKEY_WEB_BASE_URL:-http://localhost:3000}"+# When pointing at a local site, default to dev auth bypass so hosted inference+# (screenshot parse, vision) authenticates without an in-app login. An explicit+# DONKEY_DEV_AUTH_BYPASS value (including 0) is always respected.+case "$DONKEY_WEB_BASE_URL" in+ http://localhost|http://localhost:*|http://127.0.0.1|http://127.0.0.1:*|http://[::1]|http://[::1]:*)+ export DONKEY_DEV_AUTH_BYPASS="${DONKEY_DEV_AUTH_BYPASS:-1}"+ ;;+esac+stop_running_donkey_apps() {killall Donkey >/dev/null 2>&1 || trueif [ "$DEV_DISPLAY_NAME" != "Donkey" ]; then@@ -442,5 +451,6 @@ fiecho "Starting Donkey..."print_dev_overlay_status+echo "Hosted inference auth: dev-bypass=${DONKEY_DEV_AUTH_BYPASS:-0} baseURL=$DONKEY_WEB_BASE_URL"start_loggeropen -W -n "$DEV_APP_DIR"