Skip to content

Open source CapCut alternative.

TypeScript

feat(app): route mid-task system permissions through the in-notch gate

David Le852de72e6d79
diff --git a/apps/Donkey/Sources/Donkey/VertexVisionBoxDriver.swift b/apps/Donkey/Sources/Donkey/VertexVisionBoxDriver.swift
index 40b89cb8..c195a64d 100644
--- a/apps/Donkey/Sources/Donkey/VertexVisionBoxDriver.swift
+++ b/apps/Donkey/Sources/Donkey/VertexVisionBoxDriver.swift
@@ -158,7 +158,7 @@ enum VertexVisionBoxDriver {
end if
end tell
"""
- var error: NSDictionary?
- NSAppleScript(source: source)?.executeAndReturnError(&error)
+ // Never prompt mid-task for this internal nicety; skip it if Automation isn't already granted.
+ SystemPermissionCoordinator.runSystemEventsScriptIfGranted(source)
}
}
diff --git a/apps/Donkey/Sources/Donkey/VertexVisionDriver.swift b/apps/Donkey/Sources/Donkey/VertexVisionDriver.swift
index 98b1d201..5b28a035 100644
--- a/apps/Donkey/Sources/Donkey/VertexVisionDriver.swift
+++ b/apps/Donkey/Sources/Donkey/VertexVisionDriver.swift
@@ -136,7 +136,7 @@ enum VertexVisionDriver {
end if
end tell
"""
- var error: NSDictionary?
- NSAppleScript(source: source)?.executeAndReturnError(&error)
+ // Never prompt mid-task for this internal nicety; skip it if Automation isn't already granted.
+ SystemPermissionCoordinator.runSystemEventsScriptIfGranted(source)
}
}
diff --git a/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift b/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift
index 984e464b..5bed77e0 100644
--- a/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift
+++ b/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift
@@ -264,7 +264,7 @@ public enum VisionActionDriver {
end if
end tell
"""
- var error: NSDictionary?
- NSAppleScript(source: source)?.executeAndReturnError(&error)
+ // Never prompt mid-task for this internal nicety; skip it if Automation isn't already granted.
+ SystemPermissionCoordinator.runSystemEventsScriptIfGranted(source)
}
}
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
index 659a7498..e65e3283 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
@@ -235,6 +235,10 @@ public struct HarnessBuiltInToolServices: Sendable {
public var appleScriptCompiler: (@Sendable (_ source: String, _ targetApp: String?, _ bundleIdentifier: String?) async -> HarnessScriptCompileOutcome)?
public var appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?
public var skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?
+ /// Preflights macOS Automation (Apple Events) consent for a target app bundle id, WITHOUT
+ /// prompting. When this returns false, AppleScript execution raises the in-notch permission gate
+ /// instead of letting the system dialog fire mid-task. nil means "skip the pre-gate".
+ public var automationConsentGranted: (@Sendable (_ bundleIdentifier: String?) async -> Bool)?
/// Native Donkey Command Layer backend. Returns a result for a recognized
/// command, or `nil` to let dispatch fall through to `unknownTool`.
public var commandExecutor: (@Sendable (HarnessToolExecutionContext) async -> HarnessToolResult?)?
@@ -265,6 +269,7 @@ public struct HarnessBuiltInToolServices: Sendable {
appleScriptCompiler: (@Sendable (_ source: String, _ targetApp: String?, _ bundleIdentifier: String?) async -> HarnessScriptCompileOutcome)? = nil,
appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,
skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,
+ automationConsentGranted: (@Sendable (_ bundleIdentifier: String?) async -> Bool)? = nil,
commandExecutor: (@Sendable (HarnessToolExecutionContext) async -> HarnessToolResult?)? = nil,
textGenerator: (@Sendable (String) async -> String?)? = nil,
webSearcher: (@Sendable (String) async -> String?)? = nil,
@@ -281,6 +286,7 @@ public struct HarnessBuiltInToolServices: Sendable {
self.appleScriptCompiler = appleScriptCompiler
self.appleScriptExecutor = appleScriptExecutor
self.skillScriptExecutor = skillScriptExecutor
+ self.automationConsentGranted = automationConsentGranted
self.commandExecutor = commandExecutor
self.textGenerator = textGenerator
self.webSearcher = webSearcher
@@ -641,6 +647,28 @@ public enum BuiltInHarnessToolExecutors {
return failed(context, "No guarded script execution backend is configured.", reason: "missingScriptExecutionBackend")
}
+ // Pre-gate: never let Automation (Apple Events) consent fire as a bare system dialog mid-task.
+ // If the target app's automation isn't already granted, raise the in-notch permission gate;
+ // the system prompt only happens after the user approves it (then the loop re-runs this tool).
+ let targetBundleID = trimmed(artifact.metadata["bundleIdentifier"])
+ if let automationConsentGranted = services.automationConsentGranted,
+ await automationConsentGranted(targetBundleID) == false {
+ let appName = trimmed(artifact.metadata["targetApp"]) ?? "this app"
+ return HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: .waitingForPermission,
+ summary: "Needs your approval to control \(appName).",
+ metadata: [
+ "executor": "guardedScriptBackend",
+ "gate": "systemPermission",
+ "system.permission": "automation",
+ "system.target": targetBundleID ?? "",
+ "scriptArtifactID": scriptID
+ ]
+ )
+ }
+
let outcome = await executor(artifact, context)
if outcome.metadata["clarification.required"] == "true" {
let question = trimmed(outcome.metadata["clarification.question"])
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift
index b1db01d2..92cfd170 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift
@@ -176,6 +176,15 @@ public struct AppHarnessGenericLifecycle: Sendable {
return await coordinator.resume(taskID: taskID, reason: reason)
}
+ // System (TCC) permission gate: the user approved in the notch, so NOW trigger the macOS
+ // permission request. Only on a successful grant do we resume the loop to re-run the tool.
+ if continuation.metadata["gate"] == "systemPermission" {
+ guard let permission = Self.systemPermission(from: continuation.metadata) else { return nil }
+ let granted = await SystemPermissionCoordinator.request(permission)
+ guard granted else { return nil }
+ return await coordinator.resume(taskID: taskID, reason: reason)
+ }
+
guard !continuation.missingPermissions.isEmpty else { return nil }
return await coordinator.grantPermissions(
taskID: taskID,
@@ -184,6 +193,22 @@ public struct AppHarnessGenericLifecycle: Sendable {
)
}
+ private static func systemPermission(from metadata: [String: String]) -> SystemPermission? {
+ switch metadata["system.permission"] {
+ case "automation":
+ let target = metadata["system.target"]
+ return .automation(targetBundleID: (target?.isEmpty == false) ? target : nil)
+ case "screenRecording":
+ return .screenRecording
+ case "accessibility":
+ return .accessibility
+ case "microphone":
+ return .microphone
+ default:
+ return nil
+ }
+ }
+
private func loadOrCreateTask(
taskID: String,
threadID: String,
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift
index b007b2f9..b4cffdf7 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift
@@ -39,6 +39,11 @@ public enum LocalAppUserQueryHarnessServices {
skillScriptExecutor: { artifact, context in
await executeSkillScript(artifact: artifact, context: context)
},
+ // Preflight Automation consent (no prompt) so mid-task AppleScript routes through the
+ // in-notch permission gate instead of firing a bare system dialog.
+ automationConsentGranted: { bundleIdentifier in
+ SystemPermissionCoordinator.isGranted(.automation(targetBundleID: bundleIdentifier))
+ },
// The Command Layer (incl. shell_exec) is intentionally available to
// the local planner as well as the Gemini Live session; both go
// through the same DonkeyCommandBackends guardrails.
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift
index 7b69302d..eaecd872 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/DebugUIInspectionRuntime.swift
@@ -662,10 +662,9 @@ public struct DebugUIScreenCaptureService: Sendable {
}
private static func screenCaptureAccessGranted() -> Bool {
- if CGPreflightScreenCaptureAccess() {
- return true
- }
- return CGRequestScreenCaptureAccess()
+ // Preflight only — never prompt here. The system dialog is requested through the in-notch
+ // pre-gate (on user approval); runtime capture just checks and falls back if not granted.
+ CGPreflightScreenCaptureAccess()
}
private func capture(screen: NSScreen) throws -> DebugUIScreenCaptureSnapshot {
diff --git a/apps/Donkey/Sources/DonkeyRuntime/SystemPermission.swift b/apps/Donkey/Sources/DonkeyRuntime/SystemPermission.swift
new file mode 100644
index 00000000..d1ded6d7
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/SystemPermission.swift
@@ -0,0 +1,124 @@
+import ApplicationServices
+import AVFoundation
+import CoreGraphics
+import CoreServices
+import Foundation
+
+/// A macOS system (TCC) permission Donkey may need while running a task.
+public enum SystemPermission: Equatable, Sendable {
+ case screenRecording
+ case microphone
+ case accessibility
+ /// Apple Events to a target app (Automation). `nil` target means System Events.
+ case automation(targetBundleID: String?)
+}
+
+public enum SystemPermissionStatus: String, Sendable {
+ case granted
+ case notDetermined
+ case denied
+}
+
+/// The single place that checks and requests macOS TCC permissions. Everything else preflights
+/// through `status(_:)` (which never prompts) and only calls `request(_:)` after the user has
+/// approved the in-notch pre-gate — so the system dialog never appears without the user's go-ahead.
+public enum SystemPermissionCoordinator {
+ /// A short user-facing label for the pre-gate banner.
+ public static func displayName(_ permission: SystemPermission) -> String {
+ switch permission {
+ case .screenRecording:
+ return "Screen Recording"
+ case .microphone:
+ return "Microphone"
+ case .accessibility:
+ return "Accessibility"
+ case .automation(let bundleID):
+ if let bundleID, !bundleID.isEmpty {
+ return "Automation (\(bundleID))"
+ }
+ return "Automation"
+ }
+ }
+
+ /// Whether the permission is already granted — never prompts.
+ public static func status(_ permission: SystemPermission) -> SystemPermissionStatus {
+ switch permission {
+ case .screenRecording:
+ return CGPreflightScreenCaptureAccess() ? .granted : .notDetermined
+ case .microphone:
+ switch AVCaptureDevice.authorizationStatus(for: .audio) {
+ case .authorized: return .granted
+ case .notDetermined: return .notDetermined
+ case .denied, .restricted: return .denied
+ @unknown default: return .notDetermined
+ }
+ case .accessibility:
+ return AXIsProcessTrusted() ? .granted : .notDetermined
+ case .automation(let bundleID):
+ return automationStatus(targetBundleID: bundleID, askIfNeeded: false)
+ }
+ }
+
+ public static func isGranted(_ permission: SystemPermission) -> Bool {
+ status(permission) == .granted
+ }
+
+ /// Runs a System Events AppleScript ONLY when Automation consent is already granted — it never
+ /// prompts. For internal niceties (e.g. un-minimizing a window before a screenshot) that must
+ /// not raise a bare system dialog mid-task. The user's actual AppleScript tasks gate in the notch.
+ @discardableResult
+ public static func runSystemEventsScriptIfGranted(_ source: String) -> Bool {
+ guard isGranted(.automation(targetBundleID: "com.apple.systemevents")) else { return false }
+ var error: NSDictionary?
+ NSAppleScript(source: source)?.executeAndReturnError(&error)
+ return error == nil
+ }
+
+ /// Triggers the macOS permission dialog (or the grant, for automation) and reports whether it
+ /// ended up granted. Call only after the user approved the pre-gate.
+ @discardableResult
+ public static func request(_ permission: SystemPermission) async -> Bool {
+ switch permission {
+ case .screenRecording:
+ return CGRequestScreenCaptureAccess()
+ case .microphone:
+ return await withCheckedContinuation { continuation in
+ AVCaptureDevice.requestAccess(for: .audio) { granted in
+ continuation.resume(returning: granted)
+ }
+ }
+ case .accessibility:
+ // String value of kAXTrustedCheckOptionPrompt (the global is concurrency-unsafe to touch).
+ let options = ["AXTrustedCheckOptionPrompt": true] as CFDictionary
+ return AXIsProcessTrustedWithOptions(options)
+ case .automation(let bundleID):
+ return automationStatus(targetBundleID: bundleID, askIfNeeded: true) == .granted
+ }
+ }
+
+ // Apple Events / Automation consent for a specific target app.
+ private static func automationStatus(targetBundleID: String?, askIfNeeded: Bool) -> SystemPermissionStatus {
+ let bundleID = (targetBundleID?.isEmpty == false ? targetBundleID! : "com.apple.systemevents")
+ guard let data = bundleID.data(using: .utf8) else { return .notDetermined }
+
+ var addressDesc = AEAddressDesc()
+ let createStatus: OSStatus = data.withUnsafeBytes { raw in
+ OSStatus(AECreateDesc(typeApplicationBundleID, raw.baseAddress, data.count, &addressDesc))
+ }
+ guard createStatus == noErr else { return .notDetermined }
+ defer { AEDisposeDesc(&addressDesc) }
+
+ let result = AEDeterminePermissionToAutomateTarget(&addressDesc, typeWildCard, typeWildCard, askIfNeeded)
+ switch result {
+ case noErr:
+ return .granted
+ case OSStatus(errAEEventNotPermitted):
+ return .denied
+ case OSStatus(errAEEventWouldRequireUserConsent):
+ return .notDetermined
+ default:
+ // procNotFound (target not running) and other transient errors aren't a denial.
+ return .notDetermined
+ }
+ }
+}