Open source CapCut alternative.
TypeScript
feat(app): drive vision computer use with Gemini's native computer_use tool
David Lefe60d117cd33
diff --git a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swiftindex 3046ce60..26375701 100644--- a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift+++ b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift@@ -376,7 +376,6 @@ final class GeminiLiveVoiceController {let app = (call.arguments["app"] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)let goal = (call.arguments["goal"] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)let model = configuration.visionModel- let useBox = configuration.visionBoxEnabledlet callID = call.idlet toolName = call.namelet provider = visionAuthProvider@@ -402,23 +401,11 @@ final class GeminiLiveVoiceController {let summary: Stringdo {let auth = try await provider()- // Box and single-point drivers are independent (separate Outcome- // types), so read the two fields we need from each branch locally.- let completed: Bool- let turns: Int- if useBox {- let outcome = await VertexVisionBoxDriver.drive(- appName: app, bundleIdentifier: nil, goal: goal, auth: auth, model: model- )- completed = outcome.completed- turns = outcome.turns- } else {- let outcome = await VertexVisionDriver.drive(- appName: app, bundleIdentifier: nil, goal: goal, auth: auth, model: model- )- completed = outcome.completed- turns = outcome.turns- }+ let outcome = await VertexVisionDriver.drive(+ appName: app, bundleIdentifier: nil, goal: goal, auth: auth, model: model+ )+ let completed = outcome.completed+ let turns = outcome.turnsstatus = completed ? "succeeded" : "incomplete"summary = "vision \(completed ? "completed" : "did not complete") \"\(goal)\" in \(app) over \(turns) turns"} catch {diff --git a/apps/Donkey/Sources/Donkey/VertexVisionBoxDriver.swift b/apps/Donkey/Sources/Donkey/VertexVisionBoxDriver.swiftdeleted file mode 100644index c195a64d..00000000--- a/apps/Donkey/Sources/Donkey/VertexVisionBoxDriver.swift+++ /dev/null@@ -1,164 +0,0 @@-import AppKit-import DonkeyAI-import DonkeyContracts-import DonkeyRuntime-import Foundation--/// Box-based sibling of `VertexVisionDriver`. Each turn it screenshots the app-/// window, asks `GeminiVertexVisionBoxPlanner` for the next action with the target-/// as a 2D bounding box, and — for a click — tries the box center first and then a-/// few nearby points, stopping as soon as the screen changes (or `verify()`-/// passes). This makes a single turn robust to a slightly-loose box instead of-/// waiting a whole model round-trip to recover from one missed point.-///-/// Selected by `GEMINI_VISION_BOX=1` in `GeminiLiveVoiceController.launchVision`;-/// the single-point `VertexVisionDriver` remains the default. Same constraint-/// applies: must NOT run inside the Live session's `for await session.events`-/// consumer task (ScreenCaptureKit `capture` hangs there).-@MainActor-enum VertexVisionBoxDriver {- /// Self-contained outcome (the box variant does not depend on the single-point- /// driver, so it survives that driver's refactors).- struct Outcome: Sendable {- var completed: Bool- var turns: Int- var history: [String]- }-- static func drive(- appName: String,- bundleIdentifier: String?,- goal: String,- auth: GeminiVertexVisionPlanner.VertexAuth,- model: String,- settleNanoseconds: UInt64 = 1_500_000_000,- attemptSettleNanoseconds: UInt64 = 300_000_000,- maxTurns: Int = 16,- capturer: ScreenCaptureKitWindowScreenshotCapturer = ScreenCaptureKitWindowScreenshotCapturer(),- verify: (@MainActor () -> Bool)? = nil,- onTurn: (@MainActor (Int, CapturedWindowScreenshot, GeminiVertexVisionBoxPlanner.VisionBoxAction) -> Void)? = nil- ) async -> Outcome {- guard var target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {- return Outcome(completed: false, turns: 0, history: ["no \(appName) window"])- }- // Per-app operating knowledge comes from a discoverable skill pack, same- // source the single-point driver and backend vision path use.- let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(- forApp: appName, bundleIdentifier: bundleIdentifier- )- var history: [String] = []- var turns = 0- var completed = false- var lastClickKey = ""- var repeatCount = 0-- turnLoop: for _ in 0..<maxTurns {- if verify?() == true { completed = true; break }- ensureAppFrontAndRestored(appName: appName, processID: target.processID)- try? await Task.sleep(nanoseconds: 250_000_000)- if let refreshed = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) {- target = refreshed- }- guard let shot = try? await capturer.capture(target: target) else {- history.append("screenshot failed"); break- }- let compressed = ScreenshotCompression.compressedForModel(shot)-- let action: GeminiVertexVisionBoxPlanner.VisionBoxAction- do {- action = try await GeminiVertexVisionBoxPlanner.nextBoxAction(- auth: auth, model: model, goal: goal, appName: appName,- history: history, appGuidance: appGuidance, compressed: compressed, window: target.bounds- )- } catch {- history.append("vision plan failed: \(error)"); break- }- turns += 1- onTurn?(turns, shot, action)- let reason = action.reason ?? ""-- if action.action == "done" {- if let verify {- if verify() { completed = true; break }- history.append("claimed done but verify() false — your last action missed; return a tighter box")- try? await Task.sleep(nanoseconds: settleNanoseconds)- continue- }- completed = true- history.append("done: \(reason)")- break- }-- switch action.action {- case "click":- guard let points = action.screenPoints, !points.isEmpty else {- history.append("click without box: \(reason)")- break- }- let centerKey = "\(Int(points[0].x)),\(Int(points[0].y))"- repeatCount = (centerKey == lastClickKey) ? repeatCount + 1 : 0- lastClickKey = centerKey- if repeatCount >= 4 {- history.append("aborting: stuck repeating box center \(centerKey)")- break turnLoop- }-- var landedIndex: Int?- for (index, point) in points.enumerated() {- _ = MacPointerInput.moveAndClick(at: point)- if verify?() == true { landedIndex = index; completed = true; break }- try? await Task.sleep(nanoseconds: attemptSettleNanoseconds)- if let after = try? await capturer.capture(target: target),- ScreenshotChange.changed(shot.pngData, after.pngData) {- landedIndex = index- break- }- }- if let landedIndex {- let landed = points[landedIndex]- history.append("clicked box point \(landedIndex) (\(Int(landed.x)),\(Int(landed.y))) of \(points.count)\(repeatCount >= 2 ? " AGAIN" : "") — screen changed: \(reason)")- } else {- history.append("clicked \(points.count) box points, no visible change — pick a different/tighter target: \(reason)")- }- if completed { break turnLoop }- case "type":- MacKeyboardInput.type(action.text ?? "")- history.append("typed \"\(action.text ?? "")\"")- case "key":- MacKeyboardInput.pressKey(action.text ?? "return")- history.append("key \(action.text ?? "return")")- default:- history.append("ignored action \(action.action)")- }- try? await Task.sleep(nanoseconds: settleNanoseconds)- }-- if let verify, !completed { completed = verify() }- return Outcome(completed: completed, turns: turns, history: history)- }-- /// Bring an app frontmost and un-minimize its windows (a stray vision click can- /// hit the minimize button, breaking every later screenshot). Kept local so the- /// box variant stays independent of the single-point driver.- private static func ensureAppFrontAndRestored(appName: String, processID: pid_t) {- NSRunningApplication(processIdentifier: processID)?.activate()- let source = """- tell application "System Events"- if exists process "\(appName)" then- tell process "\(appName)"- set frontmost to true- try- repeat with w in windows- if value of attribute "AXMinimized" of w is true then- set value of attribute "AXMinimized" of w to false- end if- end repeat- end try- end tell- end if- end tell- """- // Never prompt mid-task for this internal nicety; skip it if Automation isn't already granted.- SystemPermissionCoordinator.runSystemEventsScriptIfGranted(source)- }-}diff --git a/apps/Donkey/Sources/Donkey/VertexVisionDriver.swift b/apps/Donkey/Sources/Donkey/VertexVisionDriver.swiftindex 5b28a035..c1a6095c 100644--- a/apps/Donkey/Sources/Donkey/VertexVisionDriver.swift+++ b/apps/Donkey/Sources/Donkey/VertexVisionDriver.swift@@ -4,16 +4,17 @@ import DonkeyContractsimport DonkeyRuntimeimport Foundation-/// Drives an app by vision: each turn it screenshots the app window, asks the-/// turn-based Vertex vision model (`GeminiVertexVisionPlanner`, default-/// `gemini-3.5-flash`) for the single next click/type/key, and executes it with the-/// app's real pointer/keyboard. This is the "look at the screen, decide, act"-/// fallback the Live command session escalates to (via `vision_control`) when no-/// fast tool can operate an app.+/// Drives an app by vision using `gemini-3.5-flash`'s built-in `computer_use` tool reached directly+/// over Vertex (`GeminiVertexVisionPlanner`). This is the "look at the screen, decide, act" fallback+/// the Live command session escalates to (via `vision_control`) when no fast tool can operate an app.///-/// IMPORTANT: must NOT be driven from inside the Live session's `for await-/// session.events` consumer task — ScreenCaptureKit `capture` hangs there. Run it-/// from a separate task (see `GeminiLiveVoiceController`).+/// The per-turn loop, focus guards, screenshot/retry, and action execution all live in+/// `VisionActionDriver`; this is a thin adapter that supplies the direct-Vertex planner so the Live+/// escalation and the hosted `createResponse` path share one driver.+///+/// IMPORTANT: must NOT be driven from inside the Live session's `for await session.events` consumer+/// task — ScreenCaptureKit `capture` hangs there. Run it from a separate task (see+/// `GeminiLiveVoiceController`).@MainActorenum VertexVisionDriver {struct Outcome: Sendable {@@ -33,110 +34,36 @@ enum VertexVisionDriver {capturer: ScreenCaptureKitWindowScreenshotCapturer = ScreenCaptureKitWindowScreenshotCapturer(),verify: (@MainActor () -> Bool)? = nil) async -> Outcome {- guard var target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {- return Outcome(completed: false, turns: 0, history: ["no \(appName) window"])- }- // Per-app operating knowledge comes from a discoverable skill pack (a- // BuiltInSkills/<app>/SKILL.md with an `apps:` line), never a hardcoded app- // list — same source the backend vision path uses.+ // Per-app operating knowledge comes from a discoverable skill pack (a BuiltInSkills/<app>/SKILL.md+ // with an `apps:` line), never a hardcoded app list — same source the hosted vision path uses.let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(forApp: appName, bundleIdentifier: bundleIdentifier)- var history: [String] = []- var turns = 0- var completed = false- var lastClickKey = ""- var repeatCount = 0-- turnLoop: for _ in 0..<maxTurns {- if verify?() == true { completed = true; break }- ensureAppFrontAndRestored(appName: appName, processID: target.processID)- try? await Task.sleep(nanoseconds: 250_000_000)- if let refreshed = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) {- target = refreshed- }- guard let shot = try? await capturer.capture(target: target) else {- history.append("screenshot failed"); break- }- let compressed = ScreenshotCompression.compressedForModel(shot)- let action: VisionActionPlanner.PlannedAction- do {- action = try await GeminiVertexVisionPlanner.nextAction(- auth: auth, model: model, goal: goal, appName: appName,- history: history, appGuidance: appGuidance, compressed: compressed, window: target.bounds+ let outcome = await VisionActionDriver.drive(+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ goal: goal,+ appGuidance: appGuidance,+ maxTurns: maxTurns,+ settleNanoseconds: settleNanoseconds,+ capture: { try await capturer.capture(target: $0) },+ verify: verify,+ onTurn: nil,+ planner: { goal, app, shot, window, history, guidance in+ try await GeminiVertexVisionPlanner.nextAction(+ auth: auth,+ model: model,+ goal: goal,+ appName: app,+ history: history,+ appGuidance: guidance,+ compressed: ScreenshotCompression.compressedForModel(shot),+ window: window)- } catch {- history.append("vision plan failed: \(error)"); break- }- turns += 1- let reason = action.reason ?? ""-- if action.action == "done" {- // Verify-don't-trust when a verifier is provided; otherwise trust the- // model's claim (the general case, no app-specific success signal).- if let verify {- if verify() { completed = true; break }- history.append("claimed done but verify() false — your last action missed; click the exact target")- try? await Task.sleep(nanoseconds: settleNanoseconds)- continue- }- completed = true- history.append("done: \(reason)")- break}+ )- switch action.action {- case "click":- if let point = action.screenPoint {- let key = "\(Int(point.x)),\(Int(point.y))"- repeatCount = (key == lastClickKey) ? repeatCount + 1 : 0- lastClickKey = key- if repeatCount >= 4 { history.append("aborting: stuck repeating click \(key)"); break turnLoop }- _ = MacPointerInput.moveAndClick(at: point)- history.append(repeatCount >= 2- ? "clicked (\(key)) AGAIN — not working; pick a DIFFERENT target/exact center: \(reason)"- : "clicked (\(key)): \(reason)")- } else {- history.append("click without point: \(reason)")- }- case "type":- MacKeyboardInput.type(action.text ?? "")- history.append("typed \"\(action.text ?? "")\"")- case "key":- MacKeyboardInput.pressKey(action.text ?? "return")- history.append("key \(action.text ?? "return")")- default:- history.append("ignored action \(action.action)")- }- try? await Task.sleep(nanoseconds: settleNanoseconds)- }-- if let verify, !completed { completed = verify() }- return Outcome(completed: completed, turns: turns, history: history)- }-- /// Bring an app frontmost and un-minimize its windows (a stray vision click can- /// hit the minimize button, breaking every later screenshot).- static func ensureAppFrontAndRestored(appName: String, processID: pid_t) {- NSRunningApplication(processIdentifier: processID)?.activate()- let source = """- tell application "System Events"- if exists process "\(appName)" then- tell process "\(appName)"- set frontmost to true- try- repeat with w in windows- if value of attribute "AXMinimized" of w is true then- set value of attribute "AXMinimized" of w to false- end if- end repeat- end try- end tell- end if- end tell- """- // Never prompt mid-task for this internal nicety; skip it if Automation isn't already granted.- SystemPermissionCoordinator.runSystemEventsScriptIfGranted(source)+ return Outcome(completed: outcome.completed, turns: outcome.turns, history: outcome.history)}}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiGenerateContent.swift b/apps/Donkey/Sources/DonkeyAI/GeminiGenerateContent.swiftindex 02df5da7..77fb5bef 100644--- a/apps/Donkey/Sources/DonkeyAI/GeminiGenerateContent.swift+++ b/apps/Donkey/Sources/DonkeyAI/GeminiGenerateContent.swift@@ -23,18 +23,23 @@ public enum GeminiGenerateContent {/// Serialize a `generateContent` request body: a single user turn whose `parts`/// are supplied by the caller (text / inlineData), plus the caller's- /// `generationConfig` (temperature, response schema, thinking level, …).+ /// `generationConfig` (temperature, response schema, thinking level, …) and, when+ /// present, a `tools` array (e.g. the built-in `computerUse` tool).public static func requestBody(parts: [[String: Any]],- generationConfig: [String: Any]+ generationConfig: [String: Any],+ tools: [[String: Any]]? = nil) throws -> Data {- let body: [String: Any] = [+ var body: [String: Any] = ["contents": [["role": "user","parts": parts]],"generationConfig": generationConfig]+ if let tools, !tools.isEmpty {+ body["tools"] = tools+ }return try JSONSerialization.data(withJSONObject: body)}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swift b/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swiftindex 53dcb163..2e4e9149 100644--- a/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swift+++ b/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swift@@ -27,13 +27,10 @@ public struct GeminiLiveConfiguration: Equatable, Sendable {/// path ignores this (its model comes from the backend mint response).public var model: String/// Model used for the per-turn vision driver (`GEMINI_VISION_MODEL`). This is a- /// turn-based `generateContent` model (not Live/bidi) — a stronger model for- /// the screenshot-grounding task than the fast realtime command model.+ /// turn-based `generateContent` model (not Live/bidi) running the built-in+ /// `computer_use` tool — a stronger model for screenshot grounding than the fast+ /// realtime command model.public var visionModel: String- /// Opt into the box-based vision driver (`GEMINI_VISION_BOX`): the planner- /// returns a 2D bounding box and the driver clicks the box center plus nearby- /// points in one turn. Off by default, leaving the single-point driver in place.- public var visionBoxEnabled: Bool/// Whether the Developer-API Live session requests AUDIO response modality/// (`GEMINI_LIVE_AUDIO_OUTPUT`). The default Dev-API model is audio-output only,/// so this defaults true; set falsey when pointing `GEMINI_LIVE_MODEL` at a@@ -55,7 +52,6 @@ public struct GeminiLiveConfiguration: Equatable, Sendable {apiKey: String? = nil,model: String = GeminiLiveConfiguration.defaultModel,visionModel: String = GeminiLiveConfiguration.defaultVisionModel,- visionBoxEnabled: Bool = false,liveAudioOutput: Bool = true) {self.enabled = enabled@@ -63,7 +59,6 @@ public struct GeminiLiveConfiguration: Equatable, Sendable {self.apiKey = apiKeyself.model = modelself.visionModel = visionModel- self.visionBoxEnabled = visionBoxEnabledself.liveAudioOutput = liveAudioOutput}@@ -84,7 +79,6 @@ public struct GeminiLiveConfiguration: Equatable, Sendable {apiKey: trimmed(environment["GEMINI_API_KEY"]),model: trimmed(environment["GEMINI_LIVE_MODEL"]) ?? defaultModel,visionModel: trimmed(environment["GEMINI_VISION_MODEL"]) ?? defaultVisionModel,- visionBoxEnabled: boolValue(environment["GEMINI_VISION_BOX"]),liveAudioOutput: boolValue(environment["GEMINI_LIVE_AUDIO_OUTPUT"], default: true))}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swift b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swiftdeleted file mode 100644index 98a24b5f..00000000--- a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swift+++ /dev/null@@ -1,114 +0,0 @@-import CoreGraphics-import DonkeyContracts-import DonkeyRuntime-import Foundation--/// Box-based sibling of `GeminiVertexVisionPlanner`. Instead of a single click-/// point, it asks the turn-based Vertex vision model to return the target control-/// as a 2D bounding box (`box = [ymin, xmin, ymax, xmax]` in Gemini's 0–1000-/// normalized space). `VertexVisionBoxGeometry` turns that box into an ordered list-/// of click points (center first, then nearby fallbacks), so a slightly-loose box-/// still lands on the control within a single turn.-///-/// Auth (token + project + location) is reused from `GeminiVertexVisionPlanner`-/// (`VertexAuth` / `mintAuth`); only the schema, prompt, and decoded shape differ.-public enum GeminiVertexVisionBoxPlanner {- /// A single planned action with the target expressed as a bounding box.- public struct VisionBoxAction: Equatable, Sendable, Codable {- public var action: String // "click" | "type" | "key" | "done"- public var box: [Double]? // [ymin, xmin, ymax, xmax] normalized 0–1000, click only- public var text: String?- public var reason: String?- /// Resolved real-screen click points (box center first), filled in post-decode.- public var screenPoints: [CGPoint]?-- private enum CodingKeys: String, CodingKey { case action, box, text, reason }- }-- public static func nextBoxAction(- auth: GeminiVertexVisionPlanner.VertexAuth,- model: String,- goal: String,- appName: String,- history: [String],- appGuidance: String? = nil,- compressed: CompressedScreenshot,- window: WindowTargetBounds,- urlSession: URLSession = .shared- ) async throws -> VisionBoxAction {- let width = Int(compressed.pixelSize.width.rounded())- let height = Int(compressed.pixelSize.height.rounded())- let generationConfig: [String: Any] = [- "temperature": 0,- "responseMimeType": "application/json",- // gemini-3.5-flash takes thinking_level (the integer thinkingBudget is ignored on 3.x).- // No maxOutputTokens is set, so the large default leaves ample room for medium thinking- // plus the small box JSON. Vertex takes the proto enum name (uppercase).- "thinkingConfig": ["thinkingLevel": "MEDIUM"],- "responseSchema": [- "type": "object",- "properties": [- "action": ["type": "string", "enum": ["click", "type", "key", "done"]],- "box": ["type": "array", "items": ["type": "number"]],- "text": ["type": "string"],- "reason": ["type": "string"]- ],- "required": ["action", "reason"]- ]- ]-- var action = try await GeminiVertexVisionPlanner.generateAction(- auth: auth,- model: model,- prompt: prompt(goal: goal, app: appName, width: width, height: height, history: history, appGuidance: appGuidance),- compressed: compressed,- generationConfig: generationConfig,- urlSession: urlSession,- decode: VisionBoxAction.self- )- if action.action == "click", let box = action.box {- let points = VisionBoxGeometry.screenPoints(box, window: window)- action.screenPoints = points.isEmpty ? nil : points- }- return action- }-- private static func prompt(goal: String, app: String, width: Int, height: Int, history: [String], appGuidance: String?) -> String {- let historyBlock = history.isEmpty- ? "This is the first action; nothing has been done yet."- : "Actions ALREADY performed, in order (do NOT repeat one that already worked):\n"- + history.suffix(8).enumerated().map { " \($0.offset + 1). \($0.element)" }.joined(separator: "\n")- let guidanceBlock: String- if let appGuidance, !appGuidance.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- guidanceBlock = """--- APP-SPECIFIC OPERATING GUIDE for "\(app)" (follow this — it describes where controls are and how to read state; it never gives fixed coordinates, so always read the current screenshot for exact positions):- \(appGuidance)- """- } else {- guidanceBlock = ""- }- return """- You are operating the macOS app "\(app)" by clicking and typing to accomplish a goal.- GOAL: \(goal)- The attached screenshot is the CURRENT state of the app window (\(width) x \(height) pixels), origin top-left.-- \(historyBlock)\(guidanceBlock)-- Decide the SINGLE next action that best progresses toward the goal given ONLY what is visible now.- - "click": move the pointer and click a control. Set "box" to a TIGHT 2D bounding box around the ONE- target control (a button, row, field, or icon). A click has no text.- - "type": type into the ALREADY-focused field. Set "text"; omit "box". Use this after clicking a text field.- - "key": press one key. Set "text" to the key name (e.g. "return"); omit "box".- - "done": the goal is fully and verifiably satisfied in the current screenshot. Omit "box".- BOX FORMAT: "box" is [ymin, xmin, ymax, xmax], each value NORMALIZED to 0–1000 relative to the image- (x=0 left … 1000 right; y=0 top … 1000 bottom). We click the box CENTER first and then a few points just- inside it, so the box must bound exactly one control as tightly as possible — too large and we click the- wrong thing.- If you clicked and the screenshot looks unchanged, the click MISSED — re-locate the target and return a- tighter, correctly-placed box; don't repeat the same one.- Keep "reason" to one short sentence.- """- }-}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swift b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swiftindex 4ac989a1..46d91ca2 100644--- a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swift+++ b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swift@@ -3,12 +3,12 @@ import DonkeyContractsimport DonkeyRuntimeimport Foundation-/// Per-turn vision planner backed by a strong turn-based Vertex model-/// (default `gemini-3.5-flash`), separate from the realtime Live command model-/// (`gemini-live-2.5-flash`). Given the current window screenshot + goal it returns-/// the single next UI action (click / type / key / done) with click coordinates in-/// Gemini's 0–1000 normalized space, mapped to the window via-/// `VisionActionPlanner.screenPoint`.+/// Per-turn vision planner backed by `gemini-3.5-flash`'s built-in `computer_use`+/// tool in the `ENVIRONMENT_DESKTOP` environment, separate from the realtime Live+/// command model. Given the current window screenshot + goal it returns the single+/// next UI action as a typed `VisionComputerAction` parsed from the model's native+/// function call (coordinates in Gemini's 0–1000 normalized space; the executor maps+/// them onto the window). No function call means the model considers the goal done.////// It calls Vertex `generateContent` directly with a Bearer token minted by the/// backend (`DonkeyBackendInferenceClient.mintLiveConnection` returns the token +@@ -29,12 +29,10 @@ public enum GeminiVertexVisionPlanner {public enum PlannerError: Error, CustomStringConvertible {case missingProjectOrLocationcase requestFailed(status: Int, body: String)- case noOutputText(body: String)public var description: String {switch self {case .missingProjectOrLocation: return "mint response lacked project/location"case let .requestFailed(status, body): return "vertex generateContent \(status): \(body.prefix(200))"- case let .noOutputText(body): return "no output text: \(body.prefix(200))"}}}@@ -58,58 +56,28 @@ public enum GeminiVertexVisionPlanner {compressed: CompressedScreenshot,window: WindowTargetBounds,urlSession: URLSession = .shared- ) async throws -> VisionActionPlanner.PlannedAction {+ ) async throws -> VisionComputerAction {let width = Int(compressed.pixelSize.width.rounded())let height = Int(compressed.pixelSize.height.rounded())- let prompt = VisionActionPlanner.visionPrompt(+ let prompt = VisionComputerUsePrompt.instructions(goal: goal, app: appName, width: width, height: height, history: history, appGuidance: appGuidance)+ // No responseSchema/responseMimeType: with the built-in computer-use tool the model answers+ // via function calls, not structured JSON. gemini-3.5-flash takes thinking_level (uppercase+ // proto enum on Vertex); the integer thinkingBudget is ignored on 3.x.let generationConfig: [String: Any] = ["temperature": 0,- "responseMimeType": "application/json",- // gemini-3.5-flash takes thinking_level (the integer thinkingBudget is ignored on 3.x).- // No maxOutputTokens is set, so the large default leaves ample room for medium thinking- // plus the small action JSON. Vertex takes the proto enum name (uppercase).- "thinkingConfig": ["thinkingLevel": "MEDIUM"],- "responseSchema": [- "type": "object",- "properties": [- "action": ["type": "string", "enum": ["click", "type", "key", "done"]],- "x": ["type": "number"],- "y": ["type": "number"],- "text": ["type": "string"],- "reason": ["type": "string"]- ],- "required": ["action", "x", "y", "reason"]- ]+ "thinkingConfig": ["thinkingLevel": "MEDIUM"]+ ]+ let tools: [[String: Any]] = [+ ["computerUse": [+ "environment": "ENVIRONMENT_DESKTOP",+ // Exclude the browser-navigation functions the desktop never uses, matching the+ // backend hosted path so the two transports offer the model the same action set.+ "excludedPredefinedFunctions": VisionComputerDesktopTool.excludedPredefinedFunctions+ ]]]- var action = try await generateAction(- auth: auth,- model: model,- prompt: prompt,- compressed: compressed,- generationConfig: generationConfig,- urlSession: urlSession,- decode: VisionActionPlanner.PlannedAction.self- )- action.screenPoint = VisionActionPlanner.screenPoint(action: action, window: window)- return action- }-- /// Shared Vertex vision turn: resolve the endpoint, post the prompt + screenshot- /// with the caller's `generationConfig` (response schema, thinking level), guard- /// status/candidate-text, then decode the JSON substring into `Output`. The two- /// planners differ only in their schema and decoded shape, which are passed in.- static func generateAction<Output: Decodable>(- auth: VertexAuth,- model: String,- prompt: String,- compressed: CompressedScreenshot,- generationConfig: [String: Any],- urlSession: URLSession,- decode: Output.Type- ) async throws -> Output {guard let url = GeminiGenerateContent.vertexURL(project: auth.project,location: auth.location,@@ -124,7 +92,8 @@ public enum GeminiVertexVisionPlanner {base64: compressed.data.base64EncodedString())],- generationConfig: generationConfig+ generationConfig: generationConfig,+ tools: tools)let request = GeminiGenerateContent.vertexRequest(url: url, bearerToken: auth.token, body: body)@@ -133,11 +102,8 @@ public enum GeminiVertexVisionPlanner {guard status == 200 else {throw PlannerError.requestFailed(status: status, body: String(data: data, encoding: .utf8) ?? "")}- guard let text = GeminiGenerateContent.candidateText(data), !text.isEmpty else {- throw PlannerError.noOutputText(body: String(data: data, encoding: .utf8) ?? "")- }- let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)- return try JSONDecoder().decode(Output.self, from: Data(json.utf8))- }+ let value = (try? JSONDecoder().decode(RemoteInferenceJSONValue.self, from: data)) ?? .null+ return try VisionComputerResponse.firstAction(in: value)+ }}diff --git a/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swiftindex 5acb655b..5a01d641 100644--- a/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift@@ -109,13 +109,10 @@ public final class PointerComputerUseToolProvider {)}let amount = max(1, min(context.call.input["amount"].flatMap(Int.init) ?? 5, 50))- let (deltaX, deltaY): (Int, Int)- switch direction {- case "up": (deltaX, deltaY) = (0, amount)- case "down": (deltaX, deltaY) = (0, -amount)- case "left": (deltaX, deltaY) = (amount, 0)- default: (deltaX, deltaY) = (-amount, 0)- }+ // Unknown direction falls back to "right", preserving the prior default branch. The sign+ // convention itself lives once in VisionComputerActionExecutor so the two scroll paths agree.+ let scrollDirection = VisionComputerAction.ScrollDirection(rawValue: direction) ?? .right+ let (deltaX, deltaY) = VisionComputerActionExecutor.scrollLineDeltas(direction: scrollDirection, lines: amount)MacPointerInput.scroll(at: point, deltaX: deltaX, deltaY: deltaY, target: routing.inputTarget)return HarnessToolResult(callID: context.call.id,@@ -175,10 +172,13 @@ public final class PointerComputerUseToolProvider {imageWidth: geometry.imageWidth,imageHeight: geometry.imageHeight)- let plan = VisionActionPlanner.PlannedAction(- action: "click", x: normalized.x, y: normalized.y, text: nil, reason: nil, screenPoint: nil+ // A screen/desktop-scope element carries the display rect it was detected in; map through that,+ // matching vision.click. Falling back to the window rect would misplace a click/scroll/drag on+ // anything detected outside the front window (a modal, a menu, another monitor).+ return VisionComputerActionExecutor.screenPoint(+ VisionComputerAction.Point(x: normalized.x, y: normalized.y),+ window: geometry.region ?? window)- return VisionActionPlanner.screenPoint(action: plan, window: window)}// MARK: - Helpersdiff --git a/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift b/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swiftindex 5bed77e0..37bcaeed 100644--- a/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift+++ b/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift@@ -5,10 +5,10 @@ import DonkeyRuntimeimport Foundation/// Drives a non-scriptable app by vision: a bounded per-turn loop that screenshots the app window,-/// asks `VisionActionPlanner` for the next click/type/key, and executes it with the real-/// pointer/keyboard until the model reports `done`. Shared by the production command router-/// (`UserQueryCommandHandler.handleVisionAction`) and the Spotify live smoke test, so both exercise-/// the exact same loop, guards, and action handling.+/// asks a computer-use planner for the next action, and runs it through+/// `VisionComputerActionExecutor` until the model stops calling the tool (goal done). Shared by the+/// Live → vision escalation and the Spotify live smoke test, so both exercise the exact same loop,+/// guards, and action handling.////// Safety: every real-input action is gated behind a frontmost check — the target window must be the/// frontmost app at the instant of the click/keystroke, so input never lands on a window the user@@ -28,16 +28,16 @@ public enum VisionActionDriver {_ window: WindowTargetBounds,_ history: [String],_ appGuidance: String?- ) async throws -> VisionActionPlanner.PlannedAction+ ) async throws -> VisionComputerAction- /// Repeated identical clicks mean the model is stuck (clicking a target that- /// never responds); abort rather than burn the whole turn budget on it.- private static let stuckClickRepeatLimit = 4+ /// Repeating the same action with no effect means the model is stuck; abort rather than burn the+ /// whole turn budget on it. Applies to any action except scroll/wait, where repeating is normal.+ private static let stuckRepeatLimit = 4public struct Outcome: Sendable {public var completed: Boolpublic var turns: Int- /// "ok" | "noWindowForApp" | "screenshotFailed" | "visionPlanFailed" | "targetNotFrontmost" | "stuckRepeatingClick" | "maxTurnsReached"+ /// "ok" | "noWindowForApp" | "screenshotFailed" | "visionPlanFailed" | "targetNotFrontmost" | "stuckRepeatingAction" | "maxTurnsReached"public var reason: Stringpublic var lastNarration: String?public var history: [String]@@ -47,7 +47,7 @@ public enum VisionActionDriver {public struct TurnInfo: Sendable {public var turn: Intpublic var screenshot: CapturedWindowScreenshot- public var action: VisionActionPlanner.PlannedAction+ public var action: VisionComputerAction}/// Convenience: drive via the backend `createResponse` planner@@ -102,8 +102,8 @@ public enum VisionActionDriver {var history: [String] = []var lastNarration: String?var turnsTaken = 0- var lastClickKey = ""- var clickRepeatCount = 0+ var lastActionSignature = ""+ var repeatCount = 0// Resolve the target window once and reuse it; only re-resolve when a capture fails (the// window moving/closing is the only thing that invalidates the cached bounds).@@ -136,14 +136,14 @@ public enum VisionActionDriver {return finish(false, turnsTaken, "screenshotFailed", lastNarration, history)}- let action: VisionActionPlanner.PlannedAction+ let action: VisionComputerActiondo {action = try await planner(goal, appName, shot, target.bounds, history, appGuidance)} catch {return finish(false, turnsTaken, "visionPlanFailed", lastNarration, history)}turnsTaken += 1- lastNarration = action.reason.flatMap { $0.isEmpty ? nil : $0 } ?? lastNarration+ lastNarration = action.intent.isEmpty ? lastNarration : action.intentonTurn?(TurnInfo(turn: turnsTaken - 1, screenshot: shot, action: action))// Focus can change during the model round-trip; re-check before any real input so we never@@ -152,48 +152,36 @@ public enum VisionActionDriver {return finish(false, turnsTaken, "targetNotFrontmost", lastNarration, history)}- // A "click" that carries text but no resolvable point is really a "type".- var effective = action.action- if effective == "click", action.screenPoint == nil, let text = action.text, !text.isEmpty {- effective = "type"- }-- switch effective {- case "done":- // Verify-don't-trust when an independent signal is available: the model- // claiming done while verify() is false means its last action missed.+ // The computer-use model signals completion by replying in words instead of calling the+ // tool. Verify-don't-trust when an independent signal is available: a "done" while+ // verify() is false means the last action missed.+ if case let .done(text) = action.kind {+ let summary = text.isEmpty ? lastNarration : textif let verify {- if verify() { return finish(true, turnsTaken, "ok", lastNarration, history) }- history.append("claimed done but the goal isn't satisfied yet — your last action missed; click the exact target")+ if verify() { return finish(true, turnsTaken, "ok", summary, history) }+ history.append("claimed done but the goal isn't satisfied yet — your last action missed; act on the exact target")} else {- return finish(true, turnsTaken, "ok", lastNarration, history)+ return finish(true, turnsTaken, "ok", summary, history)}- case "click":- if let point = action.screenPoint {- let key = "\(Int(point.x)),\(Int(point.y))"- clickRepeatCount = (key == lastClickKey) ? clickRepeatCount + 1 : 0- lastClickKey = key- if clickRepeatCount >= stuckClickRepeatLimit {- history.append("aborting: stuck repeating click \(key)")- return finish(false, turnsTaken, "stuckRepeatingClick", lastNarration, history)+ } else {+ // Stop a stuck loop that keeps repeating the same no-op action (a missed click, a+ // browser action the desktop can't run, …). Scroll/wait are exempt — repeating them is+ // a normal pattern (paging a long list, waiting for load), so their signature is nil.+ if let signature = actionSignature(action, window: target.bounds) {+ repeatCount = (signature == lastActionSignature) ? repeatCount + 1 : 0+ lastActionSignature = signature+ if repeatCount >= stuckRepeatLimit {+ history.append("aborting: stuck repeating \(signature)")+ return finish(false, turnsTaken, "stuckRepeatingAction", lastNarration, history)}- _ = MacPointerInput.moveAndClick(at: point)- history.append(clickRepeatCount >= 2- ? "clicked (\(key)) AGAIN — not working; pick a DIFFERENT target/exact center: \(action.reason ?? "")"- : "clicked at (\(key)): \(action.reason ?? "")")} else {- history.append("skipped click with no resolvable point")+ repeatCount = 0+ lastActionSignature = ""}- case "type":- let text = action.text ?? ""- MacKeyboardInput.type(text)- history.append("typed \"\(text)\"")- case "key":- let key = action.text ?? "return"- MacKeyboardInput.pressKey(key)- history.append("pressed key \(key)")- default:- history.append("ignored unknown action \(action.action)")+ let line = await VisionComputerActionExecutor.execute(action, window: target.bounds)+ history.append(repeatCount >= 2+ ? "\(line) — repeated; if nothing changed pick a DIFFERENT target/exact center"+ : line)}try? await Task.sleep(nanoseconds: settleNanoseconds)@@ -216,6 +204,29 @@ public enum VisionActionDriver {Outcome(completed: completed, turns: turns, reason: reason, lastNarration: lastNarration, history: history)}+ /// A stable signature for stuck-repeat detection, or nil for kinds where consecutive repeats are a+ /// legitimate pattern (scrolling a long list, waiting for load) and must not trip the guard.+ private static func actionSignature(_ action: VisionComputerAction, window: WindowTargetBounds) -> String? {+ switch action.kind {+ case .scroll, .wait, .done:+ return nil+ case let .click(button, count, point):+ let screen = VisionComputerActionExecutor.screenPoint(point, window: window)+ return "click:\(button.rawValue):\(count):\(Int(screen.x)),\(Int(screen.y))"+ case let .move(point):+ let screen = VisionComputerActionExecutor.screenPoint(point, window: window)+ return "move:\(Int(screen.x)),\(Int(screen.y))"+ case let .drag(from, to):+ return "drag:\(Int(from.x)),\(Int(from.y))->\(Int(to.x)),\(Int(to.y))"+ case let .type(text, _, _, _):+ return "type:\(text)"+ case let .keys(keys):+ return "keys:\(keys.joined(separator: "+"))"+ case let .unsupported(name):+ return "unsupported:\(name)"+ }+ }+private static func captureWithRetry(_ candidate: MacWindowTargetCandidate,appName: String,diff --git a/apps/Donkey/Sources/DonkeyAI/VisionActionPlanner.swift b/apps/Donkey/Sources/DonkeyAI/VisionActionPlanner.swiftindex 5a18a193..269a821e 100644--- a/apps/Donkey/Sources/DonkeyAI/VisionActionPlanner.swift+++ b/apps/Donkey/Sources/DonkeyAI/VisionActionPlanner.swift@@ -3,43 +3,22 @@ import DonkeyContractsimport DonkeyRuntimeimport Foundation-/// Goal-directed, per-turn vision driver: given the current window screenshot and a goal, ask the-/// hosted vision model for the SINGLE next action (click / type / key / done). The caller executes it,-/// re-screenshots, and asks again — so the plan adapts to whatever the UI becomes after each step-/// (search → results → artist page → play), which is exactly what's needed for apps whose post-click-/// UI you can't know in advance (Spotify, Slack, …).+/// Goal-directed, per-turn vision planner over the hosted `createResponse` boundary: given the current+/// window screenshot and a goal, it asks Gemini's built-in `computer_use` tool (macOS desktop+/// environment, via the backend's `donkey_gemini_mac_desktop_interaction` tool) for the single next UI+/// action and returns it as a typed `VisionComputerAction`. The caller executes it, re-screenshots, and+/// asks again — so the plan adapts to whatever the UI becomes after each step.////// The screenshot is compressed (downscaled + JPEG) with `ScreenshotCompression` — the same path the-/// debug UI inspection flow uses — so the model receives a small payload. The model reports click-/// coordinates in Gemini's native 0–1000 normalized space, which `screenPoint` maps to the window.-/// App-specific operating knowledge (where controls are, how to read state) is supplied via-/// `appGuidance`, sourced from a discoverable app skill — never hardcoded here.-public enum VisionActionPlannerError: Error, CustomStringConvertible {- case missingOutputText(rawResponse: String)-- public var description: String {- switch self {- case let .missingOutputText(raw): return "missingOutputText raw=\(raw)"- }- }-}--/// Driven in production by `UserQueryCommandHandler.handleVisionAction` for non-scriptable apps, and-/// by `SpotifyVisionAgentLiveSmokeTests` for live verification.+/// debug UI inspection flow uses — so the model receives a small payload. App-specific operating+/// knowledge (where controls are, how to read state) is supplied via `appGuidance`, sourced from a+/// discoverable app skill — never hardcoded here.+///+/// Driven in production by the Live → vision escalation (via the direct-Vertex+/// `GeminiVertexVisionPlanner`) and by `SpotifyVisionAgentLiveSmokeTests` for live verification of this+/// hosted path.@MainActorpublic enum VisionActionPlanner {- public struct PlannedAction: Equatable, Sendable, Codable {- public var action: String // "click" | "type" | "key" | "done"- public var x: Double?- public var y: Double?- public var text: String?- public var reason: String?- /// Resolved real-screen point for `click` actions (nil for non-click / unmappable).- public var screenPoint: CGPoint?-- private enum CodingKeys: String, CodingKey { case action, x, y, text, reason }- }-public static func nextAction(goal: String,app: String,@@ -48,87 +27,12 @@ public enum VisionActionPlanner {history: [String] = [],appGuidance: String? = nil,backend: DonkeyBackendInferenceClient- ) async throws -> PlannedAction {+ ) async throws -> VisionComputerAction {let compressed = ScreenshotCompression.compressedForModel(screenshot)let response = try await backend.createResponse(responseRequest(goal: goal, app: app, compressed: compressed, history: history, appGuidance: appGuidance))- guard let text = outputText(from: response), !text.isEmpty else {- let raw = (try? JSONEncoder().encode(response)).flatMap { String(data: $0, encoding: .utf8) } ?? "<unencodable>"- throw VisionActionPlannerError.missingOutputText(rawResponse: String(raw.prefix(2_000)))- }- let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)- var action = try JSONDecoder().decode(PlannedAction.self, from: Data(json.utf8))- action.screenPoint = screenPoint(action: action, window: window)- return action- }-- /// Gemini reports click coordinates in its native 0–1000 NORMALIZED space (x=0 left … 1000 right,- /// y=0 top … 1000 bottom of the image), NOT raw pixels — so we map normalized → window bounds.- /// This is independent of the compressed image size, which is why it stays correct after downscaling.- nonisolated static let normalizedCoordinateScale = 1_000.0-- nonisolated static func screenPoint(- action: PlannedAction,- window: WindowTargetBounds- ) -> CGPoint? {- guard let x = action.x, let y = action.y else { return nil }- let nx = min(max(x / normalizedCoordinateScale, 0), 1)- let ny = min(max(y / normalizedCoordinateScale, 0), 1)- return CGPoint(- x: window.x + nx * window.width,- y: window.y + ny * window.height- )- }-- /// Builds the vision-action prompt shared by every planner backend (the- /// `backend.createResponse` path here and the direct-Vertex- /// `GeminiVertexVisionPlanner`). Kept in one place so the prompt — the single- /// most impactful lever on click accuracy — can never drift between paths, and- /// so the discoverable per-app `appGuidance` is applied uniformly (never a- /// hardcoded app list). `width`/`height` are the model-visible image pixels.- nonisolated static func visionPrompt(- goal: String,- app: String,- width: Int,- height: Int,- history: [String],- appGuidance: String?- ) -> String {- let historyBlock = history.isEmpty- ? "This is the first action; nothing has been done yet."- : "Actions you have ALREADY performed, in order (do NOT repeat one that already worked):\n"- + history.enumerated().map { " \($0.offset + 1). \($0.element)" }.joined(separator: "\n")- let guidanceBlock: String- if let appGuidance, !appGuidance.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- guidanceBlock = """-- APP-SPECIFIC OPERATING GUIDE for "\(app)" (follow this — it describes where controls are and how to read state; it never gives fixed coordinates, so always read the current screenshot for exact positions):- \(appGuidance)- """- } else {- guidanceBlock = ""- }- return """- You are operating the macOS app "\(app)" by clicking and typing to accomplish a goal.- GOAL: \(goal)- The attached screenshot is the CURRENT state of the app window (\(width) x \(height) pixels), origin top-left.-- \(historyBlock)- \(guidanceBlock)-- Decide the SINGLE next action that best progresses toward the goal given ONLY what is visible now.- Each action type has a STRICT meaning — never overload one:- - "click": move the pointer and click. Set x and y to the center of the target. NEVER put text in a click; a click has no text.- - "type": type characters into the field that is ALREADY focused. Set "text" to the characters and set x and y to 0. Use this AFTER you have clicked a text field — do not click again, just type.- - "key": press a single key. Set "text" to the key name (e.g. "return" to submit a search) and set x and y to 0.- - "done": the goal is fully and verifiably satisfied in the current screenshot. Set x and y to 0.- COORDINATES: report x and y NORMALIZED to a 0–1000 scale relative to the image — x=0 is the left edge and x=1000 the right edge; y=0 is the top edge and y=1000 the bottom edge. (Use 0 for non-click actions.)- Look at the history and the screenshot: if you just clicked a text field, the next action should be "type", not another click. Do not get stuck repeating the same step.- If you clicked something and the screenshot looks unchanged, your click MISSED — do not repeat the same coordinate; re-locate the target and aim at its exact visual center.- CLICK PRECISELY: set x,y to the exact visual CENTER of the intended control, not above/below/beside it.- Keep "reason" to one short sentence.- """+ return try VisionComputerResponse.firstAction(in: response)}private static func responseRequest(@@ -140,10 +44,11 @@ public enum VisionActionPlanner {) -> RemoteInferenceResponseCreateRequest {let width = Int(compressed.pixelSize.width.rounded())let height = Int(compressed.pixelSize.height.rounded())- let prompt = visionPrompt(+ let prompt = VisionComputerUsePrompt.instructions(goal: goal, app: app, width: width, height: height, history: history, appGuidance: appGuidance)return RemoteInferenceResponseCreateRequest(+ donkeyProvider: "gemini",input: .array([.object(["role": .string("user"),@@ -158,50 +63,21 @@ public enum VisionActionPlanner {])]),store: false,- text: [- "format": .object([- "type": .string("json_schema"),- "name": .string("vision_action_v1"),- "strict": .bool(true),- "schema": .object([- "type": .string("object"),- "additionalProperties": .bool(false),- "required": .array([.string("action"), .string("x"), .string("y"), .string("reason")]),- "properties": .object([- "action": .object([- "type": .string("string"),- "enum": .array([.string("click"), .string("type"), .string("key"), .string("done")])- ]),- "x": .object(["type": .string("number")]),- "y": .object(["type": .string("number")]),- "text": .object(["type": .string("string")]),- "reason": .object(["type": .string("string")])- ])- ])- ])+ // The built-in computer-use tool answers via function calls, so no `text` JSON format.+ tools: [+ RemoteInferenceComputerUseTool(+ type: .geminiMacDesktopInteraction,+ metadata: ["mode": "act", "schema": "computer-use-desktop-v1"]+ ).jsonObject],- metadata: ["source": "vision-action-planner", "prompt_version": "vision-action-v1"],+ metadata: ["source": "vision-action-planner", "prompt_version": "computer-use-desktop-v1"],parameters: ["temperature": .number(0),- // Headroom for medium thinking PLUS the small action JSON, so thinking can't starve it.+ // Headroom for medium thinking PLUS the small function call, so thinking can't starve it."max_output_tokens": .number(3_000),// Gemini 3.x honors thinking_level, not the integer thinking_budget (which it ignores).- // The thought summary returns separately from the JSON, so it can't corrupt the action."thinking_level": .string("medium")])}-- private static func outputText(from value: RemoteInferenceJSONValue) -> String? {- guard let object = value.objectValue else { return nil }- if let text = object["output_text"]?.stringValue { return text }- return object["output"]?.arrayValue?- .compactMap { item -> String? in- guard let content = item.objectValue?["content"]?.arrayValue else {- return item.objectValue?["text"]?.stringValue- }- return content.compactMap { $0.objectValue?["text"]?.stringValue }.joined()- }- .joined(separator: "\n")- }}diff --git a/apps/Donkey/Sources/DonkeyAI/VisionComputerAction.swift b/apps/Donkey/Sources/DonkeyAI/VisionComputerAction.swiftnew file mode 100644index 00000000..50494313--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/VisionComputerAction.swift@@ -0,0 +1,393 @@+import DonkeyContracts+import DonkeyRuntime+import Foundation++/// One UI action requested by Gemini's built-in `computer_use` tool, normalized from the model's+/// native function call into a shape the executor can run. The model reports click coordinates in its+/// 0–1000 normalized space (origin top-left); `VisionComputerActionExecutor` maps them onto the+/// target window. The desktop tool emits a small, stable action vocabulary (click variants, move,+/// drag, scroll, type, key chords, wait); browser-only navigation functions are excluded server-side.+public struct VisionComputerAction: Sendable, Equatable {+ public enum ScrollDirection: String, Sendable, Equatable {+ case up, down, left, right+ }++ /// A point in the model's 0–1000 normalized image space (origin top-left).+ public struct Point: Sendable, Equatable {+ public var x: Double+ public var y: Double+ public init(x: Double, y: Double) {+ self.x = x+ self.y = y+ }+ }++ public enum Kind: Sendable, Equatable {+ case click(button: MacPointerInput.Button, count: Int, point: Point)+ case move(point: Point)+ case drag(from: Point, to: Point)+ case scroll(point: Point?, direction: ScrollDirection, magnitude: Double?)+ case type(text: String, point: Point?, pressEnter: Bool, clearFirst: Bool)+ case keys([String])+ case wait(seconds: Double)+ /// The model returned no function call — the goal is finished; `text` is its closing summary.+ case done(text: String)+ /// A predefined function we don't run on the macOS desktop (browser navigation, etc.).+ case unsupported(name: String)+ }++ public var kind: Kind+ /// The model's own one-line `intent` for this action, when supplied.+ public var intent: String++ public init(kind: Kind, intent: String = "") {+ self.kind = kind+ self.intent = intent+ }++ /// A one-line, human-readable description (for traces and smoke-test logs).+ public var summary: String {+ let head: String+ switch kind {+ case let .click(button, count, point):+ head = "\(VisionComputerActionExecutor.clickVerb(button: button, count: count)) (\(Int(point.x)),\(Int(point.y)))"+ case let .move(point):+ head = "move (\(Int(point.x)),\(Int(point.y)))"+ case let .drag(from, to):+ head = "drag (\(Int(from.x)),\(Int(from.y)))→(\(Int(to.x)),\(Int(to.y)))"+ case let .scroll(_, direction, _):+ head = "scroll \(direction.rawValue)"+ case let .type(text, _, pressEnter, _):+ head = "type \"\(text)\"\(pressEnter ? " ⏎" : "")"+ case let .keys(keys):+ head = "keys \(keys.joined(separator: "+"))"+ case let .wait(seconds):+ head = "wait \(seconds)s"+ case .done:+ head = "done"+ case let .unsupported(name):+ head = "unsupported \(name)"+ }+ return intent.isEmpty ? head : "\(head) :: \(intent)"+ }+}++/// Configuration shared by every desktop computer-use tool declaration. The agent never drives a web+/// browser's chrome on the macOS desktop, so the browser-navigation predefined functions are excluded+/// — leaving the GUI actions (click, type, scroll, drag, key chords, …). Defined once so the+/// direct-Vertex planner and the backend desktop tool can't drift.+public enum VisionComputerDesktopTool {+ public static let excludedPredefinedFunctions = [+ "open_web_browser",+ "navigate",+ "go_back",+ "go_forward",+ "search",+ ]+}++/// A raw computer-use function call (name + arguments) pulled from a model response, before it is+/// normalized into a `VisionComputerAction`.+public struct VisionFunctionCall: Sendable, Equatable {+ public var name: String+ public var arguments: RemoteInferenceJSONObject++ public init(name: String, arguments: RemoteInferenceJSONObject) {+ self.name = name+ self.arguments = arguments+ }+}++public extension VisionComputerAction {+ /// Normalizes a raw computer-use function call into a typed action. Tolerant of the two function+ /// naming families Gemini computer use uses across model versions — the streamlined `click` /+ /// `type` / `scroll` set and the older `click_at` / `type_text_at` / `scroll_at` set — and of+ /// snake_case argument variants, so the executor sees one stable shape.+ static func from(call: VisionFunctionCall) -> VisionComputerAction {+ let name = call.name.lowercased()+ let intent = call.string("intent", "reason", "description") ?? ""++ func tagged(_ kind: Kind) -> VisionComputerAction { VisionComputerAction(kind: kind, intent: intent) }+ func clickKind(_ button: MacPointerInput.Button, _ count: Int) -> VisionComputerAction {+ guard let point = call.point() else { return tagged(.unsupported(name: call.name)) }+ return tagged(.click(button: button, count: count, point: point))+ }++ switch name {+ case "click", "click_at", "left_click", "left_click_at", "tap", "tap_at":+ return clickKind(.left, 1)+ case "double_click", "double_click_at", "doubleclick":+ return clickKind(.left, 2)+ case "triple_click", "triple_click_at":+ return clickKind(.left, 3)+ case "right_click", "right_click_at", "context_click":+ return clickKind(.right, 1)+ case "middle_click", "middle_click_at":+ return clickKind(.center, 1)+ case "move", "mouse_move", "move_to", "hover", "hover_at":+ guard let point = call.point() else { return tagged(.unsupported(name: call.name)) }+ return tagged(.move(point: point))+ case "drag", "drag_and_drop", "dragdrop":+ // gemini-3.5-flash uses start_x/start_y/end_x/end_y; the 2.5 model used x/y ++ // destination_x/destination_y — accept both.+ guard let from = call.point(["start_x", "x"], ["start_y", "y"]),+ let to = call.point(["end_x", "destination_x", "to_x", "x2"], ["end_y", "destination_y", "to_y", "y2"])+ else { return tagged(.unsupported(name: call.name)) }+ return tagged(.drag(from: from, to: to))+ case "scroll", "scroll_at", "scroll_document", "scroll_window":+ let direction = ScrollDirection(rawValue: (call.string("direction") ?? "down").lowercased()) ?? .down+ return tagged(.scroll(+ point: call.point(),+ direction: direction,+ magnitude: call.double(["magnitude_in_pixels", "magnitude", "amount", "distance"])+ ))+ case "type", "type_text", "type_text_at", "input_text", "keyboard_type":+ let point = call.point()+ return tagged(.type(+ text: call.string("text", "value") ?? "",+ point: point,+ pressEnter: call.bool("press_enter", "enter", "submit") ?? false,+ clearFirst: call.bool("clear_before_typing", "clear") ?? (point != nil)+ ))+ case "key_combination", "hotkey", "press_key", "key", "keypress", "key_press":+ return tagged(.keys(call.keyList()))+ case "wait", "wait_5_seconds", "sleep":+ return tagged(.wait(seconds: call.double(["seconds", "duration", "duration_seconds"]) ?? defaultWaitSeconds(for: name)))+ default:+ return tagged(.unsupported(name: call.name))+ }+ }++ private static func defaultWaitSeconds(for name: String) -> Double {+ name == "wait_5_seconds" ? 5 : 1+ }+}++public enum VisionComputerResponseError: Error, CustomStringConvertible {+ /// The response carried neither a function call nor any text — an empty, safety-blocked, or+ /// truncated turn. Surfaced as an error so the driver fails the run instead of reporting the+ /// goal "done" off a model turn that produced nothing.+ case noPlan(rawPreview: String)++ public var description: String {+ switch self {+ case let .noPlan(preview): return "model returned no action and no text: \(preview.prefix(200))"+ }+ }+}++/// Pulls computer-use function calls (and any closing text) out of a model response, handling both+/// transports: the backend's normalized Responses shape (`computer_use.calls[]`, then `output[]`+/// function-call items) and the raw Vertex `generateContent` shape+/// (`candidates[].content.parts[].functionCall`).+public enum VisionComputerResponse {+ /// The single next action for one model turn: the first function call decoded into an action, or+ /// `.done` when the model finished and replied in words. Throws `noPlan` when the turn carried+ /// NEITHER a call nor text, so an empty/blocked/truncated response fails the run rather than being+ /// mistaken for completion. Shared by both planners so the two transports decode identically.+ public static func firstAction(in value: RemoteInferenceJSONValue) throws -> VisionComputerAction {+ if let call = functionCalls(in: value).first {+ return VisionComputerAction.from(call: call)+ }+ let text = outputText(in: value)+ guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw VisionComputerResponseError.noPlan(rawPreview: text)+ }+ return VisionComputerAction(kind: .done(text: text))+ }++ public static func functionCalls(in value: RemoteInferenceJSONValue) -> [VisionFunctionCall] {+ guard let object = value.objectValue else { return [] }++ if let calls = object["computer_use"]?.objectValue?["calls"]?.arrayValue {+ let parsed = calls.compactMap(hostedCall(from:))+ if !parsed.isEmpty { return parsed }+ }+ if let output = object["output"]?.arrayValue {+ let parsed = output.compactMap(outputItemCall(from:))+ if !parsed.isEmpty { return parsed }+ }+ if let candidates = object["candidates"]?.arrayValue {+ let parsed = candidates.flatMap(vertexCandidateCalls(from:))+ if !parsed.isEmpty { return parsed }+ }+ return []+ }++ /// The model's plain text — its closing "done" summary when no function call is present, or an+ /// action's narration. Thought-summary parts (Vertex) are excluded.+ public static func outputText(in value: RemoteInferenceJSONValue) -> String {+ guard let object = value.objectValue else { return "" }++ if let text = object["output_text"]?.stringValue, !text.isEmpty {+ return text+ }+ if let parts = object["candidates"]?.arrayValue?.first?+ .objectValue?["content"]?.objectValue?["parts"]?.arrayValue {+ let text = parts.compactMap { part -> String? in+ guard let partObject = part.objectValue, partObject["thought"]?.boolFlag != true else { return nil }+ return partObject["text"]?.stringValue+ }.joined(separator: "\n")+ if !text.isEmpty { return text }+ }+ if let output = object["output"]?.arrayValue {+ let text = output.compactMap { item -> String? in+ guard let itemObject = item.objectValue else { return nil }+ if let direct = itemObject["text"]?.stringValue { return direct }+ return itemObject["content"]?.arrayValue?+ .compactMap { $0.objectValue?["text"]?.stringValue }+ .joined()+ }.joined(separator: "\n")+ if !text.isEmpty { return text }+ }+ return ""+ }++ private static func hostedCall(from value: RemoteInferenceJSONValue) -> VisionFunctionCall? {+ guard let object = value.objectValue, let name = object["name"]?.stringValue else { return nil }+ return VisionFunctionCall(name: name, arguments: argumentsObject(object))+ }++ private static func outputItemCall(from value: RemoteInferenceJSONValue) -> VisionFunctionCall? {+ guard let object = value.objectValue,+ object["type"]?.stringValue == "function_call",+ let name = object["name"]?.stringValue+ else { return nil }+ return VisionFunctionCall(name: name, arguments: argumentsObject(object))+ }++ private static func vertexCandidateCalls(from value: RemoteInferenceJSONValue) -> [VisionFunctionCall] {+ guard let parts = value.objectValue?["content"]?.objectValue?["parts"]?.arrayValue else { return [] }+ return parts.compactMap { part -> VisionFunctionCall? in+ guard let call = part.objectValue?["functionCall"]?.objectValue+ ?? part.objectValue?["function_call"]?.objectValue,+ let name = call["name"]?.stringValue+ else { return nil }+ return VisionFunctionCall(name: name, arguments: argumentsObject(call))+ }+ }++ /// Reads the call's arguments whether they arrive under `arguments` (hosted/output) or `args`+ /// (Vertex / raw SDK).+ private static func argumentsObject(_ object: RemoteInferenceJSONObject) -> RemoteInferenceJSONObject {+ object["arguments"]?.objectValue ?? object["args"]?.objectValue ?? [:]+ }+}++/// Shared instruction text for the computer-use loop. Kept in one place so the direct-Vertex planner+/// and the hosted `createResponse` planner send the same framing; the action vocabulary itself comes+/// from the built-in tool, so this only states the goal, the current screen, prior steps, and the+/// discoverable per-app guidance (never a hardcoded app list, never fixed coordinates).+public enum VisionComputerUsePrompt {+ public static func instructions(+ goal: String,+ app: String,+ width: Int,+ height: Int,+ history: [String],+ appGuidance: String?+ ) -> String {+ let historyBlock = history.isEmpty+ ? "This is the first action; nothing has been done yet."+ : "Actions already performed, in order (do NOT repeat one that already worked):\n"+ + history.suffix(10).enumerated().map { " \($0.offset + 1). \($0.element)" }.joined(separator: "\n")+ let guidanceBlock: String+ if let appGuidance, !appGuidance.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ guidanceBlock = """+++ APP-SPECIFIC OPERATING GUIDE for "\(app)" (follow it — it says where controls are and how to read state; it never gives fixed coordinates, so always read the current screenshot for exact positions):+ \(appGuidance)+ """+ } else {+ guidanceBlock = ""+ }+ return """+ You are operating the macOS app "\(app)" to accomplish a goal. Use the computer tool to act on \+ the screen, one step at a time.+ GOAL: \(goal)+ The attached screenshot is the CURRENT state of the app window (\(width) x \(height) pixels), origin top-left.++ \(historyBlock)\(guidanceBlock)++ Take the SINGLE next action that best progresses toward the goal given only what is visible now. \+ If your last action produced no visible change it missed — re-locate the target and aim at its \+ exact center rather than repeating the same spot. When the goal is fully and verifiably satisfied \+ in the current screenshot, stop and reply with a one-line confirmation instead of calling the tool.+ """+ }+}++private extension VisionFunctionCall {+ func string(_ keys: String...) -> String? {+ for key in keys {+ if let value = arguments[key]?.stringValue, !value.isEmpty { return value }+ }+ return nil+ }++ func double(_ keys: [String]) -> Double? {+ for key in keys {+ if let value = arguments[key]?.doubleNumber { return value }+ }+ return nil+ }++ func bool(_ keys: String...) -> Bool? {+ for key in keys {+ if let value = arguments[key]?.boolFlag { return value }+ }+ return nil+ }++ /// A normalized point from `x`/`y` (or the supplied key aliases). Returns nil if either axis is+ /// missing, so the decoder can reject a coordinate action that carries no target.+ func point(_ xKeys: [String] = ["x"], _ yKeys: [String] = ["y"]) -> VisionComputerAction.Point? {+ guard let x = double(xKeys), let y = double(yKeys) else { return nil }+ return VisionComputerAction.Point(x: x, y: y)+ }++ /// A key chord as an ordered list, from either an array (`keys: ["control","c"]`) or a+ /// `+`-joined string (`keys: "control+c"`), or a single `key`.+ func keyList() -> [String] {+ if let array = arguments["keys"]?.arrayValue {+ return array.compactMap { $0.stringValue }+ }+ if let joined = arguments["keys"]?.stringValue {+ return joined.split(separator: "+").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }+ }+ if let single = arguments["key"]?.stringValue {+ return single.contains("+")+ ? single.split(separator: "+").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }+ : [single]+ }+ if let array = arguments["key"]?.arrayValue {+ return array.compactMap { $0.stringValue }+ }+ return []+ }+}++private extension RemoteInferenceJSONValue {+ var doubleNumber: Double? {+ switch self {+ case .number(let value): return value+ case .string(let value): return Double(value)+ default: return nil+ }+ }++ var boolFlag: Bool? {+ switch self {+ case .bool(let value): return value+ case .number(let value): return value != 0+ case .string(let value):+ switch value.trimmingCharacters(in: .whitespaces).lowercased() {+ case "true", "yes", "on", "1": return true+ case "false", "no", "off", "0": return false+ default: return nil+ }+ default: return nil+ }+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/VisionComputerActionExecutor.swift b/apps/Donkey/Sources/DonkeyAI/VisionComputerActionExecutor.swiftnew file mode 100644index 00000000..f43ed79b--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/VisionComputerActionExecutor.swift@@ -0,0 +1,146 @@+import CoreGraphics+import DonkeyContracts+import DonkeyRuntime+import Foundation++/// Runs one normalized `VisionComputerAction` against the target window with the real pointer and+/// keyboard, returning a short history line. This is the single sink for both computer-use loops (the+/// direct-Vertex Live escalation and the hosted `createResponse` path), so coordinate mapping and the+/// action vocabulary stay identical across them.+///+/// `target` is nil for foreground input (the driver brings the app frontmost and the real cursor+/// moves); a background `InputTarget` routes input to the process without warping the cursor.+@MainActor+public enum VisionComputerActionExecutor {+ @discardableResult+ public static func execute(+ _ action: VisionComputerAction,+ window: WindowTargetBounds,+ target: InputTarget? = nil+ ) async -> String {+ let note = action.intent.isEmpty ? "" : ": \(action.intent)"++ switch action.kind {+ case let .click(button, count, point):+ let screen = screenPoint(point, window: window)+ MacPointerInput.moveAndClick(at: screen, button: button, clickCount: count, target: target)+ return "\(clickLabel(button, count)) (\(label(screen)))\(note)"++ case let .move(point):+ let screen = screenPoint(point, window: window)+ MacPointerInput.move(to: screen, target: target)+ return "moved to (\(label(screen)))\(note)"++ case let .drag(from, to):+ let start = screenPoint(from, window: window)+ let end = screenPoint(to, window: window)+ MacPointerInput.drag(from: start, to: end, target: target)+ return "dragged (\(label(start))) → (\(label(end)))\(note)"++ case let .scroll(point, direction, magnitude):+ let screen = point.map { screenPoint($0, window: window) } ?? windowCenter(window)+ let (deltaX, deltaY) = scrollDeltas(direction: direction, magnitude: magnitude)+ MacPointerInput.scroll(at: screen, deltaX: deltaX, deltaY: deltaY, target: target)+ return "scrolled \(direction.rawValue) (\(label(screen)))\(note)"++ case let .type(text, point, pressEnter, clearFirst):+ if let point {+ MacPointerInput.moveAndClick(at: screenPoint(point, window: window), target: target)+ }+ if clearFirst {+ MacKeyboardInput.pressKey("a", modifiers: ["command"], target: target)+ MacKeyboardInput.pressKey("delete", target: target)+ }+ MacKeyboardInput.type(text, target: target)+ if pressEnter {+ MacKeyboardInput.pressReturn(target: target)+ }+ return "typed \"\(text)\"\(pressEnter ? " ⏎" : "")\(note)"++ case let .keys(keys):+ guard let last = keys.last else {+ // Unrecognized/empty key call: fall back to Return (submit), as the prior loop did when+ // a key action arrived without a name — better than silently doing nothing.+ MacKeyboardInput.pressReturn(target: target)+ return "pressed return (empty key combination)\(note)"+ }+ MacKeyboardInput.pressKey(last, modifiers: Array(keys.dropLast()), target: target)+ return "pressed \(keys.joined(separator: "+"))\(note)"++ case let .wait(seconds):+ let clamped = min(max(seconds, 0), 10)+ try? await Task.sleep(nanoseconds: UInt64(clamped * 1_000_000_000))+ return "waited \(formatted(clamped))s\(note)"++ case let .done(text):+ return text.isEmpty ? "done\(note)" : "done: \(text)"++ case let .unsupported(name):+ return "ignored unsupported action \(name)\(note)"+ }+ }++ /// Maps a 0–1000 normalized point onto the target window's screen bounds (top-left origin). This is+ /// independent of the compressed screenshot size, so it stays correct after downscaling. The single+ /// normalized→screen mapping shared by the computer-use loops and the harness AX/vision tools.+ /// `nonisolated` so non-MainActor coordinate math (the pointer tools) can reuse it.+ nonisolated public static func screenPoint(_ point: VisionComputerAction.Point, window: WindowTargetBounds) -> CGPoint {+ let nx = min(max(point.x / normalizedScale, 0), 1)+ let ny = min(max(point.y / normalizedScale, 0), 1)+ return CGPoint(x: window.x + nx * window.width, y: window.y + ny * window.height)+ }++ /// Gemini reports coordinates in a 0–1000 normalized space (origin top-left), independent of the+ /// raw pixel size — so detection coordinates expressed in this scale map cleanly to the window.+ nonisolated public static let normalizedScale = 1_000.0++ private static func windowCenter(_ window: WindowTargetBounds) -> CGPoint {+ CGPoint(x: window.x + window.width / 2, y: window.y + window.height / 2)+ }++ /// Maps a scroll direction to CGEvent line deltas for a given line count. CGEvent convention:+ /// positive y scrolls up, positive x scrolls left. The single home for the direction→sign mapping,+ /// shared with the harness `mouse.scroll` tool so the two scroll paths can't drift in sign.+ nonisolated public static func scrollLineDeltas(+ direction: VisionComputerAction.ScrollDirection,+ lines: Int+ ) -> (Int, Int) {+ switch direction {+ case .up: return (0, lines)+ case .down: return (0, -lines)+ case .left: return (lines, 0)+ case .right: return (-lines, 0)+ }+ }++ /// Converts an optional pixel magnitude into a coarse, clamped wheel-line count. The loop+ /// re-screenshots after each step, so an approximate amount is fine.+ private static func scrollDeltas(+ direction: VisionComputerAction.ScrollDirection,+ magnitude: Double?+ ) -> (Int, Int) {+ let lines = magnitude.map { max(1, min(Int(($0 / 80).rounded()), 20)) } ?? 6+ return scrollLineDeltas(direction: direction, lines: lines)+ }++ /// The base verb for a click variant ("click", "double-click", "right-click", …). The single home+ /// for the button+count → variant decision, so trace, history, and user-facing strings can't drift.+ nonisolated public static func clickVerb(button: MacPointerInput.Button, count: Int) -> String {+ switch button {+ case .right: return "right-click"+ case .center: return "middle-click"+ case .left:+ return count >= 3 ? "triple-click" : count == 2 ? "double-click" : "click"+ }+ }++ private static func clickLabel(_ button: MacPointerInput.Button, _ count: Int) -> String {+ "\(clickVerb(button: button, count: count))ed"+ }++ private static func label(_ point: CGPoint) -> String { "\(Int(point.x)),\(Int(point.y))" }++ private static func formatted(_ seconds: Double) -> String {+ seconds == seconds.rounded() ? String(Int(seconds)) : String(format: "%.1f", seconds)+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swiftindex 321029fb..383a4ad8 100644--- a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift@@ -400,20 +400,19 @@ public final class VisionComputerUseToolProvider {imageWidth: geometry.imageWidth,imageHeight: geometry.imageHeight)- let plan = VisionActionPlanner.PlannedAction(- action: "click", x: normalized.x, y: normalized.y, text: nil, reason: nil, screenPoint: nil- )// A screen-scope element carries the display rect it was detected in; map through that. A// window-scope element has no region, so map through the window's CURRENT bounds (re-resolved// above) to stay correct if the window moved between the capture and this click.let mappingRegion = geometry.region ?? target.bounds- guard let point = VisionActionPlanner.screenPoint(action: plan, window: mappingRegion) else {- return result(context, status: .failed, summary: "Could not map element \(elementID) to a screen point.", reason: "unmappablePoint")- }+ let point = VisionComputerActionExecutor.screenPoint(+ VisionComputerAction.Point(x: normalized.x, y: normalized.y),+ window: mappingRegion+ )let button: MacPointerInput.Button = context.call.input["button"] == "right" ? .right : .leftlet clicks = context.call.input["clicks"].flatMap(Int.init) ?? 1MacPointerInput.moveAndClick(at: point, button: button, clickCount: clicks, target: inputTarget)- let clickWord = button == .right ? "Right-clicked" : (clicks >= 3 ? "Triple-clicked" : (clicks == 2 ? "Double-clicked" : "Clicked"))+ let verb = VisionComputerActionExecutor.clickVerb(button: button, count: clicks)+ let clickWord = "\(verb.prefix(1).uppercased())\(verb.dropFirst())ed"return HarnessToolResult(callID: context.call.id,toolName: context.call.name,@@ -561,8 +560,8 @@ public final class VisionComputerUseToolProvider {public static let reuseChangedFractionThreshold = 0.02/// The element box center expressed in Gemini's 0–1000 normalized image space, so the shared- /// `VisionActionPlanner.screenPoint` maps it into the window exactly as it does for raw-coordinate- /// planning. Pure mapping, extracted so it is unit-testable without any capture or network.+ /// `VisionComputerActionExecutor.screenPoint` maps it into the window exactly as it does for the+ /// computer-use loops. Pure mapping, extracted so it is unit-testable without any capture or network.nonisolated static func normalizedCenter(bbox: DebugUIBoundingBox,imageWidth: Int,@@ -573,8 +572,8 @@ public final class VisionComputerUseToolProvider {let centerX = bbox.x + bbox.width / 2let centerY = bbox.y + bbox.height / 2return (- x: centerX / width * VisionActionPlanner.normalizedCoordinateScale,- y: centerY / height * VisionActionPlanner.normalizedCoordinateScale+ x: centerX / width * VisionComputerActionExecutor.normalizedScale,+ y: centerY / height * VisionComputerActionExecutor.normalizedScale)}diff --git a/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swift b/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swiftindex b6bce112..05b1bb82 100644--- a/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swift@@ -70,7 +70,7 @@ public typealias RemoteInferenceJSONObject = [String: RemoteInferenceJSONValue]public enum RemoteInferenceComputerUseToolType: String, Codable, Equatable, Sendable {case geminiBrowserInteraction = "donkey_gemini_browser_interaction"- case openAIMacDesktopInteraction = "donkey_openai_mac_desktop_interaction"+ case geminiMacDesktopInteraction = "donkey_gemini_mac_desktop_interaction"case debugUIInspection = "donkey_debug_ui_inspection"}diff --git a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swiftindex 53e2e00c..0a58f5a2 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift@@ -145,6 +145,20 @@ public enum MacPointerInput {public enum Button: String, Sendable {case leftcase right+ case center+ }++ /// Moves the pointer to a screen point without clicking (foreground: warps the real cursor;+ /// background: a pid-routed move that never warps the user's cursor). Mirrors the leading move the+ /// click/scroll/drag helpers perform, exposed on its own for a hover/move action.+ @discardableResult+ public static func move(to point: CGPoint, target: InputTarget? = nil) -> Bool {+ guard let source = CGEventSource(stateID: .hidSystemState) else { return false }+ guard let event = CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left) else {+ return false+ }+ post(event, screenPoint: point, to: target)+ return true}@discardableResult@@ -156,9 +170,17 @@ public enum MacPointerInput {CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left)?.post(tap: .cghidEventTap)}- let mouseButton: CGMouseButton = button == .right ? .right : .left- let downType: CGEventType = button == .right ? .rightMouseDown : .leftMouseDown- let upType: CGEventType = button == .right ? .rightMouseUp : .leftMouseUp+ let mouseButton: CGMouseButton+ let downType: CGEventType+ let upType: CGEventType+ switch button {+ case .left:+ mouseButton = .left; downType = .leftMouseDown; upType = .leftMouseUp+ case .right:+ mouseButton = .right; downType = .rightMouseDown; upType = .rightMouseUp+ case .center:+ mouseButton = .center; downType = .otherMouseDown; upType = .otherMouseUp+ }let clicks = min(max(clickCount, 1), 3)// Double/triple clicks are one down/up pair per click with an increasing click state, not// independent single clicks — apps key multi-click behavior off the event's click state.diff --git a/apps/Donkey/Sources/DonkeyRuntime/ScreenshotAnnotation.swift b/apps/Donkey/Sources/DonkeyRuntime/ScreenshotAnnotation.swiftdeleted file mode 100644index 6ea2d7f1..00000000--- a/apps/Donkey/Sources/DonkeyRuntime/ScreenshotAnnotation.swift+++ /dev/null@@ -1,112 +0,0 @@-import AppKit-import CoreGraphics-import Foundation-import ImageIO-import UniformTypeIdentifiers--/// Renders the box-based vision flow's decision onto a captured screenshot so a-/// human can verify it: the returned bounding box plus the ordered click points-/// (box center larger, the nearby fallback points smaller) and a short label.-/// Reuses the same `CGContext` + `CGImageDestination` drawing pattern as the debug-/// UI inspection sidecar, including the top-left↔bottom-left y-flip, and derives the-/// rect/points from `VisionBoxGeometry` so the drawing matches what gets clicked.-public enum ScreenshotAnnotation {- public static func annotatedPNG(- screenshot: CapturedWindowScreenshot,- box: [Double],- label: String- ) -> Data? {- annotatedPNG(pngData: screenshot.pngData, box: box, label: label)- }-- public static func annotatedPNG(pngData: Data, box: [Double], label: String) -> Data? {- guard let source = CGImageSourceCreateWithData(pngData as CFData, nil),- let image = CGImageSourceCreateImageAtIndex(source, 0, nil)- else { return nil }-- let width = image.width- let height = image.height- guard let context = CGContext(- data: nil,- width: width,- height: height,- bitsPerComponent: 8,- bytesPerRow: 0,- space: CGColorSpaceCreateDeviceRGB(),- bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue- ) else { return nil }-- context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))-- // Screenshot pixels are top-left origin; CGContext is bottom-left → flip y.- func flip(_ point: CGPoint) -> CGPoint {- CGPoint(x: point.x, y: Double(height) - point.y)- }-- if let rect = VisionBoxGeometry.pixelRect(box, imageWidth: width, imageHeight: height) {- let drawRect = CGRect(- x: rect.minX,- y: Double(height) - rect.minY - rect.height,- width: rect.width,- height: rect.height- )- context.setLineWidth(3)- context.setStrokeColor(NSColor.systemRed.cgColor)- context.setFillColor(NSColor.systemRed.withAlphaComponent(0.12).cgColor)- context.fill(drawRect)- context.stroke(drawRect)-- if !label.isEmpty {- let labelHeight: CGFloat = 18- let labelRect = CGRect(- x: drawRect.minX,- y: min(CGFloat(height) - labelHeight - 2, drawRect.maxY),- width: min(CGFloat(width) - drawRect.minX - 2, max(60, CGFloat(label.count) * 6.7 + 10)),- height: labelHeight- )- context.setFillColor(NSColor.systemRed.withAlphaComponent(0.85).cgColor)- context.fill(labelRect)- let nsContext = NSGraphicsContext(cgContext: context, flipped: false)- NSGraphicsContext.saveGraphicsState()- NSGraphicsContext.current = nsContext- (label as NSString).draw(- in: labelRect.insetBy(dx: 4, dy: 2),- withAttributes: [- .foregroundColor: NSColor.white,- .font: NSFont.systemFont(ofSize: 10, weight: .semibold)- ]- )- NSGraphicsContext.restoreGraphicsState()- }- }-- let points = VisionBoxGeometry.pixelPoints(box, imageWidth: width, imageHeight: height)- for (index, point) in points.enumerated() {- let radius: CGFloat = index == 0 ? 9 : 5- let center = flip(point)- let dot = CGRect(- x: center.x - radius,- y: center.y - radius,- width: radius * 2,- height: radius * 2- )- context.setFillColor((index == 0 ? NSColor.systemYellow : NSColor.systemGreen).withAlphaComponent(0.9).cgColor)- context.setStrokeColor(NSColor.black.cgColor)- context.setLineWidth(1.5)- context.fillEllipse(in: dot)- context.strokeEllipse(in: dot)- }-- guard let output = context.makeImage() else { return nil }- let data = NSMutableData()- guard let destination = CGImageDestinationCreateWithData(- data,- UTType.png.identifier as CFString,- 1,- nil- ) else { return nil }- CGImageDestinationAddImage(destination, output, nil)- guard CGImageDestinationFinalize(destination) else { return nil }- return data as Data- }-}diff --git a/apps/Donkey/Sources/DonkeyRuntime/VisionBoxGeometry.swift b/apps/Donkey/Sources/DonkeyRuntime/VisionBoxGeometry.swiftdeleted file mode 100644index 2d259488..00000000--- a/apps/Donkey/Sources/DonkeyRuntime/VisionBoxGeometry.swift+++ /dev/null@@ -1,74 +0,0 @@-import CoreGraphics-import DonkeyContracts-import Foundation--/// Geometry for the box-based vision flow. The vision model returns the target as-/// a 2D bounding box in Gemini's convention — `box = [ymin, xmin, ymax, xmax]` in-/// the native 0–1000 normalized space (independent of the screenshot's pixel size,-/// the same property `VisionActionPlanner.screenPoint` relies on). This is the one-/// source of truth shared by clicking (box → screen points) and drawing-/// (box → screenshot-pixel rect/points), so what we click always matches what we-/// annotate.-public enum VisionBoxGeometry {- public static let normalizedScale = 1_000.0-- /// Ordered click offsets within the target box, as fractions of the box- /// (fx, fy in [0,1]) — center first, then four inner points. All sit inside the- /// inner 40% so they remain on the control even when the box is slightly loose.- public static let clickFractions: [(fx: Double, fy: Double)] = [- (0.5, 0.5), (0.5, 0.3), (0.5, 0.7), (0.3, 0.5), (0.7, 0.5)- ]-- /// Validate + unpack a `[ymin, xmin, ymax, xmax]` box. Returns nil if it is the- /// wrong length or has zero area.- public static func bounds(- _ box: [Double]- ) -> (xmin: Double, ymin: Double, xmax: Double, ymax: Double)? {- guard box.count == 4 else { return nil }- let ymin = min(box[0], box[2])- let xmin = min(box[1], box[3])- let ymax = max(box[0], box[2])- let xmax = max(box[1], box[3])- guard xmax > xmin, ymax > ymin else { return nil }- return (xmin, ymin, xmax, ymax)- }-- /// Box → ordered normalized (0–1) image points, center first.- public static func normalizedPoints(_ box: [Double]) -> [(nx: Double, ny: Double)] {- guard let b = bounds(box) else { return [] }- return clickFractions.map { fraction in- let nx = (b.xmin + fraction.fx * (b.xmax - b.xmin)) / normalizedScale- let ny = (b.ymin + fraction.fy * (b.ymax - b.ymin)) / normalizedScale- return (min(max(nx, 0), 1), min(max(ny, 0), 1))- }- }-- /// Box → ordered real-screen points for clicking (center first), using the same- /// `window.x + nx * window.width` mapping as `VisionActionPlanner.screenPoint`.- public static func screenPoints(_ box: [Double], window: WindowTargetBounds) -> [CGPoint] {- normalizedPoints(box).map { point in- CGPoint(- x: window.x + point.nx * window.width,- y: window.y + point.ny * window.height- )- }- }-- /// Box → screenshot-pixel rect (top-left origin) for drawing.- public static func pixelRect(_ box: [Double], imageWidth: Int, imageHeight: Int) -> CGRect? {- guard let b = bounds(box) else { return nil }- return CGRect(- x: b.xmin / normalizedScale * Double(imageWidth),- y: b.ymin / normalizedScale * Double(imageHeight),- width: (b.xmax - b.xmin) / normalizedScale * Double(imageWidth),- height: (b.ymax - b.ymin) / normalizedScale * Double(imageHeight)- )- }-- /// Box → ordered screenshot-pixel points (top-left origin, center first) for drawing.- public static func pixelPoints(_ box: [Double], imageWidth: Int, imageHeight: Int) -> [CGPoint] {- normalizedPoints(box).map { point in- CGPoint(x: point.nx * Double(imageWidth), y: point.ny * Double(imageHeight))- }- }-}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveVisionBoxSpotifySmokeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveVisionBoxSpotifySmokeTests.swiftdeleted file mode 100644index 798a707a..00000000--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveVisionBoxSpotifySmokeTests.swift+++ /dev/null@@ -1,75 +0,0 @@-import AppKit-@testable import Donkey-import DonkeyAI-import DonkeyContracts-import DonkeyRuntime-import Foundation-import Testing--/// Live, doubly-gated: exercises the box-based vision driver (`VertexVisionBoxDriver`,-/// the `GEMINI_VISION_BOX=1` escalation path) driving Spotify to play. Each turn it-/// draws the model's returned bounding box + click points onto the screenshot and-/// saves it to `/tmp/donkey-vision-boxes/` so the box quality can be checked by eye —-/// the assertion only confirms the driver actually ran (grounding is probabilistic).-///-/// Gated behind `DONKEY_LIVE_SMOKE=1` and `DONKEY_LIVE_INPUT=1`. Run live:-///-/// env DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer \-/// DONKEY_LIVE_SMOKE=1 DONKEY_LIVE_INPUT=1 GEMINI_VISION_BOX=1 \-/// DONKEY_WEB_BASE_URL=http://localhost:3000 DONKEY_DEV_AUTH_BYPASS=1 \-/// swift test --filter GeminiLiveVisionBoxSpotifySmokeTests-@Suite-struct GeminiLiveVisionBoxSpotifySmokeTests {- @Test- @MainActor- func boxVisionDriverPlaysSpotify() async throws {- let environment = ProcessInfo.processInfo.environment- guard environment["DONKEY_LIVE_SMOKE"] == "1", environment["DONKEY_LIVE_INPUT"] == "1",- let config = try? DonkeyBackendInferenceConfiguration.fromEnvironment()- else { return }- let goal = environment["DONKEY_GOAL"] ?? "Search for the artist Coldplay and play their most popular song."- let visionModel = GeminiLiveConfiguration.fromEnvironment().visionModel-- let outputDir = URL(fileURLWithPath: "/tmp/donkey-vision-boxes", isDirectory: true)- try? FileManager.default.removeItem(at: outputDir)- try FileManager.default.createDirectory(at: outputDir, withIntermediateDirectories: true)-- NSWorkspace.shared.launchApplication("Spotify")- try? await Task.sleep(nanoseconds: 1_500_000_000)- LiveSmokeMusicProbe.pauseAll()-- let auth = try await GeminiVertexVisionPlanner.mintAuth(- backend: DonkeyBackendInferenceClient(configuration: config)- )-- let start = Date()- var saved = 0- let outcome = await VertexVisionBoxDriver.drive(- appName: "Spotify",- bundleIdentifier: "com.spotify.client",- goal: goal,- auth: auth,- model: visionModel,- verify: { LiveSmokeMusicProbe.playerState(ofApp: "Spotify") == "playing" },- onTurn: { turn, screenshot, action in- guard let box = action.box,- let png = ScreenshotAnnotation.annotatedPNG(- screenshot: screenshot,- box: box,- label: "\(action.action): \(action.reason ?? "")"- )- else { return }- let url = outputDir.appendingPathComponent(String(format: "turn-%02d.png", turn))- try? png.write(to: url)- saved += 1- }- )- let total = Date().timeIntervalSince(start)-- print(String(format: "[vision-box smoke / %@] %@ in %.2fs over %d turns — %d annotated frames in %@\n trace: %@",- visionModel, outcome.completed ? "PLAYING" : "DID NOT PLAY", total, outcome.turns,- saved, outputDir.path, outcome.history.joined(separator: " | ")))- // Probe (vision grounding is probabilistic): require the driver actually ran.- #expect(outcome.turns > 0, "Box vision driver never took a turn (infra failure).")- }-}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/SpotifyVisionAgentLiveSmokeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/SpotifyVisionAgentLiveSmokeTests.swiftindex a6b641c9..96d8c5e8 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/SpotifyVisionAgentLiveSmokeTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/SpotifyVisionAgentLiveSmokeTests.swift@@ -40,7 +40,7 @@ struct SpotifyVisionAgentLiveSmokeTests {// Dump exactly what the model saw (compressed) so we can inspect it.let dump = ScreenshotCompression.compressedForModel(info.screenshot)try? dump.data.write(to: URL(fileURLWithPath: "/tmp/spotify-agent-turn\(info.turn).jpg"))- log.append("turn \(info.turn): \(info.action.action) x=\(info.action.x.map { String(Int($0)) } ?? "-") y=\(info.action.y.map { String(Int($0)) } ?? "-") text=\(info.action.text ?? "") :: \(info.action.reason ?? "")")+ log.append("turn \(info.turn): \(info.action.summary)")})log.append("driver outcome: completed=\(outcome.completed) turns=\(outcome.turns) reason=\(outcome.reason)")diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionBoxGeometryTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionBoxGeometryTests.swiftdeleted file mode 100644index 2b5f19be..00000000--- a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionBoxGeometryTests.swift+++ /dev/null@@ -1,76 +0,0 @@-import CoreGraphics-import DonkeyContracts-import DonkeyRuntime-import Foundation-import ImageIO-import Testing-import UniformTypeIdentifiers--/// Deterministic, offline coverage for the box-based vision geometry and the-/// in-turn change probe. The live grounding quality is verified separately by-/// `GeminiLiveVisionBoxSpotifySmokeTests` (which saves annotated PNGs for review).-@Suite-struct VisionBoxGeometryTests {- // box = [ymin, xmin, ymax, xmax] in 0–1000 space.- private let box: [Double] = [100, 200, 300, 600]-- @Test- func clickPointsAreCenterFirst() {- // window maps 0–1000 normalized directly onto 0–1000 screen units here.- let window = WindowTargetBounds(x: 0, y: 0, width: 1_000, height: 1_000)- let points = VisionBoxGeometry.screenPoints(box, window: window)- #expect(points.count == 5)- // Box center: x = 200 + 0.5*400 = 400; y = 100 + 0.5*200 = 200.- #expect(points[0] == CGPoint(x: 400, y: 200))- // All points lie inside the box rect (200…600, 100…300).- for point in points {- #expect(point.x >= 200 && point.x <= 600)- #expect(point.y >= 100 && point.y <= 300)- }- }-- @Test- func screenPointsRespectWindowOffsetAndSize() {- let window = WindowTargetBounds(x: 100, y: 50, width: 800, height: 600)- let center = VisionBoxGeometry.screenPoints(box, window: window)[0]- // nx = 400/1000 = 0.4 → 100 + 0.4*800 = 420; ny = 200/1000 = 0.2 → 50 + 0.2*600 = 170.- #expect(center == CGPoint(x: 420, y: 170))- }-- @Test- func pixelRectScalesToImage() {- let rect = VisionBoxGeometry.pixelRect(box, imageWidth: 1_000, imageHeight: 1_000)- #expect(rect == CGRect(x: 200, y: 100, width: 400, height: 200))- }-- @Test- func malformedBoxYieldsNoPoints() {- #expect(VisionBoxGeometry.screenPoints([1, 2, 3], window: WindowTargetBounds(x: 0, y: 0, width: 10, height: 10)).isEmpty)- #expect(VisionBoxGeometry.bounds([100, 200, 100, 200]) == nil) // zero area- }-- @Test- func changeProbeDistinguishesIdenticalFromDifferent() {- let black = solidPNG(gray: 0)- let white = solidPNG(gray: 255)- #expect(ScreenshotChange.changed(black, black) == false)- #expect(ScreenshotChange.changed(black, white) == true)- }-- /// A 16x16 solid-gray PNG for the change probe.- private func solidPNG(gray: UInt8, side: Int = 16) -> Data {- let value = CGFloat(gray) / 255- let context = CGContext(- data: nil, width: side, height: side, bitsPerComponent: 8, bytesPerRow: 0,- space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue- )!- context.setFillColor(CGColor(red: value, green: value, blue: value, alpha: 1))- context.fill(CGRect(x: 0, y: 0, width: side, height: side))- let image = context.makeImage()!- let data = NSMutableData()- let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)!- CGImageDestinationAddImage(destination, image, nil)- _ = CGImageDestinationFinalize(destination)- return data as Data- }-}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerActionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerActionTests.swiftnew file mode 100644index 00000000..3be7d95a--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerActionTests.swift@@ -0,0 +1,158 @@+import DonkeyContracts+import Foundation+import Testing++@testable import DonkeyAI++/// Decoding Gemini computer-use responses into typed `VisionComputerAction`s, across both transports+/// (raw Vertex `candidates[].content.parts[].functionCall` and the backend's normalized+/// `computer_use.calls[]` / `output[]`) and both function-naming families the model uses.+struct VisionComputerActionTests {+ private func decode(_ json: String) -> RemoteInferenceJSONValue {+ try! JSONDecoder().decode(RemoteInferenceJSONValue.self, from: Data(json.utf8))+ }++ private func firstAction(_ json: String) -> VisionComputerAction? {+ guard let call = VisionComputerResponse.functionCalls(in: decode(json)).first else { return nil }+ return VisionComputerAction.from(call: call)+ }++ @Test func vertexClickAtFunctionCall() {+ let action = firstAction("""+ {"candidates":[{"content":{"parts":[+ {"functionCall":{"name":"click_at","args":{"x":500,"y":250,"intent":"tap play"}}}+ ]}}]}+ """)+ guard case let .click(button, count, point) = action?.kind else {+ Issue.record("expected click, got \(String(describing: action?.kind))"); return+ }+ #expect(button == .left)+ #expect(count == 1)+ #expect(point.x == 500 && point.y == 250)+ #expect(action?.intent == "tap play")+ }++ @Test func hostedTypeTextAtFunctionCall() {+ let action = firstAction("""+ {"computer_use":{"registered_tools":["donkey_gemini_mac_desktop_interaction"],"calls":[+ {"name":"type_text_at","arguments":{"x":100,"y":200,"text":"hello","press_enter":true}}+ ]}}+ """)+ guard case let .type(text, point, pressEnter, clearFirst) = action?.kind else {+ Issue.record("expected type, got \(String(describing: action?.kind))"); return+ }+ #expect(text == "hello")+ #expect(point?.x == 100 && point?.y == 200)+ #expect(pressEnter)+ #expect(clearFirst) // type_text_at carries coordinates, so it defaults to clearing the field+ }++ @Test func plainTypeDoesNotClear() {+ let action = firstAction("""+ {"output":[{"type":"function_call","name":"type","arguments":{"text":"hi"}}]}+ """)+ guard case let .type(_, point, _, clearFirst) = action?.kind else {+ Issue.record("expected type"); return+ }+ #expect(point == nil)+ #expect(clearFirst == false) // no focus click → typing into the already-focused field, don't wipe it+ }++ @Test func keyCombinationParsesChord() {+ let action = firstAction("""+ {"computer_use":{"calls":[{"name":"key_combination","arguments":{"keys":"control+c"}}]}}+ """)+ guard case let .keys(keys) = action?.kind else { Issue.record("expected keys"); return }+ #expect(keys == ["control", "c"])+ }++ @Test func scrollDecodesDirectionAndMagnitude() {+ let action = firstAction("""+ {"computer_use":{"calls":[{"name":"scroll","arguments":{"direction":"down","magnitude_in_pixels":800}}]}}+ """)+ guard case let .scroll(point, direction, magnitude) = action?.kind else {+ Issue.record("expected scroll"); return+ }+ #expect(point == nil)+ #expect(direction == .down)+ #expect(magnitude == 800)+ }++ @Test func dragAndDropDecodesStreamlined35Endpoints() {+ // gemini-3.5-flash emits start_x/start_y/end_x/end_y.+ let action = firstAction("""+ {"computer_use":{"calls":[{"name":"drag_and_drop","arguments":{"start_x":10,"start_y":20,"end_x":30,"end_y":40}}]}}+ """)+ guard case let .drag(from, to) = action?.kind else { Issue.record("expected drag"); return }+ #expect(from.x == 10 && from.y == 20)+ #expect(to.x == 30 && to.y == 40)+ }++ @Test func dragAndDropDecodesLegacy25Endpoints() {+ // The 2.5 computer-use model used x/y + destination_x/destination_y.+ let action = firstAction("""+ {"computer_use":{"calls":[{"name":"drag_and_drop","arguments":{"x":10,"y":20,"destination_x":30,"destination_y":40}}]}}+ """)+ guard case let .drag(from, to) = action?.kind else { Issue.record("expected drag"); return }+ #expect(from.x == 10 && from.y == 20)+ #expect(to.x == 30 && to.y == 40)+ }++ @Test func clickVariantsMapToButtonsAndCounts() {+ func kind(_ name: String) -> VisionComputerAction.Kind? {+ firstAction("{\"computer_use\":{\"calls\":[{\"name\":\"\(name)\",\"arguments\":{\"x\":1,\"y\":1}}]}}")?.kind+ }+ guard case .click(.left, 2, _)? = kind("double_click") else { Issue.record("double_click"); return }+ guard case .click(.right, 1, _)? = kind("right_click") else { Issue.record("right_click"); return }+ guard case .click(.center, 1, _)? = kind("middle_click") else { Issue.record("middle_click"); return }+ guard case .move? = kind("hover_at") else { Issue.record("hover_at→move"); return }+ }++ @Test func browserOnlyFunctionsAreUnsupportedOnDesktop() {+ let action = firstAction("""+ {"computer_use":{"calls":[{"name":"navigate","arguments":{"url":"https://example.com"}}]}}+ """)+ guard case .unsupported = action?.kind else { Issue.record("expected unsupported"); return }+ }++ @Test func noFunctionCallMeansDoneWithText() {+ let value = decode("""+ {"candidates":[{"content":{"parts":[{"text":"The song is now playing."}]}}]}+ """)+ #expect(VisionComputerResponse.functionCalls(in: value).isEmpty)+ #expect(VisionComputerResponse.outputText(in: value) == "The song is now playing.")+ }++ @Test func firstActionThrowsOnEmptyResponse() {+ // An empty / safety-blocked / truncated turn (no call, no text) must fail the run, not be+ // mistaken for "done".+ let value = decode("{\"candidates\":[{\"content\":{\"parts\":[]}}]}")+ #expect(throws: VisionComputerResponseError.self) {+ _ = try VisionComputerResponse.firstAction(in: value)+ }+ }++ @Test func firstActionReturnsDoneOnTextOnly() throws {+ let value = decode("{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"The song is playing.\"}]}}]}")+ guard case let .done(text) = try VisionComputerResponse.firstAction(in: value).kind else {+ Issue.record("expected done"); return+ }+ #expect(text == "The song is playing.")+ }++ @Test func firstActionReturnsActionOnCall() throws {+ let value = decode("{\"computer_use\":{\"calls\":[{\"name\":\"click\",\"arguments\":{\"x\":1,\"y\":2}}]}}")+ guard case .click = try VisionComputerResponse.firstAction(in: value).kind else {+ Issue.record("expected click"); return+ }+ }++ @Test func screenPointMapsNormalizedSpaceIntoWindow() {+ let window = WindowTargetBounds(x: 100, y: 50, width: 1000, height: 800)+ let point = VisionComputerActionExecutor.screenPoint(+ VisionComputerAction.Point(x: 500, y: 250), window: window+ )+ #expect(abs(point.x - 600) < 0.001) // 100 + 0.5 * 1000+ #expect(abs(point.y - 250) < 0.001) // 50 + 0.3125 * 800 = 50 + 250+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerUseToolsTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerUseToolsTests.swiftindex 0eb5338e..69c6a05d 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerUseToolsTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerUseToolsTests.swift@@ -68,12 +68,11 @@ struct VisionComputerUseToolsTests {let normalized = VisionComputerUseToolProvider.normalizedCenter(bbox: geo.bbox, imageWidth: geo.imageWidth, imageHeight: geo.imageHeight)- let plan = VisionActionPlanner.PlannedAction(- action: "click", x: normalized.x, y: normalized.y, text: nil, reason: nil, screenPoint: nil+ let point = VisionComputerActionExecutor.screenPoint(+ VisionComputerAction.Point(x: normalized.x, y: normalized.y), window: region)- let point = VisionActionPlanner.screenPoint(action: plan, window: region)- #expect(abs((point?.x ?? 0) - 2880) < 0.5)- #expect(abs((point?.y ?? 0) - 540) < 0.5)+ #expect(abs(point.x - 2880) < 0.5)+ #expect(abs(point.y - 540) < 0.5)} else {Issue.record("expected screen-scope geometry with a region")}