Open source CapCut alternative.
TypeScript
Add dev UI inspection overlay
David Le945a38eb8e54
diff --git a/apps/Donkey/Sources/Donkey/DebugUIInspectionCoordinator.swift b/apps/Donkey/Sources/Donkey/DebugUIInspectionCoordinator.swiftnew file mode 100644index 00000000..f3726ce8--- /dev/null+++ b/apps/Donkey/Sources/Donkey/DebugUIInspectionCoordinator.swift@@ -0,0 +1,163 @@+import AppKit+import DonkeyAI+import DonkeyContracts+import DonkeyRuntime+import Foundation++@MainActor+final class DebugUIInspectionCoordinator {+ private let overlayController = DebugUIInspectionOverlayController()+ private let captureService = DebugUIScreenCaptureService()+ private let configURL: URL?+ private var analyzer: (any DebugUIInspectionAnalyzing)?+ private var trackers: [UInt32: DebugUIElementTracker] = [:]+ private var lastFingerprints: [UInt32: String] = [:]+ private var timer: Timer?+ private var notificationObservers: [NSObjectProtocol] = []+ private var currentConfig: DebugUIOverlayConfiguration = .disabled+ private var isAnalyzing = false++ init(configURL: URL? = DebugUIOverlayConfiguration.defaultConfigURL()) {+ self.configURL = configURL+ }++ func start() {+ stop()+ installNotificationObservers()+ reloadConfigAndReschedule(force: true)+ refresh()+ }++ func stop() {+ timer?.invalidate()+ timer = nil+ for observer in notificationObservers {+ NotificationCenter.default.removeObserver(observer)+ NSWorkspace.shared.notificationCenter.removeObserver(observer)+ }+ notificationObservers.removeAll()+ overlayController.close()+ trackers.removeAll()+ lastFingerprints.removeAll()+ isAnalyzing = false+ currentConfig = .disabled+ }++ private func installNotificationObservers() {+ let appNotificationNames: [Notification.Name] = [+ NSApplication.didBecomeActiveNotification,+ NSApplication.didChangeScreenParametersNotification+ ]+ notificationObservers = appNotificationNames.map { name in+ NotificationCenter.default.addObserver(+ forName: name,+ object: nil,+ queue: .main+ ) { [weak self] _ in+ Task { @MainActor in+ self?.refresh(force: true)+ }+ }+ }+ let workspaceObserver = NSWorkspace.shared.notificationCenter.addObserver(+ forName: NSWorkspace.didActivateApplicationNotification,+ object: nil,+ queue: .main+ ) { [weak self] _ in+ Task { @MainActor in+ self?.refresh(force: true)+ }+ }+ notificationObservers.append(workspaceObserver)+ }++ private func reloadConfigAndReschedule(force: Bool = false) {+ let newConfig = DebugUIOverlayConfiguration.load(fileURL: configURL)+ 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 confidenceChanged = newConfig.minConfidence != currentConfig.minConfidence+ currentConfig = newConfig++ if cadenceChanged || timer == nil || force {+ timer?.invalidate()+ let newTimer = Timer(timeInterval: newConfig.cadenceSeconds, repeats: true) { [weak self] _ in+ Task { @MainActor in+ self?.refresh()+ }+ }+ timer = newTimer+ RunLoop.main.add(newTimer, forMode: .common)+ }++ if enablementChanged || scopeChanged || providerChanged || confidenceChanged {+ lastFingerprints.removeAll()+ trackers.removeAll()+ if !newConfig.enabled {+ overlayController.close()+ }+ }+ }++ private func refresh(force: Bool = false) {+ reloadConfigAndReschedule()+ guard currentConfig.enabled else { return }+ guard !isAnalyzing else { return }++ isAnalyzing = true+ Task { @MainActor in+ defer { isAnalyzing = false }+ do {+ try await analyzeVisibleScreens(force: force)+ } catch {+ overlayController.close()+ lastFingerprints.removeAll()+ trackers.removeAll()+ }+ }+ }++ private func analyzeVisibleScreens(force: Bool) async throws {+ let snapshots = try captureService.captureScreens(scope: currentConfig.screenScope)+ overlayController.closeScreens(except: Set(snapshots.map(\.screenID)))+ let analyzer = try analyzerInstance()++ for snapshot in snapshots {+ guard force || lastFingerprints[snapshot.screenID] != snapshot.fingerprint else {+ continue+ }+ lastFingerprints[snapshot.screenID] = snapshot.fingerprint++ let frame = try await analyzer.inspect(+ DebugUIInspectionRequest(+ provider: currentConfig.provider,+ screenshotBase64: snapshot.base64PNG,+ pixelSize: snapshot.pixelSize,+ minConfidence: currentConfig.minConfidence,+ metadata: [+ "screen.id": String(snapshot.screenID),+ "screen.scope": currentConfig.screenScope.rawValue+ ]+ )+ )+ var tracker = trackers[snapshot.screenID] ?? DebugUIElementTracker()+ let trackedFrame = tracker.update(with: frame)+ trackers[snapshot.screenID] = tracker+ overlayController.render(frame: trackedFrame, snapshot: snapshot)+ }+ }++ private func analyzerInstance() throws -> any DebugUIInspectionAnalyzing {+ if let analyzer {+ return analyzer+ }++ let configuration = try DonkeyBackendInferenceConfiguration.fromEnvironment()+ let created = HostedDebugUIInspectionAnalyzer(+ backend: DonkeyBackendInferenceClient(configuration: configuration)+ )+ analyzer = created+ return created+ }+}diff --git a/apps/Donkey/Sources/Donkey/DebugUIInspectionOverlayController.swift b/apps/Donkey/Sources/Donkey/DebugUIInspectionOverlayController.swiftnew file mode 100644index 00000000..0d860fa7--- /dev/null+++ b/apps/Donkey/Sources/Donkey/DebugUIInspectionOverlayController.swift@@ -0,0 +1,260 @@+import AppKit+import DonkeyContracts+import DonkeyRuntime+import QuartzCore++@MainActor+final class DebugUIInspectionOverlayController {+ private var surfaces: [UInt32: DebugUIInspectionSurface] = [:]++ func render(+ frame: DebugUIInspectionFrame,+ snapshot: DebugUIScreenCaptureSnapshot+ ) {+ let surface = surfaces[snapshot.screenID] ?? makeSurface(for: snapshot)+ surfaces[snapshot.screenID] = surface+ surface.render(frame: frame, snapshot: snapshot)+ }++ func closeScreens(except activeScreenIDs: Set<UInt32>) {+ for (screenID, surface) in surfaces where !activeScreenIDs.contains(screenID) {+ surface.close()+ surfaces.removeValue(forKey: screenID)+ }+ }++ func close() {+ for surface in surfaces.values {+ surface.close()+ }+ surfaces.removeAll()+ }++ private func makeSurface(+ for snapshot: DebugUIScreenCaptureSnapshot+ ) -> DebugUIInspectionSurface {+ let frame = CGRect(+ x: snapshot.screenFrame.origin.x,+ y: snapshot.screenFrame.origin.y,+ width: snapshot.screenFrame.size.width,+ height: snapshot.screenFrame.size.height+ )+ let rootView = DebugUIInspectionRootView(frame: CGRect(origin: .zero, size: frame.size))+ rootView.wantsLayer = true+ rootView.layer = CALayer()+ rootView.layer?.frame = rootView.bounds+ rootView.layer?.backgroundColor = NSColor.clear.cgColor+ rootView.layer?.isGeometryFlipped = true++ let panel = DebugUIInspectionPanel(+ contentRect: frame,+ styleMask: [.borderless, .nonactivatingPanel],+ backing: .buffered,+ defer: false+ )+ panel.title = "Donkey Debug UI Inspection"+ panel.contentView = rootView+ panel.backgroundColor = .clear+ panel.isOpaque = false+ panel.hasShadow = false+ panel.hidesOnDeactivate = false+ panel.isReleasedWhenClosed = false+ panel.ignoresMouseEvents = true+ panel.level = DonkeyOverlayWindowLevel.debugInspection+ panel.collectionBehavior = [+ .canJoinAllSpaces,+ .fullScreenAuxiliary,+ .ignoresCycle,+ .stationary+ ]+ panel.sharingType = .none+ panel.orderFrontRegardless()++ return DebugUIInspectionSurface(panel: panel, rootView: rootView)+ }+}++@MainActor+private final class DebugUIInspectionSurface {+ private let panel: NSPanel+ private let rootView: NSView+ private var elementLayers: [String: DebugUIInspectionElementLayers] = [:]++ init(panel: NSPanel, rootView: NSView) {+ self.panel = panel+ self.rootView = rootView+ }++ func render(+ frame: DebugUIInspectionFrame,+ snapshot: DebugUIScreenCaptureSnapshot+ ) {+ let panelFrame = CGRect(+ x: snapshot.screenFrame.origin.x,+ y: snapshot.screenFrame.origin.y,+ width: snapshot.screenFrame.size.width,+ height: snapshot.screenFrame.size.height+ )+ if panel.frame != panelFrame {+ panel.setFrame(panelFrame, display: true)+ rootView.frame = CGRect(origin: .zero, size: panelFrame.size)+ rootView.layer?.frame = rootView.bounds+ }++ let activeIDs = Set(frame.elements.map(\.id))+ for (id, layers) in elementLayers where !activeIDs.contains(id) {+ fadeOutAndRemove(layers)+ elementLayers.removeValue(forKey: id)+ }++ CATransaction.begin()+ CATransaction.setAnimationDuration(0.18)+ for element in frame.elements {+ let layers = elementLayers[element.id] ?? makeLayers(for: element)+ elementLayers[element.id] = layers+ update(layers: layers, element: element, snapshot: snapshot)+ }+ CATransaction.commit()++ panel.orderFrontRegardless()+ }++ func close() {+ panel.close()+ elementLayers.removeAll()+ }++ private func makeLayers(for element: DebugUIElement) -> DebugUIInspectionElementLayers {+ let boxLayer = CAShapeLayer()+ boxLayer.name = "debug-ui-box-\(element.id)"+ boxLayer.fillColor = nsColor(hex: element.visualStyle.overlayColor, alpha: 0.14).cgColor+ boxLayer.strokeColor = nsColor(hex: element.visualStyle.borderColor, alpha: 0.95).cgColor+ boxLayer.lineWidth = 2+ boxLayer.opacity = 0++ let textLayer = CATextLayer()+ textLayer.name = "debug-ui-label-\(element.id)"+ textLayer.contentsScale = NSScreen.main?.backingScaleFactor ?? 2+ textLayer.alignmentMode = .left+ textLayer.fontSize = 11+ textLayer.truncationMode = .end+ textLayer.isWrapped = false+ textLayer.opacity = 0++ rootView.layer?.addSublayer(boxLayer)+ rootView.layer?.addSublayer(textLayer)++ let layers = DebugUIInspectionElementLayers(box: boxLayer, label: textLayer)+ fadeIn(layers)+ return layers+ }++ private func update(+ layers: DebugUIInspectionElementLayers,+ element: DebugUIElement,+ snapshot: DebugUIScreenCaptureSnapshot+ ) {+ let screenPointSize = HotLoopSize(+ width: snapshot.screenFrame.size.width,+ height: snapshot.screenFrame.size.height,+ space: .screen+ )+ let boxFrame = DebugUIOverlayGeometry.localLayerFrame(+ for: element.bbox,+ screenshotPixelSize: snapshot.pixelSize,+ screenPointSize: screenPointSize+ ).integral+ let path = CGPath(rect: CGRect(origin: .zero, size: boxFrame.size), transform: nil)+ layers.box.frame = boxFrame+ layers.box.path = path+ layers.box.fillColor = nsColor(hex: element.visualStyle.overlayColor, alpha: 0.14).cgColor+ layers.box.strokeColor = nsColor(hex: element.visualStyle.borderColor, alpha: 0.95).cgColor++ let title = labelText(for: element)+ let labelSize = labelFrameSize(for: title, boxFrame: boxFrame)+ let labelY = max(0, boxFrame.minY - labelSize.height - 2)+ 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.frame = CGRect(+ x: max(0, min(boxFrame.minX, rootView.bounds.width - labelSize.width)),+ y: labelY,+ width: labelSize.width,+ height: labelSize.height+ ).integral+ }++ private func labelText(for element: DebugUIElement) -> String {+ let label = element.label.trimmingCharacters(in: .whitespacesAndNewlines)+ if !label.isEmpty {+ return label+ }+ return element.type.rawValue.replacingOccurrences(of: "_", with: " ")+ }++ private func labelFrameSize(for text: String, boxFrame: CGRect) -> CGSize {+ let characterWidth = 6.5+ let width = min(+ max(48, Double(text.count) * characterWidth + 14),+ max(64, Double(rootView.bounds.width - max(0, boxFrame.minX)))+ )+ return CGSize(width: width, height: 18)+ }++ private func fadeIn(_ layers: DebugUIInspectionElementLayers) {+ let animation = CABasicAnimation(keyPath: "opacity")+ animation.fromValue = 0+ animation.toValue = 1+ animation.duration = 0.16+ layers.box.opacity = 1+ layers.label.opacity = 1+ layers.box.add(animation, forKey: "fade-in")+ layers.label.add(animation, forKey: "fade-in")+ }++ private func fadeOutAndRemove(_ layers: DebugUIInspectionElementLayers) {+ CATransaction.begin()+ CATransaction.setCompletionBlock {+ layers.box.removeFromSuperlayer()+ layers.label.removeFromSuperlayer()+ }+ let animation = CABasicAnimation(keyPath: "opacity")+ animation.fromValue = layers.box.opacity+ animation.toValue = 0+ animation.duration = 0.14+ layers.box.opacity = 0+ layers.label.opacity = 0+ layers.box.add(animation, forKey: "fade-out")+ layers.label.add(animation, forKey: "fade-out")+ CATransaction.commit()+ }++ private func nsColor(hex: String, alpha: CGFloat) -> NSColor {+ let trimmed = hex.trimmingCharacters(in: CharacterSet(charactersIn: "#"))+ guard trimmed.count == 6,+ let value = UInt32(trimmed, radix: 16) else {+ return NSColor.white.withAlphaComponent(alpha)+ }++ let red = CGFloat((value >> 16) & 0xFF) / 255+ let green = CGFloat((value >> 8) & 0xFF) / 255+ let blue = CGFloat(value & 0xFF) / 255+ return NSColor(red: red, green: green, blue: blue, alpha: alpha)+ }+}++private struct DebugUIInspectionElementLayers {+ var box: CAShapeLayer+ var label: CATextLayer+}++private final class DebugUIInspectionPanel: NSPanel {+ override var canBecomeKey: Bool { false }+ override var canBecomeMain: Bool { false }+}++private final class DebugUIInspectionRootView: NSView {+ override func hitTest(_ point: NSPoint) -> NSView? {+ nil+ }+}diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swiftindex 00f5f27f..e8b4b11b 100644--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift@@ -9,6 +9,7 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {private var loginWindowController: DonkeyLoginWindowController?private var permissionSetupController: MacPermissionSetupWindowController?private var overlayController: PointerPromptOverlayController?+ private var debugInspectionCoordinator: DebugUIInspectionCoordinator?private var runtimeOnboardingController: LocalRuntimeOnboardingWindowController?func applicationDidFinishLaunching(_ notification: Notification) {@@ -67,6 +68,7 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {andEventID: AEEventID(kAEGetURL))overlayController?.stop()+ debugInspectionCoordinator?.stop()}private func showLoginWindow() {@@ -112,6 +114,10 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {overlayController = controllercontroller.show()+ let debugInspectionCoordinator = DebugUIInspectionCoordinator()+ self.debugInspectionCoordinator = debugInspectionCoordinator+ debugInspectionCoordinator.start()+let runtimeOnboardingController = LocalRuntimeOnboardingWindowController()self.runtimeOnboardingController = runtimeOnboardingControllerruntimeOnboardingController.showIfSetupNeeded()diff --git a/apps/Donkey/Sources/Donkey/DonkeyOverlayWindowLevels.swift b/apps/Donkey/Sources/Donkey/DonkeyOverlayWindowLevels.swiftnew file mode 100644index 00000000..e82ee8af--- /dev/null+++ b/apps/Donkey/Sources/Donkey/DonkeyOverlayWindowLevels.swift@@ -0,0 +1,6 @@+import AppKit++enum DonkeyOverlayWindowLevel {+ static let debugInspection: NSWindow.Level = .floating+ static let pointerPrompt: NSWindow.Level = .statusBar+}diff --git a/apps/Donkey/Sources/Donkey/PointerCoachCursorOverlayController.swift b/apps/Donkey/Sources/Donkey/PointerCoachCursorOverlayController.swiftindex 523f7ec6..6c1e67c3 100644--- a/apps/Donkey/Sources/Donkey/PointerCoachCursorOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/PointerCoachCursorOverlayController.swift@@ -46,7 +46,7 @@ final class PointerCoachCursorOverlayController {panel.hidesOnDeactivate = falsepanel.isReleasedWhenClosed = falsepanel.ignoresMouseEvents = true- panel.level = .statusBar+ panel.level = DonkeyOverlayWindowLevel.pointerPromptpanel.collectionBehavior = [.canJoinAllSpaces,.fullScreenAuxiliary,diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swiftindex 7eef0ca8..ae54d72c 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift@@ -119,7 +119,7 @@ final class PointerPromptOverlayController {panel.escapeKeyHandler = { [weak self] inself?.dismissActivePromptFromKeyboard()}- panel.level = .statusBar+ panel.level = DonkeyOverlayWindowLevel.pointerPromptpanel.collectionBehavior = [.canJoinAllSpaces,.fullScreenAuxiliary,@@ -162,7 +162,7 @@ final class PointerPromptOverlayController {panel.mouseDownHandler = { [weak self] inself?.focusStatusComposerTextInputIfAvailable()}- panel.level = .statusBar+ panel.level = DonkeyOverlayWindowLevel.pointerPromptpanel.collectionBehavior = [.canJoinAllSpaces,.fullScreenAuxiliary,diff --git a/apps/Donkey/Sources/Donkey/PointerPromptSpawnOverlayController.swift b/apps/Donkey/Sources/Donkey/PointerPromptSpawnOverlayController.swiftindex 7442a6c8..2e776f7b 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptSpawnOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptSpawnOverlayController.swift@@ -280,7 +280,7 @@ final class PointerPromptSpawnOverlayController {panel.isReleasedWhenClosed = falsepanel.becomesKeyOnlyIfNeeded = falsepanel.ignoresMouseEvents = true- panel.level = .statusBar+ panel.level = DonkeyOverlayWindowLevel.pointerPromptpanel.collectionBehavior = [.canJoinAllSpaces,.fullScreenAuxiliary,diff --git a/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionHostedAdapter.swift b/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionHostedAdapter.swiftnew file mode 100644index 00000000..ca458370--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionHostedAdapter.swift@@ -0,0 +1,309 @@+import DonkeyContracts+import Foundation++public enum DebugUIInspectionHostedAdapterError: Error, Equatable, Sendable {+ case providerReturnedAction+ case missingOutputText+ case invalidJSON(String)+}++public struct DebugUIInspectionRequest: Equatable, Sendable {+ public var provider: DebugUIInspectionProvider+ public var screenshotBase64: String+ public var pixelSize: HotLoopSize+ public var minConfidence: Double+ public var metadata: [String: String]++ public init(+ provider: DebugUIInspectionProvider,+ screenshotBase64: String,+ pixelSize: HotLoopSize,+ minConfidence: Double = 0.25,+ metadata: [String: String] = [:]+ ) {+ self.provider = provider+ self.screenshotBase64 = screenshotBase64+ self.pixelSize = pixelSize+ self.minConfidence = min(max(minConfidence, 0), 1)+ self.metadata = metadata+ }+}++public protocol DebugUIInspectionAnalyzing: Sendable {+ func inspect(_ request: DebugUIInspectionRequest) async throws -> DebugUIInspectionFrame+}++public struct HostedDebugUIInspectionAnalyzer: DebugUIInspectionAnalyzing {+ public var backend: DonkeyBackendInferenceClient+ public var decoder: JSONDecoder++ public init(+ backend: DonkeyBackendInferenceClient,+ decoder: JSONDecoder = JSONDecoder()+ ) {+ self.backend = backend+ self.decoder = decoder+ }++ public func inspect(_ request: DebugUIInspectionRequest) async throws -> DebugUIInspectionFrame {+ let response = try await backend.createResponse(responseRequest(for: request))+ return try DebugUIInspectionResponseDecoder.decode(+ response,+ decoder: decoder,+ minConfidence: request.minConfidence+ )+ }++ private func responseRequest(+ for request: DebugUIInspectionRequest+ ) -> RemoteInferenceResponseCreateRequest {+ RemoteInferenceResponseCreateRequest(+ donkeyProvider: request.provider.rawValue,+ input: .array([+ .object([+ "role": .string("user"),+ "content": .array([+ .object([+ "type": .string("input_text"),+ "text": .string(Self.prompt)+ ]),+ .object([+ "type": .string("input_image"),+ "image_url": .string("data:image/png;base64,\(request.screenshotBase64)")+ ])+ ])+ ])+ ]),+ store: false,+ text: Self.responseFormat,+ tools: [+ RemoteInferenceComputerUseTool(+ type: .debugUIInspection,+ excludedPredefinedFunctions: Self.excludedActionNames,+ metadata: [+ "mode": "read_only",+ "schema": "debug_ui_inspection_v1"+ ]+ ).jsonObject+ ],+ metadata: request.metadata.merging([+ "source": "debug-ui-inspection-overlay",+ "prompt_version": "debug-ui-inspection-v1",+ "privacy.store": "false",+ "screenshot.width": String(request.pixelSize.width),+ "screenshot.height": String(request.pixelSize.height)+ ]) { current, _ in current },+ parameters: [+ "temperature": .number(0),+ "max_output_tokens": .number(8_000)+ ]+ )+ }++ private static let prompt = """+ You are a read-only macOS UI inspection model. Analyze the screenshot and return ONLY valid JSON.++ Detect visible user-interactable UI elements. Include window controls, buttons, links, tabs, menu items, dropdowns, text inputs, search fields, checkboxes, radios, toggles, sliders, toolbar icons, sidebar items, Dock items, menu bar items, table rows, list items, tree items, clickable cards, draggable handles, resize handles, scrollbars, split panes, canvas interaction regions, floating action buttons, and icon-only controls. Prefer over-detecting interactable elements over missing them.++ Do not include static text, decorative graphics, separators, backgrounds, or non-interactable containers unless they are clearly interactive.++ Coordinates must be screenshot pixel coordinates with origin at top-left. Bounding boxes must tightly fit the clickable region. If an element is partially obscured, include it with lower confidence. Infer labels for icon-only controls when possible.++ Do not click, type, scroll, drag, navigate, call tools, or propose actions. This is visual inspection only.++ Return exactly:+ {"elements":[{"id":"stable_unique_id","type":"button","label":"Save","description":"Saves current document","bbox":{"x":120,"y":340,"width":88,"height":32},"confidence":0.98,"visual_style":{"overlay_color":"#3B82F6","border_color":"#60A5FA","label_color":"#FFFFFF"}}]}+ """++ private static let excludedActionNames = [+ "click",+ "click_at",+ "double_click",+ "drag",+ "drag_and_drop",+ "go_back",+ "go_forward",+ "hover",+ "hover_at",+ "key_combination",+ "navigate",+ "open_web_browser",+ "scroll",+ "scroll_document",+ "search",+ "type",+ "type_text",+ "type_text_at"+ ]++ private static let responseFormat: RemoteInferenceJSONObject = [+ "format": .object([+ "type": .string("json_schema"),+ "name": .string("debug_ui_inspection_v1"),+ "strict": .bool(true),+ "schema": .object([+ "type": .string("object"),+ "additionalProperties": .bool(false),+ "required": .array([.string("elements")]),+ "properties": .object([+ "elements": .object([+ "type": .string("array"),+ "items": .object([+ "type": .string("object"),+ "additionalProperties": .bool(false),+ "required": .array([+ .string("id"),+ .string("type"),+ .string("label"),+ .string("description"),+ .string("bbox"),+ .string("confidence"),+ .string("visual_style")+ ]),+ "properties": .object([+ "id": .object(["type": .string("string")]),+ "type": .object([+ "type": .string("string"),+ "enum": .array(DebugUIElementType.allCases.map { .string($0.rawValue) })+ ]),+ "label": .object(["type": .string("string")]),+ "description": .object(["type": .string("string")]),+ "bbox": .object([+ "type": .string("object"),+ "additionalProperties": .bool(false),+ "required": .array([+ .string("x"),+ .string("y"),+ .string("width"),+ .string("height")+ ]),+ "properties": .object([+ "x": .object(["type": .string("number")]),+ "y": .object(["type": .string("number")]),+ "width": .object(["type": .string("number")]),+ "height": .object(["type": .string("number")])+ ])+ ]),+ "confidence": .object([+ "type": .string("number"),+ "minimum": .number(0),+ "maximum": .number(1)+ ]),+ "visual_style": .object([+ "type": .string("object"),+ "additionalProperties": .bool(false),+ "required": .array([+ .string("overlay_color"),+ .string("border_color"),+ .string("label_color")+ ]),+ "properties": .object([+ "overlay_color": .object(["type": .string("string")]),+ "border_color": .object(["type": .string("string")]),+ "label_color": .object(["type": .string("string")])+ ])+ ])+ ])+ ])+ ])+ ])+ ])+ ])+ ]+}++public enum DebugUIInspectionResponseDecoder {+ public static func decode(+ _ response: RemoteInferenceJSONValue,+ decoder: JSONDecoder = JSONDecoder(),+ minConfidence: Double = 0.25+ ) throws -> DebugUIInspectionFrame {+ guard containsActionOutput(response) == false else {+ throw DebugUIInspectionHostedAdapterError.providerReturnedAction+ }++ let frameData: Data+ if let object = response.objectValue,+ object["elements"] != nil {+ frameData = try JSONEncoder().encode(response)+ } else {+ guard let outputText = outputText(from: response),+ !outputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ else {+ throw DebugUIInspectionHostedAdapterError.missingOutputText+ }+ frameData = Data(outputText.utf8)+ }++ do {+ return try decoder.decode(DebugUIInspectionFrame.self, from: frameData)+ .validated(minConfidence: minConfidence)+ } catch {+ throw DebugUIInspectionHostedAdapterError.invalidJSON(String(describing: error))+ }+ }++ public static func containsActionOutput(_ value: RemoteInferenceJSONValue) -> Bool {+ switch value {+ case .string(let text):+ return actionMarkers.contains { text.contains($0) }+ case .number, .bool, .null:+ return false+ case .array(let values):+ return values.contains(where: containsActionOutput)+ case .object(let object):+ if let type = object["type"]?.stringValue,+ actionTypes.contains(type) {+ return true+ }+ if object["functionCall"] != nil ||+ object["function_call"] != nil ||+ object["computer_call"] != nil {+ return true+ }+ return object.values.contains(where: containsActionOutput)+ }+ }++ private static func outputText(from value: RemoteInferenceJSONValue) -> String? {+ guard let object = value.objectValue else {+ return nil+ }++ if let text = object["output_text"]?.stringValue {+ return text+ }++ return object["output"]?.arrayValue?+ .compactMap(messageText)+ .joined(separator: "\n")+ }++ private static func messageText(from value: RemoteInferenceJSONValue) -> String? {+ guard let object = value.objectValue else {+ return nil+ }+ if let text = object["text"]?.stringValue {+ return text+ }+ return object["content"]?.arrayValue?+ .compactMap { content in+ guard let contentObject = content.objectValue else { return nil }+ return contentObject["text"]?.stringValue+ }+ .joined(separator: "\n")+ }++ private static let actionTypes = Set([+ "computer_call",+ "computer_call_output",+ "function_call"+ ])++ private static let actionMarkers = [+ "\"type\":\"computer_call\"",+ "\"type\":\"function_call\"",+ "\"functionCall\"",+ "\"function_call\""+ ]+}diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swiftindex bba17007..d9819ab2 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift@@ -74,7 +74,7 @@ public struct DonkeyBackendInferenceConfiguration: Equatable, Sendable {}}-public struct DonkeyBackendInferenceClient {+public struct DonkeyBackendInferenceClient: @unchecked Sendable {public var configuration: DonkeyBackendInferenceConfigurationpublic var httpClient: any AIHTTPClientpublic var fileManager: FileManagerdiff --git a/apps/Donkey/Sources/DonkeyContracts/DebugUIInspectionContracts.swift b/apps/Donkey/Sources/DonkeyContracts/DebugUIInspectionContracts.swiftnew file mode 100644index 00000000..04d4c344--- /dev/null+++ b/apps/Donkey/Sources/DonkeyContracts/DebugUIInspectionContracts.swift@@ -0,0 +1,204 @@+import Foundation++public enum DebugUIInspectionProvider: String, Codable, Equatable, Sendable {+ case openai+ case gemini+}++public enum DebugUIInspectionScreenScope: String, Codable, Equatable, Sendable {+ case main+ case all+}++public enum DebugUIElementType: String, Codable, CaseIterable, Equatable, Sendable {+ case button+ case link+ case input+ case checkbox+ case toggle+ case dropdown+ case tab+ case menuItem = "menu_item"+ case windowControl = "window_control"+ case draggable+ case toolbarIcon = "toolbar_icon"+ case sidebarItem = "sidebar_item"+ case listItem = "list_item"+ case slider+ case other+}++public struct DebugUIBoundingBox: Codable, Equatable, Sendable {+ public var x: Double+ public var y: Double+ public var width: Double+ public var height: Double++ public init(x: Double, y: Double, width: Double, height: Double) {+ self.x = x+ self.y = y+ self.width = width+ self.height = height+ }++ public var hasPositiveArea: Bool {+ width > 0 && height > 0+ }+}++public struct DebugUIOverlayStyle: Codable, Equatable, Sendable {+ public var overlayColor: String+ public var borderColor: String+ public var labelColor: String++ public init(+ overlayColor: String,+ borderColor: String,+ labelColor: String = "#FFFFFF"+ ) {+ self.overlayColor = overlayColor+ self.borderColor = borderColor+ self.labelColor = labelColor+ }++ public enum CodingKeys: String, CodingKey {+ case overlayColor = "overlay_color"+ case borderColor = "border_color"+ case labelColor = "label_color"+ }++ public static func style(for type: DebugUIElementType) -> DebugUIOverlayStyle {+ switch type {+ case .button:+ return DebugUIOverlayStyle(overlayColor: "#3B82F6", borderColor: "#60A5FA")+ case .link:+ return DebugUIOverlayStyle(overlayColor: "#06B6D4", borderColor: "#67E8F9")+ case .input:+ return DebugUIOverlayStyle(overlayColor: "#10B981", borderColor: "#6EE7B7")+ case .checkbox:+ return DebugUIOverlayStyle(overlayColor: "#84CC16", borderColor: "#BEF264")+ case .toggle:+ return DebugUIOverlayStyle(overlayColor: "#14B8A6", borderColor: "#5EEAD4")+ case .dropdown:+ return DebugUIOverlayStyle(overlayColor: "#8B5CF6", borderColor: "#C4B5FD")+ case .tab:+ return DebugUIOverlayStyle(overlayColor: "#F59E0B", borderColor: "#FCD34D")+ case .menuItem:+ return DebugUIOverlayStyle(overlayColor: "#EAB308", borderColor: "#FDE047")+ case .windowControl:+ return DebugUIOverlayStyle(overlayColor: "#EF4444", borderColor: "#FCA5A5")+ case .draggable:+ return DebugUIOverlayStyle(overlayColor: "#EC4899", borderColor: "#F9A8D4")+ case .toolbarIcon:+ return DebugUIOverlayStyle(overlayColor: "#6366F1", borderColor: "#A5B4FC")+ case .sidebarItem:+ return DebugUIOverlayStyle(overlayColor: "#A16207", borderColor: "#FCD34D")+ case .listItem:+ return DebugUIOverlayStyle(overlayColor: "#6B7280", borderColor: "#D1D5DB")+ case .slider:+ return DebugUIOverlayStyle(overlayColor: "#34D399", borderColor: "#A7F3D0")+ case .other:+ return DebugUIOverlayStyle(overlayColor: "#FFFFFF", borderColor: "#E5E7EB")+ }+ }+}++public struct DebugUIElement: Codable, Equatable, Sendable, Identifiable {+ public var id: String+ public var type: DebugUIElementType+ public var label: String+ public var description: String+ public var bbox: DebugUIBoundingBox+ public var confidence: Double+ public var visualStyle: DebugUIOverlayStyle++ public init(+ id: String,+ type: DebugUIElementType,+ label: String,+ description: String = "",+ bbox: DebugUIBoundingBox,+ confidence: Double,+ visualStyle: DebugUIOverlayStyle? = nil+ ) {+ self.id = id+ self.type = type+ self.label = label+ self.description = description+ self.bbox = bbox+ self.confidence = min(max(confidence, 0), 1)+ self.visualStyle = visualStyle ?? DebugUIOverlayStyle.style(for: type)+ }++ public enum CodingKeys: String, CodingKey {+ case id+ case type+ case label+ case description+ case bbox+ case confidence+ case visualStyle = "visual_style"+ }++ public init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ let type = try container.decode(DebugUIElementType.self, forKey: .type)+ self.init(+ id: try container.decode(String.self, forKey: .id),+ type: type,+ label: try container.decodeIfPresent(String.self, forKey: .label) ?? "",+ description: try container.decodeIfPresent(String.self, forKey: .description) ?? "",+ bbox: try container.decode(DebugUIBoundingBox.self, forKey: .bbox),+ confidence: try container.decodeIfPresent(Double.self, forKey: .confidence) ?? 0,+ visualStyle: try container.decodeIfPresent(DebugUIOverlayStyle.self, forKey: .visualStyle)+ )+ }++ public func replacingID(_ id: String) -> DebugUIElement {+ DebugUIElement(+ id: id,+ type: type,+ label: label,+ description: description,+ bbox: bbox,+ confidence: confidence,+ visualStyle: visualStyle+ )+ }+}++public struct DebugUIInspectionFrame: Codable, Equatable, Sendable {+ public var elements: [DebugUIElement]++ public init(elements: [DebugUIElement] = []) {+ self.elements = elements+ }++ public func validated(minConfidence: Double) -> DebugUIInspectionFrame {+ let threshold = min(max(minConfidence, 0), 1)+ return DebugUIInspectionFrame(+ elements: elements.filter { element in+ !element.id.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ && element.bbox.hasPositiveArea+ && element.confidence >= threshold+ }+ )+ }+}++public extension RemoteInferenceJSONValue {+ var stringValue: String? {+ guard case .string(let value) = self else { return nil }+ return value+ }++ var objectValue: RemoteInferenceJSONObject? {+ guard case .object(let value) = self else { return nil }+ return value+ }++ var arrayValue: [RemoteInferenceJSONValue]? {+ guard case .array(let value) = self else { return nil }+ return value+ }+}diff --git a/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swift b/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swiftindex 38af8f27..0e62a438 100644--- a/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swift@@ -71,6 +71,7 @@ public typealias RemoteInferenceJSONObject = [String: RemoteInferenceJSONValue]public enum RemoteInferenceComputerUseToolType: String, Codable, Equatable, Sendable {case geminiBrowserInteraction = "donkey_gemini_browser_interaction"case openAIMacDesktopInteraction = "donkey_openai_mac_desktop_interaction"+ case debugUIInspection = "donkey_debug_ui_inspection"}public struct RemoteInferenceComputerUseTool: Codable, Equatable, Sendable {diff --git a/apps/Donkey/Sources/DonkeyRuntime/DebugUIInspectionRuntime.swift b/apps/Donkey/Sources/DonkeyRuntime/DebugUIInspectionRuntime.swiftnew file mode 100644index 00000000..9d4da06a--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/DebugUIInspectionRuntime.swift@@ -0,0 +1,368 @@+@preconcurrency import AppKit+import CoreGraphics+import CryptoKit+import DonkeyContracts+import Foundation+import ImageIO+import UniformTypeIdentifiers++public struct DebugUIOverlayConfiguration: Equatable, Sendable {+ public var enabled: Bool+ public var provider: DebugUIInspectionProvider+ public var cadenceSeconds: TimeInterval+ public var screenScope: DebugUIInspectionScreenScope+ public var minConfidence: Double++ public init(+ enabled: Bool = false,+ provider: DebugUIInspectionProvider = .openai,+ cadenceSeconds: TimeInterval = 1.0,+ screenScope: DebugUIInspectionScreenScope = .main,+ minConfidence: Double = 0.25+ ) {+ self.enabled = enabled+ self.provider = provider+ self.cadenceSeconds = min(max(cadenceSeconds, 0.25), 10.0)+ self.screenScope = screenScope+ self.minConfidence = min(max(minConfidence, 0), 1)+ }++ public static let disabled = DebugUIOverlayConfiguration(enabled: false)++ public static func defaultConfigURL(fileManager: FileManager = .default) -> URL? {+ guard let applicationSupport = try? fileManager.url(+ for: .applicationSupportDirectory,+ in: .userDomainMask,+ appropriateFor: nil,+ create: false+ ) else {+ return nil+ }++ return applicationSupport+ .appendingPathComponent("Donkey", isDirectory: true)+ .appendingPathComponent("dev-overlay.json", isDirectory: false)+ }++ public static func load(+ fileURL: URL? = nil,+ fileManager: FileManager = .default+ ) -> DebugUIOverlayConfiguration {+ let urls: [URL]+ if let fileURL {+ urls = [fileURL]+ } else {+ urls = candidateConfigURLs(fileManager: fileManager)+ }++ guard let raw = urls.lazy.compactMap({ url -> RawDebugUIOverlayConfiguration? in+ guard fileManager.fileExists(atPath: url.path),+ let data = try? Data(contentsOf: url)+ else {+ return nil+ }+ return try? JSONDecoder().decode(RawDebugUIOverlayConfiguration.self, from: data)+ }).first else {+ return .disabled+ }++ return DebugUIOverlayConfiguration(+ enabled: raw.enabled ?? false,+ provider: raw.provider.flatMap(DebugUIInspectionProvider.init(rawValue:)) ?? .openai,+ cadenceSeconds: raw.cadenceSeconds ?? 1.0,+ screenScope: raw.screenScope.flatMap(DebugUIInspectionScreenScope.init(rawValue:)) ?? .main,+ minConfidence: raw.minConfidence ?? 0.25+ )+ }++ public static func candidateConfigURLs(+ fileManager: FileManager = .default,+ environment: [String: String] = ProcessInfo.processInfo.environment,+ bundle: Bundle = .main+ ) -> [URL] {+ var urls: [URL] = []+ if let defaultConfigURL = defaultConfigURL(fileManager: fileManager) {+ urls.append(defaultConfigURL)+ }++ #if DEBUG+ if let value = environment["DONKEY_DEV_OVERLAY_CONFIG"]?.trimmingCharacters(in: .whitespacesAndNewlines),+ !value.isEmpty {+ urls.append(URL(fileURLWithPath: value))+ }+ if let value = bundle.object(forInfoDictionaryKey: "DonkeyDevOverlayConfigPath") as? String,+ !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ urls.append(URL(fileURLWithPath: value))+ }+ urls.append(contentsOf: repoConfigCandidates(fileManager: fileManager))+ #endif++ var seen = Set<String>()+ return urls.filter { url in+ let path = url.standardizedFileURL.path+ guard !seen.contains(path) else { return false }+ seen.insert(path)+ return true+ }+ }++ #if DEBUG+ private static func repoConfigCandidates(fileManager: FileManager) -> [URL] {+ var candidates: [URL] = []+ var directory = URL(fileURLWithPath: fileManager.currentDirectoryPath, isDirectory: true)+ for _ in 0..<8 {+ candidates.append(directory.appendingPathComponent("dev-overlay.json", isDirectory: false))+ candidates.append(+ directory+ .appendingPathComponent("apps", isDirectory: true)+ .appendingPathComponent("Donkey", isDirectory: true)+ .appendingPathComponent("dev-overlay.json", isDirectory: false)+ )+ let parent = directory.deletingLastPathComponent()+ guard parent.path != directory.path else { break }+ directory = parent+ }+ return candidates+ }+ #endif+}++private struct RawDebugUIOverlayConfiguration: Codable {+ var enabled: Bool?+ var provider: String?+ var cadenceSeconds: TimeInterval?+ var screenScope: String?+ var minConfidence: Double?+}++public struct DebugUIElementTracker: Equatable, Sendable {+ private var previousElements: [DebugUIElement]++ public init(previousElements: [DebugUIElement] = []) {+ self.previousElements = previousElements+ }++ public mutating func update(with frame: DebugUIInspectionFrame) -> DebugUIInspectionFrame {+ var usedPreviousIDs = Set<String>()+ let tracked = frame.elements.map { incoming -> DebugUIElement in+ if previousElements.contains(where: { $0.id == incoming.id }) {+ usedPreviousIDs.insert(incoming.id)+ return incoming+ }++ guard let match = bestSemanticMatch(+ for: incoming,+ usedPreviousIDs: usedPreviousIDs+ ) else {+ return incoming+ }++ usedPreviousIDs.insert(match.id)+ return incoming.replacingID(match.id)+ }++ previousElements = tracked+ return DebugUIInspectionFrame(elements: tracked)+ }++ private func bestSemanticMatch(+ for incoming: DebugUIElement,+ usedPreviousIDs: Set<String>+ ) -> DebugUIElement? {+ previousElements+ .filter { previous in+ !usedPreviousIDs.contains(previous.id)+ && previous.type == incoming.type+ && normalized(previous.label) == normalized(incoming.label)+ }+ .max { left, right in+ matchScore(left.bbox, incoming.bbox) < matchScore(right.bbox, incoming.bbox)+ }+ .flatMap { candidate in+ matchScore(candidate.bbox, incoming.bbox) >= 0.25 ? candidate : nil+ }+ }++ private func matchScore(_ lhs: DebugUIBoundingBox, _ rhs: DebugUIBoundingBox) -> Double {+ let overlap = intersectionArea(lhs, rhs)+ let union = lhs.width * lhs.height + rhs.width * rhs.height - overlap+ let iou = union > 0 ? overlap / union : 0+ let centerDistance = hypot(+ (lhs.x + lhs.width / 2) - (rhs.x + rhs.width / 2),+ (lhs.y + lhs.height / 2) - (rhs.y + rhs.height / 2)+ )+ let distanceScore = max(0, 1 - centerDistance / 160)+ return max(iou, distanceScore * 0.5)+ }++ private 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 func normalized(_ value: String) -> String {+ value+ .lowercased()+ .split { !$0.isLetter && !$0.isNumber }+ .joined(separator: " ")+ }+}++public enum DebugUIOverlayGeometry {+ public static func appKitFrame(+ for bbox: DebugUIBoundingBox,+ screenshotPixelSize: HotLoopSize,+ screenFrame: HotLoopRect+ ) -> CGRect {+ guard screenshotPixelSize.width > 0,+ screenshotPixelSize.height > 0+ else {+ return .zero+ }++ let scaleX = screenFrame.size.width / screenshotPixelSize.width+ let scaleY = screenFrame.size.height / screenshotPixelSize.height+ return CGRect(+ x: screenFrame.origin.x + bbox.x * scaleX,+ y: screenFrame.origin.y + screenFrame.size.height - (bbox.y + bbox.height) * scaleY,+ width: bbox.width * scaleX,+ height: bbox.height * scaleY+ )+ }++ public static func localLayerFrame(+ for bbox: DebugUIBoundingBox,+ screenshotPixelSize: HotLoopSize,+ screenPointSize: HotLoopSize+ ) -> CGRect {+ guard screenshotPixelSize.width > 0,+ screenshotPixelSize.height > 0+ else {+ return .zero+ }++ let scaleX = screenPointSize.width / screenshotPixelSize.width+ let scaleY = screenPointSize.height / screenshotPixelSize.height+ return CGRect(+ x: bbox.x * scaleX,+ y: bbox.y * scaleY,+ width: bbox.width * scaleX,+ height: bbox.height * scaleY+ )+ }+}++public enum DebugUIScreenCaptureError: Error, Equatable, Sendable {+ case noScreenAvailable+ case missingDisplayIdentifier+ case captureFailed(displayID: UInt32)+ case pngEncodingFailed(displayID: UInt32)+}++public struct DebugUIScreenCaptureSnapshot: Equatable, Sendable {+ public var screenID: UInt32+ public var screenFrame: HotLoopRect+ public var pixelSize: HotLoopSize+ public var pngData: Data+ public var fingerprint: String++ public init(+ screenID: UInt32,+ screenFrame: HotLoopRect,+ pixelSize: HotLoopSize,+ pngData: Data,+ fingerprint: String+ ) {+ self.screenID = screenID+ self.screenFrame = screenFrame+ self.pixelSize = pixelSize+ self.pngData = pngData+ self.fingerprint = fingerprint+ }++ public var base64PNG: String {+ pngData.base64EncodedString()+ }+}++public struct DebugUIScreenCaptureService: Sendable {+ public init() {}++ public func captureScreens(+ scope: DebugUIInspectionScreenScope+ ) throws -> [DebugUIScreenCaptureSnapshot] {+ let screens: [NSScreen]+ switch scope {+ case .main:+ guard let screen = NSScreen.main ?? NSScreen.screens.first else {+ throw DebugUIScreenCaptureError.noScreenAvailable+ }+ screens = [screen]+ case .all:+ screens = NSScreen.screens+ }++ return try screens.map(capture)+ }++ private func capture(screen: NSScreen) throws -> DebugUIScreenCaptureSnapshot {+ let displayID = try Self.displayID(for: screen)+ guard let image = CGDisplayCreateImage(displayID) else {+ throw DebugUIScreenCaptureError.captureFailed(displayID: displayID)+ }+ guard let pngData = Self.pngData(from: image) else {+ throw DebugUIScreenCaptureError.pngEncodingFailed(displayID: displayID)+ }++ let frame = screen.frame+ return DebugUIScreenCaptureSnapshot(+ screenID: displayID,+ screenFrame: HotLoopRect(+ x: frame.origin.x,+ y: frame.origin.y,+ width: frame.size.width,+ height: frame.size.height,+ space: .screen+ ),+ pixelSize: HotLoopSize(+ width: Double(image.width),+ height: Double(image.height),+ space: .screen+ ),+ pngData: pngData,+ fingerprint: Self.fingerprint(for: pngData)+ )+ }++ 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 pngData(from image: CGImage) -> Data? {+ let data = NSMutableData()+ guard let destination = CGImageDestinationCreateWithData(+ data,+ UTType.png.identifier as CFString,+ 1,+ nil+ ) else {+ return nil+ }+ CGImageDestinationAddImage(destination, image, nil)+ guard CGImageDestinationFinalize(destination) else {+ return nil+ }+ return data as Data+ }++ private static func fingerprint(for data: Data) -> String {+ SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swiftnew file mode 100644index 00000000..d96c5b00--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift@@ -0,0 +1,171 @@+import DonkeyAI+import DonkeyContracts+import DonkeyRuntime+import CoreGraphics+import Foundation+import Testing++@Suite+struct DebugUIInspectionTests {+ @Test+ func missingConfigDisablesOverlay() throws {+ let url = temporaryDirectory()+ .appendingPathComponent("missing-dev-overlay.json", isDirectory: false)++ let config = DebugUIOverlayConfiguration.load(fileURL: url)++ #expect(config.enabled == false)+ #expect(config.provider == .openai)+ #expect(config.screenScope == .main)+ }++ @Test+ func invalidConfigDisablesOverlay() throws {+ let url = temporaryDirectory()+ .appendingPathComponent("invalid-dev-overlay.json", isDirectory: false)+ try Data("{".utf8).write(to: url, options: .atomic)+ defer { try? FileManager.default.removeItem(at: url) }++ let config = DebugUIOverlayConfiguration.load(fileURL: url)++ #expect(config.enabled == false)+ }++ @Test+ func enabledConfigUsesSafeDefaults() throws {+ let url = temporaryDirectory()+ .appendingPathComponent("enabled-dev-overlay.json", isDirectory: false)+ try Data(#"{"enabled":true}"#.utf8).write(to: url, options: .atomic)+ defer { try? FileManager.default.removeItem(at: url) }++ let config = DebugUIOverlayConfiguration.load(fileURL: url)++ #expect(config.enabled == true)+ #expect(config.provider == .openai)+ #expect(config.cadenceSeconds == 1.0)+ #expect(config.screenScope == .main)+ #expect(config.minConfidence == 0.25)+ }++ @Test+ func disabledRepoStyleConfigKeepsOverlayOff() throws {+ let url = temporaryDirectory()+ .appendingPathComponent("disabled-dev-overlay.json", isDirectory: false)+ try Data(+ """+ {+ "enabled": false,+ "provider": "gemini",+ "cadenceSeconds": 0.05,+ "screenScope": "all",+ "minConfidence": 2+ }+ """.utf8+ ).write(to: url, options: .atomic)+ defer { try? FileManager.default.removeItem(at: url) }++ let config = DebugUIOverlayConfiguration.load(fileURL: url)++ #expect(config.enabled == false)+ #expect(config.provider == .gemini)+ #expect(config.cadenceSeconds == 0.25)+ #expect(config.screenScope == .all)+ #expect(config.minConfidence == 1)+ }++ @Test+ func debugCandidateConfigURLsIncludeEnvironmentOverride() {+ let path = temporaryDirectory()+ .appendingPathComponent("custom-dev-overlay.json", isDirectory: false)+ .path++ let urls = DebugUIOverlayConfiguration.candidateConfigURLs(+ environment: ["DONKEY_DEV_OVERLAY_CONFIG": path]+ )++ #expect(urls.map(\.path).contains(path))+ }++ @Test+ func inspectionResponseDecodesAndFiltersElements() throws {+ let response = RemoteInferenceJSONValue.object([+ "output_text": .string(+ """+ {"elements":[+ {"id":"save","type":"button","label":"Save","description":"Saves","bbox":{"x":10,"y":20,"width":80,"height":30},"confidence":1.5,"visual_style":{"overlay_color":"#3B82F6","border_color":"#60A5FA","label_color":"#FFFFFF"}},+ {"id":"low","type":"link","label":"Low","description":"","bbox":{"x":0,"y":0,"width":10,"height":10},"confidence":0.1,"visual_style":{"overlay_color":"#06B6D4","border_color":"#67E8F9","label_color":"#FFFFFF"}}+ ]}+ """+ )+ ])++ let frame = try DebugUIInspectionResponseDecoder.decode(response, minConfidence: 0.25)++ #expect(frame.elements.map(\.id) == ["save"])+ #expect(frame.elements.first?.confidence == 1.0)+ #expect(frame.elements.first?.visualStyle == DebugUIOverlayStyle.style(for: .button))+ }++ @Test+ func inspectionResponseRejectsProviderActions() {+ let response = RemoteInferenceJSONValue.object([+ "output": .array([+ .object([+ "type": .string("function_call"),+ "name": .string("click_at")+ ])+ ])+ ])++ #expect(throws: DebugUIInspectionHostedAdapterError.providerReturnedAction) {+ _ = try DebugUIInspectionResponseDecoder.decode(response)+ }+ }++ @Test+ func trackerPreservesStableIDForMovedSemanticMatch() {+ var tracker = DebugUIElementTracker()+ _ = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "button-1", label: "Save", x: 10, y: 20)+ ]))++ let updated = tracker.update(with: DebugUIInspectionFrame(elements: [+ element(id: "provider-new-id", label: "Save", x: 36, y: 24)+ ]))++ #expect(updated.elements.first?.id == "button-1")+ }++ @Test+ func geometryConvertsScreenshotPixelsToAppKitPoints() {+ let frame = DebugUIOverlayGeometry.appKitFrame(+ for: DebugUIBoundingBox(x: 200, y: 100, width: 400, height: 200),+ screenshotPixelSize: HotLoopSize(width: 2000, height: 1000, space: .screen),+ screenFrame: HotLoopRect(x: 0, y: 0, width: 1000, height: 500, space: .screen)+ )++ #expect(frame == CGRect(x: 100, y: 350, width: 200, height: 100))+ }++ private func element(+ id: String,+ label: String,+ x: Double,+ y: Double+ ) -> DebugUIElement {+ DebugUIElement(+ id: id,+ type: .button,+ label: label,+ bbox: DebugUIBoundingBox(x: x, y: y, width: 80, height: 30),+ confidence: 0.9+ )+ }++ private func temporaryDirectory() -> URL {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("donkey-debug-ui-tests", isDirectory: true)+ try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+ return url+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swiftindex 474d4861..dc9e1ae6 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift@@ -64,6 +64,39 @@ struct DonkeyBackendInferenceClientTests {#expect(object["stream"] as? Bool == false)}+ @Test+ func createResponseSendsDebugUIInspectionToolWithoutProviderCredentials() async throws {+ let httpClient = FixtureHTTPClient(+ data: Data(#"{"output_text":"{\"elements\":[]}"}"#.utf8),+ statusCode: 200+ )+ let client = DonkeyBackendInferenceClient(+ configuration: configuration(),+ httpClient: httpClient+ )++ _ = try await client.createResponse(+ RemoteInferenceResponseCreateRequest(+ donkeyProvider: "openai",+ input: .string("inspect"),+ tools: [+ RemoteInferenceComputerUseTool(type: .debugUIInspection).jsonObject+ ],+ metadata: ["source": "debug-ui-inspection-overlay"]+ )+ )++ let request = try #require(httpClient.requests.first)+ #expect(request.value(forHTTPHeaderField: "Authorization") == nil)+ #expect(request.value(forHTTPHeaderField: "x-donkey-client-id") == "client-1")++ let object = try #require(request.httpBodyJSONObject)+ #expect(object["donkeyProvider"] as? String == "openai")+ #expect(object["store"] as? Bool == false)+ let tools = try #require(object["tools"] as? [[String: Any]])+ #expect(tools.first?["type"] as? String == "donkey_debug_ui_inspection")+ }+@Testfunc configurationUsesWebBaseEnvironmentURL() throws {let configuration = try DonkeyBackendInferenceConfiguration.fromEnvironment([diff --git a/apps/Donkey/dev-overlay.json b/apps/Donkey/dev-overlay.jsonnew file mode 100644index 00000000..95f5d92d--- /dev/null+++ b/apps/Donkey/dev-overlay.json@@ -0,0 +1,7 @@+{+ "enabled": false,+ "provider": "openai",+ "cadenceSeconds": 1.0,+ "screenScope": "main",+ "minConfidence": 0.25+}diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 0d0b87aa..7668df80 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -325,6 +325,15 @@ models may propose UI actions, but the Mac client still owns execution,confirmation gates, focus checks, permission policy, screenshots, andtool-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 overlay sends screenshots to the+hosted read-only inspection route only while a config explicitly enables it, and+accepts 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.+## State And ObservabilityTask-thread state and action-run state are related but distinct. A thread can bediff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.mdindex 8de65e40..fd97e9de 100644--- a/docs/guides/backend-apis.md+++ b/docs/guides/backend-apis.md@@ -55,7 +55,10 @@ provider names are configuration/data inside private adapters only.adapters. Browser interaction uses Gemini through`donkey_gemini_browser_interaction`; guarded macOS desktop interaction usesOpenAI through `donkey_openai_mac_desktop_interaction`, which the hosted- Responses adapter maps to OpenAI's `computer` tool.+ Responses adapter maps to OpenAI's `computer` tool. Developer-only read-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.- The Gemini adapter uses the official `@google/genai` Node/TypeScript SDK forgeneral non-streaming chat, structured Responses calls, and browsercomputer-use calls. It uses Vertex AI's global endpoint only when@@ -69,8 +72,9 @@ provider names are configuration/data inside private adapters only.`GOOGLE_APPLICATION_CREDENTIALS_JSON` as a hosted-deploy sensitive env varrather than storing Google provider credentials in the Mac app.- The OpenAI hosted Responses adapter uses `OPENAI_API_KEY` only for macOS- desktop computer-use. Keep that credential in the hosted deployment- environment; the Mac app must not carry OpenAI provider credentials.+ desktop computer-use and developer UI inspection. Keep that credential in the+ hosted deployment environment; the Mac app must not carry OpenAI provider+ credentials.## Hosted Model Creditsdiff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.mdindex 93a465d4..394a7510 100644--- a/docs/guides/pointer-prompt-overlay.md+++ b/docs/guides/pointer-prompt-overlay.md@@ -27,6 +27,24 @@ 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+ 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, it captures screenshots, asks the+ hosted read-only inspection route for strict JSON element metadata, and draws+ click-through boxes beneath Donkey's own prompt/status/spawn UI.++```json+{+ "enabled": true,+ "provider": "openai",+ "cadenceSeconds": 1.0,+ "screenScope": "main",+ "minConfidence": 0.25+}+```## Technical Guidelines@@ -48,6 +66,12 @@ quick local-app actions:- Local item prewarming must run off the main actor and must not eagerly scan protected user folders. Agent memory is stored in SQLite under Application Support and uses FTS5 plus deterministic local embeddings for retrieval; JSONL is only an explicit export/debug format. Cached local-item hits must still point to an existing path or bundle before they are used as an execution target. Runtime task definitions are loaded from agent memory; Weather, Music, and Preview definitions are benchmark fixtures unless a generated/user-reviewed definition for them is present in memory.- For scriptable apps, prefer app-native AppleScript task commands before falling back to Accessibility or keyboard input. Submit steps with an explicit structured `controlID` may execute as an Accessibility `AXPress` against button-like controls, with the control bounds carried into action traces. Bounded screenshots may supplement observation/verification according to task metadata, but screenshots remain context evidence and do not directly drive input.- Agent visualization overlays are non-interactive, non-activating panels. They may point, explain, and replay what the agent is doing or would do, but they do not synthesize mouse movement. Live keyboard or Accessibility actions remain separate guarded runtime actions. When a local-app action plan is based on an observation, preserve target-window geometry and control bounds on the evidence-backed steps so cursor replay can use pixel-grounded element positions instead of invented coordinates.+- The developer UI inspection overlay is separate from agent visualization. It+ is a transparent, non-activating, click-through, keyboard-pass-through AppKit+ panel at a lower window level than Donkey's interactive UI. It renders+ CALayer rectangles and labels from model-returned JSON only; provider action+ calls such as click, type, scroll, drag, navigation, `computer_call`, or+ `function_call` are rejected instead of executed.- Task actions in the notch, including follow-up submission and pause/resume, must cross the model/controller command boundary with the selected task ID.- Pointer prompt command handling should emit actionable `com.donkey.app` route/result logs for submitted commands, routing decisions, intent resolution, local action traces, unsupported requests, unavailable apps, and final task status. Action trace logs should state the backend, input mode, whether an element click happened, the control or bounds target, and that the overlay pointer is visual-only.@@ -67,6 +91,11 @@ Manually verify:- Normal local-app tasks can produce final visualization steps for observed, navigated, acted, and verified runtime work. Planning stays in the background. Cursor playback should target observed control centers from Accessibility, screenshot understanding, or action traces when those bounds exist, omit ungrounded steps, and must not claim completion unless the runtime verification state supports it.- The prompt supports wrapping, Shift-Return newline insertion, Return submission, Escape dismissal, outside-click dismissal, and dragging from non-input areas.- File drops on the notch attach to the active or most recent task.+- With `dev-overlay.json` enabled, interact with underlying applications while+ the debug boxes are visible; clicks, typing, scrolling, dragging, and Donkey+ prompt activation should continue to target the underlying app or Donkey UI.+ Removing the config file or setting `"enabled": false` should hide the debug+ overlay without relaunching.## Source Entry Pointsdiff --git a/scripts/package-donkey-app.sh b/scripts/package-donkey-app.shindex afa8d92a..a8aff1a8 100755--- a/scripts/package-donkey-app.sh+++ b/scripts/package-donkey-app.sh@@ -195,6 +195,7 @@ if [ -n "$RESOURCE_BUNDLE" ]; thenelif [ -d "$BUILD_DIR/.build/release/Donkey_Donkey.resources" ]; thencp -R "$BUILD_DIR/.build/release/Donkey_Donkey.resources/." "$RESOURCES_DIR/"fi+find "$APP_DIR" -name dev-overlay.json -type f -deleteprepare_app_iconSPARKLE_FRAMEWORK="$(find "$BUILD_DIR/.build" -path "*/release/Sparkle.framework" -type d | head -n 1 || true)"diff --git a/scripts/run-donkey-dev.sh b/scripts/run-donkey-dev.shindex 5ac45470..26bd4795 100755--- a/scripts/run-donkey-dev.sh+++ b/scripts/run-donkey-dev.sh@@ -216,6 +216,8 @@ write_info_plist() {<string>$escaped_web_base_url</string><key>DonkeyAuthCallbackScheme</key><string>$escaped_callback_scheme</string>+ <key>DonkeyDevOverlayConfigPath</key>+ <string>$APP_DIR/dev-overlay.json</string><key>CFBundleURLTypes</key><array><dict>diff --git a/site/src/lib/inference/adapters/gemini-computer-use.ts b/site/src/lib/inference/adapters/gemini-computer-use.tsindex a6abb607..d17da7e9 100644--- a/site/src/lib/inference/adapters/gemini-computer-use.ts+++ b/site/src/lib/inference/adapters/gemini-computer-use.ts@@ -44,6 +44,7 @@ const vertexLocation = "global";const vertexAIScope = "https://www.googleapis.com/auth/cloud-platform";export const geminiBrowserInteractionToolType = "donkey_gemini_browser_interaction";+export const debugUIInspectionToolType = "donkey_debug_ui_inspection";const fastDecisionSchemaNames = new Set(["task_intent_v1",@@ -59,6 +60,27 @@ const browserOnlyFunctionExclusions = ["drag_and_drop",];+const debugUIInspectionFunctionExclusions = [+ "click",+ "click_at",+ "double_click",+ "drag",+ "drag_and_drop",+ "go_back",+ "go_forward",+ "hover",+ "hover_at",+ "key_combination",+ "navigate",+ "open_web_browser",+ "scroll",+ "scroll_document",+ "search",+ "type",+ "type_text",+ "type_text_at",+];+export function createGeminiComputerUseProvider(environment: AdapterEnvironment = process.env,clientFactory: GeminiClientFactory = (options) => new GoogleGenAI(options),@@ -92,6 +114,7 @@ export function createGeminiComputerUseProvider(details: {supportedTools: [geminiBrowserInteractionToolType,+ debugUIInspectionToolType,],},});@@ -213,14 +236,17 @@ function geminiGenerateContentParameters(function geminiTools(registeredTools: string[], rawTools: JsonValue | undefined): Tool[] {const tools: Tool[] = [];const hasBrowser = registeredTools.includes(geminiBrowserInteractionToolType);+ const hasDebugInspection = registeredTools.includes(debugUIInspectionToolType);- if (hasBrowser) {+ if (hasBrowser || hasDebugInspection) {tools.push({computerUse: {environment: Environment.ENVIRONMENT_BROWSER,excludedPredefinedFunctions: excludedPredefinedFunctions(rawTools,- browserOnlyFunctionExclusions,+ hasDebugInspection+ ? debugUIInspectionFunctionExclusions+ : browserOnlyFunctionExclusions,),},});@@ -557,6 +583,8 @@ function registeredToolTypes(tools: JsonValue | undefined): string[] {}if (tool.type === geminiBrowserInteractionToolType) {registered.add(geminiBrowserInteractionToolType);+ } else if (tool.type === debugUIInspectionToolType) {+ registered.add(debugUIInspectionToolType);}}return [...registered];@@ -751,7 +779,8 @@ function hasExplicitUnsupportedTools(if (!isJsonObject(tool)) {return true;}- return tool.type !== geminiBrowserInteractionToolType;+ return tool.type !== geminiBrowserInteractionToolType &&+ tool.type !== debugUIInspectionToolType;});}@@ -772,6 +801,7 @@ function staticModel(model: string, computerUse: boolean): InferenceModel {computerUse,registeredTools: [geminiBrowserInteractionToolType,+ debugUIInspectionToolType,],}: { structuredOutputs: true }),diff --git a/site/src/lib/inference/adapters/hosted-responses.ts b/site/src/lib/inference/adapters/hosted-responses.tsindex d68689dd..63c7eb98 100644--- a/site/src/lib/inference/adapters/hosted-responses.ts+++ b/site/src/lib/inference/adapters/hosted-responses.ts@@ -23,6 +23,7 @@ const providerID = "hosted-responses";const openAIProviderID = "openai";const openAIBaseURL = "https://api.openai.com/v1";const openAIMacDesktopInteractionToolType = "donkey_openai_mac_desktop_interaction";+const debugUIInspectionToolType = "donkey_debug_ui_inspection";const defaultOpenAIComputerUseModel = "gpt-5.5";export function createHostedResponsesProvider(@@ -49,9 +50,9 @@ export function createHostedResponsesProvider(request: ResponseCreateRequest,): Promise<ResponseCreateResult> {ensureConfigured(configured);- if (!isOpenAIComputerToolRequest(request.body)) {+ if (!isOpenAIResponsesToolRequest(request.body)) {throw new InferenceProviderError(- "OpenAI Responses is only configured for Mac desktop computer use.",+ "OpenAI Responses is only configured for Mac desktop computer use and read-only debug UI inspection.",{statusCode: 400,code: "openai_computer_tool_required",@@ -60,6 +61,7 @@ export function createHostedResponsesProvider("computer","computer_use_preview",openAIMacDesktopInteractionToolType,+ debugUIInspectionToolType,],},},@@ -99,7 +101,7 @@ export function createHostedResponsesProvider(configured,capabilities: ["text", "image"],responseProviderIDs: [openAIProviderID],- canCreateResponse: (request) => isOpenAIComputerToolRequest(request.body),+ canCreateResponse: (request) => isOpenAIResponsesToolRequest(request.body),listModels,createResponse,};@@ -116,22 +118,34 @@ function requestBody(body: JsonObject, model: string): JsonObject {}function normalizeOpenAIComputerUseBody(body: JsonObject): JsonObject {- if (!hasOpenAIMacDesktopTool(body)) {+ const hasMacDesktopTool = hasOpenAIMacDesktopTool(body);+ const hasDebugInspectionTool = hasDebugUIInspectionTool(body);+ if (!hasMacDesktopTool && !hasDebugInspectionTool) {return body;}const tools = body.tools;const toolChoice = openAIComputerToolChoice(body.tool_choice);- return {+ const normalized: JsonObject = {...body,- instructions: openAIMacDesktopInstructions(body.instructions),+ instructions: openAIInstructions(+ body.instructions,+ hasMacDesktopTool,+ hasDebugInspectionTool,+ ),...(toolChoice === undefined ? {} : { tool_choice: toolChoice }),- ...(Array.isArray(tools)- ? {- tools: tools.map(openAIComputerToolReference),- }- : {}),};+ if (Array.isArray(tools)) {+ const normalizedTools = tools+ .map(openAIComputerToolReference)+ .filter((tool): tool is JsonObject => isJsonObject(tool));+ if (normalizedTools.length > 0) {+ normalized.tools = normalizedTools;+ } else {+ delete normalized.tools;+ }+ }+ return normalized;}function openAIComputerToolChoice(value: JsonValue | undefined): JsonValue | undefined {@@ -154,11 +168,15 @@ function openAIComputerToolChoice(value: JsonValue | undefined): JsonValue | und};}-function openAIComputerToolReference(value: JsonValue): JsonValue {+function openAIComputerToolReference(value: JsonValue): JsonValue | null {if (!isJsonObject(value)) {return value;}+ if (value.type === debugUIInspectionToolType) {+ return null;+ }+if (value.type === openAIMacDesktopInteractionToolType) {return { type: "computer" };}@@ -173,13 +191,32 @@ function openAIComputerToolReference(value: JsonValue): JsonValue {return value;}-function openAIMacDesktopInstructions(value: JsonValue | undefined) {+function openAIInstructions(+ value: JsonValue | undefined,+ hasMacDesktopTool: boolean,+ hasDebugInspectionTool: boolean,+) {+ const instructions: string[] = [];+ if (hasMacDesktopTool) {+ instructions.push(+ [+ "Use the OpenAI computer tool for non-browser Mac desktop UI work.",+ "The Mac client executes returned computer_call actions with focus, safety, permission, and screenshot feedback.",+ ].join(" "),+ );+ }+ if (hasDebugInspectionTool) {+ instructions.push(+ [+ "Perform read-only macOS UI inspection from the provided screenshot.",+ "Return strict JSON only and do not return computer_call, function_call, click, type, scroll, drag, or navigation actions.",+ ].join(" "),+ );+ }+return [stringValue(value),- [- "Use the OpenAI computer tool for non-browser Mac desktop UI work.",- "The Mac client executes returned computer_call actions with focus, safety, permission, and screenshot feedback.",- ].join(" "),+ ...instructions,].filter(Boolean).join("\n\n");}@@ -197,12 +234,15 @@ function staticModel(model: string): InferenceModel {baseURL: openAIBaseURL,api: "responses",computerUse: true,- registeredTools: [openAIMacDesktopInteractionToolType],+ registeredTools: [+ openAIMacDesktopInteractionToolType,+ debugUIInspectionToolType,+ ],},};}-function isOpenAIComputerToolRequest(body: JsonObject) {+function isOpenAIResponsesToolRequest(body: JsonObject) {const tools = body.tools;if (!Array.isArray(tools)) {return false;@@ -213,7 +253,8 @@ function isOpenAIComputerToolRequest(body: JsonObject) {isJsonObject(tool) &&(tool.type === "computer" ||tool.type === "computer_use_preview" ||- tool.type === openAIMacDesktopInteractionToolType)+ tool.type === openAIMacDesktopInteractionToolType ||+ tool.type === debugUIInspectionToolType));});}@@ -229,6 +270,17 @@ function hasOpenAIMacDesktopTool(body: JsonObject) {});}+function hasDebugUIInspectionTool(body: JsonObject) {+ const tools = body.tools;+ if (!Array.isArray(tools)) {+ return false;+ }++ return tools.some((tool) => {+ return isJsonObject(tool) && tool.type === debugUIInspectionToolType;+ });+}+function usageFromResponse(value: JsonValue): JsonValue | undefined {if (!isJsonObject(value)) {return undefined;