Open source CapCut alternative.
TypeScript
Add execution-strategy router with per-machine capability learning (overlay phase 3)
David Le03cbd63defca
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppCapabilityLearning.swift b/apps/Donkey/Sources/DonkeyRuntime/AppCapabilityLearning.swiftnew file mode 100644index 00000000..d720df27--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/AppCapabilityLearning.swift@@ -0,0 +1,159 @@+import Foundation++/// What the harness has learned about one app on THIS machine: the bundle probe plus how+/// AppleScript attempts have actually turned out here.+public struct AppScriptabilityObservation: Equatable, Sendable, Codable {+ public var bundleIdentifier: String+ public var probed: AppScriptability+ public var appleScriptSuccesses: Int+ public var appleScriptFailures: Int++ public init(+ bundleIdentifier: String,+ probed: AppScriptability,+ appleScriptSuccesses: Int = 0,+ appleScriptFailures: Int = 0+ ) {+ self.bundleIdentifier = bundleIdentifier+ self.probed = probed+ self.appleScriptSuccesses = appleScriptSuccesses+ self.appleScriptFailures = appleScriptFailures+ }+}++/// Resolves scriptability from learned evidence: actual runtime outcomes on this machine override+/// the static bundle probe. Any confirmed AppleScript success means the app works here; repeated+/// failures with no success mean it does not (regardless of what the bundle declared).+public enum AppScriptabilityResolver {+ public static let failureThreshold = 2++ public static func resolve(_ observation: AppScriptabilityObservation) -> AppScriptability {+ if observation.appleScriptSuccesses > 0 {+ return .scriptable+ }+ if observation.appleScriptFailures >= failureThreshold {+ return .notScriptable+ }+ return observation.probed+ }+}++/// Persistent per-machine record of learned app capabilities.+public protocol AppScriptabilityStore: Sendable {+ func observation(bundleIdentifier: String) -> AppScriptabilityObservation?+ func record(_ observation: AppScriptabilityObservation)+}++public final class InMemoryAppScriptabilityStore: AppScriptabilityStore, @unchecked Sendable {+ private var records: [String: AppScriptabilityObservation] = [:]+ private let lock = NSLock()++ public init() {}++ public func observation(bundleIdentifier: String) -> AppScriptabilityObservation? {+ lock.lock(); defer { lock.unlock() }+ return records[bundleIdentifier]+ }++ public func record(_ observation: AppScriptabilityObservation) {+ lock.lock(); defer { lock.unlock() }+ records[observation.bundleIdentifier] = observation+ }+}++/// JSON-backed store under Application Support, so learning persists across runs on this machine.+public final class FileAppScriptabilityStore: AppScriptabilityStore, @unchecked Sendable {+ private let url: URL+ private let lock = NSLock()+ private var cache: [String: AppScriptabilityObservation]++ public init(url: URL? = nil) {+ let resolved = url ?? Self.defaultURL()+ self.url = resolved+ self.cache = Self.load(resolved)+ }++ public func observation(bundleIdentifier: String) -> AppScriptabilityObservation? {+ lock.lock(); defer { lock.unlock() }+ return cache[bundleIdentifier]+ }++ public func record(_ observation: AppScriptabilityObservation) {+ lock.lock(); defer { lock.unlock() }+ cache[observation.bundleIdentifier] = observation+ persistLocked()+ }++ private func persistLocked() {+ guard let data = try? JSONEncoder().encode(cache) else { return }+ try? FileManager.default.createDirectory(+ at: url.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ try? data.write(to: url, options: .atomic)+ }++ private static func load(_ url: URL) -> [String: AppScriptabilityObservation] {+ guard let data = try? Data(contentsOf: url),+ let decoded = try? JSONDecoder().decode([String: AppScriptabilityObservation].self, from: data)+ else {+ return [:]+ }+ return decoded+ }++ private static func defaultURL() -> URL {+ let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ ?? URL(fileURLWithPath: NSTemporaryDirectory())+ return base+ .appendingPathComponent("Donkey", isDirectory: true)+ .appendingPathComponent("app-scriptability.json", isDirectory: false)+ }+}++/// Combines the bundle probe with the learning store: probes an app the first time it is seen on+/// this machine (and remembers it), then refines the answer from real AppleScript outcomes.+public final class AppCapabilityService: @unchecked Sendable {+ public typealias ScriptabilityProbe = @Sendable (_ bundleIdentifier: String?, _ appName: String?) -> AppScriptability++ private let store: AppScriptabilityStore+ private let probe: ScriptabilityProbe++ public init(+ store: AppScriptabilityStore = FileAppScriptabilityStore(),+ probe: @escaping ScriptabilityProbe = { MacAppScriptabilityProbe().scriptability(bundleIdentifier: $0, appName: $1) }+ ) {+ self.store = store+ self.probe = probe+ }++ /// Best current answer for the app, learned from this machine.+ public func scriptability(bundleIdentifier: String?, appName: String? = nil) -> AppScriptability {+ guard let bundleIdentifier, !bundleIdentifier.isEmpty else {+ return probe(bundleIdentifier, appName)+ }+ let observation = store.observation(bundleIdentifier: bundleIdentifier) ?? {+ // First encounter on this machine: probe the installed bundle and remember it.+ let fresh = AppScriptabilityObservation(+ bundleIdentifier: bundleIdentifier,+ probed: probe(bundleIdentifier, appName)+ )+ store.record(fresh)+ return fresh+ }()+ return AppScriptabilityResolver.resolve(observation)+ }++ /// Learn from an actual AppleScript attempt on this machine.+ public func recordAppleScriptOutcome(bundleIdentifier: String?, appName: String? = nil, succeeded: Bool) {+ guard let bundleIdentifier, !bundleIdentifier.isEmpty else { return }+ var observation = store.observation(bundleIdentifier: bundleIdentifier)+ ?? AppScriptabilityObservation(bundleIdentifier: bundleIdentifier, probed: probe(bundleIdentifier, appName))+ if succeeded {+ observation.appleScriptSuccesses += 1+ } else {+ observation.appleScriptFailures += 1+ }+ store.record(observation)+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/ExecutionStrategy.swift b/apps/Donkey/Sources/DonkeyRuntime/ExecutionStrategy.swiftnew file mode 100644index 00000000..a1cfca13--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/ExecutionStrategy.swift@@ -0,0 +1,121 @@+import AppKit+import Foundation++/// Whether an app can be driven via AppleScript, or must be driven through accessibility/UI.+public enum AppScriptability: String, Equatable, Sendable, Codable {+ case scriptable+ case notScriptable+ case unknown+}++/// Authoritative, app-derived signals used to classify scriptability. Kept as plain values so the+/// classification logic is pure and unit-testable independently of any live bundle lookup.+public struct AppScriptabilityFacts: Equatable, Sendable {+ public var bundleIdentifier: String?+ /// `Info.plist` `NSAppleScriptEnabled` (or presence of an `OSAScriptingDefinition` sdef). nil = unknown.+ public var appleScriptEnabled: Bool?+ /// The app ships the Electron framework (Chromium) — no useful AppleScript dictionary.+ public var isElectron: Bool++ public init(bundleIdentifier: String? = nil, appleScriptEnabled: Bool? = nil, isElectron: Bool = false) {+ self.bundleIdentifier = bundleIdentifier+ self.appleScriptEnabled = appleScriptEnabled+ self.isElectron = isElectron+ }+}++/// Pure classification of app scriptability from bundle-derived facts. No per-app allowlists: an+/// app is scriptable iff it ships a scripting dictionary, and non-scriptable if it is Electron or+/// declares no dictionary. This generalizes to any third-party app without maintaining a list.+public enum AppScriptabilityClassifier {+ public static func classify(_ facts: AppScriptabilityFacts) -> AppScriptability {+ if facts.isElectron { return .notScriptable }+ switch facts.appleScriptEnabled {+ case .some(true): return .scriptable+ case .some(false): return .notScriptable+ case .none: return .unknown+ }+ }+}++/// How the harness will act on the target app.+public enum ExecutionStrategy: String, Equatable, Sendable {+ /// Scriptable app — drive via AppleScript (skill scripts / dynamic AppleScript).+ case appleScript+ /// Non-scriptable app (Electron) or AppleScript failed — drive via accessibility + UI input.+ case accessibilityUI+}++/// Chooses the execution strategy so the harness figures it out by itself:+/// AppleScript for scriptable apps, accessibility/UI for Electron and non-scriptable apps, and an+/// automatic fallback to accessibility/UI whenever an AppleScript attempt actually fails.+public enum ExecutionStrategySelector {+ public static func strategy(+ scriptability: AppScriptability,+ appleScriptAttempted: Bool = false,+ appleScriptSucceeded: Bool? = nil+ ) -> ExecutionStrategy {+ // An AppleScript attempt that failed/blocked always falls back to the accessibility path.+ if appleScriptAttempted, appleScriptSucceeded == false {+ return .accessibilityUI+ }+ switch scriptability {+ case .notScriptable:+ return .accessibilityUI+ case .scriptable, .unknown:+ // Unknown apps: try AppleScript first; the runtime-failure rule above handles fallback.+ return .appleScript+ }+ }+}++/// Live probe that derives scriptability facts from the installed app bundle.+public struct MacAppScriptabilityProbe: Sendable {+ public init() {}++ public func facts(bundleIdentifier: String?, appName: String? = nil) -> AppScriptabilityFacts {+ guard let url = bundleURL(bundleIdentifier: bundleIdentifier, appName: appName) else {+ return AppScriptabilityFacts(bundleIdentifier: bundleIdentifier)+ }+ let info = Bundle(url: url)?.infoDictionary+ // An app declares AppleScript support via NSAppleScriptEnabled, an OSAScriptingDefinition,+ // or by shipping an .sdef dictionary. Having read the bundle, the absence of all three is a+ // definite "not scriptable" (not unknown).+ let appleScriptEnabled: Bool+ if let flag = info?["NSAppleScriptEnabled"] as? Bool {+ appleScriptEnabled = flag+ } else if let flag = info?["NSAppleScriptEnabled"] as? String {+ appleScriptEnabled = (flag as NSString).boolValue+ } else if info?["OSAScriptingDefinition"] != nil {+ appleScriptEnabled = true+ } else {+ appleScriptEnabled = hasScriptingDefinition(in: url)+ }+ let electronFramework = url+ .appendingPathComponent("Contents/Frameworks/Electron Framework.framework", isDirectory: true)+ let isElectron = FileManager.default.fileExists(atPath: electronFramework.path)+ return AppScriptabilityFacts(+ bundleIdentifier: bundleIdentifier ?? (info?["CFBundleIdentifier"] as? String),+ appleScriptEnabled: appleScriptEnabled,+ isElectron: isElectron+ )+ }++ private func hasScriptingDefinition(in bundleURL: URL) -> Bool {+ let resources = bundleURL.appendingPathComponent("Contents/Resources", isDirectory: true)+ guard let items = try? FileManager.default.contentsOfDirectory(atPath: resources.path) else {+ return false+ }+ return items.contains { $0.lowercased().hasSuffix(".sdef") }+ }++ public func scriptability(bundleIdentifier: String?, appName: String? = nil) -> AppScriptability {+ 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)+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AppCapabilityLearningTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AppCapabilityLearningTests.swiftnew file mode 100644index 00000000..3c46d566--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AppCapabilityLearningTests.swift@@ -0,0 +1,83 @@+import DonkeyRuntime+import Foundation+import Testing++@Suite+struct AppCapabilityLearningTests {+ // MARK: Resolver — runtime evidence overrides the static probe++ @Test+ func usesProbeWhenNoRuntimeEvidence() {+ let obs = AppScriptabilityObservation(bundleIdentifier: "x", probed: .scriptable)+ #expect(AppScriptabilityResolver.resolve(obs) == .scriptable)+ let obs2 = AppScriptabilityObservation(bundleIdentifier: "y", probed: .notScriptable)+ #expect(AppScriptabilityResolver.resolve(obs2) == .notScriptable)+ }++ @Test+ func repeatedFailuresOverrideAScriptableProbe() {+ let obs = AppScriptabilityObservation(bundleIdentifier: "x", probed: .scriptable, appleScriptFailures: 2)+ #expect(AppScriptabilityResolver.resolve(obs) == .notScriptable)+ }++ @Test+ func aSuccessOverridesEvenANotScriptableProbe() {+ let obs = AppScriptabilityObservation(+ bundleIdentifier: "x", probed: .notScriptable, appleScriptSuccesses: 1, appleScriptFailures: 5+ )+ #expect(AppScriptabilityResolver.resolve(obs) == .scriptable)+ }++ @Test+ func oneFailureIsNotEnoughToFlip() {+ let obs = AppScriptabilityObservation(bundleIdentifier: "x", probed: .scriptable, appleScriptFailures: 1)+ #expect(AppScriptabilityResolver.resolve(obs) == .scriptable)+ }++ // MARK: Service — probes once, then learns from outcomes++ /// Thread-safe call counter usable from a @Sendable probe closure.+ final class Counter: @unchecked Sendable {+ private var value = 0+ private let lock = NSLock()+ func increment() { lock.lock(); value += 1; lock.unlock() }+ var count: Int { lock.lock(); defer { lock.unlock() }; return value }+ }++ @Test+ func probesOnFirstEncounterThenLearnsFromFailures() {+ let store = InMemoryAppScriptabilityStore()+ let probeCalls = Counter()+ let service = AppCapabilityService(store: store) { _, _ in+ probeCalls.increment()+ return .scriptable // bundle says scriptable+ }++ // First lookup probes and caches.+ #expect(service.scriptability(bundleIdentifier: "com.example.app") == .scriptable)+ #expect(probeCalls.count == 1)+ // Cached: no re-probe.+ #expect(service.scriptability(bundleIdentifier: "com.example.app") == .scriptable)+ #expect(probeCalls.count == 1)++ // Two real AppleScript failures on this machine flip it to accessibility/UI.+ service.recordAppleScriptOutcome(bundleIdentifier: "com.example.app", succeeded: false)+ service.recordAppleScriptOutcome(bundleIdentifier: "com.example.app", succeeded: false)+ #expect(service.scriptability(bundleIdentifier: "com.example.app") == .notScriptable)+ }++ @Test+ func fileStorePersistsLearningAcrossInstances() {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("donkey-scriptability-\(UUID().uuidString).json")+ defer { try? FileManager.default.removeItem(at: url) }++ let first = FileAppScriptabilityStore(url: url)+ first.record(AppScriptabilityObservation(bundleIdentifier: "com.example.app", probed: .scriptable, appleScriptFailures: 3))++ let reopened = FileAppScriptabilityStore(url: url)+ let restored = reopened.observation(bundleIdentifier: "com.example.app")+ #expect(restored?.appleScriptFailures == 3)+ #expect(restored.map(AppScriptabilityResolver.resolve) == .notScriptable)+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ExecutionStrategyTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ExecutionStrategyTests.swiftnew file mode 100644index 00000000..4cc05372--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ExecutionStrategyTests.swift@@ -0,0 +1,67 @@+import DonkeyRuntime+import Foundation+import Testing++@Suite+struct ExecutionStrategyTests {+ // MARK: Scriptability classification++ @Test+ func electronIsNotScriptableRegardlessOfOtherSignals() {+ let facts = AppScriptabilityFacts(bundleIdentifier: "com.spotify.client", appleScriptEnabled: true, isElectron: true)+ #expect(AppScriptabilityClassifier.classify(facts) == .notScriptable)+ }++ @Test+ func appleScriptEnabledFlagIsAuthoritative() {+ #expect(AppScriptabilityClassifier.classify(AppScriptabilityFacts(appleScriptEnabled: true)) == .scriptable)+ #expect(AppScriptabilityClassifier.classify(AppScriptabilityFacts(appleScriptEnabled: false)) == .notScriptable)+ }++ @Test+ func appWithNoScriptingSignalsIsUnknownWithoutBundleFacts() {+ // No allowlists: a bundle id alone (no Electron marker, no AppleScript flag/sdef from the+ // bundle probe) is unknown until probed/learned.+ #expect(AppScriptabilityClassifier.classify(AppScriptabilityFacts(bundleIdentifier: "com.example.mystery")) == .unknown)+ }++ @Test+ func bundleProbeFactsDriveClassificationNotAppName() {+ // Electron app (e.g. resolved for Spotify) → not scriptable from the structural marker alone.+ #expect(AppScriptabilityClassifier.classify(AppScriptabilityFacts(bundleIdentifier: "com.spotify.client", isElectron: true)) == .notScriptable)+ // Scriptable app (e.g. Music) → scriptable from its declared scripting dictionary.+ #expect(AppScriptabilityClassifier.classify(AppScriptabilityFacts(bundleIdentifier: "com.apple.Music", appleScriptEnabled: true)) == .scriptable)+ }++ // MARK: Strategy selection++ @Test+ func scriptableUsesAppleScriptAndNonScriptableUsesAccessibility() {+ #expect(ExecutionStrategySelector.strategy(scriptability: .scriptable) == .appleScript)+ #expect(ExecutionStrategySelector.strategy(scriptability: .notScriptable) == .accessibilityUI)+ }++ @Test+ func unknownTriesAppleScriptFirst() {+ #expect(ExecutionStrategySelector.strategy(scriptability: .unknown) == .appleScript)+ }++ @Test+ func appleScriptFailureFallsBackToAccessibilityEvenForScriptableApps() {+ #expect(+ ExecutionStrategySelector.strategy(+ scriptability: .scriptable,+ appleScriptAttempted: true,+ appleScriptSucceeded: false+ ) == .accessibilityUI+ )+ // A successful AppleScript attempt does not fall back.+ #expect(+ ExecutionStrategySelector.strategy(+ scriptability: .scriptable,+ appleScriptAttempted: true,+ appleScriptSucceeded: true+ ) == .appleScript+ )+ }+}