Skip to content

Open source CapCut alternative.

TypeScript

Extract shared UI grounding matching

David Le387e9fcc04e1
diff --git a/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionHostedAdapter.swift b/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionHostedAdapter.swift
index e6ec40fa..fdc19da2 100644
--- a/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionHostedAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionHostedAdapter.swift
@@ -11,20 +11,23 @@ public enum DebugUIInspectionHostedAdapterError: Error, Equatable, Sendable {
public struct DebugUIInspectionRequest: Equatable, Sendable {
public var provider: DebugUIInspectionProvider?
- public var screenshotBase64: String
+ /// Full `data:<contentType>;base64,<…>` URL for the image. Callers prepare this with the shared
+ /// `ScreenshotCompression` helper so every hosted-vision request is downscaled + JPEG-encoded the
+ /// same way; `pixelSize` must be the size of THIS image (model coordinates map back through it).
+ public var imageDataURL: String
public var pixelSize: HotLoopSize
public var minConfidence: Double
public var metadata: [String: String]
public init(
provider: DebugUIInspectionProvider? = nil,
- screenshotBase64: String,
+ imageDataURL: String,
pixelSize: HotLoopSize,
minConfidence: Double = 0.25,
metadata: [String: String] = [:]
) {
self.provider = provider
- self.screenshotBase64 = screenshotBase64
+ self.imageDataURL = imageDataURL
self.pixelSize = pixelSize
self.minConfidence = min(max(minConfidence, 0), 1)
self.metadata = metadata
@@ -72,7 +75,7 @@ public struct HostedDebugUIInspectionAnalyzer: DebugUIInspectionAnalyzing {
]),
.object([
"type": .string("input_image"),
- "image_url": .string("data:image/png;base64,\(request.screenshotBase64)"),
+ "image_url": .string(request.imageDataURL),
"detail": .string("original")
])
])
@@ -284,6 +287,9 @@ public enum DebugUIInspectionResponseDecoder {
}
/// Extracts the JSON object from model output that may be fenced or have trailing prose.
+ /// Returns the FIRST brace-balanced `{…}` object, scanning past braces that appear inside string
+ /// literals — so trailing prose such as `{…valid…} note: see {example}` doesn't get swallowed
+ /// into malformed JSON (which the old first-`{`-to-last-`}` heuristic did).
static func jsonObjectSubstring(_ text: String) -> String {
var trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.hasPrefix("```") {
@@ -293,10 +299,38 @@ public enum DebugUIInspectionResponseDecoder {
.replacingOccurrences(of: "```", with: "")
.trimmingCharacters(in: .whitespacesAndNewlines)
}
- if let start = trimmed.firstIndex(of: "{"), let end = trimmed.lastIndex(of: "}"), start <= end {
- return String(trimmed[start...end])
+ guard let start = trimmed.firstIndex(of: "{") else { return trimmed }
+
+ var depth = 0
+ var inString = false
+ var escaped = false
+ var index = start
+ while index < trimmed.endIndex {
+ let character = trimmed[index]
+ if inString {
+ if escaped {
+ escaped = false
+ } else if character == "\\" {
+ escaped = true
+ } else if character == "\"" {
+ inString = false
+ }
+ } else {
+ switch character {
+ case "\"": inString = true
+ case "{": depth += 1
+ case "}":
+ depth -= 1
+ if depth == 0 {
+ return String(trimmed[start...index])
+ }
+ default: break
+ }
+ }
+ index = trimmed.index(after: index)
}
- return trimmed
+ // Unbalanced (truncated) output: hand back from the first brace so the decoder surfaces it.
+ return String(trimmed[start...])
}
public static func containsActionOutput(_ value: RemoteInferenceJSONValue) -> Bool {
diff --git a/apps/Donkey/Sources/DonkeyAI/VisionGroundingFlow.swift b/apps/Donkey/Sources/DonkeyAI/VisionGroundingFlow.swift
index 2219ac5c..ed593404 100644
--- a/apps/Donkey/Sources/DonkeyAI/VisionGroundingFlow.swift
+++ b/apps/Donkey/Sources/DonkeyAI/VisionGroundingFlow.swift
@@ -52,10 +52,13 @@ public enum VisionGroundingFlow {
return Outcome(screenPoint: nil, reason: "emptyScreenshot", resolvedAppName: target.appName)
}
+ // Compress (downscale + JPEG) through the shared helper so this request matches every other
+ // hosted-vision request; the model's coordinates then map back through the COMPRESSED size.
+ let compressed = ScreenshotCompression.compressedForModel(shot)
// The hosted vision model occasionally returns malformed JSON; retry a few times.
let request = DebugUIInspectionRequest(
- screenshotBase64: shot.pngData.base64EncodedString(),
- pixelSize: HotLoopSize(width: Double(shot.imageWidth), height: Double(shot.imageHeight), space: .crop),
+ imageDataURL: compressed.base64DataURL,
+ pixelSize: compressed.pixelSize,
minConfidence: minConfidence
)
var frame: DebugUIInspectionFrame?
@@ -77,8 +80,8 @@ public enum VisionGroundingFlow {
}
let point = screenPoint(
bbox: element.bbox,
- imageWidth: shot.imageWidth,
- imageHeight: shot.imageHeight,
+ imageWidth: Int(compressed.pixelSize.width.rounded()),
+ imageHeight: Int(compressed.pixelSize.height.rounded()),
window: target.bounds
)
return Outcome(screenPoint: point, reason: "ok", matchedLabel: element.label, resolvedAppName: target.appName)
@@ -88,24 +91,18 @@ public enum VisionGroundingFlow {
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))
+ let queryTokens = ControlTextRelevance.tokens(in: normalizedQuery)
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)) }
- }
- }
+ let score = ControlTextRelevance.score(
+ normalizedQuery: normalizedQuery,
+ queryTokens: queryTokens,
+ candidates: candidates
+ )
guard score > 0 else { continue }
// Tie-break toward higher model confidence.
let composite = score * 1_000 + element.confidence
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityCursorPathBuilder.swift b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityCursorPathBuilder.swift
index fbc7df32..9d55d938 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityCursorPathBuilder.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityCursorPathBuilder.swift
@@ -70,7 +70,7 @@ public enum AccessibilityCursorPathBuilder {
) -> LocalAppDiscoveredControl? {
let normalizedQuery = LocalAppTextNormalizer.normalizedPhrase(query)
guard !normalizedQuery.isEmpty else { return nil }
- let queryTokens = Set(normalizedQuery.split(separator: " ").map(String.init))
+ let queryTokens = ControlTextRelevance.tokens(in: normalizedQuery)
var best: (control: LocalAppDiscoveredControl, score: Double)?
for control in controls where !used.contains(control.id) {
@@ -80,20 +80,11 @@ public enum AccessibilityCursorPathBuilder {
.filter { !$0.isEmpty }
guard !candidates.isEmpty else { continue }
- 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 candidateTokens = Set(candidate.split(separator: " ").map(String.init))
- let overlap = queryTokens.intersection(candidateTokens).count
- if overlap > 0 {
- score = max(score, Double(overlap))
- }
- }
- }
+ let score = ControlTextRelevance.score(
+ normalizedQuery: normalizedQuery,
+ queryTokens: queryTokens,
+ candidates: candidates
+ )
guard score > 0 else { continue }
// Tie-break toward the larger control (more likely the intended, prominent target).
let area = frame.width * frame.height
diff --git a/apps/Donkey/Sources/DonkeyRuntime/SharedTextMatching.swift b/apps/Donkey/Sources/DonkeyRuntime/SharedTextMatching.swift
new file mode 100644
index 00000000..2c049b84
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/SharedTextMatching.swift
@@ -0,0 +1,64 @@
+import DonkeyContracts
+import Foundation
+
+/// Case-insensitive, bidirectional app-name matching shared by every place that has to decide
+/// whether an observed/installed app is the one the user (or a skill) named. Centralizing it keeps
+/// window-target resolution and skill/guidance lookup from drifting apart on casing/substring rules.
+public enum AppNameMatching {
+ /// True when the two names refer to the same app: equal after normalizing (case, whitespace,
+ /// trailing ".app"), or one's word set is a subset of the other's. Matching on whole-word tokens
+ /// rather than raw substrings tolerates "Music" vs "Music.app" and "Spotify" vs "Spotify Premium"
+ /// while NOT matching unrelated names that merely share a letter run (e.g. "Code" vs "Xcode").
+ public static func matches(_ lhs: String, _ rhs: String) -> Bool {
+ let left = normalize(lhs)
+ let right = normalize(rhs)
+ guard !left.isEmpty, !right.isEmpty else { return false }
+ if left == right { return true }
+ let leftTokens = ControlTextRelevance.tokens(in: left)
+ let rightTokens = ControlTextRelevance.tokens(in: right)
+ guard !leftTokens.isEmpty, !rightTokens.isEmpty else { return false }
+ return leftTokens.isSubset(of: rightTokens) || rightTokens.isSubset(of: leftTokens)
+ }
+
+ private static func normalize(_ name: String) -> String {
+ var trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ if trimmed.hasSuffix(".app") { trimmed = String(trimmed.dropLast(4)) }
+ return trimmed
+ }
+}
+
+/// Text-relevance scoring shared by control grounding (accessibility cursor paths and vision
+/// inspection). Both ground a requested control by ranking candidate strings against a query with
+/// the same ladder — exact match, then containment, then token overlap — so the scoring lives here
+/// once and a tweak (e.g. tokenization, prefix handling) applies to every grounding path at once.
+public enum ControlTextRelevance {
+ public static let exactScore = 1_000.0
+ public static let containmentScore = 500.0
+
+ /// Splits text into lowercase alphanumeric tokens for the overlap fallback.
+ public static func tokens(in text: String) -> Set<String> {
+ Set(text.split { !$0.isLetter && !$0.isNumber }.map { String($0).lowercased() })
+ }
+
+ /// Scores `candidates` (each already normalized to the caller's convention) against
+ /// `normalizedQuery`. Returns 0 when nothing matches; ties on score are left for the caller to
+ /// break (e.g. toward larger control area or higher model confidence).
+ public static func score(
+ normalizedQuery: String,
+ queryTokens: Set<String>,
+ candidates: [String]
+ ) -> Double {
+ var best = 0.0
+ for candidate in candidates where !candidate.isEmpty {
+ if candidate == normalizedQuery {
+ best = max(best, exactScore)
+ } else if candidate.contains(normalizedQuery) || normalizedQuery.contains(candidate) {
+ best = max(best, containmentScore)
+ } else {
+ let overlap = queryTokens.intersection(tokens(in: candidate)).count
+ if overlap > 0 { best = max(best, Double(overlap)) }
+ }
+ }
+ return best
+ }
+}