Skip to content

Open source CapCut alternative.

TypeScript

fix(app): gate idle vision warming on Donkey engagement

David Lea4e0bf3615ca
diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swift
index aa6e850a..5613bade 100644
--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swift
+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swift
@@ -242,6 +242,13 @@ final class UIUnderstandingCoordinator {
// 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.
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 }
guard !isAnalyzing else {
UIUnderstandingLog.overlay.debug("debug inspection skipped refresh because analysis is already running")
return
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 7472f52f..f6d8b968 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -211,6 +211,9 @@ 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 taskID = context?.task.id ?? traceID
logSubmittedCommand(command, traceID: traceID, taskID: taskID, context: context)
@@ -677,6 +680,9 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
// 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
@@ -777,6 +783,9 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
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.task(id: taskID)
let finalStatus = finalTask?.status
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyEngagement.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyEngagement.swift
new file mode 100644
index 00000000..8f37ba7b
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyEngagement.swift
@@ -0,0 +1,55 @@
+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.swift
index 4cd88640..623bb08b 100644
--- a/apps/Donkey/Sources/DonkeyAI/FrontmostVisionWarmCache.swift
+++ b/apps/Donkey/Sources/DonkeyAI/FrontmostVisionWarmCache.swift
@@ -137,6 +137,10 @@ public final class FrontmostVisionWarmCache {
// 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 ?? ""
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyEngagementTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyEngagementTests.swift
new file mode 100644
index 00000000..3f03f65b
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyEngagementTests.swift
@@ -0,0 +1,54 @@
+import XCTest
+@testable import DonkeyAI
+
+final class DonkeyEngagementTests: XCTestCase {
+ /// 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() }
+ }
+
+ func testIdleByDefault() {
+ let engagement = DonkeyEngagement(uptimeMS: { 0 })
+ XCTAssertFalse(engagement.isEngaged(), "Nothing submitted or running: not engaged.")
+ }
+
+ func testInteractionOpensWindowThenExpires() {
+ let clock = Clock()
+ let engagement = DonkeyEngagement(uptimeMS: clock.read)
+ engagement.noteInteraction()
+ XCTAssertTrue(engagement.isEngaged(windowMS: 1_000), "Just interacted: engaged.")
+ clock.advance(999)
+ XCTAssertTrue(engagement.isEngaged(windowMS: 1_000), "Inside the window: still engaged.")
+ clock.advance(2)
+ XCTAssertFalse(engagement.isEngaged(windowMS: 1_000), "Past the window: idled out.")
+ }
+
+ func testActiveRunStaysEngagedRegardlessOfWindow() {
+ let clock = Clock()
+ let engagement = DonkeyEngagement(uptimeMS: clock.read)
+ engagement.beginRun()
+ clock.advance(10_000)
+ XCTAssertTrue(engagement.isEngaged(windowMS: 1_000), "A run in flight is engaged no matter how long.")
+ engagement.endRun()
+ XCTAssertTrue(engagement.isEngaged(windowMS: 1_000), "endRun stamps an interaction: brief lingering window.")
+ clock.advance(1_001)
+ XCTAssertFalse(engagement.isEngaged(windowMS: 1_000), "After the post-run window: idled out.")
+ }
+
+ func testNestedRunsBalanceAndDoNotUnderflow() {
+ let clock = Clock()
+ let engagement = DonkeyEngagement(uptimeMS: clock.read)
+ engagement.beginRun()
+ engagement.beginRun()
+ engagement.endRun()
+ XCTAssertTrue(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)
+ XCTAssertFalse(engagement.isEngaged(windowMS: 1_000), "Depth floors at zero; window expires normally.")
+ }
+}