Open source CapCut alternative.
TypeScript
Harden Donkey Vision dev parsing
David Le271c4de513f9
diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swiftindex bd5f0935..b13077f1 100644--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift@@ -36,7 +36,13 @@ final class DebugUIInspectionCoordinator {private var lastRenderedFrames: [UInt32: DebugUIInspectionFrame] = [:]private var lastSnapshots: [UInt32: DebugUIScreenCaptureSnapshot] = [:]private var lastVisionImageHashes: [UInt32: String] = [:]+ private var visionBackoff: [UInt32: VisionBackoff] = [:]private let remoteAIEngine: RemoteAIEngine = .vision++ private struct VisionBackoff {+ var nextAttempt: Date+ var failureStreak: Int+ }private var timer: Timer?private var activeAccessibilityTimer: Timer?private var notificationObservers: [NSObjectProtocol] = []@@ -79,6 +85,7 @@ final class DebugUIInspectionCoordinator {lastRenderedFrames.removeAll()lastSnapshots.removeAll()lastVisionImageHashes.removeAll()+ visionBackoff.removeAll()isAnalyzing = falseisRefreshingActiveAccessibility = falsecurrentConfig = .disabled@@ -180,6 +187,7 @@ final class DebugUIInspectionCoordinator {lastRenderedFrames.removeAll()lastSnapshots.removeAll()lastVisionImageHashes.removeAll()+ visionBackoff.removeAll()if !newConfig.enabled {overlayController.close()}@@ -589,6 +597,11 @@ final class DebugUIInspectionCoordinator {if remoteAIEngine == .vision {let windowID = capture.target.windowID+ // Back off after failures so a broken or cold backend isn't+ // re-hit (and re-logged) every refresh cycle.+ if let backoff = visionBackoff[windowID], Date() < backoff.nextAttempt {+ continue+ }let imageHash = SHA256.hash(data: capture.parseImageData).map { String(format: "%02x", $0) }.joined()@@ -614,10 +627,13 @@ final class DebugUIInspectionCoordinator {elements.removeAll { Self.windowID(for: $0) == windowID }elements += parsedElementslastVisionImageHashes[windowID] = imageHash+ visionBackoff[windowID] = nilrenderRemoteAIFrame(stage: "vision", updatesFingerprint: false)} catch {+ let backoff = Self.nextVisionBackoff(after: visionBackoff[windowID])+ visionBackoff[windowID] = backoffDebugUIInspectionLog.overlay.error(- "debug inspection vision parse failed windowID=\(windowID, privacy: .public) error=\(String(describing: error), privacy: .public)"+ "debug inspection vision parse failed windowID=\(windowID, privacy: .public) failureStreak=\(backoff.failureStreak, privacy: .public) retryInSeconds=\(Int(backoff.nextAttempt.timeIntervalSinceNow.rounded()), privacy: .public) error=\(String(describing: error), privacy: .public)")}continue@@ -1322,6 +1338,17 @@ final class DebugUIInspectionCoordinator {return SHA256.hash(data: Data(combinedInput.utf8)).map { String(format: "%02x", $0) }.joined()}+ private static func nextVisionBackoff(after previous: VisionBackoff?) -> VisionBackoff {+ let baseSeconds = 2.0+ let capSeconds = 30.0+ let failureStreak = (previous?.failureStreak ?? 0) + 1+ let delay = min(baseSeconds * pow(2, Double(failureStreak - 1)), capSeconds)+ return VisionBackoff(+ nextAttempt: Date().addingTimeInterval(delay),+ failureStreak: failureStreak+ )+ }+private static func frameSignature(_ frame: DebugUIInspectionFrame) -> String {frame.elements.map { element in[diff --git a/site/src/app/api/inference/vision/route.ts b/site/src/app/api/inference/vision/route.tsindex 378a329a..c11145b8 100644--- a/site/src/app/api/inference/vision/route.ts+++ b/site/src/app/api/inference/vision/route.ts@@ -7,7 +7,10 @@ import {recordInferenceUsage,requireInferenceCredits,} from "@/lib/credits/inference";-import { withDonkeyAuth } from "@/lib/donkey-api-auth";+import {+ shouldBypassDonkeyInferenceCredits,+ withDonkeyAuth,+} from "@/lib/donkey-api-auth";import { InferenceProviderError } from "@/lib/inference/providers";import {checkInMemoryRateLimit,@@ -65,14 +68,19 @@ export const POST = withDonkeyAuth(async (request) => {const { image, instruction, model, returnElements, options } = parsed.data;const billedModel = instruction ? model : parseModel;- const credits = await requireInferenceCredits({- model: billedModel,- provider: inferenceProvider,- route: inferenceUsageRoutes.vision,- userId: request.donkey.userId,- });- if (!credits.ok) {- return credits.response;+ // The dev-bypass user has no real account, so skip the credit preflight and+ // usage recording (both reference a real user row) when bypassing auth.+ const bypassCredits = shouldBypassDonkeyInferenceCredits(request.donkey);+ if (!bypassCredits) {+ const credits = await requireInferenceCredits({+ model: billedModel,+ provider: inferenceProvider,+ route: inferenceUsageRoutes.vision,+ userId: request.donkey.userId,+ });+ if (!credits.ok) {+ return credits.response;+ }}try {@@ -91,31 +99,39 @@ export const POST = withDonkeyAuth(async (request) => {: {}),};- const recordedUsage = await recordInferenceUsage({- clientId: client.clientId,- metadata: { grounded: String(instruction !== undefined) },- model: billedModel,- provider: inferenceProvider,- requestKind: "vision_parse",- route: inferenceUsageRoutes.vision,- status: "succeeded",- userId: request.donkey.userId,- });+ let usageHeaders: Record<string, string> = {};+ if (bypassCredits) {+ usageHeaders["X-Donkey-Dev-Auth-Bypass"] = "true";+ } else {+ const recordedUsage = await recordInferenceUsage({+ clientId: client.clientId,+ metadata: { grounded: String(instruction !== undefined) },+ model: billedModel,+ provider: inferenceProvider,+ requestKind: "vision_parse",+ route: inferenceUsageRoutes.vision,+ status: "succeeded",+ userId: request.donkey.userId,+ });+ usageHeaders = creditUsageHeaders(recordedUsage);+ }return NextResponse.json(result, {- headers: creditUsageHeaders(recordedUsage),+ headers: usageHeaders,});} catch (error) {- await recordFailedInferenceUsage({- clientId: client.clientId,- errorCode: inferenceErrorCode(error),- metadata: { grounded: String(instruction !== undefined) },- model: billedModel,- provider: inferenceProvider,- requestKind: "vision_parse",- route: inferenceUsageRoutes.vision,- userId: request.donkey.userId,- });+ if (!bypassCredits) {+ await recordFailedInferenceUsage({+ clientId: client.clientId,+ errorCode: inferenceErrorCode(error),+ metadata: { grounded: String(instruction !== undefined) },+ model: billedModel,+ provider: inferenceProvider,+ requestKind: "vision_parse",+ route: inferenceUsageRoutes.vision,+ userId: request.donkey.userId,+ });+ }if (error instanceof InferenceProviderError) {return inferenceProviderErrorResponse(error);}