Skip to content

Open source CapCut alternative.

TypeScript

Fix debug inspection overlay alignment

David Le3156fb42664e
diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift
index 79ecfa50..beed0841 100644
--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift
+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift
@@ -28,7 +28,9 @@ final class DebugUIInspectionCoordinator {
private var lastRenderedFrames: [UInt32: DebugUIInspectionFrame] = [:]
private var lastSnapshots: [UInt32: DebugUIScreenCaptureSnapshot] = [:]
private var timer: Timer?
+ private var activeAccessibilityTimer: Timer?
private var notificationObservers: [NSObjectProtocol] = []
+ private var movementEventMonitors: [Any] = []
private var currentConfig: DebugUIOverlayConfiguration = .disabled
private var isAnalyzing = false
@@ -49,11 +51,17 @@ final class DebugUIInspectionCoordinator {
func stop() {
timer?.invalidate()
timer = nil
+ activeAccessibilityTimer?.invalidate()
+ activeAccessibilityTimer = nil
for observer in notificationObservers {
NotificationCenter.default.removeObserver(observer)
NSWorkspace.shared.notificationCenter.removeObserver(observer)
}
+ for monitor in movementEventMonitors {
+ NSEvent.removeMonitor(monitor)
+ }
notificationObservers.removeAll()
+ movementEventMonitors.removeAll()
overlayController.close()
trackers.removeAll()
lastFingerprints.removeAll()
@@ -89,6 +97,23 @@ final class DebugUIInspectionCoordinator {
}
}
notificationObservers.append(workspaceObserver)
+
+ let movementMask: NSEvent.EventTypeMask = [.leftMouseDragged, .leftMouseUp]
+ if let globalMonitor = NSEvent.addGlobalMonitorForEvents(matching: movementMask, handler: { [weak self] _ in
+ Task { @MainActor in
+ self?.reprojectRenderedFramesFromCurrentWindowBounds()
+ }
+ }) {
+ movementEventMonitors.append(globalMonitor)
+ }
+ if let localMonitor = NSEvent.addLocalMonitorForEvents(matching: movementMask, handler: { [weak self] event in
+ Task { @MainActor in
+ self?.reprojectRenderedFramesFromCurrentWindowBounds()
+ }
+ return event
+ }) {
+ movementEventMonitors.append(localMonitor)
+ }
}
private func reloadConfigAndReschedule(force: Bool = false) {
@@ -120,6 +145,22 @@ final class DebugUIInspectionCoordinator {
RunLoop.main.add(newTimer, forMode: .common)
}
+ if newConfig.enabled {
+ if activeAccessibilityTimer == nil || force {
+ activeAccessibilityTimer?.invalidate()
+ let newTimer = Timer(timeInterval: 0.12, repeats: true) { [weak self] _ in
+ Task { @MainActor in
+ self?.refreshActiveAccessibilityFrame()
+ }
+ }
+ activeAccessibilityTimer = newTimer
+ RunLoop.main.add(newTimer, forMode: .common)
+ }
+ } else {
+ activeAccessibilityTimer?.invalidate()
+ activeAccessibilityTimer = nil
+ }
+
if enablementChanged || scopeChanged || modeChanged || confidenceChanged || activeWindowChanged || targetFilterChanged {
lastFingerprints.removeAll()
trackers.removeAll()
@@ -219,9 +260,119 @@ final class DebugUIInspectionCoordinator {
lastFingerprints[screen.screenID] = fingerprint
lastRenderedFrames[screen.screenID] = trackedFrame
lastSnapshots[screen.screenID] = snapshot
+ logLayoutDiagnostics(stage: stage, screen: screen, frame: trackedFrame, captures: [])
overlayController.render(frame: trackedFrame, snapshot: snapshot)
}
+ private func refreshActiveAccessibilityFrame() {
+ guard currentConfig.enabled,
+ !isAnalyzing,
+ let screens = try? screenSurfaces(scope: currentConfig.screenScope)
+ else {
+ return
+ }
+
+ let frames = activeAccessibilityFrames()
+ guard !frames.isEmpty else { return }
+
+ for screen in screens {
+ guard let accessibilityFrame = frames[screen.screenID],
+ !accessibilityFrame.elements.isEmpty
+ else {
+ continue
+ }
+
+ let existing = lastRenderedFrames[screen.screenID] ?? DebugUIInspectionFrame()
+ let nonAccessibilityFrame = DebugUIInspectionFrame(
+ elements: existing.elements.filter { !Self.isAccessibilityEvidence($0) }
+ )
+ let fusedFrame = DebugUIInspectionFrameFusion.fused(
+ accessibilityFrame: accessibilityFrame,
+ geminiFrame: nonAccessibilityFrame
+ )
+ guard !fusedFrame.elements.isEmpty,
+ lastRenderedFrames[screen.screenID]?.isOverlayRenderEquivalent(to: fusedFrame) != true
+ else {
+ continue
+ }
+
+ let snapshot = Self.screenPointSnapshot(
+ screen: screen,
+ fingerprint: "active-accessibility-\(Self.frameSignature(fusedFrame))"
+ )
+ lastRenderedFrames[screen.screenID] = fusedFrame
+ lastSnapshots[screen.screenID] = snapshot
+ logLayoutDiagnostics(stage: "active-accessibility", screen: screen, frame: fusedFrame, captures: [])
+ overlayController.render(frame: fusedFrame, snapshot: snapshot)
+ }
+ }
+
+ private func reprojectRenderedFramesFromCurrentWindowBounds() {
+ guard currentConfig.enabled,
+ !lastRenderedFrames.isEmpty,
+ let screens = try? screenSurfaces(scope: currentConfig.screenScope)
+ else {
+ return
+ }
+
+ let candidates = Dictionary(
+ uniqueKeysWithValues: windowResolver.enumerateCandidates()
+ .filter { $0.isVisible && $0.isOnScreen && $0.safetyAssessment.status == .allowed }
+ .map { ($0.windowID, $0) }
+ )
+ let screensByID = Dictionary(uniqueKeysWithValues: screens.map { ($0.screenID, $0) })
+ var elementsByScreenID = Dictionary(
+ uniqueKeysWithValues: screens.map { ($0.screenID, [DebugUIElement]()) }
+ )
+ var changed = false
+
+ for (screenID, frame) in lastRenderedFrames {
+ for element in frame.elements {
+ guard let projected = Self.reproject(
+ element,
+ sourceScreen: screensByID[screenID],
+ currentWindowTargets: candidates,
+ screens: screens
+ ) else {
+ if Self.windowID(for: element) == nil {
+ elementsByScreenID[screenID, default: []].append(element)
+ } else {
+ changed = true
+ }
+ continue
+ }
+
+ elementsByScreenID[projected.screenID, default: []].append(projected.element)
+ changed = changed || projected.screenID != screenID || projected.element.bbox != element.bbox
+ }
+ }
+
+ guard changed else { return }
+
+ var activeScreenIDs = Set<UInt32>()
+ for screen in screens {
+ let elements = elementsByScreenID[screen.screenID] ?? []
+ if elements.isEmpty {
+ lastRenderedFrames.removeValue(forKey: screen.screenID)
+ lastSnapshots.removeValue(forKey: screen.screenID)
+ continue
+ }
+
+ activeScreenIDs.insert(screen.screenID)
+ let frame = DebugUIInspectionFrame(elements: elements.sorted(by: Self.elementSort))
+ let snapshot = Self.screenPointSnapshot(
+ screen: screen,
+ fingerprint: "window-geometry-\(Self.frameSignature(frame))"
+ )
+ lastRenderedFrames[screen.screenID] = frame
+ lastSnapshots[screen.screenID] = snapshot
+ logLayoutDiagnostics(stage: "window-geometry", screen: screen, frame: frame, captures: [])
+ overlayController.render(frame: frame, snapshot: snapshot)
+ }
+
+ overlayController.closeScreens(except: activeScreenIDs)
+ }
+
private func analyzeGeminiWindowScreens(force: Bool) async throws {
let screens = try screenSurfaces(scope: currentConfig.screenScope)
let activeScreenIDs = Set(screens.map(\.screenID))
@@ -255,6 +406,7 @@ final class DebugUIInspectionCoordinator {
let snapshot = Self.screenPointSnapshot(screen: screen, fingerprint: fingerprint)
lastRenderedFrames[screen.screenID] = trackedFrame
lastSnapshots[screen.screenID] = snapshot
+ logLayoutDiagnostics(stage: "accessibility-fallback", screen: screen, frame: trackedFrame, captures: [])
overlayController.render(frame: trackedFrame, snapshot: snapshot)
}
return
@@ -283,12 +435,12 @@ final class DebugUIInspectionCoordinator {
}
let renderedScreenIDs = Set(captures.flatMap { capture in
- screens.filter { Self.intersects(capture.target.bounds, Self.windowBounds(from: $0.appKitFrame)) }.map(\.screenID)
+ screens.filter { Self.intersects(capture.target.bounds, $0.captureFrame) }.map(\.screenID)
}).union(accessibilityFrames.keys)
ageMissingGeminiScreens(activeScreenIDs: renderedScreenIDs)
for screen in screens where renderedScreenIDs.contains(screen.screenID) {
- let screenBounds = Self.windowBounds(from: screen.appKitFrame)
+ let screenBounds = screen.captureFrame
let screenCaptures = captures.filter { Self.intersects($0.target.bounds, screenBounds) }
let accessibilityFrame = accessibilityFrames[screen.screenID] ?? DebugUIInspectionFrame()
let fingerprint = Self.fingerprint(
@@ -392,7 +544,7 @@ final class DebugUIInspectionCoordinator {
DebugUIInspectionLog.overlay.info(
"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)
+ logLayoutDiagnostics(stage: "gemini-fused", screen: screen, frame: trackedFrame, captures: screenCaptures)
lastRenderedFrames[screen.screenID] = trackedFrame
lastSnapshots[screen.screenID] = snapshot
overlayController.render(frame: trackedFrame, snapshot: snapshot)
@@ -428,6 +580,35 @@ final class DebugUIInspectionCoordinator {
}
}
+ private func activeAccessibilityFrames() -> [UInt32: DebugUIInspectionFrame] {
+ do {
+ let results = try accessibilityInspectionService.inspect(
+ scope: currentConfig.screenScope,
+ minConfidence: currentConfig.minConfidence,
+ frontmostOnly: true,
+ focusedOnly: true,
+ 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.debug(
+ "debug inspection skipped active accessibility refresh error=\(String(describing: error), privacy: .public)"
+ )
+ return [:]
+ }
+ }
+
private static func frameInScreenPointSpace(
_ frame: DebugUIInspectionFrame,
snapshot: DebugUIScreenCaptureSnapshot
@@ -511,8 +692,10 @@ final class DebugUIInspectionCoordinator {
DebugUIInspectionLog.overlay.info(
"debug inspection rendering source=accessibility screenID=\(snapshot.screenID, privacy: .public) elements=\(trackedFrame.elements.count, privacy: .public)"
)
- logSampleMappings(frame: trackedFrame, snapshot: snapshot)
lastRenderedFrames[snapshot.screenID] = trackedFrame
+ if let screen = try? screenSurfaces(scope: currentConfig.screenScope).first(where: { $0.screenID == snapshot.screenID }) {
+ logLayoutDiagnostics(stage: "accessibility", screen: screen, frame: trackedFrame, captures: [])
+ }
overlayController.render(frame: trackedFrame, snapshot: snapshot)
}
@@ -614,31 +797,86 @@ final class DebugUIInspectionCoordinator {
bundleFilters: bundleFilters,
appNameFilters: appNameFilters
)
- && screens.contains { Self.intersects(target.bounds, Self.windowBounds(from: $0.appKitFrame)) }
+ && screens.contains { Self.intersects(target.bounds, $0.captureFrame) }
}
}
- private func logSampleMappings(
+ private func logLayoutDiagnostics(
+ stage: String,
+ screen: DebugUIScreenSurface,
frame: DebugUIInspectionFrame,
- snapshot: DebugUIScreenCaptureSnapshot
+ captures: [DebugUIWindowCapture]
) {
let screenPointSize = HotLoopSize(
- width: snapshot.screenFrame.size.width,
- height: snapshot.screenFrame.size.height,
+ width: screen.appKitFrame.size.width,
+ height: screen.appKitFrame.size.height,
+ space: .screen
+ )
+ let screenshotPixelSize = HotLoopSize(
+ width: screen.appKitFrame.size.width,
+ height: screen.appKitFrame.size.height,
space: .screen
)
- for element in frame.elements.prefix(3) {
- let localFrame = DebugUIOverlayGeometry.localLayerFrame(
+ let counts = sourceCounts(frame.elements)
+ DebugUIInspectionLog.overlay.info(
+ "debug inspection layout stage=\(stage, privacy: .public) screenID=\(screen.screenID, privacy: .public) elements=\(frame.elements.count, privacy: .public) ax=\(counts.ax, privacy: .public) ai=\(counts.ai, privacy: .public) cv=\(counts.cv, privacy: .public) other=\(counts.other, privacy: .public) appKitFrame=\(Self.describe(screen.appKitFrame), privacy: .public) captureFrame=\(Self.describe(screen.captureFrame), privacy: .public)"
+ )
+
+ for capture in captures.prefix(8) {
+ DebugUIInspectionLog.overlay.info(
+ "debug inspection layout-target stage=\(stage, privacy: .public) screenID=\(screen.screenID, privacy: .public) windowID=\(capture.target.windowID, privacy: .public) app=\(capture.target.appName ?? "", privacy: .public) bundle=\(capture.target.bundleIdentifier ?? "", privacy: .public) targetBounds=\(Self.describe(capture.target.bounds), privacy: .public) screenshot=\(capture.screenshot.imageWidth, privacy: .public)x\(capture.screenshot.imageHeight, privacy: .public) parse=\(Int(capture.parsePixelSize.width.rounded()), privacy: .public)x\(Int(capture.parsePixelSize.height.rounded()), privacy: .public) method=\(capture.screenshot.captureMethod.rawValue, privacy: .public) coord=\(capture.screenshot.coordinateSpace, privacy: .public)"
+ )
+ }
+
+ for (index, element) in frame.elements.sorted(by: Self.elementSort).prefix(48).enumerated() {
+ let layerFrame = DebugUIOverlayGeometry.localLayerFrame(
for: element.bbox,
- screenshotPixelSize: snapshot.pixelSize,
+ screenshotPixelSize: screenshotPixelSize,
screenPointSize: screenPointSize
)
DebugUIInspectionLog.overlay.info(
- "debug inspection mapping id=\(element.id, privacy: .public) label=\(element.label, privacy: .public) bbox=\(Self.describe(element.bbox), privacy: .public) local=\(Self.describe(localFrame), privacy: .public) pixels=\(Self.describe(snapshot.pixelSize), privacy: .public) points=\(Self.describe(screenPointSize), privacy: .public)"
+ "debug inspection layout-element stage=\(stage, privacy: .public) idx=\(index, privacy: .public) source=\(Self.sourceName(for: element), privacy: .public) id=\(element.id, privacy: .public) label=\(Self.shortLabel(element.label), privacy: .public) confidence=\(String(format: "%.2f", element.confidence), privacy: .public) bbox=\(Self.describe(element.bbox), privacy: .public) layer=\(Self.describe(layerFrame), privacy: .public) targetWindowID=\(Self.metadataValue("target.windowID", metadata: element.metadata) ?? "", privacy: .public) targetBounds=\(Self.describe(Self.targetBounds(for: element)), privacy: .public) localBounds=\(Self.describe(Self.localBounds(for: element)), privacy: .public) metadataSource=\(Self.metadataValue("localUIElement.sources", metadata: element.metadata) ?? "", privacy: .public)"
)
}
}
+ private func sourceCounts(_ elements: [DebugUIElement]) -> (ax: Int, ai: Int, cv: Int, other: Int) {
+ var ax = 0
+ var ai = 0
+ var cv = 0
+ var other = 0
+ for element in elements {
+ switch Self.sourceName(for: element) {
+ case "AX": ax += 1
+ case "AI": ai += 1
+ case "CV": cv += 1
+ default: other += 1
+ }
+ }
+ return (ax, ai, cv, other)
+ }
+
+ private static func sourceName(for element: DebugUIElement) -> String {
+ let fusionSource = element.metadata["debugUIFusion.source"] ?? ""
+ let sources = metadataValue("localUIElement.sources", metadata: element.metadata) ?? ""
+ 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 "CV"
+ }
+ if sources.contains("accessibility") || element.id.hasPrefix("ax-") || sources.contains("window-chrome-geometry") || element.id.hasPrefix("window-chrome-") {
+ return "AX"
+ }
+ return "OTHER"
+ }
+
+ private static func shortLabel(_ value: String) -> String {
+ let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard trimmed.count > 80 else { return trimmed }
+ return String(trimmed.prefix(77)) + "..."
+ }
+
private static func describe(_ box: DebugUIBoundingBox) -> String {
String(
format: "x=%.1f y=%.1f w=%.1f h=%.1f",
@@ -659,6 +897,31 @@ final class DebugUIInspectionCoordinator {
)
}
+ private static func describe(_ rect: HotLoopRect) -> String {
+ String(
+ format: "x=%.1f y=%.1f w=%.1f h=%.1f",
+ rect.origin.x,
+ rect.origin.y,
+ rect.size.width,
+ rect.size.height
+ )
+ }
+
+ private static func describe(_ bounds: WindowTargetBounds?) -> String {
+ guard let bounds else { return "nil" }
+ return describe(bounds)
+ }
+
+ private static func describe(_ bounds: WindowTargetBounds) -> String {
+ String(
+ format: "x=%.1f y=%.1f w=%.1f h=%.1f",
+ bounds.x,
+ bounds.y,
+ bounds.width,
+ bounds.height
+ )
+ }
+
private static func describe(_ size: HotLoopSize) -> String {
String(format: "w=%.1f h=%.1f", size.width, size.height)
}
@@ -745,13 +1008,170 @@ final class DebugUIInspectionCoordinator {
&& 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 reproject(
+ _ element: DebugUIElement,
+ sourceScreen: DebugUIScreenSurface?,
+ currentWindowTargets: [UInt32: MacWindowTargetCandidate],
+ screens: [DebugUIScreenSurface]
+ ) -> (screenID: UInt32, element: DebugUIElement)? {
+ guard let windowID = windowID(for: element),
+ let target = currentWindowTargets[windowID],
+ let localBounds = localBounds(for: element)
+ else {
+ return nil
+ }
+
+ let previousTarget = targetBounds(for: element)
+ let scaleX = previousTarget.flatMap { $0.width > 0 ? target.bounds.width / $0.width : nil } ?? 1
+ let scaleY = previousTarget.flatMap { $0.height > 0 ? target.bounds.height / $0.height : nil } ?? 1
+ let absoluteBounds: WindowTargetBounds
+ if let previousTarget,
+ let sourceScreen {
+ let deltaX = target.bounds.x - previousTarget.x
+ let deltaY = target.bounds.y - previousTarget.y
+ absoluteBounds = WindowTargetBounds(
+ x: sourceScreen.captureFrame.x + element.bbox.x + deltaX,
+ y: sourceScreen.captureFrame.y + element.bbox.y + deltaY,
+ width: element.bbox.width * scaleX,
+ height: element.bbox.height * scaleY
+ )
+ } else {
+ absoluteBounds = WindowTargetBounds(
+ x: target.bounds.x + localBounds.x * scaleX,
+ y: target.bounds.y + localBounds.y * scaleY,
+ width: localBounds.width * scaleX,
+ height: localBounds.height * scaleY
+ )
+ }
+ let updatedLocalBounds = WindowTargetBounds(
+ x: localBounds.x * scaleX,
+ y: localBounds.y * scaleY,
+ width: localBounds.width * scaleX,
+ height: localBounds.height * scaleY
)
+
+ guard let screen = screens.first(where: { intersects(absoluteBounds, $0.captureFrame) }),
+ let bbox = clippedBoundingBox(absoluteBounds, screenFrame: screen.captureFrame)
+ else {
+ return nil
+ }
+
+ var metadata = element.metadata
+ metadata.merge(targetBoundsMetadata(target.bounds)) { _, new in new }
+ metadata.merge(boundsMetadata(prefix: "debugOverlay.localBounds.", bounds: updatedLocalBounds)) { _, new in new }
+ return (
+ screen.screenID,
+ DebugUIElement(
+ id: element.id,
+ type: element.type,
+ label: element.label,
+ description: element.description,
+ bbox: bbox,
+ confidence: element.confidence,
+ visualStyle: element.visualStyle,
+ metadata: metadata
+ )
+ )
+ }
+
+ 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 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 isAccessibilityEvidence(_ element: DebugUIElement) -> Bool {
+ let sources = metadataValue("localUIElement.sources", metadata: element.metadata) ?? ""
+ return sources.contains("accessibility")
+ || element.id.hasPrefix("ax-")
+ || sources.contains("window-chrome-geometry")
+ || element.id.hasPrefix("window-chrome-")
+ }
+
+ private static func windowID(for element: DebugUIElement) -> UInt32? {
+ metadataValue("target.windowID", metadata: element.metadata).flatMap(UInt32.init)
+ }
+
+ private static func targetBounds(for element: DebugUIElement) -> WindowTargetBounds? {
+ metadataBounds(prefix: "target.bounds.", metadata: element.metadata)
+ }
+
+ private static func localBounds(for element: DebugUIElement) -> WindowTargetBounds? {
+ metadataBounds(prefix: "debugOverlay.localBounds.", metadata: element.metadata)
+ }
+
+ private static func metadataBounds(
+ prefix: String,
+ metadata: [String: String]
+ ) -> WindowTargetBounds? {
+ guard let xValue = metadataValue(prefix + "x", metadata: metadata),
+ let yValue = metadataValue(prefix + "y", metadata: metadata),
+ let widthValue = metadataValue(prefix + "width", metadata: metadata),
+ let heightValue = metadataValue(prefix + "height", metadata: metadata),
+ let x = Double(xValue),
+ let y = Double(yValue),
+ let width = Double(widthValue),
+ let height = Double(heightValue),
+ width > 0,
+ height > 0
+ else {
+ return nil
+ }
+
+ return WindowTargetBounds(x: x, y: y, width: width, height: height)
+ }
+
+ private static func metadataValue(
+ _ key: String,
+ metadata: [String: String]
+ ) -> String? {
+ if let value = metadata[key] {
+ return value
+ }
+
+ let suffix = ".\(key)"
+ return metadata
+ .sorted { $0.key < $1.key }
+ .first { entry in entry.key.hasSuffix(suffix) }?
+ .value
+ }
+
+ private static func targetBoundsMetadata(_ bounds: WindowTargetBounds) -> [String: String] {
+ boundsMetadata(prefix: "target.bounds.", bounds: bounds)
+ }
+
+ 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)
+ ]
}
private static func fingerprint(
@@ -788,6 +1208,18 @@ final class DebugUIInspectionCoordinator {
return SHA256.hash(data: Data(combinedInput.utf8)).map { String(format: "%02x", $0) }.joined()
}
+ private static func frameSignature(_ frame: DebugUIInspectionFrame) -> String {
+ frame.elements.map { element in
+ [
+ element.id,
+ String(format: "%.1f", element.bbox.x),
+ String(format: "%.1f", element.bbox.y),
+ String(format: "%.1f", element.bbox.width),
+ String(format: "%.1f", element.bbox.height)
+ ].joined(separator: ":")
+ }.joined(separator: "|")
+ }
+
private static func screenPointSnapshot(
screen: DebugUIScreenSurface,
fingerprint: String
diff --git a/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift b/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift
index 173859d7..f137bc71 100644
--- a/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift
+++ b/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift
@@ -24,28 +24,23 @@ public enum ScreenshotParseDebugUIOverlayMapper {
}
guard control.confidence >= threshold,
let frame = control.frame,
+ let localBounds = overlayLocalBounds(
+ for: frame,
+ target: target,
+ capturePixelSize: capturePixelSize
+ ),
let bbox = overlayBoundingBox(
for: frame,
target: target,
capturePixelSize: capturePixelSize,
- screenFrame: screenFrame,
- flipWindowY: true
+ screenFrame: screenFrame
)
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([
+ let metadata = control.metadata
+ .merging([
"localUIElement.sources": "gemini-screenshot-parser",
"localUIElement.actionEligibility": LocalUIElementActionEligibility.guardedAction.rawValue,
"remoteScreenshotParsing.status": result.metadata["remoteScreenshotParsing.status"] ?? "used",
@@ -57,6 +52,20 @@ public enum ScreenshotParseDebugUIOverlayMapper {
"coordinate.sourceSpace": frame.space.rawValue,
"directInputActionsAllowed": "true"
]) { current, _ in current }
+ .merging(boundsMetadata(prefix: "target.bounds.", bounds: target.bounds)) { current, _ in current }
+ .merging(boundsMetadata(prefix: "debugOverlay.localBounds.", bounds: localBounds)) { current, _ in current }
+
+ 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: metadata
)
}
).validated(minConfidence: threshold)
@@ -82,15 +91,33 @@ public enum ScreenshotParseDebugUIOverlayMapper {
let centerY = 23.0
return controls.compactMap { control in
+ let localBounds = WindowTargetBounds(
+ x: control.centerX - diameter / 2,
+ y: centerY - diameter / 2,
+ width: diameter,
+ height: diameter
+ )
let bounds = WindowTargetBounds(
- x: target.bounds.x + control.centerX - diameter / 2,
- y: target.bounds.y + centerY - diameter / 2,
+ x: target.bounds.x + localBounds.x,
+ y: target.bounds.y + localBounds.y,
width: diameter,
height: diameter
)
guard let bbox = clippedBoundingBox(bounds, screenFrame: screenFrame) else {
return nil
}
+ let metadata = [
+ "localUIElement.sources": "window-chrome-geometry",
+ "localUIElement.actionEligibility": LocalUIElementActionEligibility.guardedAction.rawValue,
+ "target.windowID": String(target.windowID),
+ "target.appName": target.appName ?? "",
+ "target.bundleIdentifier": target.bundleIdentifier ?? "",
+ "target.title": target.title ?? "",
+ "coordinate.sourceSpace": "windowChromeGeometry",
+ "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: "window-chrome-\(target.windowID)-\(control.id)",
type: .windowControl,
@@ -98,16 +125,7 @@ public enum ScreenshotParseDebugUIOverlayMapper {
description: "macOS window chrome",
bbox: bbox,
confidence: 1,
- metadata: [
- "localUIElement.sources": "window-chrome-geometry",
- "localUIElement.actionEligibility": LocalUIElementActionEligibility.guardedAction.rawValue,
- "target.windowID": String(target.windowID),
- "target.appName": target.appName ?? "",
- "target.bundleIdentifier": target.bundleIdentifier ?? "",
- "target.title": target.title ?? "",
- "coordinate.sourceSpace": "windowChromeGeometry",
- "directInputActionsAllowed": "true"
- ]
+ metadata: metadata
)
}
}
@@ -123,8 +141,7 @@ public enum ScreenshotParseDebugUIOverlayMapper {
for rect: HotLoopRect,
target: MacWindowTargetCandidate,
capturePixelSize: HotLoopSize,
- screenFrame: WindowTargetBounds,
- flipWindowY: Bool = false
+ screenFrame: WindowTargetBounds
) -> DebugUIBoundingBox? {
guard rect.hasPositiveArea,
target.bounds.hasPositiveArea,
@@ -135,23 +152,7 @@ public enum ScreenshotParseDebugUIOverlayMapper {
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:
+ if rect.space == .screen {
return clippedBoundingBox(
WindowTargetBounds(
x: rect.origin.x,
@@ -163,14 +164,18 @@ public enum ScreenshotParseDebugUIOverlayMapper {
)
}
+ guard let localRect = overlayLocalBounds(
+ for: rect,
+ target: target,
+ capturePixelSize: capturePixelSize
+ ) else {
+ return nil
+ }
+
return clippedBoundingBox(
WindowTargetBounds(
x: target.bounds.x + localRect.x,
- y: target.bounds.y + mappedWindowY(
- localRect,
- targetHeight: target.bounds.height,
- flipWindowY: flipWindowY
- ),
+ y: target.bounds.y + localRect.y,
width: localRect.width,
height: localRect.height
),
@@ -178,16 +183,54 @@ public enum ScreenshotParseDebugUIOverlayMapper {
)
}
- private static func mappedWindowY(
- _ localRect: WindowTargetBounds,
- targetHeight: Double,
- flipWindowY: Bool
- ) -> Double {
- guard flipWindowY else {
- return localRect.y
+ private static func overlayLocalBounds(
+ for rect: HotLoopRect,
+ target: MacWindowTargetCandidate,
+ capturePixelSize: HotLoopSize
+ ) -> WindowTargetBounds? {
+ guard rect.hasPositiveArea,
+ target.bounds.hasPositiveArea,
+ capturePixelSize.width > 0,
+ capturePixelSize.height > 0
+ else {
+ return nil
}
- return max(0, targetHeight - localRect.y - localRect.height)
+ switch rect.space {
+ case .window, .crop:
+ return 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:
+ return 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 WindowTargetBounds(
+ x: rect.origin.x - target.bounds.x,
+ y: rect.origin.y - target.bounds.y,
+ width: rect.size.width,
+ height: rect.size.height
+ )
+ }
+ }
+
+ 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)
+ ]
}
private static func clippedBoundingBox(
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift
index 5860cd76..b8bb5bf8 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift
@@ -5,6 +5,11 @@ import CoreGraphics
import CryptoKit
import DonkeyContracts
import Foundation
+import OSLog
+
+private enum DebugUIAccessibilityInspectionLog {
+ static let overlay = Logger(subsystem: "com.donkey.app", category: "debug-ui-inspection")
+}
public struct DebugUIAccessibilityInspectionResult: Equatable, Sendable {
public var snapshot: DebugUIScreenCaptureSnapshot
@@ -218,7 +223,14 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
}
visibleWindowIndex += 1
- let controls = controlDiscovery.discover(in: snapshot).controls
+ let controlIndex = controlDiscovery.discover(in: snapshot)
+ let controls = controlIndex.controls
+ Self.logDiscoverySummary(
+ target: target,
+ snapshot: snapshot,
+ controls: controls,
+ visibleText: controlIndex.visibleText
+ )
for control in controls {
guard let candidate = accessibilityCandidate(
for: control,
@@ -272,6 +284,8 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
"windowFrameStyle.index": String(visibleWindowIndex),
"classification.reason": "accessibilityWindowFrame"
]
+ .merging(Self.boundsMetadata(prefix: "target.bounds.", bounds: target.bounds)) { current, _ in current }
+ .merging(Self.boundsMetadata(prefix: "debugOverlay.localBounds.", bounds: Self.localBounds(for: windowBounds, in: target.bounds))) { current, _ in current }
)
}
@@ -449,7 +463,15 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
description: "Window frame \(label)",
bbox: bbox,
confidence: 1,
- visualStyle: visualStyle
+ visualStyle: visualStyle,
+ metadata: [
+ "target.windowID": String(target.windowID),
+ "target.appName": target.appName ?? "",
+ "target.title": target.title ?? "",
+ "classification.reason": "accessibilityWindowFrame"
+ ]
+ .merging(Self.boundsMetadata(prefix: "target.bounds.", bounds: target.bounds)) { current, _ in current }
+ .merging(Self.boundsMetadata(prefix: "debugOverlay.localBounds.", bounds: Self.localBounds(for: windowBounds, in: target.bounds))) { current, _ in current }
)
)
}
@@ -571,7 +593,15 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
label: label,
description: Self.description(for: control, target: target),
bbox: bbox,
- confidence: 1
+ confidence: 1,
+ metadata: [
+ "target.windowID": String(target.windowID),
+ "target.appName": target.appName ?? "",
+ "target.title": target.title ?? "",
+ "classification.reason": "accessibilityControlDiscovery"
+ ]
+ .merging(Self.boundsMetadata(prefix: "target.bounds.", bounds: target.bounds)) { current, _ in current }
+ .merging(Self.boundsMetadata(prefix: "debugOverlay.localBounds.", bounds: Self.localBounds(for: bounds, in: target.bounds))) { current, _ in current }
)
)
}
@@ -661,7 +691,10 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
"accessibility.role": control.role ?? "",
"accessibility.actions": control.actions.joined(separator: ","),
"classification.reason": "accessibilityControlDiscovery"
- ].merging(control.metadata) { current, _ in current }
+ ]
+ .merging(Self.boundsMetadata(prefix: "target.bounds.", bounds: target.bounds)) { current, _ in current }
+ .merging(Self.boundsMetadata(prefix: "debugOverlay.localBounds.", bounds: Self.localBounds(for: bounds, in: target.bounds))) { current, _ in current }
+ .merging(control.metadata) { current, _ in current }
)
)
}
@@ -715,6 +748,89 @@ public struct DebugUIAccessibilityInspectionService: Sendable {
.first { !$0.isEmpty } ?? "window \(target.windowID)"
}
+ private static func logDiscoverySummary(
+ target: MacWindowTargetCandidate,
+ snapshot: MacAccessibilitySnapshot,
+ controls: [LocalAppDiscoveredControl],
+ visibleText: String
+ ) {
+ DebugUIAccessibilityInspectionLog.overlay.info(
+ "debug inspection ax-discovery windowID=\(target.windowID, privacy: .public) app=\(target.appName ?? "", privacy: .public) targetBounds=\(Self.describe(target.bounds), privacy: .public) rootFrame=\(Self.describe(snapshot.root.frame), privacy: .public) nodeCount=\(snapshot.totalNodeCount, privacy: .public) truncated=\(String(snapshot.isTreeTruncated), privacy: .public) controls=\(controls.count, privacy: .public) visibleTextChars=\(visibleText.count, privacy: .public) kinds=\(Self.controlKindSummary(controls), privacy: .public) roles=\(Self.roleSummary(snapshot.root), privacy: .public)"
+ )
+ }
+
+ private static func controlKindSummary(_ controls: [LocalAppDiscoveredControl]) -> String {
+ let counts = Dictionary(grouping: controls, by: \.kind)
+ .mapValues(\.count)
+ return counts
+ .sorted { lhs, rhs in lhs.key.rawValue < rhs.key.rawValue }
+ .map { "\($0.key.rawValue):\($0.value)" }
+ .joined(separator: ",")
+ }
+
+ private static func roleSummary(_ root: MacAccessibilitySnapshotNode) -> String {
+ var counts: [String: Int] = [:]
+ collectRoles(root, counts: &counts)
+ return counts
+ .sorted { lhs, rhs in
+ if lhs.value != rhs.value { return lhs.value > rhs.value }
+ return lhs.key < rhs.key
+ }
+ .prefix(12)
+ .map { "\($0.key):\($0.value)" }
+ .joined(separator: ",")
+ }
+
+ private static func collectRoles(
+ _ node: MacAccessibilitySnapshotNode,
+ counts: inout [String: Int]
+ ) {
+ let role = node.role ?? "nil"
+ counts[role, default: 0] += 1
+ for child in node.children {
+ collectRoles(child, counts: &counts)
+ }
+ }
+
+ private static func localBounds(
+ for bounds: WindowTargetBounds,
+ in targetBounds: WindowTargetBounds
+ ) -> WindowTargetBounds {
+ WindowTargetBounds(
+ x: bounds.x - targetBounds.x,
+ y: bounds.y - targetBounds.y,
+ width: bounds.width,
+ height: bounds.height
+ )
+ }
+
+ 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)
+ ]
+ }
+
+ private static func describe(_ bounds: WindowTargetBounds?) -> String {
+ guard let bounds else { return "nil" }
+ return describe(bounds)
+ }
+
+ private static func describe(_ bounds: WindowTargetBounds) -> String {
+ String(
+ format: "x=%.1f y=%.1f w=%.1f h=%.1f",
+ bounds.x,
+ bounds.y,
+ bounds.width,
+ bounds.height
+ )
+ }
+
private static func windowFrameStyle(at index: Int) -> DebugUIOverlayStyle {
windowFrameStyles[index % windowFrameStyles.count]
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift
index 950e04f5..d6ba121a 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift
@@ -569,11 +569,12 @@ public enum DebugUIOverlayGeometry {
let scaleX = screenPointSize.width / screenshotPixelSize.width
let scaleY = screenPointSize.height / screenshotPixelSize.height
+ let height = bbox.height * scaleY
return CGRect(
x: bbox.x * scaleX,
- y: bbox.y * scaleY,
+ y: screenPointSize.height - (bbox.y * scaleY + height),
width: bbox.width * scaleX,
- height: bbox.height * scaleY
+ height: height
)
}
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift
index e4686f1c..55294287 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift
@@ -337,7 +337,7 @@ struct DebugUIInspectionTests {
screenPointSize: HotLoopSize(width: 1000, height: 500, space: .screen)
)
- #expect(frame == CGRect(x: 100, y: 50, width: 200, height: 100))
+ #expect(frame == CGRect(x: 100, y: 350, width: 200, height: 100))
}
@Test
@@ -458,6 +458,11 @@ struct DebugUIInspectionTests {
let button = results.first?.frame.elements.last
#expect(button?.type == .button)
#expect(button?.label == "Save")
+ #expect(button?.metadata["target.windowID"] == "11")
+ #expect(button?.metadata["debugOverlay.localBounds.x"] == "20.0")
+ #expect(button?.metadata["debugOverlay.localBounds.y"] == "30.0")
+ #expect(button?.metadata["debugOverlay.localBounds.width"] == "80.0")
+ #expect(button?.metadata["debugOverlay.localBounds.height"] == "30.0")
#expect(button?.bbox == DebugUIBoundingBox(x: 120, y: 230, width: 80, height: 30))
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
index e96f25de..8b84f019 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
@@ -200,9 +200,14 @@ struct DonkeyBackendInferenceClientTests {
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.bbox == DebugUIBoundingBox(x: 150, y: 225, width: 100, height: 50))
#expect(element.metadata["directInputActionsAllowed"] == "true")
#expect(element.metadata["localUIElement.actionEligibility"] == "guardedAction")
+ #expect(element.metadata["target.windowID"] == "42")
+ #expect(element.metadata["debugOverlay.localBounds.x"] == "50.0")
+ #expect(element.metadata["debugOverlay.localBounds.y"] == "25.0")
+ #expect(element.metadata["debugOverlay.localBounds.width"] == "100.0")
+ #expect(element.metadata["debugOverlay.localBounds.height"] == "50.0")
}
@Test
@@ -247,7 +252,7 @@ struct DonkeyBackendInferenceClientTests {
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.y - 390) < 0.0001)
#expect(abs(bbox.width - 94.5) < 0.0001)
#expect(abs(bbox.height - 54) < 0.0001)
}