Open source CapCut alternative.
TypeScript
Add early Mac permission setup
David Le2af093634026
diff --git a/apps/Donkey/Sources/Donkey/Donkey.swift b/apps/Donkey/Sources/Donkey/Donkey.swiftindex f222889e..85f77ea6 100644--- a/apps/Donkey/Sources/Donkey/Donkey.swift+++ b/apps/Donkey/Sources/Donkey/Donkey.swift@@ -12,19 +12,40 @@ struct Donkey: App {}private struct LocalRuntimeSettingsView: View {+ @State private var permissionSetupController: MacPermissionSetupWindowController?@State private var runtimeSetupController: LocalRuntimeOnboardingWindowController?var body: some View {- VStack(alignment: .leading, spacing: 12) {- Text("Local Runtimes")- .font(.headline)- Text("Reopen setup to install, repair, or recheck Donkey's local model sidecars.")- .foregroundStyle(.secondary)- .fixedSize(horizontal: false, vertical: true)- Button("Set Up Local Runtimes") {- let controller = LocalRuntimeOnboardingWindowController()- runtimeSetupController = controller- controller.showSetup()+ VStack(alignment: .leading, spacing: 22) {+ VStack(alignment: .leading, spacing: 10) {+ Text("Permissions")+ .font(.headline)+ Text("Reopen setup for Accessibility, screenshot, and microphone access.")+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ Button("Open Permissions Setup") {+ let controller = MacPermissionSetupWindowController()+ permissionSetupController = controller+ controller.completed = {+ permissionSetupController = nil+ }+ controller.showSetup()+ }+ }++ Divider()++ VStack(alignment: .leading, spacing: 10) {+ Text("Local Runtimes")+ .font(.headline)+ Text("Reopen setup to install, repair, or recheck Donkey's local model sidecars.")+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ Button("Set Up Local Runtimes") {+ let controller = LocalRuntimeOnboardingWindowController()+ runtimeSetupController = controller+ controller.showSetup()+ }}}.padding(20)diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swiftindex e3f7a004..00f5f27f 100644--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift@@ -7,6 +7,7 @@ import Foundationfinal class DonkeyAppDelegate: NSObject, NSApplicationDelegate {private var authCoordinator: DonkeyAuthCoordinator?private var loginWindowController: DonkeyLoginWindowController?+ private var permissionSetupController: MacPermissionSetupWindowController?private var overlayController: PointerPromptOverlayController?private var runtimeOnboardingController: LocalRuntimeOnboardingWindowController?@@ -48,6 +49,10 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {) -> Bool {if authCoordinator?.isAuthenticated != true {showLoginWindow()+ } else if let permissionSetupController {+ permissionSetupController.showSetup()+ } else if overlayController == nil {+ startAuthenticatedAppSurfaces()}return true}@@ -75,10 +80,31 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {}private func startAuthenticatedAppSurfaces() {- guard overlayController == nil else { return }+ guard overlayController == nil,+ permissionSetupController == nil+ else { return }loginWindowController?.close()loginWindowController = nil+ NSApp.setActivationPolicy(.regular)++ let permissionSetupController = MacPermissionSetupWindowController()+ if permissionSetupController.permissionsAreReady {+ startOverlaySurfaces()+ return+ }++ self.permissionSetupController = permissionSetupController+ permissionSetupController.completed = { [weak self] in+ self?.permissionSetupController = nil+ self?.startOverlaySurfaces()+ }+ permissionSetupController.showSetup()+ }++ private func startOverlaySurfaces() {+ guard overlayController == nil else { return }+NSApp.setActivationPolicy(.accessory)let model = PointerPromptOverlayModel()diff --git a/apps/Donkey/Sources/Donkey/MacPermissionSetupWindowController.swift b/apps/Donkey/Sources/Donkey/MacPermissionSetupWindowController.swiftnew file mode 100644index 00000000..1b7f858b--- /dev/null+++ b/apps/Donkey/Sources/Donkey/MacPermissionSetupWindowController.swift@@ -0,0 +1,386 @@+@preconcurrency import ApplicationServices+import AppKit+import AVFoundation+import CoreGraphics+import DonkeyRuntime+import SwiftUI++@MainActor+final class MacPermissionSetupWindowController: NSWindowController {+ var completed: (() -> Void)?++ private let model: MacPermissionSetupModel++ init(model: MacPermissionSetupModel = MacPermissionSetupModel()) {+ self.model = model+ let view = MacPermissionSetupView(model: model)+ let hostingController = NSHostingController(rootView: view)+ let window = NSWindow(contentViewController: hostingController)+ window.title = "Enable Donkey Permissions"+ window.styleMask = [.titled, .closable, .miniaturizable]+ window.setContentSize(NSSize(width: 640, height: 560))+ window.isReleasedWhenClosed = false+ super.init(window: window)++ model.completed = { [weak self] in+ self?.close()+ self?.completed?()+ }+ }++ required init?(coder: NSCoder) {+ nil+ }++ var permissionsAreReady: Bool {+ model.refresh()+ return model.canContinue+ }++ func showSetup() {+ model.refresh()+ showWindow(nil)+ window?.center()+ window?.makeKeyAndOrderFront(nil)+ NSApp.activate(ignoringOtherApps: true)+ }+}++@MainActor+final class MacPermissionSetupModel: ObservableObject {+ @Published private(set) var statuses: [MacPermissionKind: MacPermissionAuthorizationStatus] = [:]+ @Published private(set) var requestedKinds: Set<MacPermissionKind> = []+ @Published private(set) var requestingKind: MacPermissionKind?++ var completed: (() -> Void)?++ private let requester: any MacPermissionRequesting+ private let defaults: UserDefaults+ private let requestedDefaultsKey = "MacPermissionSetup.RequestedKinds"++ init(+ requester: any MacPermissionRequesting = SystemMacPermissionRequester(),+ defaults: UserDefaults = .standard+ ) {+ self.requester = requester+ self.defaults = defaults+ requestedKinds = Self.loadRequestedKinds(+ defaults: defaults,+ key: requestedDefaultsKey+ )+ refresh()+ }++ var rows: [MacPermissionRowState] {+ MacPermissionSetupStateResolver(requestedKinds: requestedKinds)+ .rows(statuses: statuses)+ }++ var canContinue: Bool {+ MacPermissionSetupStateResolver(requestedKinds: requestedKinds)+ .allRequiredPermissionsGranted(statuses: statuses)+ }++ func refresh() {+ statuses = Dictionary(+ uniqueKeysWithValues: MacPermissionKind.coreSetup.map { kind in+ (kind, requester.status(for: kind))+ }+ )+ }++ func request(_ kind: MacPermissionKind) async {+ guard requestingKind == nil else { return }++ requestingKind = kind+ rememberRequested(kind)+ let status = await requester.request(kind)+ statuses[kind] = status+ refresh()+ requestingKind = nil+ }++ func openSystemSettings(for kind: MacPermissionKind) {+ requester.openSystemSettings(for: kind)+ }++ func continueIfReady() {+ refresh()+ guard canContinue else { return }+ completed?()+ }++ #if DEBUG+ func skipForNow() {+ completed?()+ }+ #endif++ private func rememberRequested(_ kind: MacPermissionKind) {+ requestedKinds.insert(kind)+ defaults.set(+ requestedKinds.map(\.rawValue).sorted(),+ forKey: requestedDefaultsKey+ )+ }++ private static func loadRequestedKinds(+ defaults: UserDefaults,+ key: String+ ) -> Set<MacPermissionKind> {+ Set(+ defaults.stringArray(forKey: key)?+ .compactMap(MacPermissionKind.init(rawValue:)) ?? []+ )+ }+}++@MainActor+protocol MacPermissionRequesting {+ func status(for kind: MacPermissionKind) -> MacPermissionAuthorizationStatus+ func request(_ kind: MacPermissionKind) async -> MacPermissionAuthorizationStatus+ func openSystemSettings(for kind: MacPermissionKind)+}++@MainActor+final class SystemMacPermissionRequester: MacPermissionRequesting {+ func status(for kind: MacPermissionKind) -> MacPermissionAuthorizationStatus {+ switch kind {+ case .accessibility:+ return AXIsProcessTrusted() ? .granted : .notDetermined+ 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 .denied+ }+ }+ }++ func request(_ kind: MacPermissionKind) async -> MacPermissionAuthorizationStatus {+ switch kind {+ case .accessibility:+ let options = [+ kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true+ ] as CFDictionary+ _ = AXIsProcessTrustedWithOptions(options)+ return status(for: kind)+ case .screenRecording:+ _ = CGRequestScreenCaptureAccess()+ return status(for: kind)+ case .microphone:+ let granted = await withCheckedContinuation { continuation in+ AVCaptureDevice.requestAccess(for: .audio) { isGranted in+ continuation.resume(returning: isGranted)+ }+ }+ return granted ? .granted : status(for: kind)+ }+ }++ func openSystemSettings(for kind: MacPermissionKind) {+ guard let url = URL(string: settingsURLString(for: kind)) else { return }+ NSWorkspace.shared.open(url)+ }++ private func settingsURLString(for kind: MacPermissionKind) -> String {+ switch kind {+ case .accessibility:+ return "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"+ case .screenRecording:+ return "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"+ case .microphone:+ return "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone"+ }+ }+}++private struct MacPermissionSetupView: View {+ @ObservedObject var model: MacPermissionSetupModel++ var body: some View {+ VStack(alignment: .leading, spacing: 22) {+ VStack(alignment: .leading, spacing: 10) {+ Text("Enable Donkey Permissions")+ .font(.system(size: 30, weight: .semibold))+ Text("Donkey needs these Mac permissions before it can reliably understand windows, use voice input, and act on approved local-app workflows.")+ .foregroundStyle(.secondary)+ .font(.callout)+ .fixedSize(horizontal: false, vertical: true)+ }++ VStack(spacing: 12) {+ ForEach(model.rows) { row in+ MacPermissionRowView(+ row: row,+ isRequesting: model.requestingKind == row.kind,+ enable: {+ Task { await model.request(row.kind) }+ },+ openSettings: {+ model.openSystemSettings(for: row.kind)+ }+ )+ }+ }++ HStack(alignment: .top, spacing: 10) {+ Image(systemName: "lock.shield")+ .foregroundStyle(.secondary)+ Text("Donkey uses these permissions only for user-requested tasks and guarded local-app workflows.")+ .font(.footnote)+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }++ Spacer(minLength: 0)++ HStack(spacing: 12) {+ #if DEBUG+ Button("Skip for now") {+ model.skipForNow()+ }+ .controlSize(.large)+ #endif++ Spacer()++ Button("Continue") {+ model.continueIfReady()+ }+ .keyboardShortcut(.defaultAction)+ .controlSize(.large)+ .disabled(!model.canContinue)+ }+ }+ .padding(28)+ .frame(minWidth: 640, minHeight: 560)+ .onAppear {+ model.refresh()+ }+ .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in+ model.refresh()+ }+ }+}++private struct MacPermissionRowView: View {+ var row: MacPermissionRowState+ var isRequesting: Bool+ var enable: () -> Void+ var openSettings: () -> Void++ var body: some View {+ HStack(alignment: .top, spacing: 14) {+ ZStack {+ RoundedRectangle(cornerRadius: 8)+ .fill(iconBackgroundColor)+ Image(systemName: iconName)+ .font(.system(size: 18, weight: .semibold))+ .foregroundStyle(iconColor)+ }+ .frame(width: 42, height: 42)++ VStack(alignment: .leading, spacing: 6) {+ HStack(spacing: 8) {+ Text(row.kind.title)+ .font(.headline)+ Text(statusText)+ .font(.caption.weight(.semibold))+ .foregroundStyle(statusColor)+ .padding(.horizontal, 8)+ .padding(.vertical, 3)+ .background(statusColor.opacity(0.12), in: Capsule())+ }+ Text(row.kind.reason)+ .font(.callout)+ .foregroundStyle(.primary)+ .fixedSize(horizontal: false, vertical: true)+ Text(row.kind.detail)+ .font(.footnote)+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }++ Spacer(minLength: 12)++ Button(actionTitle) {+ switch row.action {+ case .enable:+ enable()+ case .openSystemSettings:+ openSettings()+ case .ready:+ break+ }+ }+ .controlSize(.large)+ .disabled(row.action == .ready || isRequesting)+ }+ .padding(16)+ .background(Color(nsColor: .controlBackgroundColor), in: RoundedRectangle(cornerRadius: 8))+ }++ private var iconName: String {+ switch row.kind {+ case .accessibility:+ return "hand.raised"+ case .screenRecording:+ return "rectangle.on.rectangle"+ case .microphone:+ return "mic"+ }+ }++ private var iconBackgroundColor: Color {+ row.status == .granted ? Color.green.opacity(0.14) : Color.accentColor.opacity(0.14)+ }++ private var iconColor: Color {+ row.status == .granted ? .green : .accentColor+ }++ private var statusText: String {+ switch row.status {+ case .granted:+ return "Ready"+ case .notDetermined:+ return "Needed"+ case .denied:+ return "Needs Settings"+ }+ }++ private var statusColor: Color {+ switch row.status {+ case .granted:+ return .green+ case .notDetermined:+ return .orange+ case .denied:+ return .red+ }+ }++ private var actionTitle: String {+ if isRequesting {+ return "Checking..."+ }++ switch row.action {+ case .enable:+ return "Enable"+ case .ready:+ return "Ready"+ case .openSystemSettings:+ return "Open System Settings"+ }+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacPermissionSetupState.swift b/apps/Donkey/Sources/DonkeyRuntime/MacPermissionSetupState.swiftnew file mode 100644index 00000000..0ec7c0fc--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/MacPermissionSetupState.swift@@ -0,0 +1,130 @@+import Foundation++public enum MacPermissionKind: String, CaseIterable, Codable, Equatable, Hashable, Identifiable, Sendable {+ case accessibility+ case screenRecording+ case microphone++ public var id: String {+ rawValue+ }++ public static let coreSetup: [MacPermissionKind] = [+ .accessibility,+ .screenRecording,+ .microphone+ ]++ public var title: String {+ switch self {+ case .accessibility:+ return "Accessibility"+ case .screenRecording:+ return "Screenshots"+ case .microphone:+ return "Microphone"+ }+ }++ public var reason: String {+ switch self {+ case .accessibility:+ return "Lets Donkey read app controls and perform approved UI actions."+ case .screenRecording:+ return "Lets Donkey capture bounded screenshots of the target window when app structure is missing."+ case .microphone:+ return "Lets you use voice input when you choose voice mode."+ }+ }++ public var detail: String {+ switch self {+ case .accessibility:+ return "Used only after a user-requested local-app workflow passes Donkey's safety checks."+ case .screenRecording:+ return "macOS calls this Screen & System Audio Recording; Donkey captures screenshots with audio disabled."+ case .microphone:+ return "Donkey does not record continuously."+ }+ }+}++public enum MacPermissionAuthorizationStatus: String, Codable, Equatable, Sendable {+ case granted+ case notDetermined+ case denied+}++public enum MacPermissionRowAction: String, Codable, Equatable, Sendable {+ case enable+ case ready+ case openSystemSettings+}++public struct MacPermissionRowState: Codable, Equatable, Identifiable, Sendable {+ public var kind: MacPermissionKind+ public var status: MacPermissionAuthorizationStatus+ public var action: MacPermissionRowAction++ public var id: MacPermissionKind {+ kind+ }++ public init(+ kind: MacPermissionKind,+ status: MacPermissionAuthorizationStatus,+ action: MacPermissionRowAction+ ) {+ self.kind = kind+ self.status = status+ self.action = action+ }+}++public struct MacPermissionSetupStateResolver: Sendable {+ public var requestedKinds: Set<MacPermissionKind>++ public init(requestedKinds: Set<MacPermissionKind> = []) {+ self.requestedKinds = requestedKinds+ }++ public func rows(+ statuses: [MacPermissionKind: MacPermissionAuthorizationStatus],+ requiredKinds: [MacPermissionKind] = MacPermissionKind.coreSetup+ ) -> [MacPermissionRowState] {+ requiredKinds.map { kind in+ row(+ kind: kind,+ status: statuses[kind] ?? .notDetermined+ )+ }+ }++ public func row(+ kind: MacPermissionKind,+ status: MacPermissionAuthorizationStatus+ ) -> MacPermissionRowState {+ let action: MacPermissionRowAction+ switch status {+ case .granted:+ action = .ready+ case .notDetermined:+ action = requestedKinds.contains(kind) ? .openSystemSettings : .enable+ case .denied:+ action = .openSystemSettings+ }++ return MacPermissionRowState(+ kind: kind,+ status: status,+ action: action+ )+ }++ public func allRequiredPermissionsGranted(+ statuses: [MacPermissionKind: MacPermissionAuthorizationStatus],+ requiredKinds: [MacPermissionKind] = MacPermissionKind.coreSetup+ ) -> Bool {+ requiredKinds.allSatisfy { statuses[$0] == .granted }+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/SQLiteAgentMemoryStore.swift b/apps/Donkey/Sources/DonkeyRuntime/SQLiteAgentMemoryStore.swiftindex b6390c6f..bef9fab8 100644--- a/apps/Donkey/Sources/DonkeyRuntime/SQLiteAgentMemoryStore.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/SQLiteAgentMemoryStore.swift@@ -68,20 +68,16 @@ public struct AgentMemoryPrewarmOptions: Sendable {}public static func defaults() -> AgentMemoryPrewarmOptions {- let homeDirectory = FileManager.default.homeDirectoryForCurrentUserreturn AgentMemoryPrewarmOptions(applicationRoots: [URL(fileURLWithPath: "/Applications", isDirectory: true),URL(fileURLWithPath: "/Applications/Utilities", isDirectory: true),URL(fileURLWithPath: "/System/Applications", isDirectory: true),URL(fileURLWithPath: "/System/Applications/Utilities", isDirectory: true),- homeDirectory.appendingPathComponent("Applications", isDirectory: true)+ FileManager.default.homeDirectoryForCurrentUser+ .appendingPathComponent("Applications", isDirectory: true)],- fileRoots: [- homeDirectory.appendingPathComponent("Desktop", isDirectory: true),- homeDirectory.appendingPathComponent("Documents", isDirectory: true),- homeDirectory.appendingPathComponent("Downloads", isDirectory: true)- ]+ fileRoots: [])}}diff --git a/apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swift b/apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swiftindex 80991405..e53a71c5 100644--- a/apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swift@@ -429,7 +429,13 @@ public struct ContinuousTargetWindowFrameSource: DryRunStreamingFrameSource {}}-private final class ScreenCaptureKitTargetWindowFrameCapturer: TargetWindowFrameCapturing {+final class ScreenCaptureKitTargetWindowFrameCapturer: TargetWindowFrameCapturing {+ private let permissionChecker: any ScreenRecordingPermissionChecking++ init(permissionChecker: any ScreenRecordingPermissionChecking = CoreGraphicsScreenRecordingPermissionChecker()) {+ self.permissionChecker = permissionChecker+ }+var captureMethod: WindowScreenshotCaptureMethod {.screenCaptureKitDesktopIndependentWindow}@@ -441,6 +447,10 @@ private final class ScreenCaptureKitTargetWindowFrameCapturer: TargetWindowFramefunc captureFrame(target: MacWindowTargetCandidate) async throws -> CapturedTargetWindowFrame {+ guard permissionChecker.hasScreenRecordingAccess() else {+ throw WindowScreenshotCaptureError.screenRecordingPermissionDenied+ }+let content = try await SCShareableContent.currentguard let window = content.windows.first(where: { $0.windowID == target.windowID }) else {throw WindowScreenshotCaptureError.targetWindowUnavailable(windowID: target.windowID)diff --git a/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swiftindex a1936417..2db7a606 100644--- a/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift@@ -26,6 +26,7 @@ public enum WindowScreenshotCaptureError: Error, Equatable, Sendable {windowID: UInt32,occludingWindowID: UInt32)+ case screenRecordingPermissionDeniedcase targetWindowUnavailable(windowID: UInt32)case captureFailed(windowID: UInt32, reason: String)case pngEncodingFailed(windowID: UInt32)@@ -87,6 +88,16 @@ protocol WindowScreenshotCapturing {) async throws -> CapturedWindowScreenshot}+protocol ScreenRecordingPermissionChecking: Sendable {+ func hasScreenRecordingAccess() -> Bool+}++struct CoreGraphicsScreenRecordingPermissionChecker: ScreenRecordingPermissionChecking {+ func hasScreenRecordingAccess() -> Bool {+ CGPreflightScreenCaptureAccess()+ }+}+public final class WindowScreenshotCaptureService {private let artifactStore: LocalRunArtifactStoreprivate let windowResolver: MacWindowResolver@@ -283,6 +294,12 @@ public final class WindowScreenshotCaptureService {}final class ScreenCaptureKitWindowScreenshotCapturer: WindowScreenshotCapturing {+ private let permissionChecker: any ScreenRecordingPermissionChecking++ init(permissionChecker: any ScreenRecordingPermissionChecking = CoreGraphicsScreenRecordingPermissionChecker()) {+ self.permissionChecker = permissionChecker+ }+var captureMethod: WindowScreenshotCaptureMethod {.screenCaptureKitDesktopIndependentWindow}@@ -294,6 +311,10 @@ final class ScreenCaptureKitWindowScreenshotCapturer: WindowScreenshotCapturingfunc capture(target: MacWindowTargetCandidate) async throws -> CapturedWindowScreenshot {+ guard permissionChecker.hasScreenRecordingAccess() else {+ throw WindowScreenshotCaptureError.screenRecordingPermissionDenied+ }+let content = try await SCShareableContent.currentguard let window = content.windows.first(where: { $0.windowID == target.windowID }) else {throw WindowScreenshotCaptureError.targetWindowUnavailable(windowID: target.windowID)diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AgentMemoryStoreTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AgentMemoryStoreTests.swiftindex e0a9eae9..465e61db 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AgentMemoryStoreTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AgentMemoryStoreTests.swift@@ -97,6 +97,13 @@ struct AgentMemoryStoreTests {#expect(result.record.metadata["agentMemory.local.source"] == "prewarm")}+ @Test+ func defaultPrewarmOptionsDoNotScanProtectedUserFolders() {+ let options = AgentMemoryPrewarmOptions.defaults()++ #expect(options.fileRoots.isEmpty)+ }+@Testfunc storePrewarmsTaskDefinitionsAsSearchableCapabilities() throws {let root = temporaryDirectory()diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MacPermissionSetupStateTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MacPermissionSetupStateTests.swiftnew file mode 100644index 00000000..487eacb8--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MacPermissionSetupStateTests.swift@@ -0,0 +1,49 @@+@testable import DonkeyRuntime+import Testing++@Suite+struct MacPermissionSetupStateTests {+ @Test+ func unresolvedPermissionStartsWithEnableAction() {+ let resolver = MacPermissionSetupStateResolver()++ let row = resolver.row(kind: .accessibility, status: .notDetermined)++ #expect(row.action == .enable)+ #expect(row.status == .notDetermined)+ }++ @Test+ func requestedUnresolvedPermissionOpensSystemSettings() {+ let resolver = MacPermissionSetupStateResolver(requestedKinds: [.screenRecording])++ let row = resolver.row(kind: .screenRecording, status: .notDetermined)++ #expect(row.action == .openSystemSettings)+ }++ @Test+ func deniedPermissionOpensSystemSettings() {+ let resolver = MacPermissionSetupStateResolver()++ let row = resolver.row(kind: .microphone, status: .denied)++ #expect(row.action == .openSystemSettings)+ }++ @Test+ func allCorePermissionsMustBeGrantedBeforeContinue() {+ let resolver = MacPermissionSetupStateResolver()++ #expect(resolver.allRequiredPermissionsGranted(statuses: [+ .accessibility: .granted,+ .screenRecording: .granted,+ .microphone: .granted+ ]))+ #expect(!resolver.allRequiredPermissionsGranted(statuses: [+ .accessibility: .granted,+ .screenRecording: .notDetermined,+ .microphone: .granted+ ]))+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/TargetWindowFrameSourceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/TargetWindowFrameSourceTests.swiftindex c698c6ec..6d7940ac 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/TargetWindowFrameSourceTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/TargetWindowFrameSourceTests.swift@@ -52,6 +52,21 @@ struct TargetWindowFrameSourceTests {#expect(result.frames.first?.metadata["capture.copyCostMS"] == "2.0")}+ @Test+ func screenCaptureKitFrameCapturerFailsFastWhenScreenRecordingPermissionIsDenied() async throws {+ let capturer = ScreenCaptureKitTargetWindowFrameCapturer(+ permissionChecker: FakeScreenRecordingPermissionChecker(hasAccess: false)+ )++ do {+ _ = try await capturer.captureFrame(target: allowedTargetWindow())+ Issue.record("Expected screen recording permission denial")+ } catch WindowScreenshotCaptureError.screenRecordingPermissionDenied {+ } catch {+ Issue.record("Unexpected error: \(error)")+ }+ }+@Testfunc captureFramesAppliesOptionalCropWithoutWritingPlannerSnapshotArtifact() async throws {let service = makeService(@@ -305,6 +320,34 @@ struct TargetWindowFrameSourceTests {bounds: bounds)}++ private func allowedTargetWindow(+ windowID: UInt32 = 10,+ processID: Int32 = 100+ ) -> MacWindowTargetCandidate {+ MacWindowTargetCandidate(+ windowID: windowID,+ processID: processID,+ bounds: WindowTargetBounds(x: 0, y: 0, width: 100, height: 100),+ isVisible: true,+ isOnScreen: true,+ isFrontmost: true,+ isFocused: true,+ isIPhoneMirroring: false,+ safetyAssessment: WindowTargetSafetyAssessment(+ status: .allowed,+ summary: "Allowed fixture window"+ )+ )+ }+}++private struct FakeScreenRecordingPermissionChecker: ScreenRecordingPermissionChecking {+ var hasAccess: Bool++ func hasScreenRecordingAccess() -> Bool {+ hasAccess+ }}private final class FakeTargetWindowFrameCapturer: TargetWindowFrameCapturing, @unchecked Sendable {diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/WindowScreenshotCaptureServiceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/WindowScreenshotCaptureServiceTests.swiftindex 668a6744..d23f18dc 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/WindowScreenshotCaptureServiceTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/WindowScreenshotCaptureServiceTests.swift@@ -66,6 +66,21 @@ struct WindowScreenshotCaptureServiceTests {#expect(summary.artifacts.first?.metadata["capture.overlapStatus"] == "notRequired")}+ @Test+ func screenCaptureKitCapturerFailsFastWhenScreenRecordingPermissionIsDenied() async throws {+ let capturer = ScreenCaptureKitWindowScreenshotCapturer(+ permissionChecker: FakeScreenRecordingPermissionChecker(hasAccess: false)+ )++ do {+ _ = try await capturer.capture(target: allowedTargetWindow())+ Issue.record("Expected screen recording permission denial")+ } catch WindowScreenshotCaptureError.screenRecordingPermissionDenied {+ } catch {+ Issue.record("Unexpected error: \(error)")+ }+ }+@Testfunc explicitWindowSelectionIsPassedToCapturer() async throws {let root = temporaryDirectory()@@ -417,6 +432,34 @@ struct WindowScreenshotCaptureServiceTests {private func pngBytes() -> Data {Data([0x89, 0x50, 0x4E, 0x47])}++ private func allowedTargetWindow(+ windowID: UInt32 = 10,+ processID: Int32 = 100+ ) -> MacWindowTargetCandidate {+ MacWindowTargetCandidate(+ windowID: windowID,+ processID: processID,+ bounds: WindowTargetBounds(x: 0, y: 0, width: 100, height: 100),+ isVisible: true,+ isOnScreen: true,+ isFrontmost: true,+ isFocused: true,+ isIPhoneMirroring: false,+ safetyAssessment: WindowTargetSafetyAssessment(+ status: .allowed,+ summary: "Allowed fixture window"+ )+ )+ }+}++private struct FakeScreenRecordingPermissionChecker: ScreenRecordingPermissionChecking {+ var hasAccess: Bool++ func hasScreenRecordingAccess() -> Bool {+ hasAccess+ }}private final class FakeWindowScreenshotCapturer: WindowScreenshotCapturing {diff --git a/docs/guides/install-donkey.md b/docs/guides/install-donkey.mdindex 2bc97eaf..d2e2c378 100644--- a/docs/guides/install-donkey.md+++ b/docs/guides/install-donkey.md@@ -106,9 +106,12 @@ selection. The Mac client sends typed requests to the backend and does not needOpenAI, Gemini, or other provider API keys.First launch setup is therefore an account and permission setup flow, not a-local model installer. There are no supported release manifest URLs, model-weight override URLs, local LLM packages, or local model repair steps in the-hosted-model install path.+local model installer. After sign-in, Donkey asks for Accessibility,+Screenshots, and Microphone with user-visible reasons before starting the+overlay. Protected folders such as Desktop, Documents, and Downloads remain+lazy and are requested only when a user-requested local-item lookup needs them.+There are no supported release manifest URLs, model weight override URLs, local+LLM packages, or local model repair steps in the hosted-model install path.## Local Developmentdiff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.mdindex 58994c48..e66e5d91 100644--- a/docs/guides/pointer-prompt-overlay.md+++ b/docs/guides/pointer-prompt-overlay.md@@ -6,10 +6,12 @@ Donkey supports a floating macOS overlay for conversational task threads andquick local-app actions:- On first launch, Donkey shows a native welcome screen, then a Google-only Mac- sign-in screen before starting the overlay. Until the browser returns through- the `donkey://auth/callback` handoff and the app exchanges the returned code- for a Better Auth cookie, the notch surface is not shown and double-Command- activation is not registered.+ sign-in screen, then a native permission setup screen for Accessibility,+ Screenshots, and Microphone before starting the overlay. Until the browser+ returns through the `donkey://auth/callback` handoff, the app exchanges the+ returned code for a Better Auth cookie, and the core permission setup is+ complete, the notch surface is not shown and double-Command activation is not+ registered.- Double-tap Command and release to open a centered prompt with keyboard focus.- Double-tap Command and hold the second press to open the prompt in voice mode.- Show a top-center notch status surface for task progress, recent tasks, follow-up input, file drops, updates, and per-task pause/resume.@@ -22,17 +24,19 @@ quick local-app actions:- Resolve model-classified local-item requests against local apps, files, and folders by querying the current Mac with the SQLite-backed agent memory store, Spotlight/`mdfind`, and bounded filesystem fallback. If the requested local item cannot be found, keep the task safe and report that it was not found instead of falling back to a vague clarification.- Handle scriptable app tasks as guarded AppleScript automation when possible. Commands may use task metadata, generated source, or compact templates; completion is verified through generic task verification policy instead of requiring visible result text for every app.- Visualize agent work with a transparent overlay cursor. Normal local-app tasks emit a projected `AgentVisualizationPlan` once the workflow is resolved, then a verified plan from runtime evidence such as dry-run steps, observations, and action traces; visual-only demonstration turns use the same plan shape without live input. Donkey moves the overlay cursor along curved paths and types compact labels next to it while keeping the real mouse untouched.-- Maintain a background agent memory store in Application Support. The store records resolved and missing local-item lookups, prewarms apps plus common user file folders, stores runtime task definitions, keeps metadata such as kind/path/bundle ID/source/task/action, indexes records with SQLite FTS5 plus local vectors, and passes a bounded set of matching hints into the agent harness memory section for classifier and model consideration. See `docs/guides/decision-system.md` for how those hints feed typed model decisions and guarded local-app plans.+- Maintain a background agent memory store in Application Support. The store records resolved and missing local-item lookups, prewarms apps, stores runtime task definitions, keeps metadata such as kind/path/bundle ID/source/task/action, indexes records with SQLite FTS5 plus local vectors, and passes a bounded set of matching hints into the agent harness memory section for classifier and model consideration. Protected file folders such as Desktop, Documents, and Downloads stay lazy and are searched only when a user-requested local-item lookup needs them. See `docs/guides/decision-system.md` for how those hints feed typed model decisions and guarded local-app plans.- Persist task threads as searchable Core Data conversations with event history, task assets, and per-run runtime coordination for any action work attached to the thread.-- Keep the overlay non-invasive. It may request microphone permission for local waveform capture and voice commands, but it must not capture the screen, synthesize input directly, or require Accessibility permission.+- Keep the overlay non-invasive. Permission setup requests Accessibility, screenshot, and microphone access with user-visible reasons, but the overlay itself does not capture the screen or synthesize input directly. Bounded screenshots and Accessibility reads are used only by guarded local-app workflows.## Technical Guidelines- `PointerPromptOverlayController` owns AppKit surfaces, placement, hover tracking, focus, keyboard shortcut recognition, dismissal, file-drop routing, and microphone level capture.- `DonkeyAuthCoordinator` and `DonkeyLoginWindowController` own the Mac sign-in+ gate. `MacPermissionSetupWindowController` owns the post-auth core permissiongate. App startup should create the overlay controller only after a storedGoogle session exists or a pending sign-in callback validates its state token- and stores a Better Auth cookie in the app cookie jar.+ and stores a Better Auth cookie in the app cookie jar, and the permission+ setup has completed.- SwiftUI rendering lives in `DonkeyUI` and consumes state/contracts from `DonkeyContracts`. It should not perform command parsing, model calls, input execution, screen capture, or microphone capture.- `PointerPromptOverlayModel` owns product state. Durable task data is persisted through Core Data in Application Support.- Spawn display state is typed state. The model emits progress, target hints, and current selection; the overlay controller resolves hints against safe visible windows and keeps voice capture on the centered prompt; SwiftUI renders the notch cue, cursors, labels, label-to-editor transition, and selection state.diff --git a/scripts/package-donkey-app.sh b/scripts/package-donkey-app.shindex f968828b..afa8d92a 100755--- a/scripts/package-donkey-app.sh+++ b/scripts/package-donkey-app.sh@@ -261,6 +261,12 @@ cat > "$CONTENTS_DIR/Info.plist" <<PLIST<string>Donkey captures bounded screenshots for user-requested app context.</string><key>NSAppleEventsUsageDescription</key><string>Donkey uses local app automation only for user-requested actions.</string>+ <key>NSDesktopFolderUsageDescription</key>+ <string>Donkey may search Desktop files only when you ask it to find or open a local item.</string>+ <key>NSDocumentsFolderUsageDescription</key>+ <string>Donkey may search Documents files only when you ask it to find or open a local item.</string>+ <key>NSDownloadsFolderUsageDescription</key>+ <string>Donkey may search Downloads files only when you ask it to find or open a local item.</string>$SPARKLE_PLIST_KEYS</dict></plist>diff --git a/scripts/run-donkey-dev.sh b/scripts/run-donkey-dev.shindex 913ad0f6..5ac45470 100755--- a/scripts/run-donkey-dev.sh+++ b/scripts/run-donkey-dev.sh@@ -233,6 +233,12 @@ write_info_plist() {<string>Donkey captures bounded screenshots for user-requested app context.</string><key>NSAppleEventsUsageDescription</key><string>Donkey uses local app automation only for user-requested actions.</string>+ <key>NSDesktopFolderUsageDescription</key>+ <string>Donkey may search Desktop files only when you ask it to find or open a local item.</string>+ <key>NSDocumentsFolderUsageDescription</key>+ <string>Donkey may search Documents files only when you ask it to find or open a local item.</string>+ <key>NSDownloadsFolderUsageDescription</key>+ <string>Donkey may search Downloads files only when you ask it to find or open a local item.</string></dict></plist>PLIST