Open source CapCut alternative.
TypeScript
refactor(app): tie vision work to a conversation, on demand
David Lec0093ab36db9
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swiftindex 8a4d96b0..187f66e3 100644--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift@@ -15,7 +15,6 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {private var manualPermissionSetupController: MacPermissionSetupWindowController?private var overlayController: UserQueryOverlayController?private var uiUnderstandingCoordinator: UIUnderstandingCoordinator?- private var frontmostVisionWarmCache: FrontmostVisionWarmCache?/// Mirrors the auth coordinator's session phase into the overlay's `needsLogin`, so the notch/// flips to/from the login call-to-action as the session is established or expires.private var authStateCancellable: AnyCancellable?@@ -84,7 +83,6 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {andEventID: AEEventID(kAEGetURL))overlayController?.stop()- frontmostVisionWarmCache?.stop()uiUnderstandingCoordinator?.stop()}@@ -176,47 +174,36 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {// while the overlay surfaces are live, instead of receding into an accessory agent.NSApp.setActivationPolicy(.regular)- // The UI-understanding engine (AX + AI parse + per-window cache + background warming) runs in- // every build and feeds the agent. Only the visual overlay is gated: debug builds inject the- // AppKit overlay renderer (shown when the dev-overlay config turns it on), while production- // parses headlessly through a no-op renderer.+ // The UI-understanding engine exists only to draw the developer debug overlay; the agent does+ // not read from it. It parses the screen solely to render that overlay, so it is built only in+ // debug-overlay builds and never in production. The agent's only vision source is the on-demand+ // `vision.capture` tool inside a live run.#if DONKEY_DEBUG_OVERLAYlet uiUnderstandingCoordinator = UIUnderstandingCoordinator(overlayController: DebugUIInspectionOverlayController(),rendersOverlay: true)- #else- let uiUnderstandingCoordinator = UIUnderstandingCoordinator(- rendersOverlay: false- )- #endifself.uiUnderstandingCoordinator = uiUnderstandingCoordinator+ #endif- // Keep ParsedVisionStore warm: watch the frontmost window and re-parse on big changes, so a- // typed vision command reuses a fresh parse instead of paying for one inline. No-ops when the- // vision backend isn't configured.- let frontmostVisionWarmCache = FrontmostVisionWarmCache.fromEnvironment()- self.frontmostVisionWarmCache = frontmostVisionWarmCache-- // Start the always-on backend loops only while signed in; the phase observer above suspends and- // resumes them as the session changes (an expired session must not keep them issuing 401s).+ // Start the debug overlay engine (if any) only while signed in; the phase observer above stops+ // and restarts it as the session changes (its parse pass would otherwise 401 while signed out).applySessionState(isSignedIn: authCoordinator?.isAuthenticated == true, model: model)}- /// Drive the process-wide session gate and the always-on backend loops from the auth phase. Signed- /// out: close the gate (every backend call short-circuits to `.authenticationRequired` with no- /// network round trip) and fully suspend the warm cache, UI-understanding engine, and Live session,- /// so a logged-out app stops issuing guaranteed-401 requests. Signed in: reopen the gate and restart- /// them. Idempotent — `start()`/`stop()` on each loop are safe to call repeatedly.+ /// Drive the process-wide session gate, the debug overlay engine, and the Live session from the auth+ /// phase. Signed out: close the gate (every backend call short-circuits to `.authenticationRequired`+ /// with no network round trip) and suspend the overlay engine and Live session, so a logged-out app+ /// stops issuing guaranteed-401 requests. Signed in: reopen the gate and restart them. Idempotent —+ /// `start()`/`stop()` are safe to call repeatedly, and the coordinator is nil outside debug-overlay+ /// builds.private func applySessionState(isSignedIn: Bool, model: UserQueryOverlayModel?) {BackendSessionGate.shared.update(isAuthenticated: isSignedIn)if isSignedIn {uiUnderstandingCoordinator?.start()- frontmostVisionWarmCache?.start()model?.resumeLiveSession()} else {uiUnderstandingCoordinator?.stop()- frontmostVisionWarmCache?.stop()model?.suspendLiveSession()}}@@ -271,8 +258,6 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {/// `startAuthenticatedAppSurfaces()` guards on these being nil, so they must be reset here.private func teardownAuthenticatedSurfaces() {authStateCancellable = nil- frontmostVisionWarmCache?.stop()- frontmostVisionWarmCache = niluiUnderstandingCoordinator?.stop()uiUnderstandingCoordinator = niloverlayController?.stop()diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swiftindex 5613bade..0fdf4ab7 100644--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swift+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swift@@ -20,14 +20,15 @@ private enum RemoteAIEngine {case screenshotParse}-/// Always-on engine that turns the user's windows into structured UI understanding (accessibility +-/// vision elements) for the agent to reason over. It runs in every build; only the visual overlay is-/// a debug concern, injected through `DebugUIInspectionOverlayRendering`.+/// Debug-overlay engine that turns the user's windows into structured UI understanding (accessibility ++/// vision elements) purely to draw the developer overlay. It is decoupled from the agent: it never feeds+/// the agent's vision path and the agent never reads from it. It parses only while the overlay is active,+/// and exists only in debug-overlay builds — the agent's own vision is the on-demand `vision.capture`+/// tool, run-scoped and separate from this.@MainActorfinal class UIUnderstandingCoordinator {- // The real overlay renderer: AppKit in debug builds, a no-op in production. Drawing is routed- // through the gated `overlayController` accessor below so the engine keeps parsing and caching- // for the agent even while the overlay is off.+ // The real overlay renderer, injected in debug-overlay builds. Drawing is routed through the gated+ // `overlayController` accessor below; when the overlay is off the engine idles entirely.private let realOverlayController: any DebugUIInspectionOverlayRenderingprivate let noopOverlayController: any DebugUIInspectionOverlayRendering =NoopDebugUIInspectionOverlayRenderer()@@ -51,8 +52,6 @@ final class UIUnderstandingCoordinator {private var visionBackoff: [UInt32: VisionBackoff] = [:]private var lastActiveWindowIDs: [UInt32: Set<UInt32>] = [:]private var windowElementCache: [UInt32: [DebugUIElement]] = [:]- private var isWarmingBackground = false- private var lastBackgroundWarmCount: Int?private let remoteAIEngine: RemoteAIEngine = .visionprivate struct VisionBackoff {@@ -64,12 +63,10 @@ final class UIUnderstandingCoordinator {private var notificationObservers: [NSObjectProtocol] = []private var movementEventMonitors: [Any] = []private var currentConfig: DebugUIOverlayConfiguration = .disabled- // The understanding engine always parses and publishes — the agent reads the shared store- // regardless of any overlay. Only the visible overlay is gated: it draws when this instance- // renders one (debug builds) and the dev-overlay config turns it on.+ // The engine parses only while the overlay is active: this instance can render one (debug-overlay+ // builds) and the dev-overlay config turns it on. Off → the refresh pass idles and nothing is parsed.private var overlayActive: Bool { rendersOverlay && currentConfig.enabled }- // Routes every render/close to the real renderer only while the overlay is active; otherwise a- // no-op renderer, so engine bookkeeping (caching for the agent) runs without drawing anything.+ // Routes every render/close to the real renderer while the overlay is active; otherwise a no-op.private var overlayController: any DebugUIInspectionOverlayRendering {overlayActive ? realOverlayController : noopOverlayController}@@ -77,11 +74,9 @@ final class UIUnderstandingCoordinator {private var isRefreshingActiveAccessibility = false/// - Parameters:- /// - overlayController: where parsed frames are painted while the overlay is active. Production- /// injects a no-op renderer; the engine parses and caches regardless of what is drawn.- /// - rendersOverlay: whether this instance can drive a visible overlay. Render-only smoothing- /// work (the high-frequency active-window accessibility pass) is skipped when false, and the- /// overlay never draws. The engine still runs in every build.+ /// - overlayController: where parsed frames are painted while the overlay is active.+ /// - rendersOverlay: whether this instance can drive a visible overlay. When false the engine+ /// never parses or draws (it has nothing to render); only debug-overlay builds pass true.init(configURL: URL? = nil,overlayController: any DebugUIInspectionOverlayRendering = NoopDebugUIInspectionOverlayRenderer(),@@ -127,7 +122,6 @@ final class UIUnderstandingCoordinator {lastActiveWindowIDs.removeAll()windowElementCache.removeAll()isAnalyzing = false- isWarmingBackground = falseisRefreshingActiveAccessibility = falsecurrentConfig = .disabled}@@ -238,17 +232,13 @@ final class UIUnderstandingCoordinator {private func refresh(force: Bool = false) {reloadConfigAndReschedule()- // The engine runs in every build, gated only by sign-in: the AI parse pass hits the hosted- // backend, which would just 401 while signed out, so it idles until sign-in restores it (the- // app delegate also stops this coordinator on sign-out). The overlay is gated separately.+ // The hosted parse would 401 while signed out, so idle until sign-in restores it (the app+ // delegate also stops this coordinator on sign-out).guard BackendSessionGate.shared.isAuthenticated else { return }- // Only keep understanding warm around real Donkey use. With no task running and no recent- // interaction, nothing reads the store, so skip the whole capture/parse pass (active-window- // vision and background warming both) instead of draining the backend while the app idles.- // The next command stamps engagement before its first capture, which re-parses inline. The- // dev overlay is an explicit opt-in the developer is actively watching, so it keeps rendering- // live; production never renders an overlay and so always idles when Donkey isn't in use.- guard overlayActive || DonkeyEngagement.shared.isEngaged() else { return }+ // This engine exists only to draw the developer debug overlay. It parses solely while that+ // overlay is active — it never warms anything for the agent, whose only vision source is the+ // on-demand `vision.capture` tool inside a live run.+ guard overlayActive else { return }guard !isAnalyzing else {UIUnderstandingLog.overlay.debug("debug inspection skipped refresh because analysis is already running")return@@ -270,10 +260,6 @@ final class UIUnderstandingCoordinator {}}}-- // Warm background windows' overlays off the critical path so switching to any window is- // instant. This runs on its own single-flight task and does not block active rendering.- scheduleBackgroundWarm()}private func analyzeVisibleScreens(force: Bool) async throws {@@ -810,7 +796,6 @@ final class UIUnderstandingCoordinator {lastVisionElementCounts[windowID] = parsedElements.countvisionBackoff[windowID] = nilrenderRemoteAIFrame(stage: "vision", updatesFingerprint: false)- publishUnderstanding(for: capture.target, signature: signature)} catch {let backoff = Self.nextVisionBackoff(after: visionBackoff[windowID])visionBackoff[windowID] = backoff@@ -893,201 +878,6 @@ final class UIUnderstandingCoordinator {}}- /// Kick a single-flight background pass that pre-extracts and caches understanding for windows- /// the user is not currently looking at, so switching to any of them (or the agent acting on one)- /// is instant. Runs whenever the engine does; only meaningful while the active window is handled- /// live, otherwise every window is already analyzed.- private func scheduleBackgroundWarm() {- guard currentConfig.activeWindowOnly,- remoteAIEngine == .vision,- !isWarmingBackground- else {- return- }- isWarmingBackground = true- Task { @MainActor in- defer { self.isWarmingBackground = false }- guard let screens = try? self.screenSurfaces(scope: self.currentConfig.screenScope) else {- return- }- let activeWindowIDs = Set(self.visibleOverlayTargets(on: screens).map(\.windowID))- let backgroundWarmCount = self.backgroundWarmTargets(- on: screens,- excluding: activeWindowIDs- ).count- // Only log when the count changes so the ~1Hz warm pass doesn't spam an identical line.- if self.lastBackgroundWarmCount != backgroundWarmCount {- self.lastBackgroundWarmCount = backgroundWarmCount- UIUnderstandingLog.overlay.info(- "debug inspection background warm windows=\(backgroundWarmCount, privacy: .public)"- )- }- // Warm background windows that have no cached accessibility yet — the scan runs off the- // main actor since a cold first-launch walk is slow; vision is a slow network parse, so- // warm just one window per pass.- await self.warmBackgroundAccessibility(screens: screens, excluding: activeWindowIDs)- await self.warmNextBackgroundVisionWindow(screens: screens, excluding: activeWindowIDs)- }- }-- /// Cap how many background windows we ever warm, so a desktop full of windows does not trigger a- /// flood of captures and vision parses. The frontmost background windows (the ones most likely to- /// be switched to) are warmed first.- private static let backgroundWarmWindowCap = 5-- /// Candidate windows eligible for background warming: every visible, allowed window except the- /// active one(s) the live path already handles, capped to `backgroundWarmWindowCap`. Unlike- /// `visibleOverlayTargets` this ignores the frontmost/focused requirement so background windows- /// are included.- private func backgroundWarmTargets(- on screens: [DebugUIScreenSurface],- excluding excludedWindowIDs: Set<UInt32>- ) -> [MacWindowTargetCandidate] {- let bundleFilters = Set(currentConfig.targetBundleIdentifiers.map(Self.normalizedTargetFilter))- let appNameFilters = Set(currentConfig.targetAppNames.map(Self.normalizedTargetFilter))- let eligible = windowResolver.enumerateCandidates().filter { target in- target.isVisible- && target.isOnScreen- && !excludedWindowIDs.contains(target.windowID)- && target.safetyAssessment.status == .allowed- && !target.isIPhoneMirroring- && target.processID != ProcessInfo.processInfo.processIdentifier- && Self.matchesTargetFilter(- target,- bundleFilters: bundleFilters,- appNameFilters: appNameFilters- )- && screens.contains { Self.intersects(target.bounds, $0.captureFrame) }- }- return Array(eligible.prefix(Self.backgroundWarmWindowCap))- }-- private func hasCachedAccessibility(forWindow windowID: UInt32) -> Bool {- windowElementCache[windowID]?.contains(where: Self.isAccessibilityEvidence) ?? false- }-- /// Run one all-windows accessibility scan and cache the accessibility boxes for background- /// windows that have none yet. Skips entirely once every background window is covered so we are- /// not walking every app's accessibility tree on a loop.- private func warmBackgroundAccessibility(- screens: [DebugUIScreenSurface],- excluding activeWindowIDs: Set<UInt32>- ) async {- let pending = backgroundWarmTargets(on: screens, excluding: activeWindowIDs)- .filter { !hasCachedAccessibility(forWindow: $0.windowID) }- guard !pending.isEmpty else { return }- let pendingWindowIDs = Set(pending.map(\.windowID))-- // The accessibility tree walk is slow cross-process IPC — a cold first-launch scan can run- // long enough to beachball if it happens on the main actor. Snapshot the Sendable inputs and- // run `inspect` off the main actor, then resume here to merge (AX reads are thread-safe and- // the service and its results are Sendable). The `isWarmingBackground` guard around this pass- // stays held across the await, so scans never overlap.- let service = accessibilityInspectionService- let scope = currentConfig.screenScope- let minConfidence = currentConfig.minConfidence- let targetBundleIdentifiers = currentConfig.targetBundleIdentifiers- let targetAppNames = currentConfig.targetAppNames-- let results: [DebugUIAccessibilityInspectionResult]- do {- results = try await Task.detached(priority: .utility) {- try service.inspect(- scope: scope,- minConfidence: minConfidence,- frontmostOnly: false,- focusedOnly: false,- targetBundleIdentifiers: targetBundleIdentifiers,- targetAppNames: targetAppNames- )- }.value- } catch {- UIUnderstandingLog.overlay.debug(- "debug inspection background accessibility warm skipped error=\(String(describing: error), privacy: .public)"- )- return- }-- var accessibilityByWindow: [UInt32: [DebugUIElement]] = [:]- for result in results {- let frame = Self.frameInScreenPointSpace(result.frame, snapshot: result.snapshot)- for element in frame.elements {- guard let windowID = Self.windowID(for: element),- pendingWindowIDs.contains(windowID)- else {- continue- }- accessibilityByWindow[windowID, default: []].append(element)- }- }- guard !accessibilityByWindow.isEmpty else { return }- for (windowID, accessibilityElements) in accessibilityByWindow {- let existingAI = (windowElementCache[windowID] ?? []).filter { !Self.isAccessibilityEvidence($0) }- windowElementCache[windowID] = accessibilityElements + existingAI- }- UIUnderstandingLog.overlay.info(- "debug inspection warmed background accessibility windows=\(accessibilityByWindow.count, privacy: .public)"- )- }-- /// Vision-parse one not-yet-parsed background window and cache its boxes. One per pass keeps the- /// parser from being hammered; the per-window signature marks it done so we do not re-parse it.- private func warmNextBackgroundVisionWindow(- screens: [DebugUIScreenSurface],- excluding activeWindowIDs: Set<UInt32>- ) async {- let candidate = backgroundWarmTargets(on: screens, excluding: activeWindowIDs)- .first { target in- lastVisionSignatures[target.windowID] == nil- && (visionBackoff[target.windowID].map { Date() >= $0.nextAttempt } ?? true)- }- guard let target = candidate,- let screen = screens.first(where: { Self.intersects(target.bounds, $0.captureFrame) })- else {- return- }- let client: DonkeyBackendInferenceClient- do {- client = try backendInferenceClient()- } catch {- return- }-- let windowID = target.windowID- do {- let screenshot = try await windowScreenshotCapturer.capture(target: target)- let signature = ScreenshotSignature.make(fromImageData: screenshot.pngData)- let compressed = Self.compressedRemoteAIImage(from: screenshot)- let requestStart = Date()- let response = try await client.parseScreenshotVision(imageData: compressed.data)- let elapsedMs = Int(Date().timeIntervalSince(requestStart) * 1000)- let parsedElements = VisionParseDebugUIOverlayMapper.frame(- from: response,- target: target,- screenFrame: screen.captureFrame,- minConfidence: currentConfig.minConfidence- ).elements- // Keep whatever accessibility we already cached for this window and replace its vision.- let existingAccessibility = (windowElementCache[windowID] ?? []).filter(Self.isAccessibilityEvidence)- windowElementCache[windowID] = existingAccessibility + parsedElements- if let signature {- lastVisionSignatures[windowID] = signature- }- lastVisionElementCounts[windowID] = parsedElements.count- visionBackoff[windowID] = nil- publishUnderstanding(for: target, signature: signature)- UIUnderstandingLog.overlay.info(- "debug inspection warmed background vision windowID=\(windowID, privacy: .public) elapsedMs=\(elapsedMs, privacy: .public) mappedElements=\(parsedElements.count, privacy: .public)"- )- } catch {- let backoff = Self.nextVisionBackoff(after: visionBackoff[windowID])- visionBackoff[windowID] = backoff- UIUnderstandingLog.overlay.error(- "debug inspection background vision warm failed windowID=\(windowID, privacy: .public) failureStreak=\(backoff.failureStreak, privacy: .public) error=\(String(describing: error), privacy: .public)"- )- }- }-private func accessibilityFramesForRemoteAIFusion() -> [UInt32: DebugUIInspectionFrame] {do {let results = try accessibilityInspectionService.inspect(@@ -1762,46 +1552,6 @@ final class UIUnderstandingCoordinator {}}- /// Publish this window's fused accessibility + vision understanding to the shared store that the- /// agent reads when it decides what to act on. Elements are stored in window-local point space,- /// with the window's point size as the image size — exactly the geometry the agent's tools map- /// back to a screen point, so a warmed background window is instantly actionable without a parse.- private func publishUnderstanding(for target: MacWindowTargetCandidate, signature: ScreenshotSignature?) {- guard let signature else { return }- let imageWidth = Int(target.bounds.width.rounded())- let imageHeight = Int(target.bounds.height.rounded())- guard imageWidth > 0, imageHeight > 0 else { return }-- let elements = (windowElementCache[target.windowID] ?? []).compactMap { element -> DebugUIElement? in- guard let local = Self.localBounds(for: element) else { return nil }- return DebugUIElement(- id: element.id,- type: element.type,- label: element.label,- description: element.description,- bbox: DebugUIBoundingBox(x: local.x, y: local.y, width: local.width, height: local.height),- confidence: element.confidence,- visualStyle: element.visualStyle,- metadata: element.metadata- )- }- guard !elements.isEmpty else { return }-- let appKey = (target.bundleIdentifier?.isEmpty == false ? target.bundleIdentifier : nil)- ?? target.appName- ?? ""- WindowUIUnderstandingStore.shared.store(- appKey: appKey,- entry: WindowUIUnderstandingStore.Entry(- signature: signature,- elements: elements,- imagePixelWidth: imageWidth,- imagePixelHeight: imageHeight,- capturedAtUptimeMS: ProcessInfo.processInfo.systemUptime * 1_000- )- )- }-/// Pull cached elements for the given windows, reprojected onto the window's current on-screen/// position so a window that moved while unfocused still lines up. Reprojection with no source/// screen places each element from its stored window-local bounds against the window's currentdiff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 21006ebb..73098399 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -211,9 +211,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {_ command: String,context: UserQueryCommandContext?) async -> UserQueryCommandHandlingResult {- // A submitted command is a direct Donkey interaction: open the engagement window so the vision- // warm caches start (and stay) warm around this turn instead of only firing while idle.- DonkeyEngagement.shared.noteInteraction()let traceID = "user-query-\(UUID().uuidString)"let conversationID = context?.conversation.id ?? traceIDlogSubmittedCommand(command, traceID: traceID, conversationID: conversationID, context: context)@@ -504,8 +501,13 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// it returns nil — or when the call outlives its deadline — so a backend hiccup never// dead-ends or silently stalls the run.let understandingBoundary = HostedHarnessRequestUnderstanding(backend: backend, trace: trace)+ let skillSelectionCatalog = BuiltInLocalAppSkillPacks.skillSelectionCatalog()let understanding = await AIDeadline.race(seconds: Self.understandingTimeoutSeconds) {- await understandingBoundary.understand(command: command, frontmostAppName: frontmostAppName)+ await understandingBoundary.understand(+ command: command,+ frontmostAppName: frontmostAppName,+ skillCatalog: skillSelectionCatalog+ )}// TWO-TIER SPLIT. A turn the understanding boundary typed `.converse` (a greeting, a thanks, a@@ -589,6 +591,21 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {bundleIdentifier: bundleIdentifier)+ // Preload the full guides for the capability skills the understanding boundary picked for this task+ // (`relevantSkillIDs`) — the same "preload the right playbook" treatment app skills get via+ // appGuidance, generalized so a media/pdf/data task arrives with its skill in hand instead of+ // depending on the planner to discover and load it. Skip the drive-target app's own skill (already+ // in appGuidance) and cap the count so the prompt stays bounded; anything else stays loadable from+ // the catalog via skill.load.+ let appSkillID = BuiltInLocalAppSkillPacks.appSkillDescriptor(+ forApp: appName,+ bundleIdentifier: bundleIdentifier+ )?.id.lowercased()+ let preloadedSkillGuides: [String] = (understanding?.relevantSkillIDs ?? [])+ .filter { $0.lowercased() != appSkillID }+ .prefix(2)+ .compactMap { BuiltInLocalAppSkillPacks.skillGuidance(forID: $0) }+// Drive the frontmost app through the GENERIC HARNESS LOOP: the harness re-plans after every// observation, consulting `HostedHarnessStepPlanner` (the model boundary) to pick the next// tool. The planner chooses how to SEE (ax.observe vs. vision.capture) and how to ACT (ax.click,@@ -712,6 +729,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {appGuidance: appGuidance,understanding: understanding,skillCatalog: Self.installedSkillCatalog(),+ preloadedSkillGuides: preloadedSkillGuides,recalledLessons: recalledLessons,trace: trace,openWindows: {@@ -740,12 +758,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {"start traceID=\(traceID) app=\(appName) goal=\"\(command)\"")let e2eStartMS = Self.uptimeMilliseconds()- // Suspend the warm-cache monitor for the whole drive so it never races us writing the same- // app's parse. The run between these calls has no early exit, so resume always pairs with it.- VisionWarmCacheActivity.shared.suspend()- // Keep Donkey "engaged" for the whole run so the understanding warm pass stays alive however- // long the task takes; pairs with `endRun` below (this stretch has no early exit).- DonkeyEngagement.shared.beginRun()// Realtime per-step feedback: narrate every step through the spawn cursor's label (the// planner's one-line reason, falling back to the tool's own summary), and after each step that// physically moved the pointer (a click), animate the overlay cursor traveling to that exact@@ -845,10 +857,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {if holdsForegroundFocus {await foregroundFocusGate.release()}- VisionWarmCacheActivity.shared.resume()- // Run finished: drop the active-run hold and stamp an interaction so warming lingers briefly- // for a follow-up command before idling out.- DonkeyEngagement.shared.endRun()let finalTask = await genericHarnessLifecycle.coordinator.agent(id: agentID)let finalStatus = finalTask?.status@@ -1475,7 +1483,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {: " · skill_run: " + skill.scripts.map { script inscript.purpose.isEmpty ? script.id : "\(script.id) (\(script.purpose))"}.joined(separator: ", ")- return " - \(skill.id) — \(skill.description)\(apps)\(scripts)"+ return " - \(skill.id) — \(skill.summary)\(apps)\(scripts)"}return lines.joined(separator: "\n")}diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyEngagement.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyEngagement.swiftdeleted file mode 100644index 8f37ba7b..00000000--- a/apps/Donkey/Sources/DonkeyAI/DonkeyEngagement.swift+++ /dev/null@@ -1,55 +0,0 @@-import Foundation--/// Process-wide signal for whether the user is actually engaging Donkey right now. The always-on-/// vision warm caches consult this so they only spend on parses around real Donkey use instead of-/// burning the backend the entire time the app sits open and idle.-///-/// "Engaged" means either a harness run is in flight, or the last interaction (a submitted command, or-/// a just-finished run) landed within the engagement window. When neither holds, the warm caches stop-/// parsing — the first command after a quiet period pays one inline parse, which is exactly when the-/// spend is warranted.-public final class DonkeyEngagement: @unchecked Sendable {- public static let shared = DonkeyEngagement()-- /// How long after the last interaction the warm caches keep running before idling out. Long enough- /// to cover a quick follow-up without re-warming from cold, short enough that walking away stops the- /// spend within about a minute.- public static let defaultEngagementWindowMS: Double = 60_000-- private let lock = NSLock()- private var activeRunDepth = 0- private var lastInteractionUptimeMS: Double?- private let uptimeMS: @Sendable () -> Double-- public init(uptimeMS: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime * 1_000 }) {- self.uptimeMS = uptimeMS- }-- /// Record a direct user interaction with Donkey (a submitted command). Opens the engagement window.- public func noteInteraction() {- lock.lock(); lastInteractionUptimeMS = uptimeMS(); lock.unlock()- }-- /// Bracket an active harness run. While depth > 0 the user is engaged unconditionally so warming- /// keeps the understanding store fresh for the whole task, however long it runs.- public func beginRun() {- lock.lock(); activeRunDepth += 1; lock.unlock()- }-- /// Pairs with `beginRun`. Stamps an interaction on the way out so the window stays open briefly- /// after the run for a follow-up command before warming idles out.- public func endRun() {- lock.lock()- activeRunDepth = max(0, activeRunDepth - 1)- lastInteractionUptimeMS = uptimeMS()- lock.unlock()- }-- /// True when a run is in flight or the last interaction is within `windowMS`.- public func isEngaged(windowMS: Double = DonkeyEngagement.defaultEngagementWindowMS) -> Bool {- lock.lock(); defer { lock.unlock() }- if activeRunDepth > 0 { return true }- guard let last = lastInteractionUptimeMS else { return false }- return uptimeMS() - last < windowMS- }-}diff --git a/apps/Donkey/Sources/DonkeyAI/FrontmostVisionWarmCache.swift b/apps/Donkey/Sources/DonkeyAI/FrontmostVisionWarmCache.swiftdeleted file mode 100644index 623bb08b..00000000--- a/apps/Donkey/Sources/DonkeyAI/FrontmostVisionWarmCache.swift+++ /dev/null@@ -1,196 +0,0 @@-import AppKit-import DonkeyContracts-import DonkeyRuntime-import Foundation--/// Decision the warm-cache monitor makes each tick. Pure and separate from the monitor so the-/// big-change / debounce logic is unit-testable without capture or network.-public enum VisionWarmCacheDecision: String, Equatable, Sendable {- case parse- case skipUnchanged- case skipDebounced-}--public enum VisionWarmCachePolicy {- /// Parse when this is the first sighting of an app, or when the screen changed by at least- /// `bigChangeThreshold` of its cells AND we haven't parsed this app within- /// `minReparseIntervalMS`. The threshold is deliberately higher than the reuse threshold: the- /// reuse check asks "is this the same screen?", this asks "did something big happen?".- public static func decide(- previous: ScreenshotSignature?,- next: ScreenshotSignature,- bigChangeThreshold: Double,- lastParseUptimeMS: Double?,- nowUptimeMS: Double,- minReparseIntervalMS: Double- ) -> VisionWarmCacheDecision {- guard let previous else { return .parse }- let changed = next.changedFraction(from: previous)- guard changed >= bigChangeThreshold else { return .skipUnchanged }- if let lastParseUptimeMS, nowUptimeMS - lastParseUptimeMS < minReparseIntervalMS {- return .skipDebounced- }- return .parse- }-}--/// Process-wide gate that lets an active vision drive pause the warm-cache monitor, so the two never-/// race to parse and write the same app's entry in `ParsedVisionStore` at the same time.-public final class VisionWarmCacheActivity: @unchecked Sendable {- public static let shared = VisionWarmCacheActivity()-- private let lock = NSLock()- private var depth = 0-- public init() {}-- public var isSuspended: Bool {- lock.lock(); defer { lock.unlock() }- return depth > 0- }-- public func suspend() {- lock.lock(); depth += 1; lock.unlock()- }-- public func resume() {- lock.lock(); depth = max(0, depth - 1); lock.unlock()- }-}--/// Always-on, non-LLM monitor that keeps `ParsedVisionStore` warm: it watches the frontmost user-/// window's screenshot fingerprint and, when a *big* change happens, captures + parses once and-/// stores the result. So when the model later calls `screen.captureAndAnalyze`, the window is usually-/// unchanged since the last big change and the parse is reused instantly instead of paid for inline.-///-/// This is detection-driven, not action-driven: it fires on any large on-screen change (a navigation,-/// a new dialog), independent of whether the agent caused it.-@MainActor-public final class FrontmostVisionWarmCache {- private let analyzer: any DebugUIInspectionAnalyzing- private let store: ParsedVisionStore- private let capture: VisionActionDriver.ScreenshotCapture- private let permissionChecker: any ScreenRecordingPermissionChecking- private let cadenceNanoseconds: UInt64- private let bigChangeThreshold: Double- private let minReparseIntervalMS: Double- private let minConfidence: Double- private let uptimeMS: @Sendable () -> Double-- private var task: Task<Void, Never>?- private var lastSignatureByApp: [String: ScreenshotSignature] = [:]- private var lastParseUptimeMSByApp: [String: Double] = [:]-- public init(- analyzer: any DebugUIInspectionAnalyzing,- store: ParsedVisionStore = .shared,- capture: @escaping VisionActionDriver.ScreenshotCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: $0) },- permissionChecker: any ScreenRecordingPermissionChecking = CoreGraphicsScreenRecordingPermissionChecker(),- cadenceNanoseconds: UInt64 = 700_000_000,- bigChangeThreshold: Double = 0.10,- minReparseIntervalMS: Double = 1_500,- minConfidence: Double = 0.25,- uptimeMS: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime * 1_000 }- ) {- self.analyzer = analyzer- self.store = store- self.capture = capture- self.permissionChecker = permissionChecker- self.cadenceNanoseconds = cadenceNanoseconds- self.bigChangeThreshold = bigChangeThreshold- self.minReparseIntervalMS = minReparseIntervalMS- self.minConfidence = minConfidence- self.uptimeMS = uptimeMS- }-- /// Builds the monitor from the environment-configured vision backend, or returns nil when the- /// backend isn't configured (so the app simply doesn't run it).- public static func fromEnvironment() -> FrontmostVisionWarmCache? {- guard let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {- return nil- }- let backend = DonkeyBackendInferenceClient(configuration: configuration)- return FrontmostVisionWarmCache(analyzer: HostedDebugUIInspectionAnalyzer(backend: backend))- }-- public func start() {- guard task == nil else { return }- task = Task { [weak self] in- await self?.loop()- }- }-- public func stop() {- task?.cancel()- task = nil- }-- private func loop() async {- while !Task.isCancelled {- await tick()- try? await Task.sleep(nanoseconds: cadenceNanoseconds)- }- }-- func tick() async {- guard !VisionWarmCacheActivity.shared.isSuspended else { return }- // Nothing to keep warm while signed out — the parse would only 401. Skip the expensive capture- // entirely rather than spending it on a doomed backend call.- guard BackendSessionGate.shared.isAuthenticated else { return }- // Only warm around real Donkey use. While the user isn't engaging Donkey (no task running and- // no recent interaction) there is nothing to keep warm for, so skip the parse instead of- // draining the backend the whole time the app sits open and idle.- guard DonkeyEngagement.shared.isEngaged() else { return }- guard permissionChecker.hasScreenRecordingAccess() else { return }- guard let target = MacWindowResolver().frontmostUserAppTarget() else { return }- let appKey = target.bundleIdentifier.flatMap { $0.isEmpty ? nil : $0 } ?? target.appName ?? ""- guard !appKey.isEmpty else { return }- guard let shot = try? await capture(target),- let signature = ScreenshotSignature.make(fromImageData: shot.pngData) else {- return- }-- let decision = VisionWarmCachePolicy.decide(- previous: lastSignatureByApp[appKey],- next: signature,- bigChangeThreshold: bigChangeThreshold,- lastParseUptimeMS: lastParseUptimeMSByApp[appKey],- nowUptimeMS: uptimeMS(),- minReparseIntervalMS: minReparseIntervalMS- )-- // On debounce keep the OLD fingerprint so the next eligible tick still sees the big change and- // can parse once the debounce window clears. Otherwise record what we just saw.- if decision != .skipDebounced {- lastSignatureByApp[appKey] = signature- }- guard decision == .parse else { return }-- let compressed = ScreenshotCompression.compressedForModel(shot)- let imageWidth = max(1, Int(compressed.pixelSize.width.rounded()))- let imageHeight = max(1, Int(compressed.pixelSize.height.rounded()))- guard let frame = try? await analyzer.inspect(- DebugUIInspectionRequest(- imageDataURL: compressed.base64DataURL,- pixelSize: compressed.pixelSize,- minConfidence: minConfidence- )- ) else {- return- }- // A drive may have suspended us while we were capturing and parsing. Re-check before writing so- // a warm parse that started before the drive cannot overwrite the drive's fresher entry.- guard !VisionWarmCacheActivity.shared.isSuspended else { return }- store.store(- appKey: appKey,- entry: ParsedVisionStore.Entry(- signature: signature,- elements: frame.elements,- imagePixelWidth: imageWidth,- imagePixelHeight: imageHeight,- capturedAtUptimeMS: uptimeMS()- )- )- lastParseUptimeMSByApp[appKey] = uptimeMS()- }-}diff --git a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swiftindex cb3d9b16..0aa5891e 100644--- a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift@@ -42,9 +42,6 @@ public final class VisionComputerUseToolProvider {let executionPreference: ExecutionPreferencelet analyzer: any DebugUIInspectionAnalyzinglet store: ParsedVisionStore- /// Fused accessibility + vision understanding kept warm by the always-on `UIUnderstandingCoordinator`.- /// Consulted before the LLM vision path so a decision reuses already-extracted elements.- let understandingStore: WindowUIUnderstandingStorelet minConfidence: Doublelet reuseChangedFractionThreshold: Doublelet capture: VisionActionDriver.ScreenshotCapture@@ -70,7 +67,6 @@ public final class VisionComputerUseToolProvider {executionPreference: ExecutionPreference = .foreground,analyzer: any DebugUIInspectionAnalyzing,store: ParsedVisionStore = .shared,- understandingStore: WindowUIUnderstandingStore = .shared,minConfidence: Double = 0.25,reuseChangedFractionThreshold: Double = VisionComputerUseToolProvider.reuseChangedFractionThreshold,capture: @escaping VisionActionDriver.ScreenshotCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: $0) },@@ -84,7 +80,6 @@ public final class VisionComputerUseToolProvider {self.executionPreference = executionPreferenceself.analyzer = analyzerself.store = store- self.understandingStore = understandingStoreself.minConfidence = minConfidenceself.reuseChangedFractionThreshold = reuseChangedFractionThresholdself.capture = capture@@ -192,31 +187,22 @@ public final class VisionComputerUseToolProvider {let elementImageHeight: Intif let signature,- let understanding = understandingStore.reusableEntry(- appKey: appKey,- signature: signature,- changedFractionThreshold: reuseChangedFractionThreshold- ) {- // The always-on engine already extracted this window (accessibility + vision), often- // while it was in the background. Reuse it so the decision is instant and grounded in- // accessibility, not just an inline vision parse.- usedCache = true- elements = understanding.elements- elementImageWidth = understanding.imagePixelWidth- elementImageHeight = understanding.imagePixelHeight- } else if let signature,let reusable = store.reusableEntry(appKey: appKey,signature: signature,changedFractionThreshold: reuseChangedFractionThreshold) {+ // Reuse an earlier capture from THIS run when the window hasn't changed since (e.g.+ // capture → click → re-capture on an unchanged screen), so the agent doesn't pay for a+ // redundant parse. The entry was written by this same tool below on its last cache miss —+ // nothing parses the screen except this on-demand tool inside a live run.usedCache = trueelements = reusable.elementselementImageWidth = reusable.imagePixelWidthelementImageHeight = reusable.imagePixelHeight} else {// Compress only on a cache miss: a reused parse never sends the image, so encoding it- // before the reuse check would be wasted work on the common warm-cache path.+ // before the reuse check would be wasted work on the common reuse path.let compressed = ScreenshotCompression.compressedForModel(shot)let imageWidth = max(1, Int(compressed.pixelSize.width.rounded()))let imageHeight = max(1, Int(compressed.pixelSize.height.rounded()))diff --git a/apps/Donkey/Sources/DonkeyRuntime/WindowUIUnderstandingStore.swift b/apps/Donkey/Sources/DonkeyRuntime/WindowUIUnderstandingStore.swiftdeleted file mode 100644index 27d88c31..00000000--- a/apps/Donkey/Sources/DonkeyRuntime/WindowUIUnderstandingStore.swift+++ /dev/null@@ -1,75 +0,0 @@-import DonkeyContracts-import Foundation--/// Process-wide cache of the latest *fused accessibility + vision* understanding per app, produced by-/// the always-on `UIUnderstandingCoordinator`. The agent's decision tools read this first so a-/// `screen.captureAndAnalyze` reuses elements that were already extracted (often for a background-/// window) instead of paying for a fresh parse.-///-/// Like `ParsedVisionStore`, elements are stored in the parse image's pixel space together with that-/// pixel size, and reuse is gated by a `ScreenshotSignature` so a stale entry is never reused for a-/// window that has since changed. Keyed by a stable app key (bundle identifier, falling back to app-/// name) so the agent can look it up by the app it is acting on.-public final class WindowUIUnderstandingStore: @unchecked Sendable {- public static let shared = WindowUIUnderstandingStore()-- public struct Entry: Sendable {- public var signature: ScreenshotSignature- /// Fused accessibility + vision elements with `bbox` in the parse image's pixel space.- public var elements: [DebugUIElement]- public var imagePixelWidth: Int- public var imagePixelHeight: Int- public var capturedAtUptimeMS: Double-- public init(- signature: ScreenshotSignature,- elements: [DebugUIElement],- imagePixelWidth: Int,- imagePixelHeight: Int,- capturedAtUptimeMS: Double- ) {- self.signature = signature- self.elements = elements- self.imagePixelWidth = imagePixelWidth- self.imagePixelHeight = imagePixelHeight- self.capturedAtUptimeMS = capturedAtUptimeMS- }- }-- private let lock = NSLock()- private var entries: [String: Entry] = [:]-- public init() {}-- public func store(appKey: String, entry: Entry) {- let key = Self.normalize(appKey)- guard !key.isEmpty else { return }- lock.lock()- defer { lock.unlock() }- entries[key] = entry- }-- public func latest(appKey: String) -> Entry? {- let key = Self.normalize(appKey)- guard !key.isEmpty else { return nil }- lock.lock()- defer { lock.unlock() }- return entries[key]- }-- /// Returns the cached entry only when its fingerprint is close enough to `signature` to treat the- /// window as unchanged, so the caller can reuse its elements without re-parsing.- public func reusableEntry(- appKey: String,- signature: ScreenshotSignature,- changedFractionThreshold: Double- ) -> Entry? {- guard let entry = latest(appKey: appKey) else { return nil }- let changed = signature.changedFraction(from: entry.signature)- return changed <= changedFractionThreshold ? entry : nil- }-- private static func normalize(_ key: String) -> String {- key.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()- }-}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyEngagementTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyEngagementTests.swiftdeleted file mode 100644index 1fc0e71a..00000000--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyEngagementTests.swift+++ /dev/null@@ -1,60 +0,0 @@-import Foundation-import Testing-@testable import DonkeyAI--@Suite-struct DonkeyEngagementTests {- /// Drives the tracker's clock from the test so window expiry is deterministic.- private final class Clock: @unchecked Sendable {- private let lock = NSLock()- private var nowMS: Double = 0- func read() -> Double { lock.lock(); defer { lock.unlock() }; return nowMS }- func advance(_ ms: Double) { lock.lock(); nowMS += ms; lock.unlock() }- }-- @Test- func idleByDefault() {- let engagement = DonkeyEngagement(uptimeMS: { 0 })- #expect(!engagement.isEngaged(), "Nothing submitted or running: not engaged.")- }-- @Test- func interactionOpensWindowThenExpires() {- let clock = Clock()- let engagement = DonkeyEngagement(uptimeMS: clock.read)- engagement.noteInteraction()- #expect(engagement.isEngaged(windowMS: 1_000), "Just interacted: engaged.")- clock.advance(999)- #expect(engagement.isEngaged(windowMS: 1_000), "Inside the window: still engaged.")- clock.advance(2)- #expect(!engagement.isEngaged(windowMS: 1_000), "Past the window: idled out.")- }-- @Test- func activeRunStaysEngagedRegardlessOfWindow() {- let clock = Clock()- let engagement = DonkeyEngagement(uptimeMS: clock.read)- engagement.beginRun()- clock.advance(10_000)- #expect(engagement.isEngaged(windowMS: 1_000), "A run in flight is engaged no matter how long.")- engagement.endRun()- #expect(engagement.isEngaged(windowMS: 1_000), "endRun stamps an interaction: brief lingering window.")- clock.advance(1_001)- #expect(!engagement.isEngaged(windowMS: 1_000), "After the post-run window: idled out.")- }-- @Test- func nestedRunsBalanceAndDoNotUnderflow() {- let clock = Clock()- let engagement = DonkeyEngagement(uptimeMS: clock.read)- engagement.beginRun()- engagement.beginRun()- engagement.endRun()- #expect(engagement.isEngaged(windowMS: 1_000), "One run still active: engaged.")- engagement.endRun()- // Extra endRun must not drive depth negative and wedge engagement on forever.- engagement.endRun()- clock.advance(1_001)- #expect(!engagement.isEngaged(windowMS: 1_000), "Depth floors at zero; window expires normally.")- }-}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionWarmCacheTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionWarmCacheTests.swiftdeleted file mode 100644index 72858749..00000000--- a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionWarmCacheTests.swift+++ /dev/null@@ -1,77 +0,0 @@-@testable import DonkeyAI-import DonkeyRuntime-import Testing--/// Coverage for the always-on warm-cache monitor's pure change/debounce decision and the activity-/// gate that pauses it during an active drive. The capture+parse side effects are integration-only.-@Suite-struct VisionWarmCacheTests {- private func signature(fill: UInt8) -> ScreenshotSignature {- ScreenshotSignature(pixels: [UInt8](repeating: fill, count: 64 * 64), dimension: 64)- }-- @Test- func firstSightingAlwaysParses() {- let decision = VisionWarmCachePolicy.decide(- previous: nil,- next: signature(fill: 100),- bigChangeThreshold: 0.10,- lastParseUptimeMS: nil,- nowUptimeMS: 0,- minReparseIntervalMS: 1_500- )- #expect(decision == .parse)- }-- @Test- func unchangedScreenSkips() {- let decision = VisionWarmCachePolicy.decide(- previous: signature(fill: 100),- next: signature(fill: 100),- bigChangeThreshold: 0.10,- lastParseUptimeMS: 0,- nowUptimeMS: 10_000,- minReparseIntervalMS: 1_500- )- #expect(decision == .skipUnchanged)- }-- @Test- func bigChangeWithinDebounceIsDeferred() {- let decision = VisionWarmCachePolicy.decide(- previous: signature(fill: 0),- next: signature(fill: 255),- bigChangeThreshold: 0.10,- lastParseUptimeMS: 500,- nowUptimeMS: 1_000, // 500ms since last parse, under the 1500ms window- minReparseIntervalMS: 1_500- )- #expect(decision == .skipDebounced)- }-- @Test- func bigChangeAfterDebounceParses() {- let decision = VisionWarmCachePolicy.decide(- previous: signature(fill: 0),- next: signature(fill: 255),- bigChangeThreshold: 0.10,- lastParseUptimeMS: 500,- nowUptimeMS: 5_000,- minReparseIntervalMS: 1_500- )- #expect(decision == .parse)- }-- @Test- func activityGateTracksSuspendDepth() {- let gate = VisionWarmCacheActivity()- #expect(!gate.isSuspended)- gate.suspend()- gate.suspend()- #expect(gate.isSuspended)- gate.resume()- #expect(gate.isSuspended) // still one suspend outstanding- gate.resume()- #expect(!gate.isSuspended)- }-}