Open source CapCut alternative.
TypeScript
feat(app): complete computer-use input action space and focus recovery
David Le7250a92e1a95
diff --git a/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swiftnew file mode 100644index 00000000..aaf29e4d--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift@@ -0,0 +1,209 @@+import AppKit+import CoreGraphics+import DonkeyContracts+import DonkeyHarness+import DonkeyRuntime+import Foundation++/// Pointer computer-use tools that act on elements from EITHER observation source — scroll a view+/// and drag one element onto another. They resolve an element's screen point from whatever geometry+/// the observation stashed (`ax.frame.*` screen points, or `vision.bbox.*` capture pixels mapped+/// through the window's current bounds), so the planner scrolls and drags the same elements it sees,+/// regardless of how it saw them.+///+/// Safety mirrors the click tools: every action re-checks the target is frontmost at the instant of+/// input, and acts only on observed, action-eligible elements.+@MainActor+public final class PointerComputerUseToolProvider {+ public enum ToolName {+ public static let scroll = "mouse.scroll"+ public static let drag = "mouse.drag"+ }++ private let appName: String+ private let bundleIdentifier: String?++ public init(appName: String, bundleIdentifier: String?) {+ self.appName = appName+ self.bundleIdentifier = bundleIdentifier+ }++ public static var descriptors: [HarnessToolDescriptor] {+ [+ HarnessToolDescriptor(+ name: ToolName.scroll,+ pluginID: "core.computer-use.pointer",+ summary: "Scroll the frontmost window — to reach list items, page content, or controls that are below or above what was observed. Scrolls at an observed element when elementID is given, else at the window center.",+ inputSchema: [+ "direction": "\"up\", \"down\", \"left\", or \"right\" — down reveals content further below.",+ "amount": "How many lines to scroll (default 5). Use a larger number to move a full page.",+ "elementID": "Observed element to scroll at, when a specific pane must receive the scroll."+ ],+ optionalInputKeys: ["amount", "elementID"],+ requiredPermissions: [.input],+ safetyClass: .guardedInput,+ requiredContext: ["frontmost target"],+ verificationHints: ["re-observe to confirm new content scrolled into view"]+ ),+ HarnessToolDescriptor(+ name: ToolName.drag,+ pluginID: "core.computer-use.pointer",+ summary: "Drag one observed element onto another (reorder items, move files, adjust sliders by dragging the knob to a target).",+ inputSchema: [+ "fromElementID": "Observed element to pick up.",+ "toElementID": "Observed element to drop it on."+ ],+ requiredPermissions: [.input],+ safetyClass: .guardedInput,+ requiredContext: ["frontmost target", "observed elements"],+ verificationHints: ["re-observe to confirm the drop landed"]+ )+ ]+ }++ public func makeTools() -> [HarnessTool] {+ Self.descriptors.map { descriptor in+ HarnessTool(descriptor: descriptor) { context in+ await self.execute(context)+ }+ }+ }++ private func execute(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ switch context.call.name {+ case ToolName.scroll: return await scroll(context)+ case ToolName.drag: return await drag(context)+ default:+ return result(context, status: .unknownTool, summary: "Unknown pointer tool.", reason: "unknownPointerTool")+ }+ }++ private func scroll(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ let direction = context.call.input["direction"]?.lowercased() ?? ""+ guard ["up", "down", "left", "right"].contains(direction) else {+ return result(context, status: .invalidInput, summary: "mouse.scroll requires direction up, down, left, or right.", reason: "invalidDirection")+ }+ guard let target = await frontmostTarget() else {+ return notFrontmost(context)+ }+ let point: CGPoint+ if let elementID = context.call.input["elementID"], !elementID.isEmpty {+ guard let element = context.worldModel.elements.first(where: { $0.id == elementID }),+ let resolved = Self.screenPoint(for: element, window: target.bounds) else {+ return result(context, status: .failed, summary: "Element \(elementID) has no resolvable position.", reason: "elementNotFound")+ }+ point = resolved+ } else {+ point = CGPoint(+ x: target.bounds.x + target.bounds.width / 2,+ y: target.bounds.y + target.bounds.height / 2+ )+ }+ 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)+ }+ MacPointerInput.scroll(at: point, deltaX: deltaX, deltaY: deltaY)+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: "Scrolled \(direction) \(amount) line(s).",+ observations: HarnessObservationDelta(facts: ["lastAcceptedTool": context.call.name]),+ metadata: ["direction": direction, "amount": String(amount)]+ )+ }++ private func drag(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ guard let fromID = context.call.input["fromElementID"], !fromID.isEmpty,+ let toID = context.call.input["toElementID"], !toID.isEmpty else {+ return result(context, status: .invalidInput, summary: "mouse.drag requires fromElementID and toElementID.", reason: "missingElementIDs")+ }+ guard let target = await frontmostTarget() else {+ return notFrontmost(context)+ }+ guard let fromElement = context.worldModel.elements.first(where: { $0.id == fromID }),+ let start = Self.screenPoint(for: fromElement, window: target.bounds) else {+ return result(context, status: .failed, summary: "Element \(fromID) has no resolvable position.", reason: "fromElementNotFound")+ }+ guard let toElement = context.worldModel.elements.first(where: { $0.id == toID }),+ let end = Self.screenPoint(for: toElement, window: target.bounds) else {+ return result(context, status: .failed, summary: "Element \(toID) has no resolvable position.", reason: "toElementNotFound")+ }+ MacPointerInput.drag(from: start, to: end)+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: "Dragged \(fromElement.label.isEmpty ? fromID : fromElement.label) onto \(toElement.label.isEmpty ? toID : toElement.label).",+ observations: HarnessObservationDelta(facts: ["lastAcceptedTool": context.call.name]),+ metadata: [+ "fromElementID": fromID,+ "toElementID": toID,+ "fromPoint": "\(Int(start.x)),\(Int(start.y))",+ "toPoint": "\(Int(end.x)),\(Int(end.y))"+ ]+ )+ }++ // MARK: - Geometry++ /// Resolves an element's current screen point from whichever geometry its observation stashed.+ nonisolated static func screenPoint(for element: HarnessWorldElement, window: WindowTargetBounds) -> CGPoint? {+ if let axCenter = AXComputerUseToolProvider.screenCenter(from: element.metadata) {+ return axCenter+ }+ guard let geometry = VisionComputerUseToolProvider.geometry(from: element.metadata) else {+ return nil+ }+ let normalized = VisionComputerUseToolProvider.normalizedCenter(+ bbox: geometry.bbox,+ imageWidth: geometry.imageWidth,+ imageHeight: geometry.imageHeight+ )+ let plan = VisionActionPlanner.PlannedAction(+ action: "click", x: normalized.x, y: normalized.y, text: nil, reason: nil, screenPoint: nil+ )+ return VisionActionPlanner.screenPoint(action: plan, window: window)+ }++ // MARK: - Helpers++ /// Resolves the target window and ensures it is frontmost, attempting one recovery activation+ /// of the target app (never any other app) when focus drifted between observe and act.+ private func frontmostTarget() async -> MacWindowTargetCandidate? {+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier),+ await TargetFocusRecovery.ensureFrontmost(processID: pid_t(target.processID)) else {+ return nil+ }+ return target+ }++ private func notFrontmost(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ result(+ context,+ status: .failed,+ summary: "\(appName) is not frontmost; \(TargetFocusRecovery.frontmostAppName()) is in front and refocusing failed.",+ reason: "targetNotFrontmost"+ )+ }++ private func result(+ _ context: HarnessToolExecutionContext,+ status: HarnessToolResultStatus,+ summary: String,+ reason: String+ ) -> HarnessToolResult {+ HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: status,+ summary: summary,+ metadata: ["reason": reason]+ )+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swiftindex d75c149d..9d8b6558 100644--- a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift@@ -91,8 +91,13 @@ public final class VisionComputerUseToolProvider {HarnessToolDescriptor(name: ToolName.click,pluginID: "core.computer-use.vision",- summary: "Click one element returned by vision.capture.",- inputSchema: ["elementID": "Element ID from the latest screen.captureAndAnalyze."],+ summary: "Click one element returned by vision.capture. Supports right-click (context menus) and double/triple click.",+ inputSchema: [+ "elementID": "Element ID from the latest screen.captureAndAnalyze.",+ "button": "\"left\" (default) or \"right\" for a context menu.",+ "clicks": "1 (default), 2 (double-click), or 3 (triple-click)."+ ],+ optionalInputKeys: ["button", "clicks"],requiredPermissions: [.input],safetyClass: .guardedInput,requiredContext: ["frontmost target", "captured element"],@@ -110,8 +115,12 @@ public final class VisionComputerUseToolProvider {HarnessToolDescriptor(name: ToolName.pressKey,pluginID: "core.computer-use.vision",- summary: "Press one key, e.g. return to submit.",- inputSchema: ["key": "Key name such as return, tab, escape, or an arrow."],+ summary: "Press one key, optionally chorded with modifiers — e.g. return to submit, or key=c with modifiers=command to copy.",+ inputSchema: [+ "key": "Key name such as return, tab, escape, an arrow, or a single letter/digit.",+ "modifiers": "Modifier chord such as \"command\", \"command+shift\", \"option\", \"control\"."+ ],+ optionalInputKeys: ["modifiers"],requiredPermissions: [.input],safetyClass: .guardedInput,requiredContext: ["frontmost target"]@@ -264,8 +273,8 @@ public final class VisionComputerUseToolProvider {guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {return result(context, status: .failed, summary: "No window for \(appName).", reason: "noWindowForApp")}- guard isFrontmost(target) else {- return result(context, status: .failed, summary: "\(appName) is not frontmost.", reason: "targetNotFrontmost")+ guard await ensureFrontmost(target) else {+ return notFrontmost(context)}let normalized = Self.normalizedCenter(bbox: geometry.bbox,@@ -278,12 +287,15 @@ public final class VisionComputerUseToolProvider {guard let point = VisionActionPlanner.screenPoint(action: plan, window: target.bounds) else {return result(context, status: .failed, summary: "Could not map element \(elementID) to a screen point.", reason: "unmappablePoint")}- MacPointerInput.moveAndClick(at: point)+ let button: MacPointerInput.Button = context.call.input["button"] == "right" ? .right : .left+ let clicks = context.call.input["clicks"].flatMap(Int.init) ?? 1+ MacPointerInput.moveAndClick(at: point, button: button, clickCount: clicks)+ let clickWord = button == .right ? "Right-clicked" : (clicks >= 3 ? "Triple-clicked" : (clicks == 2 ? "Double-clicked" : "Clicked"))return HarnessToolResult(callID: context.call.id,toolName: context.call.name,status: .succeeded,- summary: "Clicked \(element.label.isEmpty ? elementID : element.label).",+ summary: "\(clickWord) \(element.label.isEmpty ? elementID : element.label).",observations: HarnessObservationDelta(facts: ["lastAcceptedTool": context.call.name]),metadata: ["elementID": elementID,@@ -298,8 +310,8 @@ public final class VisionComputerUseToolProvider {return result(context, status: .invalidInput, summary: "text.enter requires non-empty text.", reason: "missingText")}guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier),- isFrontmost(target) else {- return result(context, status: .failed, summary: "\(appName) is not frontmost.", reason: "targetNotFrontmost")+ await ensureFrontmost(target) else {+ return notFrontmost(context)}MacKeyboardInput.type(text)return HarnessToolResult(@@ -317,17 +329,19 @@ public final class VisionComputerUseToolProvider {return result(context, status: .invalidInput, summary: "keyboard.press requires a key.", reason: "missingKey")}guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier),- isFrontmost(target) else {- return result(context, status: .failed, summary: "\(appName) is not frontmost.", reason: "targetNotFrontmost")+ await ensureFrontmost(target) else {+ return notFrontmost(context)}- MacKeyboardInput.pressKey(key)+ let modifiers = trimmed(context.call.input["modifiers"]).map { [$0] } ?? []+ MacKeyboardInput.pressKey(key, modifiers: modifiers)+ let chord = modifiers.first.map { "\($0)+\(key)" } ?? keyreturn HarnessToolResult(callID: context.call.id,toolName: context.call.name,status: .succeeded,- summary: "Pressed \(key).",+ summary: "Pressed \(chord).",observations: HarnessObservationDelta(facts: ["lastAcceptedTool": context.call.name]),- metadata: ["key": key]+ metadata: ["key": key, "modifiers": modifiers.joined(separator: "+")])}@@ -407,8 +421,18 @@ public final class VisionComputerUseToolProvider {// MARK: - Helpers- private func isFrontmost(_ target: MacWindowTargetCandidate) -> Bool {- NSWorkspace.shared.frontmostApplication?.processIdentifier == pid_t(target.processID)+ /// Frontmost check with one recovery activation of the target app (never any other app).+ private func ensureFrontmost(_ target: MacWindowTargetCandidate) async -> Bool {+ await TargetFocusRecovery.ensureFrontmost(processID: pid_t(target.processID))+ }++ private func notFrontmost(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ result(+ context,+ status: .failed,+ summary: "\(appName) is not frontmost; \(TargetFocusRecovery.frontmostAppName()) is in front and refocusing failed.",+ reason: "targetNotFrontmost"+ )}private func trimmed(_ value: String?) -> String? {diff --git a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swiftindex 561c923e..3e4dcd4b 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift@@ -40,8 +40,13 @@ public final class AXComputerUseToolProvider {HarnessToolDescriptor(name: ToolName.click,pluginID: "core.computer-use.ax",- summary: "Click one control returned by ax.observe.",- inputSchema: ["elementID": "Element ID from the latest ax.observe."],+ summary: "Click one control returned by ax.observe. Supports right-click (context menus) and double/triple click.",+ inputSchema: [+ "elementID": "Element ID from the latest ax.observe.",+ "button": "\"left\" (default) or \"right\" for a context menu.",+ "clicks": "1 (default), 2 (double-click), or 3 (triple-click)."+ ],+ optionalInputKeys: ["button", "clicks"],requiredPermissions: [.input],safetyClass: .guardedInput,requiredContext: ["frontmost target", "observed control"],@@ -103,20 +108,29 @@ public final class AXComputerUseToolProvider {guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {return result(context, status: .failed, summary: "No window for \(appName).", reason: "noWindowForApp")}- guard isFrontmost(target) else {- return result(context, status: .failed, summary: "\(appName) is not frontmost.", reason: "targetNotFrontmost")+ guard await TargetFocusRecovery.ensureFrontmost(processID: pid_t(target.processID)) else {+ return result(+ context,+ status: .failed,+ summary: "\(appName) is not frontmost; \(TargetFocusRecovery.frontmostAppName()) is in front and refocusing failed.",+ reason: "targetNotFrontmost"+ )}let label = element.label.isEmpty ? elementID : element.label+ let button: MacPointerInput.Button = context.call.input["button"] == "right" ? .right : .left+ let clicks = context.call.input["clicks"].flatMap(Int.init) ?? 1// Prefer a native Accessibility press (AXPress): it activates the control directly, so it works// even when a coordinate click would miss (partially obscured, scrolled, zero-size hit area).// Falls back to a guarded coordinate click on the element's frame center when AX press isn't- // available (no bundle id, control doesn't support AXPress) or doesn't land.- if let bundleIdentifier, !bundleIdentifier.isEmpty, element.actions.contains("AXPress"),+ // available (no bundle id, control doesn't support AXPress) or doesn't land. Right-clicks and+ // multi-clicks have no AX action equivalent, so they always take the coordinate path.+ if button == .left, clicks == 1,+ let bundleIdentifier, !bundleIdentifier.isEmpty, element.actions.contains("AXPress"),await axPress(nodeID: element.id, bundleIdentifier: bundleIdentifier) {return clickSucceeded(context, elementID: elementID, label: label, strategy: "ax-press", point: nil)}- MacPointerInput.moveAndClick(at: center)+ MacPointerInput.moveAndClick(at: center, button: button, clickCount: clicks)return clickSucceeded(context, elementID: elementID, label: label, strategy: "coordinate", point: center)}@@ -186,7 +200,7 @@ public final class AXComputerUseToolProvider {)}- nonisolated static func screenCenter(from metadata: [String: String]) -> CGPoint? {+ public nonisolated static func screenCenter(from metadata: [String: String]) -> CGPoint? {guard let x = metadata["ax.frame.x"].flatMap(Double.init),let y = metadata["ax.frame.y"].flatMap(Double.init),let width = metadata["ax.frame.width"].flatMap(Double.init),@@ -199,10 +213,6 @@ public final class AXComputerUseToolProvider {// MARK: - Helpers- private func isFrontmost(_ target: MacWindowTargetCandidate) -> Bool {- NSWorkspace.shared.frontmostApplication?.processIdentifier == pid_t(target.processID)- }-private func trimmed(_ value: String?) -> String? {guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { return nil }return valuediff --git a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swiftindex 9622860d..66e953ed 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift@@ -29,32 +29,58 @@ public enum MacKeyboardInput {pressKey("return")}- /// Posts a single named key (return, escape, tab, arrows, …). Unknown names that look like a- /// single character are typed as text rather than silently firing the wrong key; truly unknown- /// multi-char names fall back to Return so a "submit"-style intent still does something sane.- public static func pressKey(_ name: String) {+ /// Posts a single named key (return, escape, tab, arrows, letters, …), optionally chorded with+ /// modifiers (e.g. Cmd+C). Unknown unmodified names that look like a single character are typed+ /// as text rather than silently firing the wrong key; truly unknown multi-char names fall back+ /// to Return so a "submit"-style intent still does something sane.+ public static func pressKey(_ name: String, modifiers: [String] = []) {let normalized = name.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)+ let flags = eventFlags(for: modifiers)guard let keyCode = virtualKeyCode(for: normalized) else {- if normalized.count == 1 {+ if normalized.count == 1, flags.isEmpty {type(name)} else {- postKey(36) // unknown key name → Return+ postKey(36, flags: flags) // unknown key name → Return}return}- postKey(keyCode)+ postKey(keyCode, flags: flags)}- private static func postKey(_ keyCode: CGKeyCode) {+ /// Maps typed modifier tokens (split on `+`, `,`, or whitespace) to CGEvent flags. Unknown+ /// tokens are ignored rather than guessed.+ static func eventFlags(for modifiers: [String]) -> CGEventFlags {+ var flags: CGEventFlags = []+ let tokens = modifiers.flatMap {+ $0.lowercased().components(separatedBy: CharacterSet(charactersIn: "+, "))+ }+ for token in tokens {+ switch token.trimmingCharacters(in: .whitespacesAndNewlines) {+ case "command", "cmd", "meta": flags.insert(.maskCommand)+ case "shift": flags.insert(.maskShift)+ case "option", "opt", "alt": flags.insert(.maskAlternate)+ case "control", "ctrl": flags.insert(.maskControl)+ case "fn", "function": flags.insert(.maskSecondaryFn)+ default: break+ }+ }+ return flags+ }++ private static func postKey(_ keyCode: CGKeyCode, flags: CGEventFlags = []) {guard let source = CGEventSource(stateID: .hidSystemState),let down = CGEvent(keyboardEventSource: source, virtualKey: keyCode, keyDown: true),let up = CGEvent(keyboardEventSource: source, virtualKey: keyCode, keyDown: false)else { return }+ if !flags.isEmpty {+ down.flags = flags+ up.flags = flags+ }down.post(tap: .cghidEventTap)up.post(tap: .cghidEventTap)}- private static func virtualKeyCode(for name: String) -> CGKeyCode? {+ static func virtualKeyCode(for name: String) -> CGKeyCode? {switch name {case "return", "enter", "\n", "": return 36case "tab", "\t": return 48@@ -70,25 +96,108 @@ public enum MacKeyboardInput {case "end": return 119case "pageup": return 116case "pagedown": return 121- default: return nil+ default: return ansiKeyCode(for: name)}}++ /// ANSI-layout virtual key codes for letters, digits, and common symbols, so modifier chords+ /// like Cmd+C have a concrete key to chord with.+ private static func ansiKeyCode(for name: String) -> CGKeyCode? {+ let codes: [String: CGKeyCode] = [+ "a": 0, "s": 1, "d": 2, "f": 3, "h": 4, "g": 5, "z": 6, "x": 7, "c": 8, "v": 9,+ "b": 11, "q": 12, "w": 13, "e": 14, "r": 15, "y": 16, "t": 17,+ "1": 18, "2": 19, "3": 20, "4": 21, "6": 22, "5": 23, "=": 24, "9": 25, "7": 26,+ "-": 27, "8": 28, "0": 29, "]": 30, "o": 31, "u": 32, "[": 33, "i": 34, "p": 35,+ "l": 37, "j": 38, "'": 39, "k": 40, ";": 41, "\\": 42, ",": 43, "/": 44, "n": 45,+ "m": 46, ".": 47, "`": 50+ ]+ return codes[name]+ }}-/// Low-level pointer input via CGEvent (move + left click at a screen point). Real input — callers-/// must gate this behind explicit permission/guards.+/// Low-level pointer input via CGEvent (move, click variants, scroll, drag at screen points). Real+/// input — callers must gate this behind explicit permission/guards.public enum MacPointerInput {+ public enum Button: String, Sendable {+ case left+ case right+ }+@discardableResult- public static func moveAndClick(at point: CGPoint) -> Bool {+ public static func moveAndClick(at point: CGPoint, button: Button = .left, clickCount: Int = 1) -> Bool {guard let source = CGEventSource(stateID: .hidSystemState) else { return false }CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left)?.post(tap: .cghidEventTap)- guard let down = CGEvent(mouseEventSource: source, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left),- let up = CGEvent(mouseEventSource: source, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left)- else {+ let mouseButton: CGMouseButton = button == .right ? .right : .left+ let downType: CGEventType = button == .right ? .rightMouseDown : .leftMouseDown+ let upType: CGEventType = button == .right ? .rightMouseUp : .leftMouseUp+ 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.+ for clickState in 1...clicks {+ guard let down = CGEvent(mouseEventSource: source, mouseType: downType, mouseCursorPosition: point, mouseButton: mouseButton),+ let up = CGEvent(mouseEventSource: source, mouseType: upType, mouseCursorPosition: point, mouseButton: mouseButton)+ else {+ return false+ }+ down.setIntegerValueField(.mouseEventClickState, value: Int64(clickState))+ up.setIntegerValueField(.mouseEventClickState, value: Int64(clickState))+ down.post(tap: .cghidEventTap)+ up.post(tap: .cghidEventTap)+ }+ return true+ }++ /// Scrolls by line deltas at a screen point (positive y scrolls up, positive x scrolls left,+ /// matching CGEvent wheel conventions). Moves the pointer there first so the scroll lands on+ /// the intended view.+ @discardableResult+ public static func scroll(at point: CGPoint, deltaX: Int = 0, deltaY: Int = 0) -> Bool {+ guard let source = CGEventSource(stateID: .hidSystemState) else { return false }+ CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left)?+ .post(tap: .cghidEventTap)+ guard let event = CGEvent(+ scrollWheelEvent2Source: source,+ units: .line,+ wheelCount: 2,+ wheel1: Int32(deltaY),+ wheel2: Int32(deltaX),+ wheel3: 0+ ) else {+ return false+ }+ event.location = point+ event.post(tap: .cghidEventTap)+ return true+ }++ /// Drags from one screen point to another: press, interpolated dragged moves so drop targets+ /// see continuous motion, then release at the destination.+ @discardableResult+ public static func drag(from start: CGPoint, to end: CGPoint, steps: Int = 16) -> Bool {+ guard let source = CGEventSource(stateID: .hidSystemState) else { return false }+ CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: start, mouseButton: .left)?+ .post(tap: .cghidEventTap)+ guard let down = CGEvent(mouseEventSource: source, mouseType: .leftMouseDown, mouseCursorPosition: start, mouseButton: .left) else {return false}down.post(tap: .cghidEventTap)+ usleep(40_000)+ let stepCount = max(steps, 2)+ for step in 1...stepCount {+ let fraction = Double(step) / Double(stepCount)+ let point = CGPoint(+ x: start.x + (end.x - start.x) * fraction,+ y: start.y + (end.y - start.y) * fraction+ )+ CGEvent(mouseEventSource: source, mouseType: .leftMouseDragged, mouseCursorPosition: point, mouseButton: .left)?+ .post(tap: .cghidEventTap)+ usleep(8_000)+ }+ guard let up = CGEvent(mouseEventSource: source, mouseType: .leftMouseUp, mouseCursorPosition: end, mouseButton: .left) else {+ return false+ }+ usleep(40_000)up.post(tap: .cghidEventTap)return true}@@ -131,7 +240,7 @@ public enum AccessibilityActionExecutor {targetQuery: String,liveInputEnabled: Bool,windowResolver: MacWindowResolver = MacWindowResolver(),- click: (CGPoint) -> Bool = MacPointerInput.moveAndClick+ click: (CGPoint) -> Bool = { MacPointerInput.moveAndClick(at: $0) }) -> Outcome {guard let observation = AccessibilityObserver.observe(appName: appName,diff --git a/apps/Donkey/Sources/DonkeyRuntime/TargetFocusRecovery.swift b/apps/Donkey/Sources/DonkeyRuntime/TargetFocusRecovery.swiftnew file mode 100644index 00000000..eb83ed8a--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/TargetFocusRecovery.swift@@ -0,0 +1,27 @@+import AppKit+import Foundation++/// Focus recovery for guarded input: when the target app lost frontmost status between observe and+/// act (the user glanced elsewhere, a notification stole focus), attempt ONE activation of the app+/// the task is already driving and wait briefly for the window server to comply, instead of denying+/// the input outright. Never activates any app other than the given target.+@MainActor+public enum TargetFocusRecovery {+ /// True when the target process is frontmost, after at most one recovery activation.+ public static func ensureFrontmost(processID: pid_t) async -> Bool {+ if NSWorkspace.shared.frontmostApplication?.processIdentifier == processID { return true }+ guard let app = NSRunningApplication(processIdentifier: processID) else { return false }+ app.activate()+ for _ in 0..<10 {+ try? await Task.sleep(nanoseconds: 50_000_000)+ if NSWorkspace.shared.frontmostApplication?.processIdentifier == processID { return true }+ }+ return false+ }++ /// Name of whatever is in front right now, so a focus failure can tell the planner what is+ /// blocking (e.g. a system dialog or another app) instead of failing opaquely.+ public static func frontmostAppName() -> String {+ NSWorkspace.shared.frontmostApplication?.localizedName ?? "another app"+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AccessibilityActionExecutorTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AccessibilityActionExecutorTests.swiftindex dc2340a3..93ac0299 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AccessibilityActionExecutorTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AccessibilityActionExecutorTests.swift@@ -13,4 +13,24 @@ struct AccessibilityActionExecutorTests {#expect(point.x == 140)#expect(point.y == 220)}++ @Test+ func modifierTokensMapToEventFlags() {+ #expect(MacKeyboardInput.eventFlags(for: ["command"]) == .maskCommand)+ #expect(MacKeyboardInput.eventFlags(for: ["cmd+shift"]) == [.maskCommand, .maskShift])+ #expect(MacKeyboardInput.eventFlags(for: ["option", "ctrl"]) == [.maskAlternate, .maskControl])+ // Unknown tokens are ignored rather than guessed.+ #expect(MacKeyboardInput.eventFlags(for: ["hyper"]).isEmpty)+ #expect(MacKeyboardInput.eventFlags(for: []).isEmpty)+ }++ @Test+ func letterAndNamedKeysResolveToVirtualKeyCodes() {+ // Chords like Cmd+C need concrete letter key codes, not unicode typing.+ #expect(MacKeyboardInput.virtualKeyCode(for: "c") == 8)+ #expect(MacKeyboardInput.virtualKeyCode(for: "a") == 0)+ #expect(MacKeyboardInput.virtualKeyCode(for: "return") == 36)+ #expect(MacKeyboardInput.virtualKeyCode(for: "pagedown") == 121)+ #expect(MacKeyboardInput.virtualKeyCode(for: "notakey") == nil)+ }}