Skip to content

Open source CapCut alternative.

TypeScript

feat(app): anchor AX actions to cached handles and add semantic right/double-click

David Le2589acb8c3ac
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift
index 4b6e90ea..184a49d5 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift
@@ -21,10 +21,33 @@ public final class AXComputerUseToolProvider {
private let appName: String
private let bundleIdentifier: String?
+ private let actionBackend: ActionEngineInputBackend
- public init(appName: String, bundleIdentifier: String?) {
+ public init(
+ appName: String,
+ bundleIdentifier: String?,
+ actionBackend: ActionEngineInputBackend = MacAccessibilityActionEngineInputBackend()
+ ) {
self.appName = appName
self.bundleIdentifier = bundleIdentifier
+ self.actionBackend = actionBackend
+ }
+
+ /// The semantic AX action to attempt for a click gesture, or nil to take the coordinate path. Gated
+ /// on the control advertising the action so we never claim a press that the control can't perform.
+ /// Right-click maps to the context-menu action and double-click to open; single left-click keeps the
+ /// existing press. Triple-clicks and unadvertised gestures fall through to coordinates.
+ nonisolated static func semanticAction(
+ button: MacPointerInput.Button,
+ clicks: Int,
+ advertised: Set<String>
+ ) -> String? {
+ switch (button, clicks) {
+ case (.right, _): return advertised.contains("AXShowMenu") ? "AXShowMenu" : nil
+ case (.left, 2): return advertised.contains("AXOpen") ? "AXOpen" : nil
+ case (.left, 1): return advertised.contains("AXPress") ? "AXPress" : nil
+ default: return nil
+ }
}
public static var descriptors: [HarnessToolDescriptor] {
@@ -138,15 +161,22 @@ public final class AXComputerUseToolProvider {
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. 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)
+ // Prefer a native Accessibility action: it activates the control directly, so it works even when
+ // a coordinate click would miss (partially obscured, scrolled, zero-size hit area). Single
+ // left-click presses, right-click shows the context menu, and double-click opens — each only when
+ // the control advertises that action. Falls back to a guarded coordinate click on the frame
+ // center when no semantic action applies, there's no bundle id, or the AX action doesn't land.
+ let advertised = Set(element.actions)
+ if let bundleIdentifier, !bundleIdentifier.isEmpty,
+ let action = Self.semanticAction(button: button, clicks: clicks, advertised: advertised),
+ await axPerform(nodeID: element.id, action: action, bundleIdentifier: bundleIdentifier) {
+ return clickSucceeded(
+ context,
+ elementID: elementID,
+ label: label,
+ strategy: "ax-" + action.dropFirst(2).lowercased(),
+ point: nil
+ )
}
MacPointerInput.moveAndClick(at: center, button: button, clickCount: clicks)
return clickSucceeded(context, elementID: elementID, label: label, strategy: "coordinate", point: center)
@@ -221,10 +251,10 @@ public final class AXComputerUseToolProvider {
)
}
- /// Performs an `AXPress` on the control identified by `nodeID` via the Accessibility action backend,
- /// which re-checks that `bundleIdentifier` is the frontmost app before acting. Returns whether the
- /// press landed.
- private func axPress(nodeID: String, bundleIdentifier: String) async -> Bool {
+ /// Performs an AX `action` (e.g. `AXPress`, `AXShowMenu`, `AXOpen`) on the control identified by
+ /// `nodeID` via the action backend, which re-checks that `bundleIdentifier` is the frontmost app and
+ /// that the control still advertises the action before acting. Returns whether the action landed.
+ private func axPerform(nodeID: String, action: String, bundleIdentifier: String) async -> Bool {
let command = ActionEngineCommand(
id: UUID().uuidString,
traceID: "ax-click",
@@ -236,12 +266,12 @@ public final class AXComputerUseToolProvider {
),
metadata: [
"accessibility.nodeID": nodeID,
- "accessibility.action": "AXPress",
+ "accessibility.action": action,
"bundleIdentifier": bundleIdentifier,
"controlID": nodeID
]
)
- let outcome = await MacAccessibilityActionEngineInputBackend().execute(command)
+ let outcome = await actionBackend.execute(command)
return outcome.executed
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
index dbe37980..0eb1f368 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
@@ -293,16 +293,24 @@ public struct MacAccessibilityActionEngineInputBackend: ActionEngineInputBackend
return result(command, executed: false, reason: "targetAppNotFrontmost")
}
- let appElement = AXUIElementCreateApplication(application.processIdentifier)
- guard let element = resolveElement(nodeID: nodeID, application: appElement) else {
- return result(command, executed: false, reason: "accessibilityNodeNotFound")
+ // Prefer the live handle captured at observe time: it stays bound to the same logical control
+ // even if the tree reordered, so we act on what we observed rather than whatever now sits at the
+ // old node index. Fall back to the positional re-walk, and surface a distinct "stale" reason when
+ // neither resolves so the planner re-observes instead of retrying a vanished node.
+ let element: AXUIElement
+ if let cached = cachedElement(processID: application.processIdentifier, nodeID: nodeID),
+ isAlive(cached) {
+ element = cached
+ } else if let walked = resolveElement(
+ nodeID: nodeID,
+ application: AXUIElementCreateApplication(application.processIdentifier)
+ ) {
+ element = walked
+ } else {
+ return result(command, executed: false, reason: "accessibilityNodeStale")
}
- switch action {
- case "AXPress":
- let error = AXUIElementPerformAction(element, kAXPressAction as CFString)
- return result(command, executed: error == .success, reason: String(describing: error))
- case "AXSetValue":
+ if action == "AXSetValue" {
guard let value = command.metadata["accessibility.value"] ?? command.key else {
return result(command, executed: false, reason: "missingAccessibilityValue")
}
@@ -312,9 +320,72 @@ public struct MacAccessibilityActionEngineInputBackend: ActionEngineInputBackend
value as CFTypeRef
)
return result(command, executed: error == .success, reason: String(describing: error))
- default:
+ }
+
+ guard let performAction = Self.performAction(for: action) else {
return result(command, executed: false, reason: "unsupportedAccessibilityAction")
}
+ // Re-check at dispatch that the live element still advertises this action and is enabled; the
+ // observe-time action list can go stale. On a miss the caller falls back to a coordinate click.
+ guard advertises(element, action: action), isEnabled(element) else {
+ return result(command, executed: false, reason: "accessibilityActionNotAdvertised")
+ }
+ let error = AXUIElementPerformAction(element, performAction)
+ return result(command, executed: error == .success, reason: String(describing: error))
+ }
+
+ /// The live handle observed for `nodeID`, read on the main actor (the cache is MainActor-confined and
+ /// `AXUIElement` is not Sendable). Mirrors `frontmostApplication()`'s main-thread hop.
+ private func cachedElement(processID: pid_t, nodeID: String) -> AXUIElement? {
+ let lookup = {
+ MainActor.assumeIsolated {
+ MacAccessibilityElementHandleCache.shared.handle(processID: processID, nodeID: nodeID)
+ }
+ }
+ return Thread.isMainThread ? lookup() : DispatchQueue.main.sync(execute: lookup)
+ }
+
+ /// Whether the AX handle still points at a live control — a cheap attribute read fails once the
+ /// element is destroyed, which is exactly when a cached handle must be discarded.
+ private func isAlive(_ element: AXUIElement) -> Bool {
+ var value: CFTypeRef?
+ return AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &value) == .success
+ }
+
+ private func advertises(_ element: AXUIElement, action: String) -> Bool {
+ var names: CFArray?
+ guard AXUIElementCopyActionNames(element, &names) == .success,
+ let actions = names as? [String]
+ else {
+ return false
+ }
+ return actions.contains(action)
+ }
+
+ /// Treats a missing `AXEnabled` attribute as enabled: many container/menu elements never expose it,
+ /// and only an explicit `false` should block the action.
+ private func isEnabled(_ element: AXUIElement) -> Bool {
+ var value: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(element, kAXEnabledAttribute as CFString, &value) == .success else {
+ return true
+ }
+ return (value as? Bool) ?? true
+ }
+
+ /// Maps a supported perform-style action name to its AX constant. `AXSetValue` is handled separately
+ /// because it sets an attribute rather than performing an action.
+ private static func performAction(for action: String) -> CFString? {
+ switch action {
+ case "AXPress": return kAXPressAction as CFString
+ case "AXShowMenu": return kAXShowMenuAction as CFString
+ // No SDK constant ships for the open action, but apps (e.g. Finder) advertise the "AXOpen"
+ // string; AX matches on the name, so the literal is exactly what a constant would resolve to.
+ case "AXOpen": return "AXOpen" as CFString
+ case "AXPick": return kAXPickAction as CFString
+ case "AXConfirm": return kAXConfirmAction as CFString
+ case "AXCancel": return kAXCancelAction as CFString
+ default: return nil
+ }
}
private func frontmostApplication() -> FrontmostAccessibilityApplication? {