Open source CapCut alternative.
TypeScript
Stream debug UI evidence
David Le305f77130654
diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swiftindex beed0841..3dcf63c7 100644--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift@@ -33,6 +33,7 @@ final class DebugUIInspectionCoordinator {private var movementEventMonitors: [Any] = []private var currentConfig: DebugUIOverlayConfiguration = .disabledprivate var isAnalyzing = false+ private var isRefreshingActiveAccessibility = falseinit(configURL: URL? = nil) {self.configURL = configURL@@ -68,6 +69,7 @@ final class DebugUIInspectionCoordinator {lastRenderedFrames.removeAll()lastSnapshots.removeAll()isAnalyzing = false+ isRefreshingActiveAccessibility = falsecurrentConfig = .disabled}@@ -266,14 +268,58 @@ final class DebugUIInspectionCoordinator {private func refreshActiveAccessibilityFrame() {guard currentConfig.enabled,- !isAnalyzing,+ !isRefreshingActiveAccessibility,let screens = try? screenSurfaces(scope: currentConfig.screenScope)else {return}- let frames = activeAccessibilityFrames()- guard !frames.isEmpty else { return }+ isRefreshingActiveAccessibility = true+ defer { isRefreshingActiveAccessibility = false }++ do {+ let results = try accessibilityInspectionService.inspectProgressively(+ scope: currentConfig.screenScope,+ minConfidence: currentConfig.minConfidence,+ frontmostOnly: true,+ focusedOnly: true,+ targetBundleIdentifiers: currentConfig.targetBundleIdentifiers,+ targetAppNames: currentConfig.targetAppNames+ ) { [weak self] partialResults in+ self?.renderActiveAccessibilityResults(+ partialResults,+ screens: screens,+ stage: "active-accessibility-progress"+ )+ }+ renderActiveAccessibilityResults(+ results,+ screens: screens,+ stage: "active-accessibility"+ )+ } catch {+ DebugUIInspectionLog.overlay.debug(+ "debug inspection skipped active accessibility refresh error=\(String(describing: error), privacy: .public)"+ )+ }+ }++ private func renderActiveAccessibilityResults(+ _ results: [DebugUIAccessibilityInspectionResult],+ screens: [DebugUIScreenSurface],+ stage: String+ ) {+ let frames = Dictionary(+ uniqueKeysWithValues: results.map { result in+ (+ result.snapshot.screenID,+ Self.frameInScreenPointSpace(+ result.frame,+ snapshot: result.snapshot+ )+ )+ }+ )for screen in screens {guard let accessibilityFrame = frames[screen.screenID],@@ -283,11 +329,30 @@ final class DebugUIInspectionCoordinator {}let existing = lastRenderedFrames[screen.screenID] ?? DebugUIInspectionFrame()+ let progressiveAccessibilityFrame: DebugUIInspectionFrame+ if stage.contains("progress") {+ let incomingIDs = Set(accessibilityFrame.elements.map(\.id))+ let incomingWindowIDs = Set(accessibilityFrame.elements.compactMap(Self.windowID(for:)))+ let carriedAccessibilityElements = existing.elements.filter { element in+ guard Self.isAccessibilityEvidence(element),+ !incomingIDs.contains(element.id),+ let windowID = Self.windowID(for: element)+ else {+ return false+ }+ return incomingWindowIDs.contains(windowID)+ }+ progressiveAccessibilityFrame = DebugUIInspectionFrame(+ elements: carriedAccessibilityElements + accessibilityFrame.elements+ )+ } else {+ progressiveAccessibilityFrame = accessibilityFrame+ }let nonAccessibilityFrame = DebugUIInspectionFrame(elements: existing.elements.filter { !Self.isAccessibilityEvidence($0) })let fusedFrame = DebugUIInspectionFrameFusion.fused(- accessibilityFrame: accessibilityFrame,+ accessibilityFrame: progressiveAccessibilityFrame,geminiFrame: nonAccessibilityFrame)guard !fusedFrame.elements.isEmpty,@@ -296,14 +361,21 @@ final class DebugUIInspectionCoordinator {continue}+ var tracker = trackers[screen.screenID] ?? DebugUIElementTracker()+ let trackedFrame = tracker.update(+ with: fusedFrame,+ renderNewElementsImmediately: true+ )+ trackers[screen.screenID] = tracker+let snapshot = Self.screenPointSnapshot(screen: screen,- fingerprint: "active-accessibility-\(Self.frameSignature(fusedFrame))"+ fingerprint: "\(stage)-\(Self.frameSignature(trackedFrame))")- lastRenderedFrames[screen.screenID] = fusedFrame+ lastRenderedFrames[screen.screenID] = trackedFramelastSnapshots[screen.screenID] = snapshot- logLayoutDiagnostics(stage: "active-accessibility", screen: screen, frame: fusedFrame, captures: [])- overlayController.render(frame: fusedFrame, snapshot: snapshot)+ logLayoutDiagnostics(stage: stage, screen: screen, frame: trackedFrame, captures: [])+ overlayController.render(frame: trackedFrame, snapshot: snapshot)}}@@ -454,11 +526,54 @@ final class DebugUIInspectionCoordinator {)continue}- lastFingerprints[screen.screenID] = fingerprintlet localEvidenceFrame = accessibilityFrame- var elements: [DebugUIElement] = []+ let currentWindowIDs = Set(screenCaptures.map(\.target.windowID))+ var elements = (lastRenderedFrames[screen.screenID]?.elements ?? [])+ .filter { element in+ guard !Self.isAccessibilityEvidence(element) else { return false }+ guard let windowID = Self.windowID(for: element) else { return true }+ return currentWindowIDs.contains(windowID)+ }++ func renderGeminiFrame(stage: String, updatesFingerprint: Bool) {+ var tracker = trackers[screen.screenID] ?? DebugUIElementTracker()+ let geminiFrame = DebugUIInspectionFrame(elements: elements)+ let fusedFrame = DebugUIInspectionFrameFusion.fused(+ accessibilityFrame: localEvidenceFrame,+ geminiFrame: geminiFrame+ )+ let trackedFrame = tracker.update(+ with: fusedFrame,+ renderNewElementsImmediately: true+ )+ trackers[screen.screenID] = tracker+ if !force,+ let previousFrame = lastRenderedFrames[screen.screenID],+ trackedFrame.isOverlayRenderEquivalent(to: previousFrame) {+ DebugUIInspectionLog.overlay.debug(+ "debug inspection skipped stable \(stage, privacy: .public) render screenID=\(screen.screenID, privacy: .public)"+ )+ return+ }++ let snapshot = Self.screenPointSnapshot(+ screen: screen,+ fingerprint: updatesFingerprint ? fingerprint : "\(fingerprint)-\(stage)-\(Self.frameSignature(trackedFrame))"+ )+ DebugUIInspectionLog.overlay.info(+ "debug inspection rendering source=\(stage, privacy: .public) 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)"+ )+ logLayoutDiagnostics(stage: stage, screen: screen, frame: trackedFrame, captures: screenCaptures)+ if updatesFingerprint {+ lastFingerprints[screen.screenID] = fingerprint+ }+ lastRenderedFrames[screen.screenID] = trackedFrame+ lastSnapshots[screen.screenID] = snapshot+ overlayController.render(frame: trackedFrame, snapshot: snapshot)+ }+for capture in screenCaptures {let capturePixelSize = HotLoopSize(width: capture.parsePixelSize.width,@@ -501,18 +616,32 @@ final class DebugUIInspectionCoordinator {])do {- let result = try await client.parseScreenshot(+ let result = try await client.parseScreenshotStream(request,imageData: capture.parseImageData,contentType: capture.parseContentType- )- elements += ScreenshotParseDebugUIOverlayMapper.frame(+ ) { partialResult in+ let parsedElements = ScreenshotParseDebugUIOverlayMapper.frame(+ from: partialResult,+ target: capture.target,+ capturePixelSize: capturePixelSize,+ screenFrame: screenBounds,+ minConfidence: self.currentConfig.minConfidence+ ).elements+ elements.removeAll { Self.windowID(for: $0) == capture.target.windowID }+ elements += parsedElements+ renderGeminiFrame(stage: "gemini-progress", updatesFingerprint: false)+ }+ let parsedElements = ScreenshotParseDebugUIOverlayMapper.frame(from: result,target: capture.target,capturePixelSize: capturePixelSize,screenFrame: screenBounds,minConfidence: currentConfig.minConfidence).elements+ elements.removeAll { Self.windowID(for: $0) == capture.target.windowID }+ elements += parsedElements+ renderGeminiFrame(stage: "gemini-progress", updatesFingerprint: false)} catch {DebugUIInspectionLog.overlay.error("debug inspection gemini parse failed windowID=\(capture.target.windowID, privacy: .public) error=\(String(describing: error), privacy: .public)"@@ -520,34 +649,7 @@ final class DebugUIInspectionCoordinator {}}- var tracker = trackers[screen.screenID] ?? DebugUIElementTracker()- let geminiFrame = DebugUIInspectionFrame(elements: elements)- let fusedFrame = DebugUIInspectionFrameFusion.fused(- accessibilityFrame: localEvidenceFrame,- geminiFrame: geminiFrame- )- let trackedFrame = tracker.update(- with: fusedFrame,- renderNewElementsImmediately: true- )- trackers[screen.screenID] = tracker- if !force,- let previousFrame = lastRenderedFrames[screen.screenID],- trackedFrame.isOverlayRenderEquivalent(to: previousFrame) {- DebugUIInspectionLog.overlay.debug(- "debug inspection skipped stable gemini render screenID=\(screen.screenID, privacy: .public)"- )- continue- }-- let snapshot = Self.screenPointSnapshot(screen: screen, fingerprint: fingerprint)- 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)"- )- logLayoutDiagnostics(stage: "gemini-fused", screen: screen, frame: trackedFrame, captures: screenCaptures)- lastRenderedFrames[screen.screenID] = trackedFrame- lastSnapshots[screen.screenID] = snapshot- overlayController.render(frame: trackedFrame, snapshot: snapshot)+ renderGeminiFrame(stage: "gemini-fused", updatesFingerprint: true)}}@@ -807,37 +909,10 @@ final class DebugUIInspectionCoordinator {frame: DebugUIInspectionFrame,captures: [DebugUIWindowCapture]) {- let screenPointSize = HotLoopSize(- 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- )- 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: screenshotPixelSize,- screenPointSize: screenPointSize- )- DebugUIInspectionLog.overlay.info(- "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)"- )- }+ _ = stage+ _ = screen+ _ = frame+ _ = captures}private func sourceCounts(_ elements: [DebugUIElement]) -> (ax: Int, ai: Int, cv: Int, other: Int) {diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swiftindex 924d6c38..f3d0ae93 100644--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift@@ -183,7 +183,11 @@ private final class DebugUIInspectionSurface {let path = CGPath(rect: CGRect(origin: .zero, size: boxFrame.size), transform: nil)layers.box.frame = boxFramelayers.box.path = path- layers.box.fillColor = fillColor(for: element)+ layers.box.fillColor = fillColor(+ for: element,+ boxFrame: boxFrame,+ containerSize: rootView.bounds.size+ )layers.box.strokeColor = strokeColor(for: element)layers.box.lineDashPattern = lineDashPattern(for: element)layers.box.lineWidth = lineWidth(for: element)@@ -211,17 +215,15 @@ private final class DebugUIInspectionSurface {return base}- private func fillColor(for element: DebugUIElement) -> CGColor {- if element.id.hasPrefix("window-") {- return NSColor.clear.cgColor- }- if sourceKind(for: element) == .ai {- return nsColor(hex: "#FF2D55", alpha: 0.16).cgColor- }- if sourceKind(for: element) == .nativeVisual {- return nsColor(hex: "#00C7BE", alpha: 0.13).cgColor- }- return nsColor(hex: element.visualStyle.overlayColor, alpha: 0.14).cgColor+ private func fillColor(+ for element: DebugUIElement,+ boxFrame: CGRect? = nil,+ containerSize: CGSize? = nil+ ) -> CGColor {+ _ = element+ _ = boxFrame+ _ = containerSize+ return NSColor.clear.cgColor}private func strokeColor(for element: DebugUIElement) -> CGColor {@@ -231,7 +233,12 @@ private final class DebugUIInspectionSurface {case .nativeVisual:return nsColor(hex: "#00C7BE", alpha: 0.95).cgColorcase .accessibility:- return nsColor(hex: "#34D399", alpha: 0.95).cgColor+ return accessibilityColor(+ for: element,+ saturation: 0.68,+ brightness: 1.0,+ alpha: 0.95+ )case .other:return nsColor(hex: element.visualStyle.borderColor, alpha: 0.95).cgColor}@@ -244,7 +251,12 @@ private final class DebugUIInspectionSurface {case .nativeVisual:return nsColor(hex: "#00C7BE", alpha: 0.92).cgColorcase .accessibility:- return nsColor(hex: "#34D399", alpha: 0.92).cgColor+ return accessibilityColor(+ for: element,+ saturation: 0.72,+ brightness: 0.82,+ alpha: 0.92+ )case .other:return nsColor(hex: element.visualStyle.overlayColor, alpha: 0.92).cgColor}@@ -286,6 +298,41 @@ private final class DebugUIInspectionSurface {return .other}+ private func accessibilityRole(for element: DebugUIElement) -> String {+ if let role = element.metadata["accessibility.role"], !role.isEmpty {+ return role+ }+ if let role = element.metadata.first(where: { key, _ in key.hasSuffix(".accessibility.role") })?.value,+ !role.isEmpty {+ return role+ }+ return ""+ }++ private func accessibilityColor(+ for element: DebugUIElement,+ saturation: CGFloat,+ brightness: CGFloat,+ alpha: CGFloat+ ) -> CGColor {+ let key = accessibilityRole(for: element).isEmpty+ ? element.type.rawValue+ : accessibilityRole(for: element)+ let hue = CGFloat(Self.stableHash(key) % 360) / 360+ return NSColor(+ calibratedHue: hue,+ saturation: saturation,+ brightness: brightness,+ alpha: alpha+ ).cgColor+ }++ private static func stableHash(_ value: String) -> UInt32 {+ value.utf8.reduce(UInt32(2_166_136_261)) { hash, byte in+ (hash ^ UInt32(byte)) &* 16_777_619+ }+ }+private func fadeIn(_ layers: DebugUIInspectionElementLayers) {let animation = CABasicAnimation(keyPath: "opacity")animation.fromValue = 0diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swiftindex 5a622abf..3f97990b 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift@@ -133,34 +133,106 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {imageData: Data? = nil,contentType: String = "image/png") async throws -> LocalUIUnderstandingResult {- guard let imageData = try imageData ?? understandingRequest.imageFileURL.map({ try Data(contentsOf: $0) }) else {- throw DonkeyBackendInferenceClientError.missingDownloadPayload("screenshot")- }-- var request = makeRequest(path: "/api/inference/screenshots/parse/")- request.httpMethod = "POST"- var metadata = understandingRequest.metadata- metadata["screenshot.scope"] = metadata["screenshot.scope"] ?? "targetWindow"- metadata["screenshot.desktopCaptureAllowed"] = "false"- request.httpBody = try JSONEncoder().encode(- RemoteScreenshotParseRequest(- imageBase64: imageData.base64EncodedString(),- contentType: contentType,- pixelSize: understandingRequest.pixelSize ?? HotLoopSize(- width: 1,- height: 1,- space: .window- ),- traceID: understandingRequest.traceID,- targetID: understandingRequest.targetID,- cropBounds: understandingRequest.cropBounds,- metadata: metadata- )+ let request = try makeScreenshotParseRequest(+ understandingRequest,+ imageData: imageData,+ contentType: contentType,+ stream: false)let data = try await send(request)return try JSONDecoder().decode(LocalUIUnderstandingResult.self, from: data)}+ public func parseScreenshotStream(+ _ understandingRequest: LocalUIUnderstandingRequest,+ imageData: Data? = nil,+ contentType: String = "image/png",+ onPartialResult: @escaping @MainActor @Sendable (LocalUIUnderstandingResult) -> Void+ ) async throws -> LocalUIUnderstandingResult {+ var request = try makeScreenshotParseRequest(+ understandingRequest,+ imageData: imageData,+ contentType: contentType,+ stream: true+ )+ request.setValue("text/event-stream", forHTTPHeaderField: "Accept")++ let (lines, response) = try await httpClient.streamLines(request)+ var responseBodyLines: [String] = []+ guard (200..<300).contains(response.statusCode) else {+ for try await line in lines {+ responseBodyLines.append(line)+ }+ throw DonkeyBackendInferenceClientError.httpStatus(+ response.statusCode,+ responseBodyLines.joined(separator: "\n")+ )+ }++ let decoder = JSONDecoder()+ var finalResult: LocalUIUnderstandingResult?+ var eventName: String?+ var eventID: String?+ var dataLines: [String] = []++ func flushEvent() async throws {+ guard !dataLines.isEmpty else {+ eventName = nil+ eventID = nil+ return+ }++ let event = RemoteInferenceServerSentEvent(+ event: eventName,+ data: dataLines.joined(separator: "\n"),+ id: eventID+ )+ eventName = nil+ eventID = nil+ dataLines.removeAll()++ switch event.event {+ case "partial":+ let result = try decoder.decode(+ LocalUIUnderstandingResult.self,+ from: Data(event.data.utf8)+ )+ await onPartialResult(result)+ case "final":+ finalResult = try decoder.decode(+ LocalUIUnderstandingResult.self,+ from: Data(event.data.utf8)+ )+ case "error":+ let error = (try? decoder.decode(RemoteScreenshotParseStreamError.self, from: Data(event.data.utf8)))+ throw DonkeyBackendInferenceClientError.httpStatus(+ response.statusCode,+ error?.message ?? event.data+ )+ default:+ break+ }+ }++ for try await line in lines {+ if line.isEmpty {+ try await flushEvent()+ } else if line.hasPrefix("event:") {+ eventName = String(line.dropFirst("event:".count)).trimmingCharacters(in: .whitespaces)+ } else if line.hasPrefix("id:") {+ eventID = String(line.dropFirst("id:".count)).trimmingCharacters(in: .whitespaces)+ } else if line.hasPrefix("data:") {+ dataLines.append(String(line.dropFirst("data:".count)).trimmingCharacters(in: .whitespaces))+ }+ }+ try await flushEvent()++ guard let finalResult else {+ throw DonkeyBackendInferenceClientError.invalidResponse+ }+ return finalResult+ }+public func makeStreamingChatRequest(_ completionRequest: RemoteInferenceChatCompletionRequest) throws -> URLRequest {@@ -263,6 +335,41 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {return request}+ private func makeScreenshotParseRequest(+ _ understandingRequest: LocalUIUnderstandingRequest,+ imageData: Data?,+ contentType: String,+ stream: Bool+ ) throws -> URLRequest {+ guard let imageData = try imageData ?? understandingRequest.imageFileURL.map({ try Data(contentsOf: $0) }) else {+ throw DonkeyBackendInferenceClientError.missingDownloadPayload("screenshot")+ }++ var request = makeRequest(path: "/api/inference/screenshots/parse/")+ request.httpMethod = "POST"+ var metadata = understandingRequest.metadata+ metadata["screenshot.scope"] = metadata["screenshot.scope"] ?? "targetWindow"+ metadata["screenshot.desktopCaptureAllowed"] = "false"+ request.httpBody = try JSONEncoder().encode(+ RemoteScreenshotParseRequest(+ imageBase64: imageData.base64EncodedString(),+ contentType: contentType,+ pixelSize: understandingRequest.pixelSize ?? HotLoopSize(+ width: 1,+ height: 1,+ space: .window+ ),+ traceID: understandingRequest.traceID,+ targetID: understandingRequest.targetID,+ cropBounds: understandingRequest.cropBounds,+ metadata: metadata,+ stream: stream+ )+ )+ return request+ }++private func send(_ request: URLRequest) async throws -> Data {let (data, response) = try await httpClient.send(request)guard (200..<300).contains(response.statusCode) else {@@ -409,4 +516,11 @@ private struct RemoteScreenshotParseRequest: Encodable {var targetID: Stringvar cropBounds: HotLoopRect?var metadata: [String: String]+ var stream: Bool+}++private struct RemoteScreenshotParseStreamError: Decodable {+ var error: String?+ var message: String+ var details: RemoteInferenceJSONValue?}diff --git a/apps/Donkey/Sources/DonkeyAI/HostedPlannerHintAdapter.swift b/apps/Donkey/Sources/DonkeyAI/HostedPlannerHintAdapter.swiftindex 16797c0b..956fe69a 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedPlannerHintAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedPlannerHintAdapter.swift@@ -101,6 +101,7 @@ public struct PlannerHintAdapterResult: Equatable, Sendable {public protocol AIHTTPClient: Sendable {func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)+ func streamLines(_ request: URLRequest) async throws -> (AsyncThrowingStream<String, Error>, HTTPURLResponse)}public struct URLSessionAIHTTPClient: AIHTTPClient {@@ -113,6 +114,40 @@ public struct URLSessionAIHTTPClient: AIHTTPClient {}return (data, httpResponse)}++ public func streamLines(_ request: URLRequest) async throws -> (AsyncThrowingStream<String, Error>, HTTPURLResponse) {+ let (bytes, response) = try await URLSession.shared.bytes(for: request)+ guard let httpResponse = response as? HTTPURLResponse else {+ throw AIHTTPClientError.invalidHTTPResponse+ }+ let stream = AsyncThrowingStream<String, Error> { continuation in+ Task {+ do {+ for try await line in bytes.lines {+ continuation.yield(line)+ }+ continuation.finish()+ } catch {+ continuation.finish(throwing: error)+ }+ }+ }+ return (stream, httpResponse)+ }+}++public extension AIHTTPClient {+ func streamLines(_ request: URLRequest) async throws -> (AsyncThrowingStream<String, Error>, HTTPURLResponse) {+ let (data, response) = try await send(request)+ let text = String(data: data, encoding: .utf8) ?? ""+ let stream = AsyncThrowingStream<String, Error> { continuation in+ for line in text.components(separatedBy: .newlines) {+ continuation.yield(line)+ }+ continuation.finish()+ }+ return (stream, response)+ }}public enum AIHTTPClientError: Error, Equatable, Sendable {diff --git a/apps/Donkey/Sources/DonkeyAI/RemoteScreenshotParsingUIUnderstandingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/RemoteScreenshotParsingUIUnderstandingAdapter.swiftindex b08d2473..0e98b43e 100644--- a/apps/Donkey/Sources/DonkeyAI/RemoteScreenshotParsingUIUnderstandingAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/RemoteScreenshotParsingUIUnderstandingAdapter.swift@@ -46,12 +46,52 @@ public struct RemoteScreenshotParsingLocalUIUnderstandingAdapter: LocalUIUndersttry await client.parseScreenshot(request)}+ public func understandStream(+ _ request: LocalUIUnderstandingRequest+ ) -> AsyncThrowingStream<LocalUIUnderstandingStreamEvent, Error> {+ AsyncThrowingStream { continuation in+ Task {+ do {+ let final = try await client.parseScreenshotStream(request) { partial in+ continuation.yield(.partial(partial))+ }+ continuation.yield(.final(final))+ continuation.finish()+ } catch {+ continuation.finish(throwing: error)+ }+ }+ }+ }+func understand(_ request: LocalUIUnderstandingRequest,imageData: Data) async throws -> LocalUIUnderstandingResult {try await client.parseScreenshot(request, imageData: imageData)}++ func understandStream(+ _ request: LocalUIUnderstandingRequest,+ imageData: Data+ ) -> AsyncThrowingStream<LocalUIUnderstandingStreamEvent, Error> {+ AsyncThrowingStream { continuation in+ Task {+ do {+ let final = try await client.parseScreenshotStream(+ request,+ imageData: imageData+ ) { partial in+ continuation.yield(.partial(partial))+ }+ continuation.yield(.final(final))+ continuation.finish()+ } catch {+ continuation.finish(throwing: error)+ }+ }+ }+ }}public struct RemoteFallbackLocalUIUnderstandingAdapter: LocalUIUnderstandingRunning {@@ -122,6 +162,94 @@ public struct RemoteFallbackLocalUIUnderstandingAdapter: LocalUIUnderstandingRun}}+ public func understandStream(+ _ request: LocalUIUnderstandingRequest+ ) -> AsyncThrowingStream<LocalUIUnderstandingStreamEvent, Error> {+ AsyncThrowingStream { continuation in+ Task {+ do {+ try await streamUnderstanding(request, continuation: continuation)+ } catch {+ continuation.finish(throwing: error)+ }+ }+ }+ }++ private func streamUnderstanding(+ _ request: LocalUIUnderstandingRequest,+ continuation: AsyncThrowingStream<LocalUIUnderstandingStreamEvent, Error>.Continuation+ ) async throws {+ let primaryResult = try? await primary.understand(request)+ if let primaryResult, primaryEvidenceIsGood(primaryResult) {+ continuation.yield(.final(primaryResult))+ continuation.finish()+ return+ }++ guard let imageFileURL = request.imageFileURL else {+ if let primaryResult {+ continuation.yield(.final(primaryResult))+ continuation.finish()+ return+ }+ throw LocalUIUnderstandingError.unavailable("missingImagePath")+ }++ let imageData: Data+ do {+ imageData = try Data(contentsOf: imageFileURL)+ } catch {+ if let primaryResult {+ continuation.yield(.final(primaryResult))+ continuation.finish()+ return+ }+ throw LocalUIUnderstandingError.unavailable("missingImageData")+ }++ let fingerprint = Self.fingerprint(for: imageData)+ let allowed = await throttle.shouldAllow(+ targetID: request.targetID,+ imageFingerprint: fingerprint+ )+ guard allowed else {+ if let primaryResult {+ continuation.yield(.final(annotatedPrimaryResult(primaryResult, status: "throttled")))+ continuation.finish()+ return+ }+ throw LocalUIUnderstandingError.unavailable("remoteScreenshotParsingThrottled")+ }++ do {+ for try await event in remote.understandStream(request, imageData: imageData) {+ switch event {+ case .partial(var partial):+ partial.metadata = partial.metadata.merging([+ "remoteScreenshotParsing.status": "streaming",+ "remoteScreenshotParsing.fingerprint": fingerprint+ ]) { current, _ in current }+ continuation.yield(.partial(bestResult(primary: primaryResult, remote: partial)))+ case .final(var final):+ final.metadata = final.metadata.merging([+ "remoteScreenshotParsing.status": "used",+ "remoteScreenshotParsing.fingerprint": fingerprint+ ]) { current, _ in current }+ continuation.yield(.final(bestResult(primary: primaryResult, remote: final)))+ }+ }+ continuation.finish()+ } catch {+ if let primaryResult {+ continuation.yield(.final(annotatedPrimaryResult(primaryResult, status: "failed")))+ continuation.finish()+ return+ }+ throw error+ }+ }+private func primaryEvidenceIsGood(_ result: LocalUIUnderstandingResult) -> Bool {result.confidence >= minimumPrimaryConfidence&& (!result.controls.isEmpty || !result.visibleText.isEmpty || !result.formFields.isEmpty)diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swiftindex aa2d73a2..4867cf52 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift@@ -108,6 +108,34 @@ public struct LocalAppAccessibilityControlDiscovery: Sendable {)}+ func visibleText(for node: MacAccessibilitySnapshotNode) -> String? {+ bestLabel(for: node)+ }++ func control(for node: MacAccessibilitySnapshotNode) -> LocalAppDiscoveredControl? {+ let kind = controlKind(for: node)+ let controlLabel = labelForControl(node, kind: kind)+ guard kind != .unknown, let controlLabel else {+ return nil+ }++ return LocalAppDiscoveredControl(+ id: node.nodeID,+ kind: kind,+ role: node.role,+ label: controlLabel,+ valueSummary: node.valueSummary,+ frame: node.frame,+ isEnabled: node.isEnabled ?? true,+ actions: node.actions,+ metadata: [+ "accessibility.nodeID": node.nodeID,+ "controlKind": kind.rawValue,+ "controlID": inferredControlID(label: controlLabel, kind: kind)+ ]+ )+ }+public func observedFormFields(in snapshot: MacAccessibilitySnapshot) -> [LocalDocumentFormField] {discover(in: snapshot).controls.filter { [.textField, .searchField, .checkbox].contains($0.kind) }@@ -136,26 +164,8 @@ public struct LocalAppAccessibilityControlDiscovery: Sendable {visibleText.append(label)}- let kind = controlKind(for: node)- let controlLabel = labelForControl(node, kind: kind)- if kind != .unknown, let controlLabel {- controls.append(- LocalAppDiscoveredControl(- id: node.nodeID,- kind: kind,- role: node.role,- label: controlLabel,- valueSummary: node.valueSummary,- frame: node.frame,- isEnabled: node.isEnabled ?? true,- actions: node.actions,- metadata: [- "accessibility.nodeID": node.nodeID,- "controlKind": kind.rawValue,- "controlID": inferredControlID(label: controlLabel, kind: kind)- ]- )- )+ if let control = control(for: node) {+ controls.append(control)}for child in node.children {@@ -176,7 +186,7 @@ public struct LocalAppAccessibilityControlDiscovery: Sendable {if let label = bestLabel(for: node) {return label}- if kind == .listItem {+ if kind == .listItem || kind == .group {return descendantText(for: node) ?? "list item"}return nil@@ -218,6 +228,16 @@ public struct LocalAppAccessibilityControlDiscovery: Sendable {descendantText(for: node) != nil {return .listItem}+ if role == "AXGroup",+ node.frame?.hasPositiveArea == true,+ descendantText(for: node) != nil {+ return .group+ }+ if (role == "AXStaticText" || role == "AXImage"),+ node.frame?.hasPositiveArea == true,+ bestLabel(for: node) != nil {+ return .group+ }if role == "AXSearchField" { return .searchField }if role == "AXTextField" || role == "AXTextArea" || role == "AXComboBox" {return .textFielddiff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swiftindex f4f9cda9..4f99dff7 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swift@@ -235,7 +235,7 @@ public actor LocalAppHarnessStepExecutor {traceID: traceID,metadata: ["reason": reason])- let observation = await appController.observe(definition: definition)+ let observation = await observeAppState(definition: definition, intent: intent, reason: reason)latestObservation = observationinitialActionPlan = initialActionPlan ?? LocalAppTaskAdapter(definition: definition).evidenceBackedActionPlan(for: intent, observation: observation)@@ -250,6 +250,45 @@ public actor LocalAppHarnessStepExecutor {)}+ private func observeAppState(+ definition: LocalAppTaskDefinition,+ intent: TaskIntent,+ reason: String+ ) async -> LocalAppTaskObservation {+ await appController.observe(definition: definition) { partialObservation in+ await self.recordPartialObservation(+ partialObservation,+ definition: definition,+ intent: intent,+ reason: reason+ )+ }+ }++ private func recordPartialObservation(+ _ observation: LocalAppTaskObservation,+ definition: LocalAppTaskDefinition,+ intent: TaskIntent,+ reason: String+ ) async {+ latestObservation = observationWithActionEvidence(observation)+ initialActionPlan = initialActionPlan ?? LocalAppTaskAdapter(definition: definition)+ .evidenceBackedActionPlan(for: intent, observation: latestObservation)+ await coordinator?.recordToolEvent(+ capability: .perception,+ decision: permissionPolicy.decision(for: .perception),+ toolName: "local-app-observation",+ summary: "Observed partial streaming UI evidence",+ traceID: traceID,+ metadata: [+ "reason": reason,+ "stream": "partial",+ "controlCount": observation.metadata["controlCount"] ?? "",+ "source": observation.metadata["runtime.backend"] ?? observation.metadata["observer"] ?? ""+ ]+ )+ }+private func executeAction(_ context: HarnessToolExecutionContext,tool: LocalAppActionPlanTool,@@ -332,7 +371,7 @@ public actor LocalAppHarnessStepExecutor {} else {latestStatus = .failedSafelatestStatusReason = "actionDenied"- let observation = await appController.observe(definition: definition)+ let observation = await observeAppState(definition: definition, intent: intent, reason: "actionDenied")latestObservation = observationWithActionEvidence(observation)return HarnessToolResult(callID: context.call.id,@@ -357,7 +396,7 @@ public actor LocalAppHarnessStepExecutor {}try? await Task.sleep(nanoseconds: 200_000_000)- let observation = await appController.observe(definition: definition)+ let observation = await observeAppState(definition: definition, intent: intent, reason: "postAction")latestObservation = observationWithActionEvidence(observation)latestStatus = .needsUserReviewlatestStatusReason = "actionExecutedAwaitingVerification"@@ -422,7 +461,7 @@ public actor LocalAppHarnessStepExecutor {}try? await Task.sleep(nanoseconds: 700_000_000)- let observation = await appController.observe(definition: definition)+ let observation = await observeAppState(definition: definition, intent: intent, reason: "appleScriptCompleted")latestObservation = observationWithActionEvidence(observation)latestStatus = .completedlatestStatusReason = "appleScriptAutomationCompleted"@@ -464,7 +503,7 @@ public actor LocalAppHarnessStepExecutor {traceID: traceID,metadata: ["modelToolName": context.call.name])- let observation = await appController.observe(definition: definition)+ let observation = await observeAppState(definition: definition, intent: intent, reason: "verify")latestObservation = observationWithActionEvidence(observation)let plan = LocalAppTaskAdapter(definition: definition).evidenceBackedActionPlan(for: intent, observation: latestObservation)diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskExecutionSupport.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskExecutionSupport.swiftindex 27c08e9e..ee1d6921 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskExecutionSupport.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskExecutionSupport.swift@@ -61,6 +61,22 @@ public protocol LocalAppTaskAppControlling: Sendable {@MainActorfunc observe(definition: LocalAppTaskDefinition) async -> LocalAppTaskObservation++ @MainActor+ func observe(+ definition: LocalAppTaskDefinition,+ onPartialObservation: @escaping @Sendable (LocalAppTaskObservation) async -> Void+ ) async -> LocalAppTaskObservation+}++public extension LocalAppTaskAppControlling {+ @MainActor+ func observe(+ definition: LocalAppTaskDefinition,+ onPartialObservation: @escaping @Sendable (LocalAppTaskObservation) async -> Void+ ) async -> LocalAppTaskObservation {+ await observe(definition: definition)+ }}public enum LocalAppTaskActionEngines {@@ -178,6 +194,14 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {@MainActorpublic func observe(definition: LocalAppTaskDefinition) async -> LocalAppTaskObservation {+ await observe(definition: definition, onPartialObservation: { _ in })+ }++ @MainActor+ public func observe(+ definition: LocalAppTaskDefinition,+ onPartialObservation: @escaping @Sendable (LocalAppTaskObservation) async -> Void+ ) async -> LocalAppTaskObservation {let runningApplication = runningApplication(for: definition.targetApp)let isFocused = NSWorkspace.shared.frontmostApplication?.bundleIdentifier == definition.targetApp.bundleIdentifierlet verificationKey = definition.metadata["verificationTextKey"]@@ -258,7 +282,9 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {definition: definition,runningApplication: runningApplication,isFocused: isFocused,- verificationKey: verificationKey+ verificationKey: verificationKey,+ accessibilityObservation: accessibilityObservation,+ onPartialObservation: onPartialObservation) else {var metadata = accessibilityObservation.metadatametadata["screenshotUnderstanding.status"] = "unavailable"@@ -304,7 +330,9 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {definition: LocalAppTaskDefinition,runningApplication: NSRunningApplication?,isFocused: Bool,- verificationKey: String+ verificationKey: String,+ accessibilityObservation: LocalAppTaskObservation,+ onPartialObservation: @escaping @Sendable (LocalAppTaskObservation) async -> Void) async -> LocalAppTaskObservation? {guard runningApplication != nil,let target = try? MacWindowResolver().selectTarget(),@@ -362,12 +390,47 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {)do {- return try await uiUnderstandingRunner.understand(request).observation(for: request)+ var finalObservation: LocalAppTaskObservation?+ for try await event in uiUnderstandingRunner.understandStream(request) {+ switch event {+ case .partial(let result):+ await onPartialObservation(+ Self.fusedObservation(+ accessibilityObservation: accessibilityObservation,+ screenshotObservation: result.observation(for: request)+ )+ )+ case .final(let result):+ finalObservation = result.observation(for: request)+ }+ }+ return finalObservation} catch {return nil}}+ private static func fusedObservation(+ accessibilityObservation: LocalAppTaskObservation,+ screenshotObservation: LocalAppTaskObservation+ ) -> LocalAppTaskObservation {+ let controls = accessibilityObservation.availableControls.merging(+ screenshotObservation.availableControls+ ) { current, new in current || new }+ return LocalAppTaskObservation(+ appIsRunning: accessibilityObservation.appIsRunning || screenshotObservation.appIsRunning,+ appIsFocused: accessibilityObservation.appIsFocused || screenshotObservation.appIsFocused,+ availableControls: controls,+ visibleText: accessibilityObservation.visibleText.merging(+ screenshotObservation.visibleText+ ) { current, _ in current },+ confidence: max(accessibilityObservation.confidence, screenshotObservation.confidence),+ metadata: accessibilityObservation.metadata.merging(+ screenshotObservation.metadata+ ) { current, _ in current }+ )+ }+@MainActorprivate func accessibilityControlIndex(for definition: LocalAppTaskDefinition,diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swiftindex b8bb5bf8..263c27d9 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIAccessibilityInspectionService.swift@@ -53,7 +53,7 @@ public struct DebugUIAccessibilityInspectionService: Sendable {self.init(windowResolver: MacWindowResolver(),capturer: ApplicationServicesMacAccessibilitySnapshotCapturer(- maximumTraversalNanoseconds: 700_000_000+ maximumTraversalNanoseconds: 2_000_000_000),screenProvider: AppKitDebugUIScreenMetadataProvider(),screenCapturer: DebugUIScreenCaptureService(),@@ -114,6 +114,53 @@ public struct DebugUIAccessibilityInspectionService: Sendable {)}+ public func inspectProgressively(+ scope: DebugUIInspectionScreenScope,+ minConfidence: Double,+ frontmostOnly: Bool = false,+ focusedOnly: Bool = false,+ targetBundleIdentifiers: [String] = [],+ targetAppNames: [String] = [],+ onPartialResults: ([DebugUIAccessibilityInspectionResult]) -> Void+ ) throws -> [DebugUIAccessibilityInspectionResult] {+ let screens = try screenProvider.screens(scope: scope)+ guard !screens.isEmpty else {+ throw DebugUIAccessibilityInspectionError.noScreenAvailable+ }++ let targets = visibleInspectableTargets(+ on: screens,+ frontmostOnly: frontmostOnly,+ focusedOnly: focusedOnly,+ targetBundleIdentifiers: targetBundleIdentifiers,+ targetAppNames: targetAppNames+ )+ guard capturer.trustStatus() == .trusted else {+ throw DebugUIAccessibilityInspectionError.accessibilityNotTrusted+ }+ guard !targets.isEmpty else {+ return []+ }++ guard let progressiveCapturer = capturer as? any MacAccessibilitySnapshotProgressCapturing else {+ let results = localElementDetectionResults(+ screens: screens,+ targets: targets,+ minConfidence: minConfidence+ )+ onPartialResults(results)+ return results+ }++ return progressiveLocalElementDetectionResults(+ screens: screens,+ targets: targets,+ minConfidence: minConfidence,+ progressiveCapturer: progressiveCapturer,+ onPartialResults: onPartialResults+ )+ }+private func localElementDetectionResults(screens: [DebugUIScreenMetadata],targets: [MacWindowTargetCandidate],@@ -124,6 +171,206 @@ public struct DebugUIAccessibilityInspectionService: Sendable {targets: targets)+ return inspectionResults(+ screens: screens,+ candidatesByScreenID: candidatesByScreenID,+ minConfidence: minConfidence,+ fingerprintSalt: "final"+ )+ }++ private func progressiveLocalElementDetectionResults(+ screens: [DebugUIScreenMetadata],+ targets: [MacWindowTargetCandidate],+ minConfidence: Double,+ progressiveCapturer: any MacAccessibilitySnapshotProgressCapturing,+ onPartialResults: ([DebugUIAccessibilityInspectionResult]) -> Void+ ) -> [DebugUIAccessibilityInspectionResult] {+ var candidatesByScreenID = Dictionary(+ uniqueKeysWithValues: screens.map { ($0.screenID, [LocalUIElementCandidate]()) }+ )+ let limits = Self.debugOverlayAccessibilityLimits+ var occludingWindowBounds: [WindowTargetBounds] = []+ var visibleWindowIndex = 0+ var pendingCandidateCount = 0+ var publishSequence = 0+ var lastPublishUptime = ProcessInfo.processInfo.systemUptime++ func publishPartial(force: Bool, target: MacWindowTargetCandidate) {+ let now = ProcessInfo.processInfo.systemUptime+ guard force || pendingCandidateCount >= 8 || now - lastPublishUptime >= 0.045 else {+ return+ }+ pendingCandidateCount = 0+ lastPublishUptime = now+ publishSequence += 1+ let results = inspectionResults(+ screens: screens,+ candidatesByScreenID: candidatesByScreenID,+ minConfidence: minConfidence,+ fingerprintSalt: "progress-\(publishSequence)"+ )+ guard results.contains(where: { !$0.frame.elements.isEmpty }) else {+ return+ }+ onPartialResults(results)+ }++ for target in targets {+ var windowBounds = target.bounds+ var visibleWindowIsRenderable = false+ var partialControls: [LocalAppDiscoveredControl] = []+ var partialVisibleText: [String] = []+ var emittedCandidateIDs = Set<String>()++ let tree = try? progressiveCapturer.captureTree(+ target: target,+ limits: limits+ ) { node in+ if node.nodeID == "ax-1" {+ windowBounds = node.frame ?? target.bounds+ visibleWindowIsRenderable = Self.isVisible(+ windowBounds,+ occludingWindowBounds: occludingWindowBounds+ )+ if visibleWindowIsRenderable {+ for screen in screens where Self.intersects(windowBounds, screen.captureFrame) {+ if let candidate = windowCandidate(+ target: target,+ windowBounds: windowBounds,+ screen: screen,+ visibleWindowIndex: visibleWindowIndex+ ), emittedCandidateIDs.insert(candidate.id).inserted {+ candidatesByScreenID[screen.screenID, default: []].append(candidate)+ pendingCandidateCount += 1+ }+ }+ publishPartial(force: true, target: target)+ }+ return+ }++ if let text = controlDiscovery.visibleText(for: node) {+ partialVisibleText.append(text)+ }+ if visibleWindowIsRenderable,+ let candidate = broadAccessibilityCandidate(+ for: node,+ target: target,+ windowBounds: windowBounds,+ screens: screens,+ occludingWindowBounds: occludingWindowBounds+ ),+ emittedCandidateIDs.insert(candidate.candidate.id).inserted {+ candidatesByScreenID[candidate.screenID, default: []].append(candidate.candidate)+ pendingCandidateCount += 1+ publishPartial(force: false, target: target)+ }++ guard visibleWindowIsRenderable,+ let control = controlDiscovery.control(for: node)+ else {+ return+ }+ partialControls.append(control)++ guard let candidate = accessibilityCandidate(+ for: control,+ target: target,+ windowBounds: windowBounds,+ screens: screens,+ occludingWindowBounds: occludingWindowBounds+ ), emittedCandidateIDs.insert(candidate.candidate.id).inserted+ else {+ return+ }++ candidatesByScreenID[candidate.screenID, default: []].append(candidate.candidate)+ pendingCandidateCount += 1+ publishPartial(force: false, target: target)+ }++ guard let tree else {+ occludingWindowBounds.append(target.bounds)+ continue+ }++ let snapshot = MacAccessibilitySnapshot(+ target: target,+ limits: limits,+ root: tree.root,+ totalNodeCount: tree.totalNodeCount,+ isTreeTruncated: tree.isTreeTruncated+ )+ let finalWindowBounds = snapshot.root.frame ?? target.bounds+ defer { occludingWindowBounds.append(finalWindowBounds) }++ removeCandidates(for: target, from: &candidatesByScreenID)+ guard Self.isVisible(finalWindowBounds, occludingWindowBounds: occludingWindowBounds) else {+ continue+ }++ for screen in screens where Self.intersects(finalWindowBounds, screen.captureFrame) {+ if let candidate = windowCandidate(+ target: target,+ windowBounds: finalWindowBounds,+ screen: screen,+ visibleWindowIndex: visibleWindowIndex+ ) {+ candidatesByScreenID[screen.screenID, default: []].append(candidate)+ }+ }+ visibleWindowIndex += 1++ let controlIndex = controlDiscovery.discover(in: snapshot)+ let controls = controlIndex.controls+ Self.logDiscoverySummary(+ target: target,+ snapshot: snapshot,+ controls: controls,+ visibleText: controlIndex.visibleText.isEmpty+ ? partialVisibleText.joined(separator: " ")+ : controlIndex.visibleText+ )+ for control in controls {+ guard let candidate = accessibilityCandidate(+ for: control,+ target: target,+ windowBounds: finalWindowBounds,+ screens: screens,+ occludingWindowBounds: occludingWindowBounds+ ) else {+ continue+ }+ candidatesByScreenID[candidate.screenID, default: []].append(candidate.candidate)+ }+ for candidate in broadAccessibilityCandidates(+ root: snapshot.root,+ target: target,+ windowBounds: finalWindowBounds,+ screens: screens,+ occludingWindowBounds: occludingWindowBounds+ ) {+ candidatesByScreenID[candidate.screenID, default: []].append(candidate.candidate)+ }+ pendingCandidateCount = 1+ publishPartial(force: true, target: target)+ }++ return inspectionResults(+ screens: screens,+ candidatesByScreenID: candidatesByScreenID,+ minConfidence: minConfidence,+ fingerprintSalt: "final"+ )+ }++ private func inspectionResults(+ screens: [DebugUIScreenMetadata],+ candidatesByScreenID: [UInt32: [LocalUIElementCandidate]],+ minConfidence: Double,+ fingerprintSalt: String+ ) -> [DebugUIAccessibilityInspectionResult] {return screens.map { screen inlet fallbackSnapshot = DebugUIScreenCaptureSnapshot(screenID: screen.screenID,@@ -145,37 +392,36 @@ public struct DebugUIAccessibilityInspectionService: Sendable {from: screen.captureFrame,to: snapshot.pixelSize)- let targetWindowBounds = Self.targetWindowBounds(in: accessibilityCandidates)- let trace = elementDetectionService.detect(- LocalUIElementDetectionRequest(- traceID: "debug-ui-local-\(screen.screenID)-\(snapshot.fingerprint)",- screenshotPNGData: nil,- pixelSize: snapshot.pixelSize,- accessibilityCandidates: accessibilityCandidates,- minConfidence: minConfidence,- metadata: [- "screen.id": String(screen.screenID),- "screen.scope": screens.count > 1 ? "all" : "main",- "donkeyVision.local": "accessibility"- ]- )- )- let frame = elementDetectionService.debugInspectionFrame(- from: trace.clippedToTargetWindows(targetWindowBounds)+ let frame = DebugUIInspectionFrame(+ elements: accessibilityCandidates+ .filter { $0.bounds.hasPositiveArea }+ .map(Self.debugElementFromUnfilteredAccessibilityCandidate)+ .sorted(by: Self.elementSort))- .validated(minConfidence: minConfidence)let fingerprint = Self.fingerprint(for: screen, elements: frame.elements)let outputSnapshot = DebugUIScreenCaptureSnapshot(screenID: snapshot.screenID,screenFrame: snapshot.screenFrame,pixelSize: snapshot.pixelSize,pngData: snapshot.pngData,- fingerprint: "\(snapshot.fingerprint)-\(fingerprint)"+ fingerprint: "\(snapshot.fingerprint)-\(fingerprint)-\(fingerprintSalt)")return DebugUIAccessibilityInspectionResult(snapshot: outputSnapshot, frame: frame)}}+ private func removeCandidates(+ for target: MacWindowTargetCandidate,+ from candidatesByScreenID: inout [UInt32: [LocalUIElementCandidate]]+ ) {+ let windowID = String(target.windowID)+ for screenID in candidatesByScreenID.keys {+ candidatesByScreenID[screenID]?.removeAll { candidate in+ candidate.metadata["target.windowID"] == windowID+ }+ }+ }+private func accessibilityCandidatesByScreen(screens: [DebugUIScreenMetadata],targets: [MacWindowTargetCandidate]@@ -183,12 +429,7 @@ public struct DebugUIAccessibilityInspectionService: Sendable {var candidatesByScreenID = Dictionary(uniqueKeysWithValues: screens.map { ($0.screenID, [LocalUIElementCandidate]()) })- let limits = MacAccessibilitySnapshotLimits(- maxDepth: 6,- maxChildrenPerNode: 90,- maxTotalNodes: 1_200,- maxTextLength: 120- )+ let limits = Self.debugOverlayAccessibilityLimitsvar occludingWindowBounds: [WindowTargetBounds] = []var visibleWindowIndex = 0@@ -243,6 +484,15 @@ public struct DebugUIAccessibilityInspectionService: Sendable {}candidatesByScreenID[candidate.screenID, default: []].append(candidate.candidate)}+ for candidate in broadAccessibilityCandidates(+ root: snapshot.root,+ target: target,+ windowBounds: windowBounds,+ screens: screens,+ occludingWindowBounds: occludingWindowBounds+ ) {+ candidatesByScreenID[candidate.screenID, default: []].append(candidate.candidate)+ }}return candidatesByScreenID@@ -289,24 +539,6 @@ public struct DebugUIAccessibilityInspectionService: Sendable {)}- private static func targetWindowBounds(- in candidates: [LocalUIElementCandidate]- ) -> [WindowTargetBounds] {- candidates.compactMap { candidate in- guard candidate.source == .accessibility,- candidate.typeHint == .draggable- else {- return nil- }- return WindowTargetBounds(- x: candidate.bounds.origin.x,- y: candidate.bounds.origin.y,- width: candidate.bounds.size.width,- height: candidate.bounds.size.height- )- }- }-private static func scaleCandidates(_ candidates: [LocalUIElementCandidate],from captureFrame: WindowTargetBounds,@@ -359,12 +591,7 @@ public struct DebugUIAccessibilityInspectionService: Sendable {var elementsByScreenID = Dictionary(uniqueKeysWithValues: screens.map { ($0.screenID, [DebugUIElement]()) })- let limits = MacAccessibilitySnapshotLimits(- maxDepth: 6,- maxChildrenPerNode: 90,- maxTotalNodes: 600,- maxTextLength: 120- )+ let limits = Self.debugOverlayAccessibilityLimitsvar occludingWindowBounds: [WindowTargetBounds] = []for target in targets {@@ -624,12 +851,71 @@ public struct DebugUIAccessibilityInspectionService: Sendable {case .listItem:return .listItemcase .group:- return control.actions.contains("AXPress") ? .button : nil+ return control.actions.contains("AXPress") ? .button : .listItemcase .unknown:return nil}}+ private static func broadElementType(forRole role: String) -> DebugUIElementType? {+ switch role {+ case "AXRow", "AXOutlineRow", "AXCell", "AXGroup", "AXImage", "AXStaticText":+ return .listItem+ case "AXButton", "AXMenuButton":+ return .button+ case "AXLink":+ return .link+ case "AXMenuItem":+ return .menuItem+ case "AXSearchField", "AXTextField", "AXTextArea", "AXComboBox":+ return .input+ case "AXCheckBox", "AXRadioButton":+ return .checkbox+ default:+ return .other+ }+ }++ private static func broadLabel(+ for node: MacAccessibilitySnapshotNode,+ role: String+ ) -> String? {+ if let label = [node.label, node.title, node.valueSummary]+ .compactMap({ $0?.trimmingCharacters(in: .whitespacesAndNewlines) })+ .first(where: { !$0.isEmpty }) {+ return label+ }++ var labels: [String] = []+ collectLabels(node, labels: &labels)+ let descendantLabel = labels+ .prefix(8)+ .joined(separator: " ")+ .trimmingCharacters(in: .whitespacesAndNewlines)+ if !descendantLabel.isEmpty {+ return descendantLabel+ }++ if role == "AXImage" {+ return "image"+ }+ return "\(role) \(node.nodeID)"+ }++ private static func collectLabels(+ _ node: MacAccessibilitySnapshotNode,+ labels: inout [String]+ ) {+ for child in node.children {+ if let label = [child.label, child.title, child.valueSummary]+ .compactMap({ $0?.trimmingCharacters(in: .whitespacesAndNewlines) })+ .first(where: { !$0.isEmpty }) {+ labels.append(label)+ }+ collectLabels(child, labels: &labels)+ }+ }+private func accessibilityCandidate(for control: LocalAppDiscoveredControl,target: MacWindowTargetCandidate,@@ -699,6 +985,158 @@ public struct DebugUIAccessibilityInspectionService: Sendable {)}+ private func broadAccessibilityCandidates(+ root: MacAccessibilitySnapshotNode,+ target: MacWindowTargetCandidate,+ windowBounds: WindowTargetBounds,+ screens: [DebugUIScreenMetadata],+ occludingWindowBounds: [WindowTargetBounds]+ ) -> [(screenID: UInt32, candidate: LocalUIElementCandidate)] {+ var candidates: [(screenID: UInt32, candidate: LocalUIElementCandidate)] = []+ collectBroadAccessibilityCandidates(+ node: root,+ target: target,+ windowBounds: windowBounds,+ screens: screens,+ occludingWindowBounds: occludingWindowBounds,+ candidates: &candidates+ )+ return candidates+ }++ private func collectBroadAccessibilityCandidates(+ node: MacAccessibilitySnapshotNode,+ target: MacWindowTargetCandidate,+ windowBounds: WindowTargetBounds,+ screens: [DebugUIScreenMetadata],+ occludingWindowBounds: [WindowTargetBounds],+ candidates: inout [(screenID: UInt32, candidate: LocalUIElementCandidate)]+ ) {+ if let candidate = broadAccessibilityCandidate(+ for: node,+ target: target,+ windowBounds: windowBounds,+ screens: screens,+ occludingWindowBounds: occludingWindowBounds+ ) {+ candidates.append(candidate)+ }++ for child in node.children {+ collectBroadAccessibilityCandidates(+ node: child,+ target: target,+ windowBounds: windowBounds,+ screens: screens,+ occludingWindowBounds: occludingWindowBounds,+ candidates: &candidates+ )+ }+ }++ private func broadAccessibilityCandidate(+ for node: MacAccessibilitySnapshotNode,+ target: MacWindowTargetCandidate,+ windowBounds: WindowTargetBounds,+ screens: [DebugUIScreenMetadata],+ occludingWindowBounds: [WindowTargetBounds]+ ) -> (screenID: UInt32, candidate: LocalUIElementCandidate)? {+ guard node.nodeID != "ax-1",+ let rawBounds = node.frame+ else {+ return nil+ }+ let role = node.role ?? "AXUnknown"+ let type = Self.broadElementType(forRole: role) ?? .other+ let label = Self.broadLabel(for: node, role: role) ?? "\(role) \(node.nodeID)"++ guard let bounds = DebugUIAccessibilityGeometry.normalizedBounds(+ for: rawBounds,+ targetBounds: windowBounds,+ rootBounds: windowBounds+ ),+ let screen = screens.first(where: { Self.intersects(bounds, $0.captureFrame) }),+ let bbox = DebugUIAccessibilityGeometry.boundingBox(+ for: bounds,+ screenFrame: screen.captureFrame+ )+ else {+ return nil+ }++ return (+ screen.screenID,+ LocalUIElementCandidate(+ id: "ax-node-\(target.windowID)-\(node.nodeID)",+ source: .accessibility,+ signalKind: role == "AXStaticText" ? .text : .accessibilityRole,+ typeHint: type,+ label: label,+ role: role,+ bounds: HotLoopRect(+ x: bbox.x,+ y: bbox.y,+ width: bbox.width,+ height: bbox.height,+ space: .screen+ ),+ confidence: role == "AXStaticText" ? 0.82 : 0.9,+ actions: node.actions,+ metadata: [+ "target.windowID": String(target.windowID),+ "target.appName": target.appName ?? "",+ "target.title": target.title ?? "",+ "accessibility.nodeID": node.nodeID,+ "accessibility.role": role,+ "accessibility.actions": node.actions.joined(separator: ","),+ "classification.reason": "accessibilityBroadNodeEvidence"+ ]+ .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 }+ )+ )+ }++ private static func debugElementFromUnfilteredAccessibilityCandidate(+ _ candidate: LocalUIElementCandidate+ ) -> DebugUIElement {+ let type = candidate.typeHint ?? .other+ let label = candidate.label?.trimmingCharacters(in: .whitespacesAndNewlines)+ let fallbackLabel = [+ candidate.role,+ candidate.metadata["accessibility.role"],+ candidate.id+ ]+ .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }+ .first { !$0.isEmpty } ?? type.rawValue+ return DebugUIElement(+ id: candidate.id,+ type: type,+ label: label?.isEmpty == false ? label! : fallbackLabel,+ description: [+ candidate.source.rawValue,+ candidate.signalKind.rawValue,+ candidate.role ?? ""+ ].filter { !$0.isEmpty }.joined(separator: " "),+ bbox: DebugUIBoundingBox(+ x: candidate.bounds.origin.x,+ y: candidate.bounds.origin.y,+ width: candidate.bounds.size.width,+ height: candidate.bounds.size.height+ ),+ confidence: candidate.confidence,+ visualStyle: DebugUIOverlayStyle.style(for: type),+ metadata: candidate.metadata.merging([+ "debugOverlay.unfilteredAccessibility": "true",+ "localUIElement.sources": candidate.source.rawValue,+ "localUIElement.reasonCodes": [+ "\(candidate.source.rawValue).\(candidate.signalKind.rawValue)",+ "debugUnfilteredAX"+ ].joined(separator: ",")+ ]) { current, _ in current }+ )+ }+private static func isWindowControl(_ control: LocalAppDiscoveredControl) -> Bool {let label = control.label.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()return ["close", "minimize", "zoom", "fullscreen", "full screen"].contains(label)@@ -754,9 +1192,10 @@ public struct DebugUIAccessibilityInspectionService: Sendable {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)"- )+ _ = target+ _ = snapshot+ _ = controls+ _ = visibleText}private static func controlKindSummary(_ controls: [LocalAppDiscoveredControl]) -> String {@@ -835,6 +1274,13 @@ public struct DebugUIAccessibilityInspectionService: Sendable {windowFrameStyles[index % windowFrameStyles.count]}+ private static let debugOverlayAccessibilityLimits = MacAccessibilitySnapshotLimits(+ maxDepth: 32,+ maxChildrenPerNode: 10_000,+ maxTotalNodes: 50_000,+ maxTextLength: 300+ )+private static let windowFrameStyles: [DebugUIOverlayStyle] = [DebugUIOverlayStyle(overlayColor: "#EF4444", borderColor: "#F87171", labelColor: "#FFFFFF"),DebugUIOverlayStyle(overlayColor: "#F97316", borderColor: "#FB923C", labelColor: "#FFFFFF"),diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swiftindex 1a33918e..f0d158c5 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift@@ -144,10 +144,33 @@ public struct LocalUIUnderstandingResult: Codable, Equatable, Sendable {}}+public enum LocalUIUnderstandingStreamEvent: Equatable, Sendable {+ case partial(LocalUIUnderstandingResult)+ case final(LocalUIUnderstandingResult)+}+public protocol LocalUIUnderstandingRunning: Sendable {func understand(_ request: LocalUIUnderstandingRequest) async throws -> LocalUIUnderstandingResult}+public extension LocalUIUnderstandingRunning {+ func understandStream(+ _ request: LocalUIUnderstandingRequest+ ) -> AsyncThrowingStream<LocalUIUnderstandingStreamEvent, Error> {+ AsyncThrowingStream { continuation in+ Task {+ do {+ let result = try await understand(request)+ continuation.yield(.final(result))+ continuation.finish()+ } catch {+ continuation.finish(throwing: error)+ }+ }+ }+ }+}+public struct ProcessBackedLocalUIUnderstandingAdapter: LocalUIUnderstandingRunning {public var sidecarRunner: any LocalJSONSidecarRunningpublic var encoder: JSONEncoderdiff --git a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swiftindex 45c50284..c05f0f2d 100644--- a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift@@ -56,6 +56,14 @@ protocol MacAccessibilitySnapshotCapturing: Sendable {) throws -> MacAccessibilitySnapshotTree}+protocol MacAccessibilitySnapshotProgressCapturing: MacAccessibilitySnapshotCapturing {+ func captureTree(+ target: MacWindowTargetCandidate,+ limits: MacAccessibilitySnapshotLimits,+ onNode: (MacAccessibilitySnapshotNode) -> Void+ ) throws -> MacAccessibilitySnapshotTree+}+public final class MacAccessibilitySnapshotCaptureService {private let artifactStore: LocalRunArtifactStoreprivate let windowResolver: MacWindowResolver@@ -340,7 +348,7 @@ public struct MacAccessibilityNativeDialogDetector: Sendable {}-final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing {+final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotProgressCapturing {private let maximumTraversalNanoseconds: UInt64init(maximumTraversalNanoseconds: UInt64 = 200_000_000) {@@ -354,6 +362,14 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilitfunc captureTree(target: MacWindowTargetCandidate,limits: MacAccessibilitySnapshotLimits+ ) throws -> MacAccessibilitySnapshotTree {+ try captureTree(target: target, limits: limits, onNode: { _ in })+ }++ func captureTree(+ target: MacWindowTargetCandidate,+ limits: MacAccessibilitySnapshotLimits,+ onNode: (MacAccessibilitySnapshotNode) -> Void) throws -> MacAccessibilitySnapshotTree {let application = AXUIElementCreateApplication(target.processID)let deadlineUptime = ProcessInfo.processInfo.systemUptime@@ -367,10 +383,12 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilitlet rawRoot = readRawNode(rootElement,depth: 0,+ path: "ax-1",limits: limits,deadlineUptime: deadlineUptime,remainingNodeCount: &remainingNodeCount,- isTreeTruncated: &isTreeTruncated+ isTreeTruncated: &isTreeTruncated,+ onNode: onNode) ?? RawMacAccessibilitySnapshotNode(role: "AXUnknown",title: target.title,@@ -411,10 +429,12 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilitprivate func readRawNode(_ element: AXUIElement,depth: Int,+ path: String,limits: MacAccessibilitySnapshotLimits,deadlineUptime: TimeInterval,remainingNodeCount: inout Int,- isTreeTruncated: inout Bool+ isTreeTruncated: inout Bool,+ onNode: (MacAccessibilitySnapshotNode) -> Void) -> RawMacAccessibilitySnapshotNode? {guard !hasTimedOut(deadlineUptime) else {isTreeTruncated = true@@ -427,24 +447,51 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilit}remainingNodeCount -= 1+ let role = stringAttribute(kAXRoleAttribute as CFString, from: element)+ let title = stringAttribute(kAXTitleAttribute as CFString, from: element)+ let label = stringAttribute(kAXDescriptionAttribute as CFString, from: element)+ let valueSummary = valueSummaryAttribute(kAXValueAttribute as CFString, from: element)+ let frame = frame(from: element)+ let isEnabled = boolAttribute(kAXEnabledAttribute as CFString, from: element)+ let isFocused = boolAttribute(kAXFocusedAttribute as CFString, from: element)+ let actions = actionNames(from: element)++ onNode(+ MacAccessibilitySnapshotNode(+ nodeID: path,+ role: Self.summarizeText(role, limit: limits.maxTextLength),+ title: Self.summarizeText(title, limit: limits.maxTextLength),+ label: Self.summarizeText(label, limit: limits.maxTextLength),+ valueSummary: Self.summarizeText(valueSummary, limit: limits.maxTextLength),+ frame: frame,+ isEnabled: isEnabled,+ isFocused: isFocused,+ actions: actions.compactMap {+ Self.summarizeText($0, limit: limits.maxTextLength)+ }+ )+ )+let children = childNodes(for: element,depth: depth,+ path: path,limits: limits,deadlineUptime: deadlineUptime,remainingNodeCount: &remainingNodeCount,- isTreeTruncated: &isTreeTruncated+ isTreeTruncated: &isTreeTruncated,+ onNode: onNode)return RawMacAccessibilitySnapshotNode(- role: stringAttribute(kAXRoleAttribute as CFString, from: element),- title: stringAttribute(kAXTitleAttribute as CFString, from: element),- label: stringAttribute(kAXDescriptionAttribute as CFString, from: element),- valueSummary: valueSummaryAttribute(kAXValueAttribute as CFString, from: element),- frame: frame(from: element),- isEnabled: boolAttribute(kAXEnabledAttribute as CFString, from: element),- isFocused: boolAttribute(kAXFocusedAttribute as CFString, from: element),- actions: actionNames(from: element),+ role: role,+ title: title,+ label: label,+ valueSummary: valueSummary,+ frame: frame,+ isEnabled: isEnabled,+ isFocused: isFocused,+ actions: actions,children: children)}@@ -452,10 +499,12 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilitprivate func childNodes(for element: AXUIElement,depth: Int,+ path: String,limits: MacAccessibilitySnapshotLimits,deadlineUptime: TimeInterval,remainingNodeCount: inout Int,- isTreeTruncated: inout Bool+ isTreeTruncated: inout Bool,+ onNode: (MacAccessibilitySnapshotNode) -> Void) -> [RawMacAccessibilitySnapshotNode] {guard !hasTimedOut(deadlineUptime) else {isTreeTruncated = true@@ -483,18 +532,38 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilit)return rawChildren- .compactMap { child in+ .enumerated()+ .compactMap { index, child inreadRawNode(child,depth: depth + 1,+ path: "\(path).\(index + 1)",limits: limits,deadlineUptime: deadlineUptime,remainingNodeCount: &remainingNodeCount,- isTreeTruncated: &isTreeTruncated+ isTreeTruncated: &isTreeTruncated,+ onNode: onNode)}}+ private static func summarizeText(+ _ value: String?,+ limit: Int+ ) -> String? {+ guard let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines),+ !trimmed.isEmpty+ else {+ return nil+ }++ guard trimmed.count <= limit else {+ return "[redacted length=\(trimmed.count)]"+ }++ return trimmed+ }+private func hasTimedOut(_ deadlineUptime: TimeInterval) -> Bool {ProcessInfo.processInfo.systemUptime >= deadlineUptime}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swiftindex 55294287..0c8dbbed 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift@@ -1111,6 +1111,190 @@ struct DebugUIInspectionTests {#expect(row.bbox == DebugUIBoundingBox(x: 10, y: 240, width: 190, height: 52))}+ @Test+ func accessibilityInspectionDrawsNativeMusicTilesFromAXGroups() throws {+ let screen = DebugUIScreenMetadata(+ screenID: 1,+ appKitFrame: HotLoopRect(x: 0, y: 0, width: 1200, height: 900, space: .screen),+ captureFrame: WindowTargetBounds(x: 0, y: 0, width: 1200, height: 900)+ )+ let capturer = DebugUIFakeAccessibilityCapturer(+ tree: MacAccessibilitySnapshotTreeBuilder.build(+ root: RawMacAccessibilitySnapshotNode(+ role: "AXWindow",+ title: "Music",+ frame: WindowTargetBounds(x: 0, y: 0, width: 1200, height: 900),+ children: [+ RawMacAccessibilitySnapshotNode(+ role: "AXGroup",+ frame: WindowTargetBounds(x: 560, y: 540, width: 250, height: 260),+ isEnabled: true,+ actions: [],+ children: [+ RawMacAccessibilitySnapshotNode(+ role: "AXImage",+ label: "New This Week artwork",+ frame: WindowTargetBounds(x: 560, y: 540, width: 250, height: 220)+ ),+ RawMacAccessibilitySnapshotNode(+ role: "AXStaticText",+ valueSummary: "New This Week",+ frame: WindowTargetBounds(x: 560, y: 770, width: 160, height: 24)+ )+ ]+ )+ ]+ ),+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)+ )+ )+ let service = DebugUIAccessibilityInspectionService(+ windowResolver: MacWindowResolver(+ provider: DebugUIFixtureWindowProvider(+ windows: [+ MacWindowProviderWindow(+ windowID: 8,+ processID: 100,+ appName: "Music",+ bounds: WindowTargetBounds(x: 0, y: 0, width: 1200, height: 900)+ )+ ],+ frontmostProcessID: 100+ )+ ),+ capturer: capturer,+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),+ currentProcessID: 999+ )++ let results = try service.inspect(scope: .main, minConfidence: 0.25)+ let tile = try #require(results.first?.frame.elements.first { $0.label.contains("New This Week") })++ #expect(tile.type == .listItem)+ #expect(tile.bbox == DebugUIBoundingBox(x: 560, y: 540, width: 250, height: 260))+ #expect(tile.metadata.values.contains("readOnlyEvidence") || tile.metadata.values.contains("cursorVisualization"))+ }++ @Test+ func accessibilityInspectionDrawsMusicTileTextAndImagesFromBroadAXNodes() throws {+ let screen = DebugUIScreenMetadata(+ screenID: 1,+ appKitFrame: HotLoopRect(x: 0, y: 0, width: 1200, height: 900, space: .screen),+ captureFrame: WindowTargetBounds(x: 0, y: 0, width: 1200, height: 900)+ )+ let capturer = DebugUIFakeAccessibilityCapturer(+ tree: MacAccessibilitySnapshotTreeBuilder.build(+ root: RawMacAccessibilitySnapshotNode(+ role: "AXWindow",+ title: "Music",+ frame: WindowTargetBounds(x: 0, y: 0, width: 1200, height: 900),+ children: [+ RawMacAccessibilitySnapshotNode(+ role: "AXImage",+ label: "Happy Hits artwork",+ frame: WindowTargetBounds(x: 530, y: 175, width: 290, height: 290)+ ),+ RawMacAccessibilitySnapshotNode(+ role: "AXStaticText",+ valueSummary: "Happy Hits",+ frame: WindowTargetBounds(x: 530, y: 482, width: 120, height: 24)+ ),+ RawMacAccessibilitySnapshotNode(+ role: "AXStaticText",+ valueSummary: "Apple Music Feel Good",+ frame: WindowTargetBounds(x: 530, y: 512, width: 210, height: 22)+ )+ ]+ ),+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)+ )+ )+ let service = DebugUIAccessibilityInspectionService(+ windowResolver: MacWindowResolver(+ provider: DebugUIFixtureWindowProvider(+ windows: [+ MacWindowProviderWindow(+ windowID: 9,+ processID: 100,+ appName: "Music",+ bounds: WindowTargetBounds(x: 0, y: 0, width: 1200, height: 900)+ )+ ],+ frontmostProcessID: 100+ )+ ),+ capturer: capturer,+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),+ currentProcessID: 999+ )++ let results = try service.inspect(scope: .main, minConfidence: 0.25)+ let labels = results.first?.frame.elements.map(\.label) ?? []++ #expect(labels.contains { $0.contains("Happy Hits artwork") })+ #expect(labels.contains { $0.contains("Happy Hits") })+ #expect(labels.contains { $0.contains("Apple Music Feel Good") })+ }++ @Test+ func accessibilityProgressiveInspectionPublishesBroadAXNodes() throws {+ let screen = DebugUIScreenMetadata(+ screenID: 1,+ appKitFrame: HotLoopRect(x: 0, y: 0, width: 1200, height: 900, space: .screen),+ captureFrame: WindowTargetBounds(x: 0, y: 0, width: 1200, height: 900)+ )+ let tileNodes = (0..<8).map { index in+ RawMacAccessibilitySnapshotNode(+ role: "AXStaticText",+ valueSummary: "Music tile \(index + 1)",+ frame: WindowTargetBounds(x: 530, y: 180 + Double(index * 34), width: 180, height: 24)+ )+ }+ let capturer = DebugUIFakeAccessibilityCapturer(+ tree: MacAccessibilitySnapshotTreeBuilder.build(+ root: RawMacAccessibilitySnapshotNode(+ role: "AXWindow",+ title: "Music",+ frame: WindowTargetBounds(x: 0, y: 0, width: 1200, height: 900),+ children: tileNodes+ ),+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6)+ )+ )+ let service = DebugUIAccessibilityInspectionService(+ windowResolver: MacWindowResolver(+ provider: DebugUIFixtureWindowProvider(+ windows: [+ MacWindowProviderWindow(+ windowID: 10,+ processID: 100,+ appName: "Music",+ bounds: WindowTargetBounds(x: 0, y: 0, width: 1200, height: 900)+ )+ ],+ frontmostProcessID: 100+ )+ ),+ capturer: capturer,+ screenProvider: DebugUIFixtureScreenProvider(screens: [screen]),+ currentProcessID: 999+ )+ var partialBatches: [[DebugUIAccessibilityInspectionResult]] = []++ let finalResults = try service.inspectProgressively(+ scope: .main,+ minConfidence: 0.25,+ onPartialResults: { partialBatches.append($0) }+ )+ let partialLabels = partialBatches.flatMap { batch in+ batch.flatMap { $0.frame.elements.map(\.label) }+ }+ let finalLabels = finalResults.flatMap { $0.frame.elements.map(\.label) }++ #expect(partialLabels.contains("Music tile 8"))+ #expect(finalLabels.contains("Music tile 8"))+ }+private func element(id: String,label: String,@@ -1139,7 +1323,7 @@ struct DebugUIInspectionTests {}}-private final class DebugUIFakeAccessibilityCapturer: MacAccessibilitySnapshotCapturing, @unchecked Sendable {+private final class DebugUIFakeAccessibilityCapturer: MacAccessibilitySnapshotProgressCapturing, @unchecked Sendable {var trust: MacAccessibilityTrustStatusvar tree: MacAccessibilitySnapshotTreevar treesByWindowID: [UInt32: MacAccessibilitySnapshotTree]@@ -1169,6 +1353,26 @@ private final class DebugUIFakeAccessibilityCapturer: MacAccessibilitySnapshotCacapturedWindowIDs.append(target.windowID)return treesByWindowID[target.windowID] ?? tree}++ func captureTree(+ target: MacWindowTargetCandidate,+ limits: MacAccessibilitySnapshotLimits,+ onNode: (MacAccessibilitySnapshotNode) -> Void+ ) throws -> MacAccessibilitySnapshotTree {+ let tree = try captureTree(target: target, limits: limits)+ emit(tree.root, to: onNode)+ return tree+ }++ private func emit(+ _ node: MacAccessibilitySnapshotNode,+ to onNode: (MacAccessibilitySnapshotNode) -> Void+ ) {+ onNode(node)+ for child in node.children {+ emit(child, to: onNode)+ }+ }}private struct DebugUIFixtureScreenProvider: DebugUIScreenMetadataProviding {diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swiftindex 8b84f019..502a2e8a 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift@@ -147,6 +147,7 @@ struct DonkeyBackendInferenceClientTests {#expect(object["contentType"] as? String == "image/png")#expect(object["traceID"] as? String == "trace-1")#expect(object["targetID"] as? String == "target-1")+ #expect(object["stream"] as? Bool == false)let pixelSize = try #require(object["pixelSize"] as? [String: Any])#expect(pixelSize["width"] as? Double == 200)#expect(pixelSize["height"] as? Double == 100)@@ -155,6 +156,82 @@ struct DonkeyBackendInferenceClientTests {#expect(metadata["screenshot.desktopCaptureAllowed"] as? String == "false")}+ @Test+ @MainActor+ func parseScreenshotStreamUsesSSEAndEmitsPartialBeforeFinal() async throws {+ let partial = LocalUIUnderstandingResult(+ controls: [+ LocalUIUnderstandingControl(+ id: "partial-play",+ label: "Play",+ kind: .button,+ frame: HotLoopRect(x: 10, y: 20, width: 80, height: 40, space: .window),+ confidence: 0.7+ )+ ],+ confidence: 0.7,+ metadata: ["screenshotParser.stream": "partial"]+ )+ let final = LocalUIUnderstandingResult(+ controls: [+ LocalUIUnderstandingControl(+ id: "partial-play",+ label: "Play",+ kind: .button,+ frame: HotLoopRect(x: 10, y: 20, width: 80, height: 40, space: .window),+ confidence: 0.7+ ),+ LocalUIUnderstandingControl(+ id: "final-shuffle",+ label: "Shuffle",+ kind: .button,+ frame: HotLoopRect(x: 100, y: 20, width: 90, height: 40, space: .window),+ confidence: 0.8+ )+ ],+ confidence: 0.8,+ metadata: ["screenshotParser.stream": "final"]+ )+ let encoder = JSONEncoder()+ let responseText = [+ "event: partial",+ "data: \(String(data: try encoder.encode(partial), encoding: .utf8)!)",+ "",+ "event: final",+ "data: \(String(data: try encoder.encode(final), encoding: .utf8)!)",+ "",+ ].joined(separator: "\n")+ let httpClient = FixtureHTTPClient(+ data: Data(responseText.utf8),+ statusCode: 200,+ headerFields: ["Content-Type": "text/event-stream"]+ )+ let client = DonkeyBackendInferenceClient(+ configuration: configuration(),+ httpClient: httpClient+ )++ var partials: [LocalUIUnderstandingResult] = []+ let result = try await client.parseScreenshotStream(+ LocalUIUnderstandingRequest(+ traceID: "trace-stream",+ targetID: "target-stream",+ pixelSize: HotLoopSize(width: 200, height: 100, space: .window)+ ),+ imageData: Data("png".utf8)+ ) { partial in+ partials.append(partial)+ }++ #expect(partials.map(\.controls.count) == [1])+ #expect(partials.first?.controls.first?.id == "partial-play")+ #expect(result.controls.map(\.id) == ["partial-play", "final-shuffle"])+ let request = try #require(httpClient.requests.first)+ #expect(request.value(forHTTPHeaderField: "Accept") == "text/event-stream")+ let object = try #require(request.httpBodyJSONObject)+ #expect(object["stream"] as? Bool == true)+ }+@Testfunc screenshotParseOverlayMapperConvertsWindowPixelsToScreenOverlayCoordinates() throws {let result = LocalUIUnderstandingResult(@@ -441,6 +518,97 @@ struct DonkeyBackendInferenceClientTests {#expect(httpClient.requests.count == 1)}+ @Test+ func remoteFallbackStreamsPartialAndFinalScreenshotEvidence() async throws {+ let imageURL = FileManager.default.temporaryDirectory+ .appendingPathComponent("donkey-remote-screenshot-stream-\(UUID().uuidString).png")+ try Data("stream-image".utf8).write(to: imageURL)+ defer {+ try? FileManager.default.removeItem(at: imageURL)+ }++ let partial = LocalUIUnderstandingResult(+ controls: [+ LocalUIUnderstandingControl(+ id: "partial-row",+ label: "Partial Row",+ kind: .listItem,+ confidence: 0.62+ )+ ],+ confidence: 0.62,+ metadata: ["screenshotParser.stream": "partial"]+ )+ let final = LocalUIUnderstandingResult(+ controls: [+ LocalUIUnderstandingControl(+ id: "partial-row",+ label: "Partial Row",+ kind: .listItem,+ confidence: 0.62+ ),+ LocalUIUnderstandingControl(+ id: "final-play",+ label: "Play",+ kind: .button,+ confidence: 0.91+ )+ ],+ confidence: 0.91,+ metadata: ["screenshotParser.stream": "final"]+ )+ let encoder = JSONEncoder()+ let responseText = [+ "event: partial",+ "data: \(String(data: try encoder.encode(partial), encoding: .utf8)!)",+ "",+ "event: final",+ "data: \(String(data: try encoder.encode(final), encoding: .utf8)!)",+ "",+ ].joined(separator: "\n")+ let httpClient = FixtureHTTPClient(+ data: Data(responseText.utf8),+ statusCode: 200,+ headerFields: ["Content-Type": "text/event-stream"]+ )+ let adapter = RemoteFallbackLocalUIUnderstandingAdapter(+ primary: StaticUIUnderstandingRunner(result: LocalUIUnderstandingResult(confidence: 0.1)),+ remote: RemoteScreenshotParsingLocalUIUnderstandingAdapter(+ client: DonkeyBackendInferenceClient(+ configuration: configuration(),+ httpClient: httpClient+ )+ ),+ throttle: RemoteScreenshotParsingThrottle(minimumInterval: 60)+ )++ let stream = adapter.understandStream(+ LocalUIUnderstandingRequest(+ traceID: "trace-stream-fallback",+ targetID: "target-stream-fallback",+ imageFileURL: imageURL,+ pixelSize: HotLoopSize(width: 100, height: 100, space: .window)+ )+ )+ var eventSummaries: [String] = []+ for try await event in stream {+ switch event {+ case .partial(let result):+ eventSummaries.append("partial:\(result.controls.map(\.id).joined(separator: ",")):\(result.metadata["remoteScreenshotParsing.status"] ?? "")")+ case .final(let result):+ eventSummaries.append("final:\(result.controls.map(\.id).joined(separator: ",")):\(result.metadata["remoteScreenshotParsing.status"] ?? "")")+ }+ }++ #expect(eventSummaries == [+ "partial:partial-row:streaming",+ "final:partial-row,final-play:used",+ ])+ let request = try #require(httpClient.requests.first)+ let object = try #require(request.httpBodyJSONObject)+ #expect(object["stream"] as? Bool == true)+ }+@Testfunc configurationUsesWebBaseEnvironmentURL() throws {let configuration = try DonkeyBackendInferenceConfiguration.fromEnvironment([diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 03026ff1..d749caf9 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -250,6 +250,13 @@ vision, OCR, and hover evidence enrich the world model, labels, and layout. WhenAccessibility cannot resolve the target, scoped AI screenshot boxes may become asecondary actionable target for a guarded coordinate click.+Screenshot understanding is a structured evidence source, not an overlay-only+feature. Hosted screenshot parsers may stream partial UI-understanding results+while a final parse is still running. The local-app controller forwards those+partial controls, labels, boxes, confidence values, and provenance metadata into+the same observation path used for actions, then replaces or augments them with+the final parse result when it arrives.+Element actions execute only after the harness validates:- target focusdiff --git a/site/src/app/api/inference/screenshots/parse/route.ts b/site/src/app/api/inference/screenshots/parse/route.tsindex 0aeb43ce..b98d4d09 100644--- a/site/src/app/api/inference/screenshots/parse/route.ts+++ b/site/src/app/api/inference/screenshots/parse/route.ts@@ -22,9 +22,11 @@ import {} from "@/lib/inference/responses";import {parseScreenshot,+ parseScreenshotStream,screenshotParseModelForRequest,} from "@/lib/inference/screenshot-parsing";import { screenshotParseRequestSchema } from "@/lib/inference/screenshot-parsing/schema";+import type { ScreenshotParseRequest } from "@/lib/inference/screenshot-parsing/schema";export const dynamic = "force-dynamic";@@ -78,6 +80,15 @@ export const POST = withDonkeyAuth(async (request) => {return credits.response;}+ if (parsed.data.stream) {+ return streamScreenshotParseResponse({+ clientId: client.clientId,+ model,+ request: parsed.data,+ userId: request.donkey.userId,+ });+ }+try {const result = await parseScreenshot(parsed.data);const recordedUsage = await recordInferenceUsage({@@ -121,3 +132,90 @@ export const POST = withDonkeyAuth(async (request) => {throw error;}});++function streamScreenshotParseResponse(input: {+ clientId: string;+ model: string;+ request: ScreenshotParseRequest;+ userId: string;+}) {+ const encoder = new TextEncoder();+ const stream = new ReadableStream<Uint8Array>({+ async start(controller) {+ try {+ for await (const event of parseScreenshotStream(input.request)) {+ if (event.type === "partial") {+ controller.enqueue(encoder.encode(serverSentEvent("partial", event.result)));+ continue;+ }++ const recordedUsage = await recordInferenceUsage({+ clientId: input.clientId,+ metadata: {+ parserProvider: "gemini-flash",+ streaming: true,+ },+ model: event.model,+ provider: event.provider,+ requestKind: "screenshot_parse",+ route: inferenceUsageRoutes.screenshotParse,+ status: "succeeded",+ usage: event.usage,+ userId: input.userId,+ });+ controller.enqueue(+ encoder.encode(+ serverSentEvent("final", {+ ...event.result,+ metadata: {+ ...event.result.metadata,+ ...creditUsageHeaders(recordedUsage),+ },+ }),+ ),+ );+ }+ } catch (error) {+ await recordFailedInferenceUsage({+ clientId: input.clientId,+ errorCode: inferenceErrorCode(error),+ metadata: {+ parserProvider: "gemini-flash",+ streaming: true,+ },+ model: input.model,+ provider: "gemini",+ requestKind: "screenshot_parse",+ route: inferenceUsageRoutes.screenshotParse,+ userId: input.userId,+ });+ controller.enqueue(+ encoder.encode(+ serverSentEvent("error", {+ error: inferenceErrorCode(error),+ message: error instanceof Error ? error.message : "Screenshot parsing failed.",+ details: error instanceof InferenceProviderError ? error.details : null,+ }),+ ),+ );+ } finally {+ controller.close();+ }+ },+ });++ return new Response(stream, {+ headers: {+ "Cache-Control": "no-cache, no-transform",+ "Connection": "keep-alive",+ "Content-Type": "text/event-stream; charset=utf-8",+ "X-Accel-Buffering": "no",+ "X-Donkey-Inference-Model": input.model,+ "X-Donkey-Inference-Provider": "gemini",+ },+ });+}++function serverSentEvent(event: string, data: unknown) {+ return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;+}diff --git a/site/src/lib/inference/screenshot-parsing/gemini-flash.ts b/site/src/lib/inference/screenshot-parsing/gemini-flash.tsindex 228406e8..ef74e332 100644--- a/site/src/lib/inference/screenshot-parsing/gemini-flash.ts+++ b/site/src/lib/inference/screenshot-parsing/gemini-flash.ts@@ -19,18 +19,17 @@ import {} from "@/lib/inference/json";import {InferenceProviderError,- type JsonObject,type JsonValue,} from "@/lib/inference/providers";import {geminiScreenshotParseOutputSchema,+ geminiScreenshotControlSchema,type GeminiScreenshotParseOutput,type HotLoopRectJSON,type ScreenshotParseRequest,} from "@/lib/inference/screenshot-parsing/schema";import type {ScreenshotParserProvider,- ScreenshotParserProviderResult,ScreenshotParserResult,} from "@/lib/inference/screenshot-parsing/types";@@ -87,6 +86,63 @@ export function createGeminiFlashScreenshotParser(metadata: result.metadata,};},+ async *stream(request) {+ ensureConfigured(config.configured);+ const client = clientFactory(config.options);+ const model = screenshotParseModelForRequest(request, environment);+ const startedAt = performance.now();+ const generator = await streamGeminiContent(client, request, model);+ let accumulatedText = "";+ let emittedControlCount = 0;+ let latestUsage: JsonValue | undefined;++ for await (const chunk of generator) {+ accumulatedText += geminiResponseText(chunk);+ latestUsage = usageFromGeminiResponse(toJsonValue(chunk)) ?? latestUsage;++ const partialOutput = partialGeminiOutput(accumulatedText);+ if (partialOutput.controls.length <= emittedControlCount) {+ continue;+ }++ emittedControlCount = partialOutput.controls.length;+ const result = normalizedScreenshotResult(request, partialOutput, {+ provider: geminiProviderID,+ parserProvider: screenshotProviderID,+ model,+ service: config.service,+ location: config.location,+ latencyMs: String(Math.round(performance.now() - startedAt)),+ "screenshotParser.stream": "partial",+ });+ yield {+ type: "partial",+ provider: geminiProviderID,+ model,+ result,+ metadata: result.metadata,+ };+ }++ const output = parseGeminiOutputText(accumulatedText);+ const result = normalizedScreenshotResult(request, output, {+ provider: geminiProviderID,+ parserProvider: screenshotProviderID,+ model,+ service: config.service,+ location: config.location,+ latencyMs: String(Math.round(performance.now() - startedAt)),+ "screenshotParser.stream": "final",+ });+ yield {+ type: "final",+ provider: geminiProviderID,+ model,+ result,+ usage: latestUsage,+ metadata: result.metadata,+ };+ },};}@@ -283,7 +339,10 @@ function isDebugOverlayRequest(request: ScreenshotParseRequest) {}function parseGeminiOutput(rawBody: JsonValue) {- const text = geminiText(rawBody);+ return parseGeminiOutputText(geminiText(rawBody));+}++function parseGeminiOutputText(text: string) {let parsed: unknown;try {parsed = JSON.parse(text);@@ -311,6 +370,118 @@ function parseGeminiOutput(rawBody: JsonValue) {return output.data;}+async function streamGeminiContent(+ client: GeminiClient,+ request: ScreenshotParseRequest,+ model: string,+) {+ try {+ return await client.models.generateContentStream(+ geminiRequestParameters(request, model),+ );+ } catch (error) {+ throw geminiProviderError(error);+ }+}++function partialGeminiOutput(text: string): GeminiScreenshotParseOutput {+ const controls = extractArrayObjectTexts(text, "controls")+ .map((controlText) => {+ try {+ return JSON.parse(controlText) as unknown;+ } catch {+ return null;+ }+ })+ .map((control) => geminiScreenshotControlSchema.safeParse(control))+ .filter((control) => control.success)+ .map((control) => control.data);++ return {+ visibleText: [],+ controls,+ formFields: [],+ confidence: controls.reduce(+ (confidence, control) => Math.max(confidence, control.confidence),+ 0,+ ),+ };+}++function extractArrayObjectTexts(jsonText: string, propertyName: string) {+ const propertyIndex = jsonText.indexOf(`"${propertyName}"`);+ if (propertyIndex < 0) {+ return [];+ }++ const arrayStart = jsonText.indexOf("[", propertyIndex);+ if (arrayStart < 0) {+ return [];+ }++ const objects: string[] = [];+ let objectStart = -1;+ let objectDepth = 0;+ let arrayDepth = 0;+ let inString = false;+ let escaped = false;++ for (let index = arrayStart; index < jsonText.length; index += 1) {+ const character = jsonText[index];++ if (inString) {+ if (escaped) {+ escaped = false;+ } else if (character === "\\") {+ escaped = true;+ } else if (character === "\"") {+ inString = false;+ }+ continue;+ }++ if (character === "\"") {+ inString = true;+ continue;+ }++ if (character === "[") {+ arrayDepth += 1;+ continue;+ }++ if (character === "]") {+ arrayDepth -= 1;+ if (arrayDepth === 0) {+ break;+ }+ continue;+ }++ if (arrayDepth !== 1) {+ continue;+ }++ if (character === "{") {+ if (objectDepth === 0) {+ objectStart = index;+ }+ objectDepth += 1;+ continue;+ }++ if (character === "}") {+ objectDepth -= 1;+ if (objectDepth === 0 && objectStart >= 0) {+ objects.push(jsonText.slice(objectStart, index + 1));+ objectStart = -1;+ }+ }+ }++ return objects;+}+function geminiText(rawBody: JsonValue) {if (isJsonObject(rawBody) && typeof rawBody.text === "string") {return rawBody.text;@@ -330,6 +501,16 @@ function geminiText(rawBody: JsonValue) {.trim();}+function geminiResponseText(response: unknown) {+ const directText = response !== null+ && typeof response === "object"+ && "text" in response+ && typeof response.text === "string"+ ? response.text+ : undefined;+ return directText ?? geminiText(toJsonValue(response));+}+export function rectFromGeminiBox(box: [number, number, number, number],imageWidth: number,diff --git a/site/src/lib/inference/screenshot-parsing/index.ts b/site/src/lib/inference/screenshot-parsing/index.tsindex 3298ffaa..c17131c0 100644--- a/site/src/lib/inference/screenshot-parsing/index.ts+++ b/site/src/lib/inference/screenshot-parsing/index.ts@@ -6,6 +6,7 @@ import {import type {ScreenshotParserProvider,ScreenshotParserProviderResult,+ ScreenshotParserProviderStreamEvent,} from "@/lib/inference/screenshot-parsing/types";import type { ScreenshotParseRequest } from "@/lib/inference/screenshot-parsing/schema";@@ -31,3 +32,33 @@ export async function parseScreenshot(return provider.parse(request);}++export async function* parseScreenshotStream(+ request: ScreenshotParseRequest,+ provider: ScreenshotParserProvider = createScreenshotParserProvider(),+): AsyncGenerator<ScreenshotParserProviderStreamEvent> {+ if (!provider.configured) {+ throw new InferenceProviderError("Screenshot parser provider is not configured.", {+ statusCode: 503,+ code: "missing_provider_credentials",+ details: {+ provider: "gemini-flash",+ },+ });+ }++ if (!provider.stream) {+ const result = await provider.parse(request);+ yield {+ type: "final",+ provider: result.provider,+ model: result.model,+ result: result.result,+ usage: result.usage,+ metadata: result.metadata,+ };+ return;+ }++ yield* provider.stream(request);+}diff --git a/site/src/lib/inference/screenshot-parsing/schema.ts b/site/src/lib/inference/screenshot-parsing/schema.tsindex f7697f64..2f0bf68c 100644--- a/site/src/lib/inference/screenshot-parsing/schema.ts+++ b/site/src/lib/inference/screenshot-parsing/schema.ts@@ -4,19 +4,16 @@ import { toJsonObject } from "@/lib/inference/json";const metadataSchema = z.record(z.string().min(1).max(64), z.string().max(512));const coordinateSpaceSchema = z.enum(["screen", "window", "crop", "normalizedTarget"]);-const controlKindValues = [- "button",- "textField",- "searchField",- "checkbox",- "link",- "menuItem",- "listItem",- "group",- "unknown",-] as const;-const controlKindSchema = z.enum(controlKindValues);-type ControlKind = z.infer<typeof controlKindSchema>;+type ControlKind =+ | "button"+ | "textField"+ | "searchField"+ | "checkbox"+ | "link"+ | "menuItem"+ | "listItem"+ | "group"+ | "unknown";export const hotLoopSizeSchema = z.object({width: z.number().positive().max(20_000),@@ -41,6 +38,7 @@ export const screenshotParseRequestSchema = z.object({targetID: z.string().min(1).max(256).optional(),cropBounds: hotLoopRectSchema.optional(),metadata: metadataSchema.optional().default({}),+ stream: z.boolean().optional().default(false),}).transform((value) => ({...value,metadata: toJsonObject(value.metadata),diff --git a/site/src/lib/inference/screenshot-parsing/types.ts b/site/src/lib/inference/screenshot-parsing/types.tsindex cdf075cf..1548a666 100644--- a/site/src/lib/inference/screenshot-parsing/types.ts+++ b/site/src/lib/inference/screenshot-parsing/types.ts@@ -37,7 +37,25 @@ export type ScreenshotParserProviderResult = {metadata: JsonObject;};+export type ScreenshotParserProviderStreamEvent =+ | {+ type: "partial";+ provider: string;+ model: string;+ result: ScreenshotParserResult;+ metadata: JsonObject;+ }+ | {+ type: "final";+ provider: string;+ model: string;+ result: ScreenshotParserResult;+ usage?: JsonValue;+ metadata: JsonObject;+ };+export type ScreenshotParserProvider = {configured: boolean;parse: (request: ScreenshotParseRequest) => Promise<ScreenshotParserProviderResult>;+ stream?: (request: ScreenshotParseRequest) => AsyncGenerator<ScreenshotParserProviderStreamEvent>;};