Open source CapCut alternative.
TypeScript
Allow guarded AI visual target clicks
David Lefe5929777477
diff --git a/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionFrameFusion.swift b/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionFrameFusion.swiftindex 338af40a..24756fb9 100644--- a/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionFrameFusion.swift+++ b/apps/Donkey/Sources/DonkeyAI/DebugUIInspectionFrameFusion.swift@@ -60,8 +60,8 @@ public enum DebugUIInspectionFrameFusion {visualStyle: element.visualStyle,metadata: element.metadata.merging(["debugUIFusion.source": "gemini",- "localUIElement.actionEligibility": "readOnlyEvidence",- "directInputActionsAllowed": "false"+ "localUIElement.actionEligibility": "guardedAction",+ "directInputActionsAllowed": "true"]) { current, _ in current })}diff --git a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swiftindex b9086c01..3e4572d1 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift@@ -357,7 +357,8 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {"Apply App skill guidance for app-specific workflows, control strategies, required metadata, and output shapes. Do not invent app-specific behavior that is absent from task definitions, catalog data, memory, or loaded skill guidance.","When App finder catalog JSON is non-empty and you use local_app_interaction, choose the target app only from a catalog entry with supportStatus supported and a matching capability. Set metadata.appFinder.selectedAppID to the exact appID, metadata.appFinder.selectedCapabilityID to the capability id, and metadata.appFinder.controlProfile to one declared control profile. Never select candidate, unsupported, or denied entries for execution.","For local_app_interaction, select the most likely local app, set targetAppName and entities.appName to the human app name, set entities.goal, and when text must be entered set entities.query plus normalizedEntities.query.",- "For local_app_interaction, fill planSteps with allowed toolName values only: app.openOrFocus, app.observe, ui.newDocument, ui.focusSearch, ui.focusAddressBar, ui.focusTextEntry, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",+ "For local_app_interaction, fill planSteps with allowed toolName values only: app.openOrFocus, app.observe, ui.newDocument, ui.focusSearch, ui.focusAddressBar, ui.focusTextEntry, ui.setText, ui.clickTarget, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",+ "Use ui.clickTarget when the intended action is to click or submit a visible control by Accessibility or AI visual evidence instead of pressing Return. Put the semantic or observed visual target id in controlID.","Verification may be a set of verifier steps. Use app.verifyCommand for guarded command evidence, app.verifyVisibleText for observed result text, and include both when both kinds of evidence are needed.","When ui.setText is present, entities.query and normalizedEntities.query must be non-empty, the step inputEntity should usually be query, and controlID/focusKey should describe the guarded UI strategy.","For every other task type, planSteps should not contain executable toolName values.",diff --git a/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift b/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swiftindex 2520851b..b97009bc 100644--- a/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift+++ b/apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift@@ -45,7 +45,7 @@ public enum ScreenshotParseDebugUIOverlayMapper {confidence: control.confidence,metadata: control.metadata.merging(["localUIElement.sources": "gemini-screenshot-parser",- "localUIElement.actionEligibility": LocalUIElementActionEligibility.readOnlyEvidence.rawValue,+ "localUIElement.actionEligibility": LocalUIElementActionEligibility.guardedAction.rawValue,"remoteScreenshotParsing.status": result.metadata["remoteScreenshotParsing.status"] ?? "used","remoteScreenshotParsing.provider": result.metadata["parserProvider"] ?? result.metadata["runtime.backend"] ?? "gemini-screenshot-parser","target.windowID": String(target.windowID),@@ -53,7 +53,7 @@ public enum ScreenshotParseDebugUIOverlayMapper {"target.bundleIdentifier": target.bundleIdentifier ?? "","target.title": target.title ?? "","coordinate.sourceSpace": frame.space.rawValue,- "directInputActionsAllowed": "false"+ "directInputActionsAllowed": "true"]) { current, _ in current })}@@ -98,13 +98,13 @@ public enum ScreenshotParseDebugUIOverlayMapper {confidence: 1,metadata: ["localUIElement.sources": "window-chrome-geometry",- "localUIElement.actionEligibility": LocalUIElementActionEligibility.readOnlyEvidence.rawValue,+ "localUIElement.actionEligibility": LocalUIElementActionEligibility.guardedAction.rawValue,"target.windowID": String(target.windowID),"target.appName": target.appName ?? "","target.bundleIdentifier": target.bundleIdentifier ?? "","target.title": target.title ?? "","coordinate.sourceSpace": "windowChromeGeometry",- "directInputActionsAllowed": "false"+ "directInputActionsAllowed": "true"])}diff --git a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swiftindex 3836e59b..e832f6d3 100644--- a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift@@ -89,6 +89,7 @@ public enum LocalAppActionPlanTool: String, Codable, CaseIterable, Equatable, Secase focusAddressBar = "ui.focusAddressBar"case focusTextEntry = "ui.focusTextEntry"case setText = "ui.setText"+ case clickTarget = "ui.clickTarget"case pressReturn = "ui.pressReturn"case verifyCommand = "app.verifyCommand"case verifyVisibleText = "app.verifyVisibleText"diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swiftindex 10b3f952..9cbd7780 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swift@@ -99,6 +99,13 @@ public actor LocalAppHarnessStepExecutor {permissions: [.input],safety: .guardedInput),+ descriptor(+ .clickTarget,+ summary: "Click one model-selected Accessibility or AI visual target.",+ input: ["controlID": "Model-selected Accessibility control id or AI visual segment id."],+ permissions: [.input],+ safety: .guardedInput+ ),descriptor(.pressReturn,summary: "Run one guarded model-planned Return submit action.",@@ -166,7 +173,7 @@ public actor LocalAppHarnessStepExecutor {return await openOrFocus(context, definition: definition, intent: intent, availability: availability)case .observeApp:return await observe(context, definition: definition, intent: intent, reason: "observe")- case .newDocument, .focusSearch, .focusAddressBar, .focusTextEntry, .setText, .pressReturn:+ case .newDocument, .focusSearch, .focusAddressBar, .focusTextEntry, .setText, .clickTarget, .pressReturn:return await executeAction(context, tool: tool, definition: definition, intent: intent, availability: availability)case .verifyCommand, .verifyVisibleText:return await verify(context, tool: tool, definition: definition, intent: intent)@@ -443,6 +450,13 @@ public actor LocalAppHarnessStepExecutor {)}return candidates.first?.withHarnessIssuedAt(Self.now())+ ?? visualClickCommand(+ tool: tool,+ context: context,+ adapter: adapter,+ intent: intent,+ controlID: controlID+ )}private func matchesStructuredInputs(@@ -470,6 +484,49 @@ public actor LocalAppHarnessStepExecutor {return true}+ private func visualClickCommand(+ tool: LocalAppActionPlanTool,+ context: HarnessToolExecutionContext,+ adapter: LocalAppTaskAdapter,+ intent: TaskIntent,+ controlID: String?+ ) -> ActionEngineCommand? {+ guard [.focusSearch, .focusAddressBar, .focusTextEntry, .clickTarget].contains(tool),+ let controlID,+ let observation = latestObservation,+ let targetBounds = LocalAppObservationGeometry.screenControlBounds(+ controlID: controlID,+ metadata: observation.metadata+ )+ else {+ return nil+ }++ return ActionEngineCommand(+ id: "\(intent.intentID)-visual-click-\(Self.slug(controlID))",+ traceID: intent.metadata["traceID"] ?? intent.intentID,+ targetID: adapter.targetID,+ kind: .tap,+ issuedAt: Self.now(),+ targetBounds: targetBounds,+ metadata: LocalAppObservationGeometry.groundedMetadata(+ controlID: controlID,+ observation: observation+ ).merging([+ "taskIntentID": intent.intentID,+ "taskType": intent.taskType,+ "targetApp": adapter.definition.targetApp.appName,+ "bundleIdentifier": adapter.definition.targetApp.bundleIdentifier ?? "",+ "workflowStepID": context.call.input["modelStepID"] ?? "visual-click-\(Self.slug(controlID))",+ "workflowStepRole": role(for: tool),+ "controlID": controlID,+ "inputStrategy": "visual-coordinate",+ "visualFallback": "aiOrObservedBounds",+ "plan.tool": tool.rawValue+ ]) { current, _ in current }+ )+ }+private func observationWithActionEvidence(_ observation: LocalAppTaskObservation?) -> LocalAppTaskObservation? {guard var observation else { return nil }let executed = actionTraces.filter(\.executed)@@ -673,7 +730,7 @@ public actor LocalAppHarnessStepExecutor {private func role(for tool: LocalAppActionPlanTool) -> String {switch tool {- case .newDocument, .pressReturn:+ case .newDocument, .clickTarget, .pressReturn:return LocalAppTaskStepRole.submit.rawValuecase .focusSearch, .focusAddressBar, .focusTextEntry:return LocalAppTaskStepRole.focusControl.rawValue@@ -719,6 +776,12 @@ public actor LocalAppHarnessStepExecutor {]}+ private static func slug(_ value: String) -> String {+ LocalAppTextNormalizer.normalizedPhrase(value)+ .split(separator: " ")+ .joined(separator: "-")+ }+private static func descriptor(_ tool: LocalAppActionPlanTool,summary: String,diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppObservationGeometry.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppObservationGeometry.swiftindex 235ed588..fb7d898d 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppObservationGeometry.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppObservationGeometry.swift@@ -106,6 +106,27 @@ enum LocalAppObservationGeometry {normalizedControlBounds(controlID: controlID, metadata: metadata) != nil}+ static func screenControlBounds(+ controlID: String,+ metadata: [String: String]+ ) -> HotLoopRect? {+ guard let rect = metadataRect(prefix: "\(controlPrefix(controlID))bounds.", metadata: metadata),+ rect.hasPositiveArea+ else {+ return nil+ }+ if rect.space == .screen {+ return rect+ }+ guard let mapper = coordinateMapper(metadata: metadata),+ let screenRect = mapper.convert(rect, to: .screen),+ screenRect.hasPositiveArea+ else {+ return nil+ }+ return screenRect+ }+static func normalizedStepBounds(metadata: [String: String]) -> HotLoopRect? {metadataRect(prefix: "control.bounds.", metadata: metadata).flatMap { rect innormalizedBounds(rect, metadata: metadata)diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swiftindex 94336f9c..2a71c31b 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift@@ -1211,6 +1211,17 @@ public struct LocalAppTaskCatalog: Sendable {"plan.tool": tool.rawValue]))+ case .clickTarget:+ steps.append(LocalAppTaskWorkflowStepDefinition(+ id: "model-plan-click-target-\(submitIndex)",+ role: .submit,+ summary: "Click the model-selected visual or Accessibility target",+ metadata: [+ "controlID": plan.controlID,+ "plan.tool": tool.rawValue+ ]+ ))+ submitIndex += 1case .pressReturn:steps.append(LocalAppTaskWorkflowStepDefinition(id: "model-plan-press-return-\(submitIndex)",diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskVerificationPolicy.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskVerificationPolicy.swiftindex 2cc344a6..bae79ab6 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskVerificationPolicy.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskVerificationPolicy.swift@@ -31,7 +31,7 @@ enum LocalAppTaskVerificationPolicy {case .verifyVisibleText:return .visibleTextcase .openOrFocusApp, .observeApp, .newDocument, .focusSearch, .focusAddressBar,- .focusTextEntry, .setText, .pressReturn, nil:+ .focusTextEntry, .setText, .clickTarget, .pressReturn, nil:break}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swiftindex 824963e7..1a33918e 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift@@ -87,15 +87,19 @@ public struct LocalUIUnderstandingResult: Codable, Equatable, Sendable {}public func observation(for request: LocalUIUnderstandingRequest) -> LocalAppTaskObservation {+ let controlsAllowDirectInput = controls.contains {+ $0.metadata["directInputActionsAllowed"] == "true"+ || $0.metadata["localUIElement.actionEligibility"] == "guardedAction"+ }var observationMetadata = request.metadata.merging(metadata) { _, new in new }observationMetadata.merge(["observer": "local-ui-understanding","traceID": request.traceID,"targetID": request.targetID,"controlCount": String(controls.count),- "formFieldCount": String(formFields.count),- "directInputActionsAllowed": "false"+ "formFieldCount": String(formFields.count)]) { current, _ in current }+ observationMetadata["directInputActionsAllowed"] = String(controlsAllowDirectInput)if let cropBounds = request.cropBounds {observationMetadata.merge(LocalAppObservationGeometry.cropBoundsMetadata(cropBounds)diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacKeyboardActionEngineInputBackend.swift b/apps/Donkey/Sources/DonkeyRuntime/MacKeyboardActionEngineInputBackend.swiftindex a21097a6..4ad4958f 100644--- a/apps/Donkey/Sources/DonkeyRuntime/MacKeyboardActionEngineInputBackend.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/MacKeyboardActionEngineInputBackend.swift@@ -21,6 +21,7 @@ struct MacKeyboardTextEntryExecution: Equatable, Sendable {public struct MacKeyboardActionEngineInputBackend: ActionEngineInputBackend {private let keyCommandPoster: @Sendable (String) -> Bool+ private let mouseClickPoster: @Sendable (CGPoint) -> Boolprivate let textEntryExecutor: @Sendable (String,@escaping @Sendable (String) -> Bool@@ -28,21 +29,28 @@ public struct MacKeyboardActionEngineInputBackend: ActionEngineInputBackend {public init() {self.keyCommandPoster = Self.postKeyCommand+ self.mouseClickPoster = Self.postMouseClickself.textEntryExecutor = Self.pasteText}init(keyCommandPoster: @escaping @Sendable (String) -> Bool,+ mouseClickPoster: @escaping @Sendable (CGPoint) -> Bool = Self.postMouseClick,textEntryExecutor: @escaping @Sendable (String,@escaping @Sendable (String) -> Bool) async -> MacKeyboardTextEntryExecution) {self.keyCommandPoster = keyCommandPoster+ self.mouseClickPoster = mouseClickPosterself.textEntryExecutor = textEntryExecutor}public func execute(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult {+ if command.kind == .tap {+ return await executeTap(command)+ }+guard command.kind == .key, let key = command.key else {return result(command: command,@@ -85,6 +93,52 @@ public struct MacKeyboardActionEngineInputBackend: ActionEngineInputBackend {)}+ private func executeTap(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult {+ guard let point = screenCenter(of: command.targetBounds) else {+ return result(+ command: command,+ executed: false,+ metadata: [+ "liveInputBackend": "mac-keyboard",+ "inputMode": "coordinateClick",+ "elementClick": "true",+ "reason": "missingScreenTargetBounds"+ ]+ )+ }++ let executed = mouseClickPoster(point)+ if executed {+ try? await Task.sleep(nanoseconds: 80_000_000)+ }+ return result(+ command: command,+ executed: executed,+ metadata: [+ "liveInputBackend": "mac-keyboard",+ "inputMode": "coordinateClick",+ "elementClick": "true",+ "targetPoint.x": String(Double(point.x)),+ "targetPoint.y": String(Double(point.y)),+ "controlID": command.metadata["controlID"] ?? "",+ "visualFallback": command.metadata["visualFallback"] ?? ""+ ]+ )+ }++ private func screenCenter(of rect: HotLoopRect?) -> CGPoint? {+ guard let rect,+ rect.hasPositiveArea,+ rect.space == .screen+ else {+ return nil+ }+ return CGPoint(+ x: rect.origin.x + rect.size.width / 2,+ y: rect.origin.y + rect.size.height / 2+ )+ }+private func result(command: ActionEngineCommand,executed: Bool,@@ -166,6 +220,28 @@ public struct MacKeyboardActionEngineInputBackend: ActionEngineInputBackend {return true}+ private static func postMouseClick(at point: CGPoint) -> Bool {+ guard let source = CGEventSource(stateID: .hidSystemState),+ let mouseDown = CGEvent(+ mouseEventSource: source,+ mouseType: .leftMouseDown,+ mouseCursorPosition: point,+ mouseButton: .left+ ),+ let mouseUp = CGEvent(+ mouseEventSource: source,+ mouseType: .leftMouseUp,+ mouseCursorPosition: point,+ mouseButton: .left+ )+ else {+ return false+ }+ mouseDown.post(tap: .cghidEventTap)+ mouseUp.post(tap: .cghidEventTap)+ return true+ }+private static func flags(for modifiers: [String]) -> CGEventFlags {var flags: CGEventFlags = []for modifier in modifiers.map({ $0.lowercased() }) {diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swiftindex 2cce90bb..e96f25de 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift@@ -201,8 +201,8 @@ struct DonkeyBackendInferenceClientTests {#expect(element.id == "gemini-42-review")#expect(element.type == .button)#expect(element.bbox == DebugUIBoundingBox(x: 150, y: 425, width: 100, height: 50))- #expect(element.metadata["directInputActionsAllowed"] == "false")- #expect(element.metadata["localUIElement.actionEligibility"] == "readOnlyEvidence")+ #expect(element.metadata["directInputActionsAllowed"] == "true")+ #expect(element.metadata["localUIElement.actionEligibility"] == "guardedAction")}@Test@@ -307,8 +307,8 @@ struct DonkeyBackendInferenceClientTests {#expect(ids.contains("gemini-voice"))let geminiElement = try #require(fused.elements.first { $0.id == "gemini-voice" })#expect(geminiElement.metadata["debugUIFusion.source"] == "gemini")- #expect(geminiElement.metadata["directInputActionsAllowed"] == "false")- #expect(geminiElement.metadata["localUIElement.actionEligibility"] == "readOnlyEvidence")+ #expect(geminiElement.metadata["directInputActionsAllowed"] == "true")+ #expect(geminiElement.metadata["localUIElement.actionEligibility"] == "guardedAction")}@Testdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swiftindex 4093007b..719f600a 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift@@ -1,4 +1,5 @@import DonkeyContracts+import DonkeyHarness@testable import DonkeyRuntimeimport Foundationimport Testing@@ -993,6 +994,92 @@ struct LocalAppTaskTests {#expect(groundedMetadata["control.bounds.space"] == HotLoopCoordinateSpace.normalizedTarget.rawValue)}+ @Test @MainActor+ func visualObservationBoundsCanDriveModelPlannedClickTarget() async throws {+ let catalog = LocalAppTaskCatalog(+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,+ availabilityProvider: StaticLocalAppAvailabilityProvider(+ installedBundleIdentifiers: ["com.apple.Music"]+ )+ )+ let intent = genericLocalAppInteractionIntent(+ appName: "Music",+ query: "Sample Track",+ planTools: [.openOrFocusApp, .observeApp, .clickTarget, .verifyCommand]+ )+ let resolution = catalog.resolve(intent: intent)+ let definition = try #require(resolution.definition)+ var metadata = LocalAppObservationGeometry.targetBoundsMetadata(+ WindowTargetBounds(x: 100, y: 200, width: 500, height: 300)+ )+ metadata.merge(LocalAppObservationGeometry.controlMetadata(+ controlID: "search",+ frame: HotLoopRect(x: 50, y: 60, width: 100, height: 40, space: .window),+ source: .localUIUnderstanding,+ label: "Search",+ kind: .button,+ confidence: 0.82,+ extra: [+ "localUIElement.actionEligibility": "guardedAction",+ "directInputActionsAllowed": "true"+ ]+ )) { current, _ in current }+ let observation = LocalAppTaskObservation(+ appIsRunning: true,+ appIsFocused: true,+ availableControls: ["search": true],+ visibleText: ["visibleText": "Search"],+ confidence: 0.82,+ metadata: metadata+ )+ let backend = RecordingLocalAppTaskInputBackend()+ let executor = LocalAppHarnessStepExecutor(+ command: "click the visible search target",+ traceID: "trace-visual-click",+ resolution: resolution,+ appController: FakeLocalAppTaskAppController(+ launchObservation: observation,+ finalObservation: observation+ ),+ actionEngineFactory: { _ in+ ActionEngineGuardrail(+ configuration: ActionEngineConfiguration(liveInputEnabled: true),+ inputBackend: backend+ )+ }+ )+ let registry = HarnessToolRegistry()+ await executor.registerTools(in: registry)++ _ = await registry.execute(+ HarnessToolCall(id: "observe", name: LocalAppActionPlanTool.observeApp.rawValue),+ taskID: "task-visual-click",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.screenCapture, .accessibility, .input]+ )+ let clickResult = await registry.execute(+ HarnessToolCall(+ id: "click",+ name: LocalAppActionPlanTool.clickTarget.rawValue,+ input: [+ "controlID": "search",+ "modelStepID": "click-search"+ ]+ ),+ taskID: "task-visual-click",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.screenCapture, .accessibility, .input]+ )++ let command = try #require(await backend.executedCommands().first)+ #expect(clickResult.status == .succeeded)+ #expect(command.kind == .tap)+ #expect(command.metadata["inputStrategy"] == "visual-coordinate")+ #expect(command.metadata["visualFallback"] == "aiOrObservedBounds")+ #expect(command.targetBounds == HotLoopRect(x: 150, y: 260, width: 100, height: 40, space: .screen))+ #expect(definition.workflowSteps.contains { $0.metadata["plan.tool"] == "ui.clickTarget" })+ }+@Test @MainActorfunc documentApprovalRunnerExecutesOnlyApprovedFields() async throws {let backend = RecordingLocalAppTaskInputBackend()@@ -1264,17 +1351,28 @@ private final class FakeLocalAppTaskAppController: LocalAppTaskAppControlling {private actor RecordingLocalAppTaskInputBackend: ActionEngineInputBackend {private var keys: [String] = []+ private var commands: [ActionEngineCommand] = []func execute(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult {+ commands.append(command)keys.append(command.key ?? "")return ActionEngineInputBackendResult(executed: true,completedAt: command.issuedAt,- metadata: ["liveInputBackend": "recording-local-app-task"]+ metadata: [+ "liveInputBackend": "recording-local-app-task",+ "inputMode": command.kind == .tap ? "coordinateClick" : "keyCommand",+ "elementClick": String(command.kind == .tap),+ "controlID": command.metadata["controlID"] ?? ""+ ])}func executedKeys() -> [String] {keys}++ func executedCommands() -> [ActionEngineCommand] {+ commands+ }}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MacKeyboardActionEngineInputBackendTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MacKeyboardActionEngineInputBackendTests.swiftindex 59b5ae1d..b7e3b761 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/MacKeyboardActionEngineInputBackendTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MacKeyboardActionEngineInputBackendTests.swift@@ -1,5 +1,6 @@@testable import DonkeyRuntimeimport DonkeyContracts+import CoreGraphicsimport Foundationimport Testing@@ -65,6 +66,40 @@ struct MacKeyboardActionEngineInputBackendTests {#expect(recorder.commands() == ["Command+F"])}+ @Test+ func tapCommandsClickCenterOfScreenTargetBounds() async {+ let recorder = MouseClickRecorder()+ let backend = MacKeyboardActionEngineInputBackend(+ keyCommandPoster: { _ in false },+ mouseClickPoster: { point in+ recorder.append(point)+ return true+ },+ textEntryExecutor: { _, _ in+ MacKeyboardTextEntryExecution(executed: false, inputMode: "pasteboardText")+ }+ )++ let result = await backend.execute(ActionEngineCommand(+ id: "tap-visual-send",+ traceID: "trace-coordinate-click",+ targetID: "local-app-task-test",+ kind: .tap,+ issuedAt: RunTraceTimestamp(+ wallClock: Date(timeIntervalSince1970: 0),+ monotonicUptimeNanoseconds: 0+ ),+ targetBounds: HotLoopRect(x: 100, y: 200, width: 80, height: 40, space: .screen),+ metadata: ["controlID": "send", "visualFallback": "aiOrObservedBounds"]+ ))++ #expect(result.executed == true)+ #expect(result.metadata["inputMode"] == "coordinateClick")+ #expect(result.metadata["elementClick"] == "true")+ #expect(result.metadata["controlID"] == "send")+ #expect(recorder.points() == [CGPoint(x: 140, y: 220)])+ }+private func command(key: String,metadata: [String: String] = [:]@@ -101,3 +136,21 @@ private final class KeyboardCommandRecorder: @unchecked Sendable {return commands}}++private final class MouseClickRecorder: @unchecked Sendable {+ private let lock = NSLock()+ private var recordedPoints: [CGPoint] = []++ func append(_ point: CGPoint) {+ lock.lock()+ recordedPoints.append(point)+ lock.unlock()+ }++ func points() -> [CGPoint] {+ lock.lock()+ let points = recordedPoints+ lock.unlock()+ return points+ }+}diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex b3f01f1e..03026ff1 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -246,8 +246,9 @@ plugins, skills, catalogs, or memory, not in core harness conditionals.Computer use is one tool family inside the harness.Accessibility is the primary source for actionable UI elements. Screenshots,-vision, OCR, and hover evidence can enrich the world model, labels, and layout,-but they must not authorize live input by themselves.+vision, OCR, and hover evidence enrich the world model, labels, and layout. When+Accessibility cannot resolve the target, scoped AI screenshot boxes may become a+secondary actionable target for a guarded coordinate click.Element actions execute only after the harness validates:@@ -259,9 +260,10 @@ Element actions execute only after the harness validates:- safety class- verification criteria-Models choose semantic targets and tool calls. They do not micromanage pixels.-Coordinate input is fallback evidence only and must pass the same guarded-execution checks as other input.+Models choose semantic targets and tool calls. They may choose an observed AI+visual target when no Accessibility target is available. Coordinate input is a+fallback execution path and must pass the same guarded execution checks as other+input.Verification must be backed by task evidence. A local-app command attempt is notverified merely because the target app is focused or running after execution;diff --git a/docs/guides/donkey-vision.md b/docs/guides/donkey-vision.mdindex 97788a88..a20afa8d 100644--- a/docs/guides/donkey-vision.md+++ b/docs/guides/donkey-vision.md@@ -63,17 +63,21 @@ that the position came from the model.## Safety Boundary-Donkey Vision is observation. It does not authorize live input by itself.+Donkey Vision is observation first, and it can now supply a secondary live-input+target when Accessibility cannot provide a better element.-Vision evidence can help Donkey plan, explain, debug, and decide where to look-next. Live input still has to pass through the guarded action boundary: target-validation, focus checks, permission policy, action eligibility, and runtime-verification.+Vision evidence can help Donkey plan, explain, debug, decide where to look next,+and choose a coordinate click target. Live input still has to pass through the+guarded action boundary: target validation, focus checks, permission policy,+action eligibility, and runtime verification.AI-derived evidence is especially constrained:-- AI boxes are read-only evidence.-- AI output must not enable direct clicks, typing, scrolling, or dragging.+- AI boxes may be interactable when they come from a scoped app/window or+ system-navigation screenshot and are marked `guardedAction`.+- AI output may provide a coordinate click target after the Accessibility path+ fails or is unavailable. The executor clicks the guarded target center, not an+ unbounded desktop coordinate.- Screenshots sent to hosted AI must be scoped to an app/window or asystem-navigation surface, never the full desktop.- Screenshots are not persisted or logged as general product data.@@ -90,7 +94,8 @@ The distinction matters. If an `AI` box is visibly off, that is expected modellocalization error and should not be fixed by adding arbitrary coordinateoffsets. Prefer improving local geometry, fusion, or the screenshot scope. If an`AX` box is off, that is a local coordinate mapping bug and should be fixed in-the Mac geometry path.+the Mac geometry path. Live input tries Accessibility first, then AI visual+targets, then guarded coordinate click fallback.The debug config uses Donkey Vision as the mode:@@ -128,4 +133,5 @@ High-signal entry points:- Do not make provider selection the UI or config model for Donkey Vision.- Prefer app/window-scoped screenshots and local geometry.- Keep AI evidence marked and visually distinct.-- Keep live input authorization separate from visual evidence.+- Allow AI visual targets to drive guarded coordinate clicks only after focus,+ permission, target-window, and action-eligibility checks pass.diff --git a/docs/guides/user-query-overlay.md b/docs/guides/user-query-overlay.mdindex 9ef370f8..f31ed7a8 100644--- a/docs/guides/user-query-overlay.md+++ b/docs/guides/user-query-overlay.md@@ -33,8 +33,9 @@ quick local-app actions:not bundle the repo config and only honor the Application Support path. Whenno config exists, the config is invalid, or `"enabled": false`, the debugoverlay is fully disabled. When enabled, Donkey Vision fuses Accessibility and- hosted AI screenshot parsing. Local geometry wins; AI boxes are read-only- evidence and are visually marked as `AI`. The overlay never sends a full+ hosted AI screenshot parsing. Local geometry wins; AI boxes can be+ interactable through guarded coordinate fallback and are visually marked as+ `AI`. The overlay never sends a fulldesktop screenshot to hosted AI: it captures safe app/window orsystem-navigation surfaces only. See`docs/guides/donkey-vision.md`.@@ -67,16 +68,17 @@ quick local-app actions:- The centered composer keeps text and voice modes on the same input surface. Double-Command release opens focused text input, double-Command hold opens the same input with voice active, and typed text promotes the send button while the microphone affordance becomes secondary.- Voice capture and transcription remain separate. The controller records bounded local audio and publishes levels; transcription is model-backed through the hosted agent-harness boundary before transcript text enters the turn path.- Local item prewarming must run off the main actor and must not eagerly scan protected user folders. Agent memory is stored in SQLite under Application Support and uses FTS5 plus deterministic local embeddings for retrieval; JSONL is only an explicit export/debug format. Cached local-item hits must still point to an existing path or bundle before they are used as an execution target. Runtime task definitions are the generic open/local-app interaction seeds plus generated or user-reviewed definitions loaded from memory.-- For scriptable apps, prefer app-native AppleScript task commands before falling back to Accessibility or keyboard input. Submit steps with an explicit structured `controlID` may execute as an Accessibility `AXPress` against button-like controls, with the control bounds carried into action traces. Bounded screenshots may supplement observation/verification according to task metadata, but screenshots remain context evidence and do not directly drive input.+- For scriptable apps, prefer app-native AppleScript task commands before falling back to Accessibility, AI visual targets, or keyboard input. Submit steps with an explicit structured `controlID` may execute as an Accessibility `AXPress` against button-like controls, or as a guarded coordinate click against an AI visual target when Accessibility is unavailable. Control bounds are carried into action traces.- Agent visualization overlays are non-interactive, non-activating panels. They may point, explain, and replay what the agent is doing or would do, but they do not synthesize mouse movement. Live keyboard or Accessibility actions remain separate guarded runtime actions. When a local-app action plan is based on an observation, preserve target-window geometry and control bounds on the evidence-backed steps so cursor replay can use pixel-grounded element positions instead of invented coordinates.- The developer UI inspection overlay is separate from agent visualization. Itis a transparent, non-activating, click-through, keyboard-pass-through AppKitpanel at a lower window level than Donkey's interactive UI. It rendersCALayer rectangles and labels from local Accessibility or hover-probe detectoroutput only. Provider action calls such as click, type, scroll, drag,- navigation, `computer_call`, or `function_call` are rejected instead of- executed. Hover-only detections are visualization/read-only evidence and must- not become live input authority.+ navigation, `computer_call`, or `function_call` are rejected by the overlay+ itself. Live input is executed only by the guarded local-app runtime.+ Hover-only detections are visualization/read-only evidence and must not+ become live input authority.- Task actions in the notch, including follow-up submission and pause/resume, must cross the model/controller command boundary with the selected task ID.- User-query command handling should emit actionable `com.donkey.app` route/result logs for submitted commands, routing decisions, intent resolution, local action traces, unsupported requests, unavailable apps, and final task status. Action trace logs should state the backend, input mode, whether an element click happened, the control or bounds target, and that the overlay pointer is visual-only.diff --git a/site/src/lib/inference/screenshot-parsing/gemini-flash.ts b/site/src/lib/inference/screenshot-parsing/gemini-flash.tsindex 53e139b2..228406e8 100644--- a/site/src/lib/inference/screenshot-parsing/gemini-flash.ts+++ b/site/src/lib/inference/screenshot-parsing/gemini-flash.ts@@ -117,6 +117,7 @@ export function normalizedScreenshotResult(const controls = output.controls.map((control, index) => {const id = control.id?.trim() || `gemini-control-${index + 1}`;+ const controlID = normalizedControlID(control.label, control.kind, id);return {id,label: control.label,@@ -124,9 +125,12 @@ export function normalizedScreenshotResult(frame: rectFromGeminiBox(control.box_2d, request.pixelSize.width, request.pixelSize.height),confidence: clamp01(control.confidence),metadata: {- controlID: id,+ controlID,+ segmentID: id,source: "gemini-screenshot-parser",boxFormat: "ymin,xmin,ymax,xmax/1000",+ "localUIElement.actionEligibility": "guardedAction",+ directInputActionsAllowed: "true",},};});@@ -156,13 +160,25 @@ export function normalizedScreenshotResult(metadata: toJsonObject({...metadata,"runtime.backend": "gemini-screenshot-parser",- "directInputActionsAllowed": "false",+ "directInputActionsAllowed": "true","screenshotParser.controlCount": String(controls.length),"screenshotParser.formFieldCount": String(formFields.length),}),};}+function normalizedControlID(label: string, kind: string, fallbackID: string) {+ const normalized = label+ .trim()+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "");+ if (kind === "searchField") {+ return "search";+ }+ return normalized || fallbackID;+}+function geminiRequestParameters(request: ScreenshotParseRequest,model: string,