Skip to content

Open source CapCut alternative.

TypeScript

Drive non-scriptable app tasks by vision

David Le8dfa819147fb
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index b89f4d31..5986d337 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -289,6 +289,20 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
)
}
+ // Execution-strategy router: for a non-scriptable target app (Electron, no dictionary), the
+ // AppleScript/skill path can't act — drive it by vision instead. Scriptable/unknown apps fall
+ // through to the AppleScript-first generic harness loop below.
+ if let visionResult = await handleVisionActionIfNonScriptable(
+ resolution: resolution,
+ trace: taskIntentResult.trace,
+ command: commandRedaction.redactedText,
+ traceID: traceID,
+ taskID: taskID,
+ modelMetadata: modelMetadata
+ ) {
+ return visionResult
+ }
+
let decision = AppHarnessDecision(
kind: .runLocalTask,
taskIntentID: resolution.intent?.intentID,
@@ -336,6 +350,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
taskID: taskID,
runtime: genericRuntime
)
+ Self.recordAppleScriptScriptability(resolution: resolution, runSteps: runSteps)
let runStep = runSteps.last
let verificationStep = runSteps.last { step in
step.toolResult?.toolName == LocalAppActionPlanTool.verifyCommand.rawValue
@@ -617,9 +632,20 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
return result
}
- /// Parses planner `guidanceTargets` ("Label::query; Label::query") into ordered path targets.
+ /// Parses planner `guidanceTargets` into ordered path targets. The planner emits a JSON array of
+ /// `{label, query}` objects — robust to labels/queries that contain punctuation (`:`, `;`, …),
+ /// which a delimiter-based format would mis-split. A legacy `"Label::query; …"` string is still
+ /// accepted as a fallback for older planner output.
private static func guidanceTargets(from raw: String) -> [AccessibilityCursorPathTarget] {
- raw.components(separatedBy: ";").compactMap { entry in
+ let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return [] }
+
+ if let data = trimmed.data(using: .utf8),
+ let decoded = try? JSONDecoder().decode([GuidanceTargetWire].self, from: data) {
+ return decoded.compactMap(\.pathTarget)
+ }
+
+ return trimmed.components(separatedBy: ";").compactMap { entry in
let parts = entry.components(separatedBy: "::")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
let query = (parts.count > 1 ? parts[1] : parts.first ?? "")
@@ -629,6 +655,223 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
}
}
+ private struct GuidanceTargetWire: Decodable {
+ var label: String?
+ var query: String
+
+ var pathTarget: AccessibilityCursorPathTarget? {
+ let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmedQuery.isEmpty else { return nil }
+ let trimmedLabel = (label ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ return AccessibilityCursorPathTarget(
+ query: trimmedQuery,
+ label: trimmedLabel.isEmpty ? trimmedQuery : trimmedLabel,
+ kind: .targetControl
+ )
+ }
+ }
+
+ // MARK: - Vision Action Route (non-scriptable apps)
+
+ /// If the resolved target app genuinely can't be driven by AppleScript/keystrokes — an Electron app,
+ /// or one this machine has LEARNED fails AppleScript — drive it by vision via the shared
+ /// `VisionActionDriver`. Returns nil (use the normal AppleScript/keystroke path) when the app is
+ /// scriptable, when it merely lacks a dictionary (System-Events keystrokes still work), when input
+ /// isn't permitted, or when the hosted backend can't be reached. Honors the planner's confirm
+ /// request: an action flagged `needsConfirmation` asks the user first rather than auto-driving.
+ private func handleVisionActionIfNonScriptable(
+ resolution: LocalAppTaskCatalogResolution,
+ trace: AIModelCallTrace,
+ command: String,
+ traceID: String,
+ taskID: String,
+ modelMetadata: [String: String]
+ ) async -> UserQueryCommandHandlingResult? {
+ guard permissionPolicy.allowedCapabilities.contains(.input) else { return nil }
+ guard let intent = resolution.intent else { return nil }
+ let appName = intent.targetApp.appName
+ guard !appName.isEmpty, appName.lowercased() != "none" else { return nil }
+ let bundleIdentifier = intent.targetApp.bundleIdentifier
+
+ let scriptability = AppCapabilityService.shared.scriptability(
+ bundleIdentifier: bundleIdentifier,
+ appName: appName
+ )
+ guard ExecutionStrategySelector.strategy(scriptability: scriptability) == .accessibilityUI else {
+ return nil
+ }
+ // Only pre-empt the AppleScript/keystroke path for apps that truly can't use it: Electron
+ // (Chromium-rendered, no usable dictionary/keystroke automation) or apps that have actually
+ // failed AppleScript here. A native app that merely lacks a scripting dictionary can still be
+ // driven by System-Events keystrokes, so leave it on the existing path.
+ let isElectron = MacAppScriptabilityProbe().facts(
+ bundleIdentifier: bundleIdentifier,
+ appName: appName
+ ).isElectron
+ let learnedFailure = AppCapabilityService.shared.hasLearnedAppleScriptFailure(bundleIdentifier: bundleIdentifier)
+ guard isElectron || learnedFailure else { return nil }
+
+ guard let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {
+ return nil
+ }
+
+ // Never auto-drive the real pointer/keyboard for an action the planner asked to confirm; ask.
+ if intent.needsConfirmation {
+ return await confirmVisionAction(
+ appName: appName,
+ trace: trace,
+ traceID: traceID,
+ taskID: taskID,
+ modelMetadata: modelMetadata
+ )
+ }
+
+ let backend = DonkeyBackendInferenceClient(configuration: configuration)
+ let goal = trace.metadata["genericHarness.intent.goal"]
+ .flatMap { $0.isEmpty ? nil : $0 } ?? command
+ let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(
+ forApp: appName,
+ bundleIdentifier: bundleIdentifier
+ )
+
+ let outcome = await VisionActionDriver.drive(
+ appName: appName,
+ bundleIdentifier: bundleIdentifier,
+ goal: goal,
+ appGuidance: appGuidance,
+ backend: backend
+ )
+
+ let response = outcome.completed
+ ? (outcome.lastNarration ?? "Done.")
+ : "I tried operating \(appName) but couldn't confirm the goal was finished."
+ let decision = AppHarnessDecision(
+ kind: .respond,
+ message: response,
+ traceID: traceID,
+ metadata: [
+ "structuredDecision": "true",
+ "router": "modelVisionAction",
+ "visionAction.completed": String(outcome.completed)
+ ]
+ )
+ let result = UserQueryCommandHandlingResult(
+ status: outcome.completed ? .completed : .failedSafe,
+ threadStatus: outcome.completed ? .completed : .failed,
+ decision: decision,
+ summary: response,
+ traceID: traceID,
+ metadata: modelMetadata.merging([
+ "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,
+ "appHarness.router": "modelVisionAction",
+ "visionAction.app": appName,
+ "visionAction.completed": String(outcome.completed),
+ "visionAction.turns": String(outcome.turns),
+ "visionAction.reason": outcome.reason
+ ]) { _, new in new }
+ )
+ if outcome.completed {
+ _ = await genericHarnessLifecycle.coordinator.complete(
+ taskID: taskID,
+ reason: "User query vision action completed"
+ )
+ } else {
+ _ = await genericHarnessLifecycle.coordinator.failSafe(
+ taskID: taskID,
+ reason: "User query vision action did not confirm completion"
+ )
+ }
+ await coordinatorRegistry.finish(taskID: taskID)
+ logHandlingResult(
+ result,
+ stage: "visionAction",
+ hint: outcome.completed ? "Drove \(appName) by vision." : "Vision action stopped: \(outcome.reason)."
+ )
+ return result
+ }
+
+ /// Asks the user before driving an app by vision, when the planner flagged the action for
+ /// confirmation. Mirrors the clarification route — no input is performed.
+ private func confirmVisionAction(
+ appName: String,
+ trace: AIModelCallTrace,
+ traceID: String,
+ taskID: String,
+ modelMetadata: [String: String]
+ ) async -> UserQueryCommandHandlingResult {
+ let goal = trace.metadata["genericHarness.intent.goal"].flatMap { $0.isEmpty ? nil : $0 }
+ let question = goal.map { "I can do that in \(appName) by controlling it directly (\($0)). Want me to go ahead?" }
+ ?? "I can do that in \(appName) by controlling it directly. Want me to go ahead?"
+ let decision = AppHarnessDecision(
+ kind: .askClarification,
+ message: question,
+ traceID: traceID,
+ metadata: [
+ "structuredDecision": "true",
+ "router": "modelVisionActionConfirm"
+ ]
+ )
+ let result = UserQueryCommandHandlingResult(
+ status: .needsConfirmation,
+ threadStatus: .waitingForClarification,
+ decision: decision,
+ summary: question,
+ traceID: traceID,
+ metadata: modelMetadata.merging([
+ "appHarness.decision": AppHarnessDecisionKind.askClarification.rawValue,
+ "appHarness.router": "modelVisionActionConfirm",
+ "visionAction.app": appName
+ ]) { _, new in new }
+ )
+ _ = await genericHarnessLifecycle.coordinator.waitForUser(
+ taskID: taskID,
+ question: question,
+ reason: "Vision action requires confirmation before driving the app"
+ )
+ await coordinatorRegistry.finish(taskID: taskID)
+ logHandlingResult(
+ result,
+ stage: "visionActionConfirm",
+ hint: "Asked before driving \(appName) by vision."
+ )
+ return result
+ }
+
+ /// Records whether the AppleScript path actually worked for the target app, so the strategy router
+ /// learns per machine: repeated failures flip an app to the accessibility/vision path, a success
+ /// keeps it on AppleScript. Best-effort — only fires when the run executed an AppleScript action
+ /// and we know the app's bundle identifier.
+ private static func recordAppleScriptScriptability(
+ resolution: LocalAppTaskCatalogResolution,
+ runSteps: [HarnessStepExecutionResult]
+ ) {
+ guard let bundleIdentifier = (resolution.definition?.targetApp.bundleIdentifier
+ ?? resolution.intent?.targetApp.bundleIdentifier),
+ !bundleIdentifier.isEmpty
+ else {
+ return
+ }
+ let appName = resolution.definition?.targetApp.appName ?? resolution.intent?.targetApp.appName
+
+ var sawAppleScript = false
+ var anySucceeded = false
+ for step in runSteps {
+ guard let toolResult = step.toolResult else { continue }
+ let isAppleScript = toolResult.metadata["liveInputBackend"] == "mac-apple-script"
+ || toolResult.metadata["appleScript.output"] != nil
+ || toolResult.toolName == "automation.applescript.execute"
+ guard isAppleScript else { continue }
+ sawAppleScript = true
+ if toolResult.status == .succeeded { anySucceeded = true }
+ }
+ guard sawAppleScript else { return }
+ AppCapabilityService.shared.recordAppleScriptOutcome(
+ bundleIdentifier: bundleIdentifier,
+ appName: appName,
+ succeeded: anySucceeded
+ )
+ }
+
// MARK: - Generic Harness Task Execution
private func finalizeGenericHarnessTask(
diff --git a/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift b/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift
new file mode 100644
index 00000000..59a61f45
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift
@@ -0,0 +1,170 @@
+import AppKit
+import CoreGraphics
+import DonkeyContracts
+import DonkeyRuntime
+import 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.
+///
+/// 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
+/// switched to during a model round-trip.
+@MainActor
+public enum VisionActionDriver {
+ public typealias ScreenshotCapture = @MainActor (MacWindowTargetCandidate) async throws -> CapturedWindowScreenshot
+
+ public struct Outcome: Sendable {
+ public var completed: Bool
+ public var turns: Int
+ /// "ok" | "noWindowForApp" | "screenshotFailed" | "visionPlanFailed" | "targetNotFrontmost" | "maxTurnsReached"
+ public var reason: String
+ public var lastNarration: String?
+ public var history: [String]
+ }
+
+ /// Per-turn callback (the planned action + the exact screenshot the model saw) for logging/dumping.
+ public struct TurnInfo: Sendable {
+ public var turn: Int
+ public var screenshot: CapturedWindowScreenshot
+ public var action: VisionActionPlanner.PlannedAction
+ }
+
+ public static func drive(
+ appName: String,
+ bundleIdentifier: String?,
+ goal: String,
+ appGuidance: String?,
+ backend: DonkeyBackendInferenceClient,
+ maxTurns: Int = 12,
+ settleNanoseconds: UInt64 = 1_200_000_000,
+ capture: @escaping ScreenshotCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: $0) },
+ onTurn: (@MainActor (TurnInfo) -> Void)? = nil
+ ) async -> Outcome {
+ var history: [String] = []
+ var lastNarration: String?
+ var turnsTaken = 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).
+ guard var target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {
+ return Outcome(completed: false, turns: 0, reason: "noWindowForApp", lastNarration: nil, history: history)
+ }
+ activate(target)
+
+ for _ in 0..<maxTurns {
+ // Ensure the target is frontmost before we screenshot + act; re-activate only if needed.
+ if !isFrontmost(target) {
+ activate(target)
+ try? await Task.sleep(nanoseconds: 250_000_000)
+ guard let refreshed = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {
+ return finish(false, turnsTaken, "noWindowForApp", lastNarration, history)
+ }
+ target = refreshed
+ guard isFrontmost(target) else {
+ return finish(false, turnsTaken, "targetNotFrontmost", lastNarration, history)
+ }
+ }
+
+ guard let shot = await captureWithRetry(target, appName: appName, bundleIdentifier: bundleIdentifier, capture: capture, target: &target) else {
+ return finish(false, turnsTaken, "screenshotFailed", lastNarration, history)
+ }
+
+ let action: VisionActionPlanner.PlannedAction
+ do {
+ action = try await VisionActionPlanner.nextAction(
+ goal: goal,
+ app: appName,
+ screenshot: shot,
+ window: target.bounds,
+ history: history,
+ appGuidance: appGuidance,
+ backend: backend
+ )
+ } catch {
+ return finish(false, turnsTaken, "visionPlanFailed", lastNarration, history)
+ }
+ turnsTaken += 1
+ lastNarration = action.reason.flatMap { $0.isEmpty ? nil : $0 } ?? lastNarration
+ onTurn?(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
+ // click/type into a window the user switched to.
+ guard isFrontmost(target) else {
+ 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":
+ return finish(true, turnsTaken, "ok", lastNarration, history)
+ case "click":
+ if let point = action.screenPoint {
+ _ = MacPointerInput.moveAndClick(at: point)
+ history.append("clicked at (\(Int(point.x)),\(Int(point.y))): \(action.reason ?? "")")
+ } else {
+ history.append("skipped click with no resolvable point")
+ }
+ 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)")
+ }
+
+ try? await Task.sleep(nanoseconds: settleNanoseconds)
+ }
+
+ return finish(false, turnsTaken, "maxTurnsReached", lastNarration, history)
+ }
+
+ private static func finish(
+ _ completed: Bool,
+ _ turns: Int,
+ _ reason: String,
+ _ lastNarration: String?,
+ _ history: [String]
+ ) -> Outcome {
+ Outcome(completed: completed, turns: turns, reason: reason, lastNarration: lastNarration, history: history)
+ }
+
+ private static func captureWithRetry(
+ _ candidate: MacWindowTargetCandidate,
+ appName: String,
+ bundleIdentifier: String?,
+ capture: ScreenshotCapture,
+ target: inout MacWindowTargetCandidate
+ ) async -> CapturedWindowScreenshot? {
+ if let shot = try? await capture(candidate) { return shot }
+ // The window may have moved/closed; re-resolve once and retry.
+ guard let refreshed = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier),
+ let shot = try? await capture(refreshed)
+ else {
+ return nil
+ }
+ target = refreshed
+ return shot
+ }
+
+ private static func isFrontmost(_ target: MacWindowTargetCandidate) -> Bool {
+ NSWorkspace.shared.frontmostApplication?.processIdentifier == pid_t(target.processID)
+ }
+
+ private static func activate(_ target: MacWindowTargetCandidate) {
+ let app = NSRunningApplication(processIdentifier: pid_t(target.processID))
+ _ = app?.activate()
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/VisionActionPlanner.swift b/apps/Donkey/Sources/DonkeyAI/VisionActionPlanner.swift
index 28d61216..c005fffd 100644
--- a/apps/Donkey/Sources/DonkeyAI/VisionActionPlanner.swift
+++ b/apps/Donkey/Sources/DonkeyAI/VisionActionPlanner.swift
@@ -24,6 +24,8 @@ public enum VisionActionPlannerError: Error, CustomStringConvertible {
}
}
+/// Driven in production by `UserQueryCommandHandler.handleVisionAction` for non-scriptable apps, and
+/// by `SpotifyVisionAgentLiveSmokeTests` for live verification.
@MainActor
public enum VisionActionPlanner {
public struct PlannedAction: Equatable, Sendable, Codable {
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift
index d60637f5..9622860d 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift
@@ -7,13 +7,18 @@ public enum MacKeyboardInput {
/// Types arbitrary text by posting per-character unicode key events.
public static func type(_ text: String) {
guard let source = CGEventSource(stateID: .hidSystemState) else { return }
- for scalar in text.unicodeScalars where scalar.value <= 0xFFFF {
- var unit = UniChar(scalar.value)
- guard let down = CGEvent(keyboardEventSource: source, virtualKey: 0, keyDown: true),
+ // Post one event per Character, using its full UTF-16 representation. Characters outside the
+ // Basic Multilingual Plane (emoji, CJK extensions, …) encode as a surrogate pair, so we send
+ // both code units together in a single event rather than truncating to one UniChar — which
+ // would silently drop the character.
+ for character in text {
+ var units = Array(character.utf16)
+ guard !units.isEmpty,
+ let down = CGEvent(keyboardEventSource: source, virtualKey: 0, keyDown: true),
let up = CGEvent(keyboardEventSource: source, virtualKey: 0, keyDown: false)
else { continue }
- down.keyboardSetUnicodeString(stringLength: 1, unicodeString: &unit)
- up.keyboardSetUnicodeString(stringLength: 1, unicodeString: &unit)
+ down.keyboardSetUnicodeString(stringLength: units.count, unicodeString: &units)
+ up.keyboardSetUnicodeString(stringLength: units.count, unicodeString: &units)
down.post(tap: .cghidEventTap)
up.post(tap: .cghidEventTap)
}
@@ -21,13 +26,53 @@ public enum MacKeyboardInput {
/// Posts a Return keypress (virtual key 36).
public static func pressReturn() {
+ 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) {
+ let normalized = name.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
+ guard let keyCode = virtualKeyCode(for: normalized) else {
+ if normalized.count == 1 {
+ type(name)
+ } else {
+ postKey(36) // unknown key name → Return
+ }
+ return
+ }
+ postKey(keyCode)
+ }
+
+ private static func postKey(_ keyCode: CGKeyCode) {
guard let source = CGEventSource(stateID: .hidSystemState),
- let down = CGEvent(keyboardEventSource: source, virtualKey: 36, keyDown: true),
- let up = CGEvent(keyboardEventSource: source, virtualKey: 36, keyDown: false)
+ let down = CGEvent(keyboardEventSource: source, virtualKey: keyCode, keyDown: true),
+ let up = CGEvent(keyboardEventSource: source, virtualKey: keyCode, keyDown: false)
else { return }
down.post(tap: .cghidEventTap)
up.post(tap: .cghidEventTap)
}
+
+ private static func virtualKeyCode(for name: String) -> CGKeyCode? {
+ switch name {
+ case "return", "enter", "\n", "": return 36
+ case "tab", "\t": return 48
+ case "space", "spacebar", " ": return 49
+ case "escape", "esc": return 53
+ case "delete", "backspace": return 51
+ case "forwarddelete", "fwddelete": return 117
+ case "left", "leftarrow": return 123
+ case "right", "rightarrow": return 124
+ case "down", "downarrow": return 125
+ case "up", "uparrow": return 126
+ case "home": return 115
+ case "end": return 119
+ case "pageup": return 116
+ case "pagedown": return 121
+ default: return nil
+ }
+ }
}
/// Low-level pointer input via CGEvent (move + left click at a screen point). Real input — callers
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityObserver.swift b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityObserver.swift
index 1f11a64c..7228a1f5 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityObserver.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityObserver.swift
@@ -46,18 +46,18 @@ public enum AccessibilityObserver {
resolver: MacWindowResolver = MacWindowResolver()
) -> MacWindowTargetCandidate? {
if appName != nil || bundleIdentifier != nil {
+ // A specific app was requested: only ever return that app's window. If it isn't running /
+ // has no window, return nil — never fall back to the frontmost window, which would
+ // silently ground (and potentially click) in an unrelated app the user didn't name.
let candidates = resolver.enumerateCandidates()
- if let match = candidates.first(where: { candidate in
+ return candidates.first { candidate in
if let bundleIdentifier, let candidateBundle = candidate.bundleIdentifier {
return candidateBundle.caseInsensitiveCompare(bundleIdentifier) == .orderedSame
}
if let appName, let candidateApp = candidate.appName {
- return candidateApp.localizedCaseInsensitiveContains(appName)
- || appName.localizedCaseInsensitiveContains(candidateApp)
+ return AppNameMatching.matches(candidateApp, appName)
}
return false
- }) {
- return match
}
}
return try? resolver.selectTarget()
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppCapabilityLearning.swift b/apps/Donkey/Sources/DonkeyRuntime/AppCapabilityLearning.swift
index d720df27..f64f284f 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/AppCapabilityLearning.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/AppCapabilityLearning.swift
@@ -116,6 +116,11 @@ public final class FileAppScriptabilityStore: AppScriptabilityStore, @unchecked
public final class AppCapabilityService: @unchecked Sendable {
public typealias ScriptabilityProbe = @Sendable (_ bundleIdentifier: String?, _ appName: String?) -> AppScriptability
+ /// App-lifetime instance backing the production execution-strategy decision: the command router
+ /// consults `scriptability(...)` to pick AppleScript vs the accessibility/vision path, and records
+ /// each real AppleScript outcome here so the choice adapts per machine.
+ public static let shared = AppCapabilityService()
+
private let store: AppScriptabilityStore
private let probe: ScriptabilityProbe
@@ -144,7 +149,21 @@ public final class AppCapabilityService: @unchecked Sendable {
return AppScriptabilityResolver.resolve(observation)
}
- /// Learn from an actual AppleScript attempt on this machine.
+ /// True when this machine has LEARNED (from real attempts) that AppleScript doesn't work for the
+ /// app — repeated failures with no success — as opposed to merely lacking a scripting dictionary.
+ /// The router uses this to decide whether to pre-empt the AppleScript/keystroke path for vision.
+ public func hasLearnedAppleScriptFailure(bundleIdentifier: String?) -> Bool {
+ guard let bundleIdentifier, !bundleIdentifier.isEmpty,
+ let observation = store.observation(bundleIdentifier: bundleIdentifier)
+ else {
+ return false
+ }
+ return observation.appleScriptSuccesses == 0
+ && observation.appleScriptFailures >= AppScriptabilityResolver.failureThreshold
+ }
+
+ /// Learn from an actual AppleScript attempt on this machine. Called by the command router after
+ /// each AppleScript-backed run (`UserQueryCommandHandler.recordAppleScriptScriptability`).
public func recordAppleScriptOutcome(bundleIdentifier: String?, appName: String? = nil, succeeded: Bool) {
guard let bundleIdentifier, !bundleIdentifier.isEmpty else { return }
var observation = store.observation(bundleIdentifier: bundleIdentifier)
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ExecutionStrategy.swift b/apps/Donkey/Sources/DonkeyRuntime/ExecutionStrategy.swift
index a1cfca13..a0b35064 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ExecutionStrategy.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ExecutionStrategy.swift
@@ -113,9 +113,28 @@ public struct MacAppScriptabilityProbe: Sendable {
AppScriptabilityClassifier.classify(facts(bundleIdentifier: bundleIdentifier, appName: appName))
}
- private func bundleURL(bundleIdentifier: String?, appName _: String?) -> URL? {
- // Resolve by bundle identifier (reliable); name-only resolution is intentionally not used.
- guard let bundleIdentifier else { return nil }
- return NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier)
+ private func bundleURL(bundleIdentifier: String?, appName: String?) -> URL? {
+ // Resolve by bundle identifier first (reliable).
+ if let bundleIdentifier, !bundleIdentifier.isEmpty,
+ let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) {
+ return url
+ }
+ // Fall back to the display name: the planner often knows an app only by name. Prefer an
+ // EXACT running-app name match (so "Mail" doesn't resolve "YubiKey Mail Helper"), then a
+ // fuzzy running-app match, then Launch Services' lookup by application name.
+ guard let appName, !appName.isEmpty else { return nil }
+ let running = NSWorkspace.shared.runningApplications
+ let wanted = appName.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
+ if let exact = running.first(where: {
+ ($0.localizedName ?? "").lowercased().trimmingCharacters(in: .whitespacesAndNewlines) == wanted
+ }), let url = exact.bundleURL {
+ return url
+ }
+ if let fuzzy = running.first(where: {
+ AppNameMatching.matches($0.localizedName ?? "", appName)
+ }), let url = fuzzy.bundleURL {
+ return url
+ }
+ return NSWorkspace.shared.fullPath(forApplication: appName).map { URL(fileURLWithPath: $0) }
}
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift
index 3e70c744..8b8a64dd 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift
@@ -7,12 +7,19 @@ public enum BuiltInLocalAppSkillPacks {
Bundle.module.resourceURL?.appendingPathComponent("BuiltInSkills", isDirectory: true)
}
- public static func descriptors() -> [HarnessSkillDescriptor] {
+ /// Built-in skills ship inside the bundle and never change at runtime, so discover them (which
+ /// walks the BuiltInSkills tree and reads every SKILL.md from disk) exactly once. Callers on the
+ /// planning hot path — `defaultContext` and `appOperatingGuidance` run per turn — reuse this.
+ private static let cachedDescriptors: [HarnessSkillDescriptor] = {
guard let rootURL else { return [] }
return HarnessSkillFileSystemSource(
roots: [rootURL],
sourceKind: .builtIn
).discover()
+ }()
+
+ public static func descriptors() -> [HarnessSkillDescriptor] {
+ cachedDescriptors
}
public static func instructionSnippet(
@@ -39,8 +46,12 @@ public enum BuiltInLocalAppSkillPacks {
/// Returns the operating playbook for an app-specific skill (one whose `apps:` frontmatter names
/// this app by display name or bundle identifier), or nil if no app-specific skill is installed.
- /// This is how the runtime learns how to drive a particular app WITHOUT any hardcoded app list:
- /// add a `BuiltInSkills/<app>/SKILL.md` with an `apps:` line and the guidance is discovered here.
+ /// This is how the runtime learns how to drive a particular app WITHOUT a hardcoded app list:
+ /// add a `BuiltInSkills/<app>/SKILL.md` with an `apps:` line and it is discovered here.
+ ///
+ /// Consumed by the vision-driving action path (`VisionActionPlanner` via
+ /// `UserQueryCommandHandler.handleVisionAction`) to supply per-app operating guidance when a
+ /// non-scriptable app is driven by vision.
public static func appOperatingGuidance(
forApp appName: String,
bundleIdentifier: String? = nil,
@@ -56,9 +67,9 @@ public enum BuiltInLocalAppSkillPacks {
let match = descriptors().first { descriptor in
let apps = (descriptor.metadata["apps"] ?? "")
.split(separator: ",")
- .map { $0.lowercased().trimmingCharacters(in: .whitespacesAndNewlines) }
+ .map { String($0).trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty }
- return apps.contains { app in wanted.contains { $0 == app || $0.contains(app) || app.contains($0) } }
+ return apps.contains { app in wanted.contains { AppNameMatching.matches($0, app) } }
}
guard let match else { return nil }
let body = bounded(strippedSkillMetadata(from: match.description), maxCharacters: maxCharacters)
@@ -162,7 +173,7 @@ public struct LocalAppTaskSkillContext: Equatable, Sendable {
appFinderCatalog: [LocalAppFinderCatalogEntry]
) -> [(descriptor: HarnessSkillDescriptor, score: Int)] {
// App-specific operating skills (those declaring `apps:`) are vision-driving playbooks
- // consumed only via `appOperatingGuidance(forApp:)` during execution — they are not
+ // consumed via `appOperatingGuidance(forApp:)` by the vision action path — they are not
// intent-planning skills, so keep them out of the planner's skill catalog/ranking.
let descriptors = BuiltInLocalAppSkillPacks.descriptors()
.filter { ($0.metadata["apps"] ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
@@ -214,11 +225,6 @@ public struct LocalAppTaskSkillContext: Equatable, Sendable {
}
private static func tokens(in value: String) -> Set<String> {
- Set(
- value.lowercased()
- .split { !$0.isLetter && !$0.isNumber }
- .map(String.init)
- .filter { !$0.isEmpty }
- )
+ ControlTextRelevance.tokens(in: value)
}
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/SpotifyVisionAgentLiveSmokeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/SpotifyVisionAgentLiveSmokeTests.swift
index 054f2fbc..a6b641c9 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/SpotifyVisionAgentLiveSmokeTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/SpotifyVisionAgentLiveSmokeTests.swift
@@ -20,7 +20,6 @@ struct SpotifyVisionAgentLiveSmokeTests {
let goal = env["DONKEY_GOAL"] ?? "Search for the artist Coldplay and play their most popular song."
let backend = DonkeyBackendInferenceClient(configuration: config, httpClient: URLSessionAIHTTPClient())
- let capturer = ScreenCaptureKitWindowScreenshotCapturer()
// App-specific operating playbook, discovered from BuiltInSkills/spotify/SKILL.md by app name
// (no hardcoded app logic in code — add a SKILL.md to teach the agent a new app).
let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(forApp: "Spotify", bundleIdentifier: "com.spotify.client")
@@ -28,63 +27,28 @@ struct SpotifyVisionAgentLiveSmokeTests {
NSWorkspace.shared.launchApplication("Spotify")
try? await Task.sleep(nanoseconds: 1_500_000_000)
+ // Drive via the SAME shared loop production uses, so this smoke test validates the real path.
var log: [String] = []
- var history: [String] = []
- for turn in 0..<12 {
- guard let target = AccessibilityObserver.resolveTarget(appName: "Spotify", bundleIdentifier: nil) else {
- log.append("turn \(turn): no window"); break
+ let outcome = await VisionActionDriver.drive(
+ appName: "Spotify",
+ bundleIdentifier: "com.spotify.client",
+ goal: goal,
+ appGuidance: appGuidance,
+ backend: backend,
+ settleNanoseconds: 2_200_000_000,
+ onTurn: { info in
+ // 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 ?? "")")
}
- guard let shot = try? await capturer.capture(target: target) else {
- log.append("turn \(turn): capture failed"); break
- }
- // Dump exactly what the model sees (compressed) so we can inspect it.
- let dump = ScreenshotCompression.compressedForModel(shot)
- let dumpPath = "/tmp/spotify-agent-turn\(turn).jpg"
- try? dump.data.write(to: URL(fileURLWithPath: dumpPath))
- log.append("turn \(turn): window=(\(Int(target.bounds.x)),\(Int(target.bounds.y)) \(Int(target.bounds.width))x\(Int(target.bounds.height))) model-image=\(Int(dump.pixelSize.width))x\(Int(dump.pixelSize.height)) -> \(dumpPath)")
- let action: VisionActionPlanner.PlannedAction
- do {
- action = try await VisionActionPlanner.nextAction(goal: goal, app: "Spotify", screenshot: shot, window: target.bounds, history: history, appGuidance: appGuidance, backend: backend)
- } catch {
- log.append("turn \(turn): planner error \(error)"); break
- }
- log.append("turn \(turn): \(action.action) x=\(action.x.map { String(Int($0)) } ?? "-") y=\(action.y.map { String(Int($0)) } ?? "-") text=\(action.text ?? "") :: \(action.reason ?? "")")
+ )
+ log.append("driver outcome: completed=\(outcome.completed) turns=\(outcome.turns) reason=\(outcome.reason)")
- // Effective action: a "click" that carries text but no point is really a "type".
- var effective = action.action
- if effective == "click", action.screenPoint == nil, let t = action.text, !t.isEmpty {
- effective = "type"
- }
-
- switch effective {
- case "done":
- log.append("turn \(turn): model reports DONE")
- // Verify the agent's claim against the app's real playback state.
- let state = Self.spotifyPlayerState()
- log.append("verified player state: \(state)")
- #expect(state == "playing", "Agent finished but Spotify is not playing.\n\(log.joined(separator: "\n"))")
- return
- case "click":
- if let p = action.screenPoint {
- _ = MacPointerInput.moveAndClick(at: p)
- history.append("clicked at (\(Int(action.x ?? 0)),\(Int(action.y ?? 0))) — \(action.reason ?? "")")
- } else {
- history.append("attempted click but no coordinates were given — \(action.reason ?? "")")
- }
- case "type":
- if let t = action.text { MacKeyboardInput.type(t); history.append("typed \"\(t)\"") }
- case "key":
- MacKeyboardInput.pressReturn()
- history.append("pressed return")
- default:
- break
- }
- try? await Task.sleep(nanoseconds: 2_200_000_000)
- }
- // Loop ended without the model declaring done — still verify the end state.
+ // Verify the agent's claim against the app's REAL playback state (independent of vision).
let state = Self.spotifyPlayerState()
- log.append("loop ended; verified player state: \(state)")
- #expect(state == "playing", "Vision agent loop ended without playing music.\n\(log.joined(separator: "\n"))")
+ log.append("verified player state: \(state)")
+ #expect(state == "playing", "Vision agent finished but Spotify is not playing.\n\(log.joined(separator: "\n"))")
}
/// Reads Spotify's real playback state via Automation (NSAppleScript), independent of vision,
diff --git a/apps/Donkey/docs/adaptive-grounded-overlay-plan.md b/apps/Donkey/docs/adaptive-grounded-overlay-plan.md
index bc123fc0..2cab95b5 100644
--- a/apps/Donkey/docs/adaptive-grounded-overlay-plan.md
+++ b/apps/Donkey/docs/adaptive-grounded-overlay-plan.md
@@ -1,5 +1,15 @@
# Adaptive grounded pointer overlay — implementation plan
+> **Status: wired into the live command router.** The guidance route (`"show me where X is"` →
+> AX-grounded cursor overlay) runs via `UserQueryCommandHandler.handleGuidance`. The action side is
+> live too: `UserQueryCommandHandler` consults `ExecutionStrategySelector` (backed by
+> `AppCapabilityService.shared`, which learns per-machine scriptability) after intent resolution; an
+> Electron app (or one this machine has learned fails AppleScript) is driven by vision via the shared
+> `VisionActionDriver` (per-turn `VisionActionPlanner` + real pointer/keyboard, gated by a frontmost
+> check before every input), supplied with per-app guidance from the matching `BuiltInSkills/<app>/SKILL.md`.
+> Each AppleScript-backed run records its outcome via `recordAppleScriptScriptability`, so apps that
+> repeatedly fail AppleScript flip to the vision path. See "How it is wired" at the end.
+
## Context
Donkey can drive scriptable apps via AppleScript (e.g. Music, now playing reliably through the
@@ -121,6 +131,32 @@ which is why skill/AppleScript runs produce `noGroundedTargets`).
- **Element resolution quality** on Electron: AX labels can be sparse; may need the screenshot +
local-UI-understanding fallback (`strategyOrder: accessibility,windowMetadata,screenshotForLocalModel`)
to locate controls when AX is thin.
+
+## How it is wired
+
+In `UserQueryCommandHandler.continueHandlingNonVisualizationCommand`, after intent resolution and the
+conversation/clarification routing:
+
+1. `handleVisionActionIfNonScriptable` consults `AppCapabilityService.shared.scriptability(...)` +
+ `ExecutionStrategySelector.strategy(...)` for the resolved target app. It only pre-empts the
+ AppleScript/keystroke path when the app is **Electron** or has a **learned AppleScript failure**
+ (`hasLearnedAppleScriptFailure`); a native app that merely lacks a scripting dictionary stays on
+ the existing path (System-Events keystrokes still work for it).
+2. Such an app is driven by the shared `VisionActionDriver.drive(...)`: a bounded per-turn loop that
+ resolves + activates the window once, captures, asks `VisionActionPlanner.nextAction` for the next
+ click/type/key, and executes it until the model reports `done`. Every real-input action is gated
+ by a frontmost check, so input never lands on a window the user switched to mid-round-trip. The
+ same driver backs `SpotifyVisionAgentLiveSmokeTests`. Per-app operating guidance comes from
+ `BuiltInLocalAppSkillPacks.appOperatingGuidance(forApp:)`.
+3. If the planner flagged the action `needsConfirmation`, the route asks the user first
+ (`confirmVisionAction`) instead of auto-driving.
+4. After every AppleScript-backed run, `recordAppleScriptScriptability` calls
+ `AppCapabilityService.shared.recordAppleScriptOutcome(...)`, so an app that keeps failing
+ AppleScript (≥2 failures, no success) flips to the vision path on the next request, and a success
+ keeps it on AppleScript.
+
+Guarded by the `.input` permission; the vision route no-ops back to the AppleScript path when the
+hosted backend or the target window can't be reached.
- **Capability detection** accuracy (scriptable vs not) — start with an allowlist + runtime failure
fallback; refine over time.
- Environment for live demo: Spotify must be installed/running and the runner AX-granted.