Open source CapCut alternative.
TypeScript
Add env-gated vision navigation route
David Lec260d66d6108
diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swiftindex 16fd6609..697b8753 100644--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift@@ -35,7 +35,7 @@ final class DebugUIInspectionCoordinator {private var lastFingerprints: [UInt32: String] = [:]private var lastRenderedFrames: [UInt32: DebugUIInspectionFrame] = [:]private var lastSnapshots: [UInt32: DebugUIScreenCaptureSnapshot] = [:]- private var lastVisionImageHashes: [UInt32: String] = [:]+ private var lastVisionSignatures: [UInt32: ScreenshotSignature] = [:]private var visionBackoff: [UInt32: VisionBackoff] = [:]private let remoteAIEngine: RemoteAIEngine = .vision@@ -84,7 +84,7 @@ final class DebugUIInspectionCoordinator {lastFingerprints.removeAll()lastRenderedFrames.removeAll()lastSnapshots.removeAll()- lastVisionImageHashes.removeAll()+ lastVisionSignatures.removeAll()visionBackoff.removeAll()isAnalyzing = falseisRefreshingActiveAccessibility = false@@ -186,7 +186,7 @@ final class DebugUIInspectionCoordinator {trackers.removeAll()lastRenderedFrames.removeAll()lastSnapshots.removeAll()- lastVisionImageHashes.removeAll()+ lastVisionSignatures.removeAll()visionBackoff.removeAll()if !newConfig.enabled {overlayController.close()@@ -266,7 +266,7 @@ final class DebugUIInspectionCoordinator {return}- var tracker = trackers[screen.screenID] ?? DebugUIElementTracker()+ var tracker = trackers[screen.screenID] ?? Self.makeElementTracker()let trackedFrame = tracker.update(with: frame)trackers[screen.screenID] = trackerguard force@@ -378,7 +378,7 @@ final class DebugUIInspectionCoordinator {continue}- var tracker = trackers[screen.screenID] ?? DebugUIElementTracker()+ var tracker = trackers[screen.screenID] ?? Self.makeElementTracker()let trackedFrame = tracker.update(with: fusedFrame,renderNewElementsImmediately: true@@ -489,7 +489,7 @@ final class DebugUIInspectionCoordinator {continue}lastFingerprints[screen.screenID] = fingerprint- var tracker = trackers[screen.screenID] ?? DebugUIElementTracker()+ var tracker = trackers[screen.screenID] ?? Self.makeElementTracker()let trackedFrame = tracker.update(with: accessibilityFrame)trackers[screen.screenID] = trackerlet snapshot = Self.screenPointSnapshot(screen: screen, fingerprint: fingerprint)@@ -559,7 +559,7 @@ final class DebugUIInspectionCoordinator {}func renderRemoteAIFrame(stage: String, updatesFingerprint: Bool) {- var tracker = trackers[screen.screenID] ?? DebugUIElementTracker()+ var tracker = trackers[screen.screenID] ?? Self.makeElementTracker()let remoteAIFrame = DebugUIInspectionFrame(elements: elements)let fusedFrame = DebugUIInspectionFrameFusion.fused(accessibilityFrame: localEvidenceFrame,@@ -610,17 +610,21 @@ final class DebugUIInspectionCoordinator {if let backoff = visionBackoff[windowID], Date() < backoff.nextAttempt {continue}- let imageHash = SHA256.hash(data: capture.parseImageData)- .map { String(format: "%02x", $0) }- .joined()- // Skip the network call when this window's pixels are unchanged- // since the last successful vision parse; its elements are still- // carried forward in `elements`. Server-side caching comes later.- if lastVisionImageHashes[windowID] == imageHash {- DebugUIInspectionLog.overlay.debug(- "debug inspection skipped unchanged vision windowID=\(windowID, privacy: .public)"- )- continue+ // Skip the network call when this window looks unchanged since the last+ // successful vision parse; its elements are still carried forward in+ // `elements`. We compare a scale-normalized grayscale signature with a+ // per-pixel noise floor instead of an exact byte hash, so caret blink,+ // the clock, cursor motion, or a sub-pixel resize don't force a re-parse.+ // Built from the raw capture so JPEG quantization noise never enters.+ let signature = ScreenshotSignature.make(fromImageData: capture.screenshot.pngData)+ if let signature, let previous = lastVisionSignatures[windowID] {+ let changedFraction = signature.changedFraction(from: previous)+ if changedFraction <= Self.visionChangedFractionThreshold {+ DebugUIInspectionLog.overlay.debug(+ "debug inspection skipped unchanged vision windowID=\(windowID, privacy: .public) changedFraction=\(changedFraction, privacy: .public)"+ )+ continue+ }}do {DebugUIInspectionLog.overlay.info(@@ -642,7 +646,9 @@ final class DebugUIInspectionCoordinator {)elements.removeAll { Self.windowID(for: $0) == windowID }elements += parsedElements- lastVisionImageHashes[windowID] = imageHash+ if let signature {+ lastVisionSignatures[windowID] = signature+ }visionBackoff[windowID] = nilrenderRemoteAIFrame(stage: "vision", updatesFingerprint: false)} catch {@@ -854,7 +860,7 @@ final class DebugUIInspectionCoordinator {lastFingerprints[snapshot.screenID] = snapshot.fingerprintlastSnapshots[snapshot.screenID] = snapshot- var tracker = trackers[snapshot.screenID] ?? DebugUIElementTracker()+ var tracker = trackers[snapshot.screenID] ?? Self.makeElementTracker()let trackedFrame = tracker.update(with: result.frame)trackers[snapshot.screenID] = trackerif !force,@@ -889,7 +895,7 @@ final class DebugUIInspectionCoordinator {private func ageMissingScreens(activeScreenIDs: Set<UInt32>) {let missingScreenIDs = Set(lastRenderedFrames.keys).subtracting(activeScreenIDs)for screenID in missingScreenIDs {- var tracker = trackers[screenID] ?? DebugUIElementTracker()+ var tracker = trackers[screenID] ?? Self.makeElementTracker()let trackedFrame = tracker.update(with: DebugUIInspectionFrame())trackers[screenID] = trackerif trackedFrame.elements.isEmpty {@@ -1354,6 +1360,24 @@ final class DebugUIInspectionCoordinator {return SHA256.hash(data: Data(combinedInput.utf8)).map { String(format: "%02x", $0) }.joined()}+ /// A window must change by more than this fraction of its normalized grayscale cells before+ /// we re-run a vision parse. ~1.2% of a 64x64 grid is ~50 cells — enough to ignore caret/clock+ /// flicker while still catching a small new control or panel.+ private static let visionChangedFractionThreshold = 0.012++ /// Tracker used for the debug overlay. Carry-forward is disabled so each render shows exactly+ /// the current parse's elements: vision (OmniParser) reassigns IDs and jitters labels every+ /// parse, so the default multi-frame carry-forward would keep stale boxes alive and pile up+ /// overlapping duplicates on screen. New elements render immediately and anything absent from+ /// the latest frame is dropped at once — i.e. the previous overlay is cleared before the next.+ private static func makeElementTracker() -> DebugUIElementTracker {+ DebugUIElementTracker(+ appearanceThreshold: 1,+ disappearanceTolerance: 0,+ movementConfirmationSamples: 1+ )+ }+private static func nextVisionBackoff(after previous: VisionBackoff?) -> VisionBackoff {let baseSeconds = 2.0let capSeconds = 30.0diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 5986d337..6487d6c0 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -15,6 +15,38 @@ private enum UserQueryLog {static let commands = Logger(subsystem: "com.donkey.app", category: "user-query")}+/// End-to-end vision-grounding telemetry. Intentionally NOT `#if DEBUG`-gated and mirrored to+/// stdout: these are the latency numbers we capture for marketing, so they must be visible when+/// running a release binary from the terminal — not just in a debug build's os_log stream.+private enum VisionGroundingLog {+ static let logger = Logger(subsystem: "com.donkey.app", category: "vision-grounding")++ static func emit(_ message: String) {+ logger.notice("\(message, privacy: .public)")+ print("[grounding-e2e] \(message)")+ }+}++/// Configurable, env-gated "vision navigation" route. When enabled, a typed query is grounded+/// straight into on-screen actions by `VisionActionDriver` against the FRONTMOST user app —+/// bypassing the intent/AppleScript pipeline entirely. Gated by `DONKEY_VISION_NAV` so it is+/// trivial to turn off and revert to the standard route; the value is injectable so callers and+/// tests can force it on or off without touching the environment.+struct VisionNavigationMode: Equatable, Sendable {+ var isEnabled: Bool++ static let disabled = VisionNavigationMode(isEnabled: false)++ static func fromEnvironment(+ _ environment: [String: String] = ProcessInfo.processInfo.environment+ ) -> VisionNavigationMode {+ let raw = (environment["DONKEY_VISION_NAV"] ?? "")+ .trimmingCharacters(in: .whitespacesAndNewlines)+ .lowercased()+ return VisionNavigationMode(isEnabled: ["1", "true", "yes", "on"].contains(raw))+ }+}+struct UserQueryCommandHandlingResult: Equatable, Sendable {var status: LocalAppTaskLiveRunStatusvar threadStatus: UserQueryTaskStatus@@ -100,6 +132,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {var coordinatorRegistry: UserQueryRunCoordinatorRegistryvar genericHarnessLifecycle: AppHarnessGenericLifecyclevar memoryStore: SQLiteAgentMemoryStore?+ var visionNavigationMode: VisionNavigationModeinit(catalog: LocalAppTaskCatalog = .defaultLocal(),@@ -116,7 +149,8 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {memoryRetriever: SemanticRunMemoryRetriever = SemanticRunMemoryRetriever(),coordinatorRegistry: UserQueryRunCoordinatorRegistry = UserQueryRunCoordinatorRegistry(),genericHarnessLifecycle: AppHarnessGenericLifecycle = AppHarnessGenericLifecycle(),- memoryStore: SQLiteAgentMemoryStore? = .shared+ memoryStore: SQLiteAgentMemoryStore? = .shared,+ visionNavigationMode: VisionNavigationMode = .fromEnvironment()) {self.catalog = catalogself.coordinatorRegistry = coordinatorRegistry@@ -128,6 +162,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {self.memoryRetriever = memoryRetrieverself.genericHarnessLifecycle = genericHarnessLifecycleself.memoryStore = memoryStore+ self.visionNavigationMode = visionNavigationMode}func handleSubmittedCommand(@@ -190,6 +225,19 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {}let coordinator = await coordinatorRegistry.coordinator(for: taskID)++ // Vision-navigation route (env-gated by `DONKEY_VISION_NAV`): ground the typed query+ // directly into on-screen actions against the frontmost app, skipping intent parsing and+ // the AppleScript pipeline. Configurable so we can revert to the standard route below.+ if visionNavigationMode.isEnabled {+ return await handleVisionNavigation(+ command: command,+ traceID: traceID,+ taskID: taskID,+ preparedTurnMetadata: Self.genericHarnessMetadata(preparedTurn: genericPreparedTurn)+ )+ }+let modelInput = Self.modelInput(for: command,context: context,@@ -837,6 +885,199 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {return result}+ // MARK: - Vision Navigation Route (frontmost app, env-gated)++ /// Drives the FRONTMOST user app by vision to satisfy the typed query, end to end: resolve the+ /// frontmost window, ground the query into a screenshot→action loop with `VisionActionDriver`,+ /// and console-log the grounding latency (time-to-first-action and total) for telemetry.+ ///+ /// `@MainActor` because window resolution, the driver, and the per-turn timing closure all run on+ /// the main actor — keeping it isolated lets the timing accumulators stay plain locals.+ @MainActor+ private func handleVisionNavigation(+ command: String,+ traceID: String,+ taskID: String,+ preparedTurnMetadata: [String: String]+ ) async -> UserQueryCommandHandlingResult {+ guard permissionPolicy.allowedCapabilities.contains(.input) else {+ return await failVisionNavigation(+ response: "Vision navigation needs input permission, which isn't granted.",+ reason: "inputNotPermitted",+ appName: "",+ traceID: traceID,+ taskID: taskID,+ preparedTurnMetadata: preparedTurnMetadata+ )+ }+ guard let target = Self.frontmostUserAppTarget() else {+ return await failVisionNavigation(+ response: "I couldn't find a frontmost app window to navigate. Focus the app you want, then type your request.",+ reason: "noFrontmostApp",+ appName: "",+ traceID: traceID,+ taskID: taskID,+ preparedTurnMetadata: preparedTurnMetadata+ )+ }+ let appName = target.appName ?? "the frontmost app"+ let bundleIdentifier = target.bundleIdentifier++ guard let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {+ return await failVisionNavigation(+ response: "The vision backend isn't configured (set DONKEY_WEB_BASE_URL), so I couldn't navigate by vision.",+ reason: "visionBackendUnavailable",+ appName: appName,+ traceID: traceID,+ taskID: taskID,+ preparedTurnMetadata: preparedTurnMetadata+ )+ }+ let backend = DonkeyBackendInferenceClient(configuration: configuration)+ let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(+ forApp: appName,+ bundleIdentifier: bundleIdentifier+ )++ VisionGroundingLog.emit(+ "start traceID=\(traceID) app=\(appName) goal=\"\(command)\""+ )+ let e2eStartMS = Self.uptimeMilliseconds()+ var timeToFirstActionMS: Double?+ let outcome = await VisionActionDriver.drive(+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ goal: command,+ appGuidance: appGuidance,+ backend: backend,+ onTurn: { info in+ // Time-to-first-grounded-action: from query submit to the first on-screen action the+ // model grounded from the screenshot + query. This is the headline grounding number.+ guard timeToFirstActionMS == nil else { return }+ let elapsed = Self.uptimeMilliseconds() - e2eStartMS+ timeToFirstActionMS = elapsed+ VisionGroundingLog.emit(+ "time-to-first-action traceID=\(traceID) app=\(appName) ms=\(Self.formatLatency(elapsed)) action=\(info.action.action)"+ )+ }+ )+ let e2eTotalMS = Self.uptimeMilliseconds() - e2eStartMS+ let averagePerTurnMS = outcome.turns > 0 ? e2eTotalMS / Double(outcome.turns) : 0+ VisionGroundingLog.emit(+ "complete traceID=\(traceID) app=\(appName) completed=\(outcome.completed) reason=\(outcome.reason) turns=\(outcome.turns) e2eTotalMS=\(Self.formatLatency(e2eTotalMS)) timeToFirstActionMS=\(Self.formatLatency(timeToFirstActionMS ?? 0)) avgPerTurnMS=\(Self.formatLatency(averagePerTurnMS))"+ )++ let response = outcome.completed+ ? (outcome.lastNarration ?? "Done.")+ : "I tried navigating \(appName) by vision but couldn't confirm the goal was finished."+ let decision = AppHarnessDecision(+ kind: .respond,+ message: response,+ traceID: traceID,+ metadata: [+ "structuredDecision": "true",+ "router": "visionNavigation",+ "visionNavigation.completed": String(outcome.completed)+ ]+ )+ let result = UserQueryCommandHandlingResult(+ status: outcome.completed ? .completed : .failedSafe,+ threadStatus: outcome.completed ? .completed : .failed,+ decision: decision,+ summary: response,+ traceID: traceID,+ metadata: preparedTurnMetadata.merging([+ "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,+ "appHarness.router": "visionNavigation",+ "visionNavigation.app": appName,+ "visionNavigation.completed": String(outcome.completed),+ "visionNavigation.turns": String(outcome.turns),+ "visionNavigation.reason": outcome.reason,+ "grounding.e2eTotalMS": Self.formatLatency(e2eTotalMS),+ "grounding.timeToFirstActionMS": Self.formatLatency(timeToFirstActionMS ?? 0),+ "grounding.avgPerTurnMS": Self.formatLatency(averagePerTurnMS)+ ]) { _, new in new }+ )+ if outcome.completed {+ _ = await genericHarnessLifecycle.coordinator.complete(+ taskID: taskID,+ reason: "User query vision navigation completed"+ )+ } else {+ _ = await genericHarnessLifecycle.coordinator.failSafe(+ taskID: taskID,+ reason: "User query vision navigation did not confirm completion"+ )+ }+ await coordinatorRegistry.finish(taskID: taskID)+ logHandlingResult(+ result,+ stage: "visionNavigation",+ hint: outcome.completed ? "Navigated \(appName) by vision." : "Vision navigation stopped: \(outcome.reason)."+ )+ return result+ }++ /// Fail-safe exit for the vision-navigation route when it can't even start (no frontmost app,+ /// backend unconfigured, input not permitted). Mirrors the other non-local routes' lifecycle.+ private func failVisionNavigation(+ response: String,+ reason: String,+ appName: String,+ traceID: String,+ taskID: String,+ preparedTurnMetadata: [String: String]+ ) async -> UserQueryCommandHandlingResult {+ VisionGroundingLog.emit("aborted traceID=\(traceID) reason=\(reason) app=\(appName)")+ let decision = AppHarnessDecision(+ kind: .respond,+ message: response,+ traceID: traceID,+ metadata: [+ "structuredDecision": "true",+ "router": "visionNavigation",+ "visionNavigation.abortReason": reason+ ]+ )+ let result = UserQueryCommandHandlingResult(+ status: .failedSafe,+ threadStatus: .failed,+ decision: decision,+ summary: response,+ traceID: traceID,+ metadata: preparedTurnMetadata.merging([+ "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,+ "appHarness.router": "visionNavigation",+ "visionNavigation.abortReason": reason+ ]) { _, new in new }+ )+ _ = await genericHarnessLifecycle.coordinator.failSafe(+ taskID: taskID,+ reason: "User query vision navigation could not start: \(reason)"+ )+ await coordinatorRegistry.finish(taskID: taskID)+ logHandlingResult(result, stage: "visionNavigation", hint: response)+ return result+ }++ /// Resolves the user's frontmost real window for vision navigation. Donkey's own overlay panels+ /// float above layer 0 and are already excluded by the window enumerator, but we also skip our+ /// own process so we never drive Donkey's UI. Candidates come back in front-to-back z-order, so+ /// the first match is the app the user was last working in.+ @MainActor+ private static func frontmostUserAppTarget() -> MacWindowTargetCandidate? {+ let ownProcessID = ProcessInfo.processInfo.processIdentifier+ let ownBundleID = Bundle.main.bundleIdentifier+ return MacWindowResolver().enumerateCandidates().first { candidate in+ if candidate.processID == ownProcessID { return false }+ if let ownBundleID, let candidateBundle = candidate.bundleIdentifier,+ candidateBundle.caseInsensitiveCompare(ownBundleID) == .orderedSame {+ return false+ }+ return true+ }+ }+/// Records whether the AppleScript path actually worked for the target app, so the strategy router/// learns per machine: repeated failures flip an app to the accessibility/vision path, a success/// keeps it on AppleScript. Best-effort — only fires when the run executed an AppleScript actiondiff --git a/apps/Donkey/Sources/DonkeyRuntime/ScreenshotSignature.swift b/apps/Donkey/Sources/DonkeyRuntime/ScreenshotSignature.swiftnew file mode 100644index 00000000..6b2a8b7e--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/ScreenshotSignature.swift@@ -0,0 +1,102 @@+import CoreGraphics+import Foundation+import ImageIO++/// A compact, scale-normalized fingerprint of a screenshot used to decide whether a window+/// changed enough to justify re-running an expensive vision parse.+///+/// We deliberately do NOT use an exact byte hash (e.g. SHA256 of the JPEG): a live window is+/// almost never byte-identical between frames — a blinking caret, the menu-bar clock, cursor+/// motion, or a sub-pixel resize all flip bytes and defeat exact matching, forcing a re-parse+/// every cadence tick. Instead we downscale to a fixed small grayscale grid and compare with a+/// per-pixel noise floor, counting the *fraction* of cells that changed. That ignores trivial+/// churn while still tripping on a localized UI change (a new button, dialog, or panel).+public struct ScreenshotSignature: Equatable, Sendable {+ /// Edge length of the normalized grayscale grid. Fixed so capture-height jitter (e.g. 672 vs+ /// 704px) never matters and the comparison is always defined.+ public static let dimension = 64++ /// Row-major grayscale luma, `dimension * dimension` bytes.+ public let pixels: [UInt8]+ public let dimension: Int++ public init(pixels: [UInt8], dimension: Int) {+ self.pixels = pixels+ self.dimension = dimension+ }++ /// Build a signature from encoded image data (PNG, JPEG, anything ImageIO decodes).+ /// Returns nil if the data cannot be decoded.+ public static func make(+ fromImageData data: Data,+ dimension: Int = dimension+ ) -> ScreenshotSignature? {+ guard let source = CGImageSourceCreateWithData(data as CFData, nil),+ let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else {+ return nil+ }+ return make(from: image, dimension: dimension)+ }++ /// Build a signature by downscaling a CGImage into a fixed grayscale grid.+ public static func make(+ from image: CGImage,+ dimension: Int = dimension+ ) -> ScreenshotSignature? {+ guard dimension > 0 else { return nil }+ let count = dimension * dimension+ var buffer = [UInt8](repeating: 0, count: count)+ let grayspace = CGColorSpaceCreateDeviceGray()+ let built: Bool = buffer.withUnsafeMutableBytes { raw in+ guard let context = CGContext(+ data: raw.baseAddress,+ width: dimension,+ height: dimension,+ bitsPerComponent: 8,+ bytesPerRow: dimension,+ space: grayspace,+ bitmapInfo: CGImageAlphaInfo.none.rawValue+ ) else {+ return false+ }+ // Low interpolation averages source pixels into each cell, smoothing out sub-pixel+ // noise and antialiasing flicker that we want to ignore.+ context.interpolationQuality = .low+ context.draw(image, in: CGRect(x: 0, y: 0, width: dimension, height: dimension))+ return true+ }+ guard built else { return nil }+ return ScreenshotSignature(pixels: buffer, dimension: dimension)+ }++ /// Fraction (0...1) of cells whose absolute luma delta exceeds `perPixelNoise`.+ ///+ /// `perPixelNoise` absorbs small per-cell variation (compression artifacts, antialiasing,+ /// a flickering caret). Returns 1 (treated as fully changed) when the signatures are not+ /// directly comparable, so callers conservatively re-parse.+ public func changedFraction(+ from other: ScreenshotSignature,+ perPixelNoise: UInt8 = 12+ ) -> Double {+ guard dimension == other.dimension,+ pixels.count == other.pixels.count,+ !pixels.isEmpty else {+ return 1+ }+ let noise = Int(perPixelNoise)+ var changed = 0+ for index in pixels.indices where abs(Int(pixels[index]) - Int(other.pixels[index])) > noise {+ changed += 1+ }+ return Double(changed) / Double(pixels.count)+ }++ /// Whether `other` differs enough from this signature to warrant re-processing.+ public func changed(+ from other: ScreenshotSignature,+ perPixelNoise: UInt8 = 12,+ changedFractionThreshold: Double = 0.012+ ) -> Bool {+ changedFraction(from: other, perPixelNoise: perPixelNoise) > changedFractionThreshold+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swiftindex 0c8dbbed..e0115d18 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DebugUIInspectionTests.swift@@ -167,6 +167,35 @@ struct DebugUIInspectionTests {}}+ @Test+ func trackerWithoutCarryForwardClearsPreviousFrameBeforeRenderingNext() {+ // Mirrors the debug overlay's tracker config (appearanceThreshold 1, disappearanceTolerance 0):+ // vision reassigns element IDs every parse, so any carry-forward leaves stale boxes stacked on+ // screen. With no carry-forward, the previous overlay is fully replaced by the next parse.+ var tracker = DebugUIElementTracker(+ appearanceThreshold: 1,+ disappearanceTolerance: 0,+ movementConfirmationSamples: 1+ )+ let first = tracker.update(+ with: DebugUIInspectionFrame(elements: [+ element(id: "ai-1-a", label: "Coldplay", x: 10, y: 20),+ element(id: "ai-1-b", label: "Notifications", x: 100, y: 20)+ ]),+ renderNewElementsImmediately: true+ )+ #expect(Set(first.elements.map(\.id)) == ["ai-1-a", "ai-1-b"])++ // Next parse: brand-new IDs, no semantic overlap. The old boxes must not linger.+ let second = tracker.update(+ with: DebugUIInspectionFrame(elements: [+ element(id: "ai-2-c", label: "Search", x: 300, y: 400)+ ]),+ renderNewElementsImmediately: true+ )+ #expect(second.elements.map(\.id) == ["ai-2-c"])+ }+@Testfunc trackerPreservesStableIDForMovedSemanticMatch() {var tracker = DebugUIElementTracker()diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ScreenshotSignatureTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ScreenshotSignatureTests.swiftnew file mode 100644index 00000000..fb19901b--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ScreenshotSignatureTests.swift@@ -0,0 +1,109 @@+import CoreGraphics+@testable import DonkeyRuntime+import Foundation+import ImageIO+import Testing+import UniformTypeIdentifiers++@Suite+struct ScreenshotSignatureTests {+ /// Draw a solid-color image, optionally painting a filled rect on top so we can simulate a+ /// localized UI change of a controllable size.+ private func image(+ width: Int,+ height: Int,+ background: CGFloat = 0.5,+ patch: CGRect? = nil,+ patchColor: CGFloat = 0.0+ ) -> CGImage {+ let space = CGColorSpaceCreateDeviceGray()+ let context = CGContext(+ data: nil,+ width: width,+ height: height,+ bitsPerComponent: 8,+ bytesPerRow: width,+ space: space,+ bitmapInfo: CGImageAlphaInfo.none.rawValue+ )!+ context.setFillColor(gray: background, alpha: 1)+ context.fill(CGRect(x: 0, y: 0, width: width, height: height))+ if let patch {+ context.setFillColor(gray: patchColor, alpha: 1)+ context.fill(patch)+ }+ return context.makeImage()!+ }++ @Test("identical frames report zero change")+ func identicalFramesUnchanged() {+ let a = ScreenshotSignature.make(from: image(width: 400, height: 300))!+ let b = ScreenshotSignature.make(from: image(width: 400, height: 300))!+ #expect(a.changedFraction(from: b) == 0)+ #expect(!a.changed(from: b))+ }++ @Test("capture-height jitter on identical content stays below threshold")+ func scaleJitterStaysUnchanged() {+ // Same content, different capture heights (the 672 vs 704 case from the logs).+ let a = ScreenshotSignature.make(from: image(width: 1_280, height: 672))!+ let b = ScreenshotSignature.make(from: image(width: 1_280, height: 704))!+ #expect(!a.changed(from: b))+ }++ @Test("a tiny localized change is ignored, a large one is caught")+ func thresholdSeparatesNoiseFromRealChange() {+ let base = ScreenshotSignature.make(from: image(width: 640, height: 480))!++ // ~1px-ish blip in a 640x480 frame — like a blinking caret. Below threshold.+ let blip = ScreenshotSignature.make(+ from: image(width: 640, height: 480, patch: CGRect(x: 10, y: 10, width: 4, height: 12))+ )!+ #expect(!base.changed(from: blip))++ // A large panel appearing covers a big fraction of the frame — above threshold.+ let panel = ScreenshotSignature.make(+ from: image(width: 640, height: 480, patch: CGRect(x: 0, y: 0, width: 320, height: 480))+ )!+ #expect(base.changed(from: panel))+ }++ @Test("decodes encoded image data")+ func decodesEncodedData() throws {+ let cg = image(width: 200, height: 200)+ let data = NSMutableData()+ let dest = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)!+ CGImageDestinationAddImage(dest, cg, nil)+ #expect(CGImageDestinationFinalize(dest))+ let signature = ScreenshotSignature.make(fromImageData: data as Data)+ #expect(signature != nil)+ }++ // MARK: - Live capture (opt-in)++ /// Runs against real screen captures when paths are provided, e.g. captures of the Spotify+ /// window. Set env vars to two frames that should read as "unchanged" (e.g. progress bar+ /// advancing during playback) and, optionally, a third "changed" frame (a different view).+ /// SCREENSHOT_SIG_UNCHANGED_A, SCREENSHOT_SIG_UNCHANGED_B, SCREENSHOT_SIG_CHANGED+ @Test("real captures: small churn skips, real change re-parses")+ func liveCaptureBehaves() throws {+ let env = ProcessInfo.processInfo.environment+ guard let pathA = env["SCREENSHOT_SIG_UNCHANGED_A"],+ let pathB = env["SCREENSHOT_SIG_UNCHANGED_B"] else {+ return // not provided — skip+ }+ let a = try #require(ScreenshotSignature.make(fromImageData: Data(contentsOf: URL(fileURLWithPath: pathA))))+ let b = try #require(ScreenshotSignature.make(fromImageData: Data(contentsOf: URL(fileURLWithPath: pathB))))++ let churn = a.changedFraction(from: b)+ print("[ScreenshotSignature] unchanged-pair changedFraction=\(churn)")+ #expect(!a.changed(from: b), "near-identical frames should be treated as unchanged (was \(churn))")++ if let pathC = env["SCREENSHOT_SIG_CHANGED"] {+ let c = try #require(ScreenshotSignature.make(fromImageData: Data(contentsOf: URL(fileURLWithPath: pathC))))+ let delta = a.changedFraction(from: c)+ print("[ScreenshotSignature] changed-pair changedFraction=\(delta)")+ #expect(a.changed(from: c), "a different view should trip a re-parse (was \(delta))")+ }+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionNavigationModeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionNavigationModeTests.swiftnew file mode 100644index 00000000..1e8851fb--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionNavigationModeTests.swift@@ -0,0 +1,30 @@+@testable import Donkey+import Testing++/// Unit coverage for the configurable, env-gated vision-navigation route flag. The route itself+/// drives real input/screenshots (covered by the live smoke pattern), but the on/off parsing is+/// pure and must stay reliable so the path is easy to enable and revert.+@Suite+struct VisionNavigationModeTests {+ @Test+ func enabledForTruthyValues() {+ for value in ["1", "true", "TRUE", "Yes", "on"] {+ let mode = VisionNavigationMode.fromEnvironment(["DONKEY_VISION_NAV": value])+ #expect(mode.isEnabled, "expected \"\(value)\" to enable vision navigation")+ }+ }++ @Test+ func disabledByDefaultAndForFalsyValues() {+ #expect(VisionNavigationMode.fromEnvironment([:]).isEnabled == false)+ for value in ["", "0", "false", "off", "no", " "] {+ let mode = VisionNavigationMode.fromEnvironment(["DONKEY_VISION_NAV": value])+ #expect(mode.isEnabled == false, "expected \"\(value)\" to leave vision navigation off")+ }+ }++ @Test+ func toleratesSurroundingWhitespaceAndCase() {+ #expect(VisionNavigationMode.fromEnvironment(["DONKEY_VISION_NAV": " On "]).isEnabled)+ }+}diff --git a/plans/master-plan.md b/plans/master-plan.mdindex af677b2a..da1555b7 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -27,6 +27,14 @@ even when there are no active tasks.surface, not a real product/testing UI. We need a better way to view andevaluate raw vision output (boxes, labels, per-window parse latency, hit/skip onthe local image-hash cache) while iterating. Scope/shape TBD.+ - Iteration affordance now in place: an env-gated "vision navigation" route+ (`DONKEY_VISION_NAV=1`, `VisionNavigationMode` in `UserQueryCommandHandler`)+ sends a typed query straight to `VisionActionDriver` against the frontmost+ app, so you can type one request after another and watch it navigate. It+ console-logs end-to-end grounding latency (time-to-first-action and total)+ under the `vision-grounding` logger / `[grounding-e2e]` stdout prefix. The+ flag is configurable/revertible; this is a dev-test path, not yet a product+ surface.## Invariants