Skip to content

Open source CapCut alternative.

TypeScript

Wire manual capture events through RunCoordinator

David Le0c0188aff3f9
diff --git a/apps/Donkey/Sources/DonkeyContracts/AccessibilitySnapshotContracts.swift b/apps/Donkey/Sources/DonkeyContracts/AccessibilitySnapshotContracts.swift
new file mode 100644
index 00000000..1c9e076f
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyContracts/AccessibilitySnapshotContracts.swift
@@ -0,0 +1,240 @@
+import Foundation
+
+public enum MacAccessibilityTrustStatus: String, Codable, Equatable, Sendable {
+ case trusted
+ case notTrusted
+}
+
+public struct MacAccessibilitySnapshotLimits: Codable, Equatable, Sendable {
+ public var maxDepth: Int
+ public var maxChildrenPerNode: Int
+ public var maxTotalNodes: Int
+ public var maxTextLength: Int
+
+ public init(
+ maxDepth: Int = 2,
+ maxChildrenPerNode: Int = 25,
+ maxTotalNodes: Int = 100,
+ maxTextLength: Int = 80
+ ) {
+ self.maxDepth = max(0, maxDepth)
+ self.maxChildrenPerNode = max(0, maxChildrenPerNode)
+ self.maxTotalNodes = max(1, maxTotalNodes)
+ self.maxTextLength = max(1, maxTextLength)
+ }
+
+ public static let `default` = MacAccessibilitySnapshotLimits()
+}
+
+public struct MacAccessibilitySnapshotNode: Codable, Equatable, Sendable {
+ public var nodeID: String
+ public var role: String?
+ public var title: String?
+ public var label: String?
+ public var valueSummary: String?
+ public var frame: WindowTargetBounds?
+ public var isEnabled: Bool?
+ public var isFocused: Bool?
+ public var actions: [String]
+ public var children: [MacAccessibilitySnapshotNode]
+ public var isChildrenTruncated: Bool
+
+ public init(
+ nodeID: String,
+ role: String? = nil,
+ title: String? = nil,
+ label: String? = nil,
+ valueSummary: String? = nil,
+ frame: WindowTargetBounds? = nil,
+ isEnabled: Bool? = nil,
+ isFocused: Bool? = nil,
+ actions: [String] = [],
+ children: [MacAccessibilitySnapshotNode] = [],
+ isChildrenTruncated: Bool = false
+ ) {
+ self.nodeID = nodeID
+ self.role = role
+ self.title = title
+ self.label = label
+ self.valueSummary = valueSummary
+ self.frame = frame
+ self.isEnabled = isEnabled
+ self.isFocused = isFocused
+ self.actions = actions
+ self.children = children
+ self.isChildrenTruncated = isChildrenTruncated
+ }
+}
+
+public struct RawMacAccessibilitySnapshotNode: Codable, Equatable, Sendable {
+ public var role: String?
+ public var title: String?
+ public var label: String?
+ public var valueSummary: String?
+ public var frame: WindowTargetBounds?
+ public var isEnabled: Bool?
+ public var isFocused: Bool?
+ public var actions: [String]
+ public var children: [RawMacAccessibilitySnapshotNode]
+
+ public init(
+ role: String? = nil,
+ title: String? = nil,
+ label: String? = nil,
+ valueSummary: String? = nil,
+ frame: WindowTargetBounds? = nil,
+ isEnabled: Bool? = nil,
+ isFocused: Bool? = nil,
+ actions: [String] = [],
+ children: [RawMacAccessibilitySnapshotNode] = []
+ ) {
+ self.role = role
+ self.title = title
+ self.label = label
+ self.valueSummary = valueSummary
+ self.frame = frame
+ self.isEnabled = isEnabled
+ self.isFocused = isFocused
+ self.actions = actions
+ self.children = children
+ }
+}
+
+public struct MacAccessibilitySnapshotTree: Codable, Equatable, Sendable {
+ public var root: MacAccessibilitySnapshotNode
+ public var totalNodeCount: Int
+ public var isTreeTruncated: Bool
+
+ public init(
+ root: MacAccessibilitySnapshotNode,
+ totalNodeCount: Int,
+ isTreeTruncated: Bool
+ ) {
+ self.root = root
+ self.totalNodeCount = totalNodeCount
+ self.isTreeTruncated = isTreeTruncated
+ }
+}
+
+public enum MacAccessibilitySnapshotTreeBuilder {
+ public static func build(
+ root: RawMacAccessibilitySnapshotNode,
+ limits: MacAccessibilitySnapshotLimits
+ ) -> MacAccessibilitySnapshotTree {
+ var emittedNodeCount = 0
+ var isTreeTruncated = false
+ let rootNode = buildNode(
+ root,
+ path: "ax-1",
+ depth: 0,
+ limits: limits,
+ emittedNodeCount: &emittedNodeCount,
+ isTreeTruncated: &isTreeTruncated
+ ) ?? MacAccessibilitySnapshotNode(nodeID: "ax-1")
+
+ return MacAccessibilitySnapshotTree(
+ root: rootNode,
+ totalNodeCount: emittedNodeCount,
+ isTreeTruncated: isTreeTruncated
+ )
+ }
+
+ private static func buildNode(
+ _ rawNode: RawMacAccessibilitySnapshotNode,
+ path: String,
+ depth: Int,
+ limits: MacAccessibilitySnapshotLimits,
+ emittedNodeCount: inout Int,
+ isTreeTruncated: inout Bool
+ ) -> MacAccessibilitySnapshotNode? {
+ guard emittedNodeCount < limits.maxTotalNodes else {
+ isTreeTruncated = true
+ return nil
+ }
+
+ emittedNodeCount += 1
+ let canReadChildren = depth < limits.maxDepth
+ let allowedChildCount = canReadChildren
+ ? min(rawNode.children.count, limits.maxChildrenPerNode)
+ : 0
+ var children: [MacAccessibilitySnapshotNode] = []
+
+ for (index, child) in rawNode.children.prefix(allowedChildCount).enumerated() {
+ guard let childNode = buildNode(
+ child,
+ path: "\(path).\(index + 1)",
+ depth: depth + 1,
+ limits: limits,
+ emittedNodeCount: &emittedNodeCount,
+ isTreeTruncated: &isTreeTruncated
+ ) else {
+ break
+ }
+
+ children.append(childNode)
+ }
+
+ let omittedChildren = rawNode.children.count > children.count
+ if omittedChildren {
+ isTreeTruncated = true
+ }
+
+ return MacAccessibilitySnapshotNode(
+ nodeID: path,
+ role: summarizeText(rawNode.role, limit: limits.maxTextLength),
+ title: summarizeText(rawNode.title, limit: limits.maxTextLength),
+ label: summarizeText(rawNode.label, limit: limits.maxTextLength),
+ valueSummary: summarizeText(rawNode.valueSummary, limit: limits.maxTextLength),
+ frame: rawNode.frame,
+ isEnabled: rawNode.isEnabled,
+ isFocused: rawNode.isFocused,
+ actions: rawNode.actions.compactMap {
+ summarizeText($0, limit: limits.maxTextLength)
+ },
+ children: children,
+ isChildrenTruncated: omittedChildren
+ )
+ }
+
+ private static func summarizeText(
+ _ value: String?,
+ limit: Int
+ ) -> String? {
+ guard let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !trimmed.isEmpty
+ else {
+ return nil
+ }
+
+ guard trimmed.count <= limit else {
+ return "[redacted length=\(trimmed.count)]"
+ }
+
+ return trimmed
+ }
+}
+
+public struct MacAccessibilitySnapshot: Codable, Equatable, Sendable {
+ public var schemaVersion: Int
+ public var target: MacWindowTargetCandidate
+ public var limits: MacAccessibilitySnapshotLimits
+ public var root: MacAccessibilitySnapshotNode
+ public var totalNodeCount: Int
+ public var isTreeTruncated: Bool
+
+ public init(
+ schemaVersion: Int = 1,
+ target: MacWindowTargetCandidate,
+ limits: MacAccessibilitySnapshotLimits,
+ root: MacAccessibilitySnapshotNode,
+ totalNodeCount: Int,
+ isTreeTruncated: Bool
+ ) {
+ self.schemaVersion = schemaVersion
+ self.target = target
+ self.limits = limits
+ self.root = root
+ self.totalNodeCount = totalNodeCount
+ self.isTreeTruncated = isTreeTruncated
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
new file mode 100644
index 00000000..5f3cc0ab
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
@@ -0,0 +1,627 @@
+@preconcurrency import ApplicationServices
+import CoreGraphics
+import DonkeyContracts
+import Foundation
+
+public enum MacAccessibilitySnapshotCaptureError: Error, Equatable, Sendable {
+ case missingPreparedRun(runID: String)
+ case unsafeTarget(
+ windowID: UInt32,
+ status: WindowTargetSafetyStatus
+ )
+ case captureFailed(windowID: UInt32, reason: String)
+}
+
+public struct MacAccessibilitySnapshotCaptureResult: Equatable, Sendable {
+ public var target: MacWindowTargetCandidate
+ public var artifact: RunArtifactRecord
+ public var snapshot: MacAccessibilitySnapshot
+
+ public init(
+ target: MacWindowTargetCandidate,
+ artifact: RunArtifactRecord,
+ snapshot: MacAccessibilitySnapshot
+ ) {
+ self.target = target
+ self.artifact = artifact
+ self.snapshot = snapshot
+ }
+}
+
+public struct MacAccessibilityPermissionDeniedResult: Equatable, Sendable {
+ public var target: MacWindowTargetCandidate
+ public var eventRecord: RunTraceEventRecord
+
+ public init(
+ target: MacWindowTargetCandidate,
+ eventRecord: RunTraceEventRecord
+ ) {
+ self.target = target
+ self.eventRecord = eventRecord
+ }
+}
+
+public enum MacAccessibilitySnapshotCaptureOutcome: Equatable, Sendable {
+ case captured(MacAccessibilitySnapshotCaptureResult)
+ case permissionDenied(MacAccessibilityPermissionDeniedResult)
+}
+
+protocol MacAccessibilitySnapshotCapturing {
+ func trustStatus() -> MacAccessibilityTrustStatus
+ func captureTree(
+ target: MacWindowTargetCandidate,
+ limits: MacAccessibilitySnapshotLimits
+ ) throws -> MacAccessibilitySnapshotTree
+}
+
+public final class MacAccessibilitySnapshotCaptureService {
+ private let artifactStore: LocalRunArtifactStore
+ private let windowResolver: MacWindowResolver
+ private let capturer: any MacAccessibilitySnapshotCapturing
+
+ public convenience init(artifactStore: LocalRunArtifactStore) {
+ self.init(
+ artifactStore: artifactStore,
+ windowResolver: MacWindowResolver(),
+ capturer: ApplicationServicesMacAccessibilitySnapshotCapturer()
+ )
+ }
+
+ init(
+ artifactStore: LocalRunArtifactStore,
+ windowResolver: MacWindowResolver,
+ capturer: any MacAccessibilitySnapshotCapturing
+ ) {
+ self.artifactStore = artifactStore
+ self.windowResolver = windowResolver
+ self.capturer = capturer
+ }
+
+ public func captureSnapshot(
+ runID: String,
+ selection: MacWindowSelectionRequest = MacWindowSelectionRequest(),
+ limits: MacAccessibilitySnapshotLimits = .default,
+ artifactID: String = "accessibility-\(UUID().uuidString)"
+ ) async throws -> MacAccessibilitySnapshotCaptureOutcome {
+ let summary: RunTraceSummary
+ do {
+ summary = try await artifactStore.summary(runID: runID)
+ } catch LocalRunArtifactStoreError.missingSummary {
+ throw MacAccessibilitySnapshotCaptureError.missingPreparedRun(runID: runID)
+ }
+
+ let target = try windowResolver.selectTarget(selection)
+ guard target.safetyAssessment.status == .allowed else {
+ throw MacAccessibilitySnapshotCaptureError.unsafeTarget(
+ windowID: target.windowID,
+ status: target.safetyAssessment.status
+ )
+ }
+
+ guard capturer.trustStatus() == .trusted else {
+ let eventRecord = try await artifactStore.appendEvent(
+ permissionDeniedEvent(
+ summary: summary,
+ target: target
+ ),
+ runID: runID
+ )
+
+ return .permissionDenied(
+ MacAccessibilityPermissionDeniedResult(
+ target: target,
+ eventRecord: eventRecord
+ )
+ )
+ }
+
+ let tree: MacAccessibilitySnapshotTree
+ do {
+ tree = try capturer.captureTree(
+ target: target,
+ limits: limits
+ )
+ } catch let error as MacAccessibilitySnapshotCaptureError {
+ throw error
+ } catch {
+ throw MacAccessibilitySnapshotCaptureError.captureFailed(
+ windowID: target.windowID,
+ reason: String(describing: error)
+ )
+ }
+
+ let snapshot = MacAccessibilitySnapshot(
+ target: target,
+ limits: limits,
+ root: tree.root,
+ totalNodeCount: tree.totalNodeCount,
+ isTreeTruncated: tree.isTreeTruncated
+ )
+ let snapshotData = try Self.encoder().encode(snapshot)
+ let reservedPath = try await artifactStore.reserveArtifactPath(
+ runID: runID,
+ artifactID: artifactID,
+ kind: .accessibilitySnapshot,
+ fileExtension: "json"
+ )
+ try snapshotData.write(to: reservedPath.fileURL, options: .atomic)
+
+ let artifact = try await artifactStore.recordArtifact(
+ runID: runID,
+ artifactID: reservedPath.artifactID,
+ kind: .accessibilitySnapshot,
+ relativePath: reservedPath.relativePath,
+ contentType: "application/json",
+ byteCount: Int64(snapshotData.count),
+ metadata: metadata(
+ runID: runID,
+ traceID: summary.traceID,
+ target: target,
+ snapshot: snapshot
+ )
+ )
+
+ return .captured(
+ MacAccessibilitySnapshotCaptureResult(
+ target: target,
+ artifact: artifact,
+ snapshot: snapshot
+ )
+ )
+ }
+
+ private func permissionDeniedEvent(
+ summary: RunTraceSummary,
+ target: MacWindowTargetCandidate
+ ) -> RunEvent {
+ let reason = "Accessibility permission is not granted"
+ var metadata = targetMetadata(
+ runID: summary.runID,
+ traceID: summary.traceID,
+ target: target
+ )
+ metadata["accessibility.trustStatus"] = MacAccessibilityTrustStatus.notTrusted.rawValue
+
+ return RunEvent(
+ sequence: summary.eventCount + 1,
+ stream: .tool,
+ summary: reason,
+ payload: .tool(
+ ToolRunEvent(
+ capability: .accessibility,
+ decision: .deny(reason: reason),
+ toolName: "mac-accessibility-snapshot"
+ )
+ ),
+ traceID: summary.traceID,
+ metadata: metadata
+ )
+ }
+
+ private func metadata(
+ runID: String,
+ traceID: String,
+ target: MacWindowTargetCandidate,
+ snapshot: MacAccessibilitySnapshot
+ ) -> [String: String] {
+ var values = targetMetadata(
+ runID: runID,
+ traceID: traceID,
+ target: target
+ )
+ values["accessibility.trustStatus"] = MacAccessibilityTrustStatus.trusted.rawValue
+ values["accessibility.nodeCount"] = String(snapshot.totalNodeCount)
+ values["accessibility.isTreeTruncated"] = String(snapshot.isTreeTruncated)
+ values["accessibility.limits.maxDepth"] = String(snapshot.limits.maxDepth)
+ values["accessibility.limits.maxChildrenPerNode"] = String(snapshot.limits.maxChildrenPerNode)
+ values["accessibility.limits.maxTotalNodes"] = String(snapshot.limits.maxTotalNodes)
+ values["accessibility.limits.maxTextLength"] = String(snapshot.limits.maxTextLength)
+ return values
+ }
+
+ private func targetMetadata(
+ runID: String,
+ traceID: String,
+ target: MacWindowTargetCandidate
+ ) -> [String: String] {
+ var values = [
+ "runID": runID,
+ "traceID": traceID,
+ "target.windowID": String(target.windowID),
+ "target.processID": String(target.processID),
+ "target.bounds.x": String(target.bounds.x),
+ "target.bounds.y": String(target.bounds.y),
+ "target.bounds.width": String(target.bounds.width),
+ "target.bounds.height": String(target.bounds.height),
+ "target.isVisible": String(target.isVisible),
+ "target.isOnScreen": String(target.isOnScreen),
+ "target.isFrontmost": String(target.isFrontmost),
+ "target.isFocused": String(target.isFocused),
+ "target.isIPhoneMirroring": String(target.isIPhoneMirroring),
+ "target.safety.status": target.safetyAssessment.status.rawValue,
+ "target.safety.reasons": target.safetyAssessment.reasons.map(\.rawValue).joined(separator: ",")
+ ]
+
+ if let appName = target.appName {
+ values["target.appName"] = appName
+ }
+
+ if let bundleIdentifier = target.bundleIdentifier {
+ values["target.bundleIdentifier"] = bundleIdentifier
+ }
+
+ if let title = target.title {
+ values["target.title"] = title
+ }
+
+ return values
+ }
+
+ private static func encoder() -> JSONEncoder {
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.sortedKeys]
+ return encoder
+ }
+}
+
+private final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing {
+ func trustStatus() -> MacAccessibilityTrustStatus {
+ AXIsProcessTrusted() ? .trusted : .notTrusted
+ }
+
+ func captureTree(
+ target: MacWindowTargetCandidate,
+ limits: MacAccessibilitySnapshotLimits
+ ) throws -> MacAccessibilitySnapshotTree {
+ let application = AXUIElementCreateApplication(target.processID)
+ let rootElement = resolveWindowElement(
+ for: target,
+ in: application
+ ) ?? application
+ var remainingNodeCount = limits.maxTotalNodes
+ var isTreeTruncated = false
+ let rawRoot = readRawNode(
+ rootElement,
+ depth: 0,
+ limits: limits,
+ remainingNodeCount: &remainingNodeCount,
+ isTreeTruncated: &isTreeTruncated
+ ) ?? RawMacAccessibilitySnapshotNode(
+ role: "AXUnknown",
+ title: target.title,
+ frame: target.bounds
+ )
+
+ var tree = MacAccessibilitySnapshotTreeBuilder.build(
+ root: rawRoot,
+ limits: limits
+ )
+ tree.isTreeTruncated = tree.isTreeTruncated || isTreeTruncated
+ return tree
+ }
+
+ private func resolveWindowElement(
+ for target: MacWindowTargetCandidate,
+ in application: AXUIElement
+ ) -> AXUIElement? {
+ if let focusedWindow = elementAttribute(
+ kAXFocusedWindowAttribute as CFString,
+ from: application
+ ), matches(focusedWindow, target: target) {
+ return focusedWindow
+ }
+
+ let windows = elementArrayAttribute(
+ kAXWindowsAttribute as CFString,
+ from: application,
+ limit: 100
+ )
+ if let match = windows.first(where: { matches($0, target: target) }) {
+ return match
+ }
+
+ return windows.first
+ }
+
+ private func readRawNode(
+ _ element: AXUIElement,
+ depth: Int,
+ limits: MacAccessibilitySnapshotLimits,
+ remainingNodeCount: inout Int,
+ isTreeTruncated: inout Bool
+ ) -> RawMacAccessibilitySnapshotNode? {
+ guard remainingNodeCount > 0 else {
+ isTreeTruncated = true
+ return nil
+ }
+
+ remainingNodeCount -= 1
+ let children = childNodes(
+ for: element,
+ depth: depth,
+ limits: limits,
+ remainingNodeCount: &remainingNodeCount,
+ isTreeTruncated: &isTreeTruncated
+ )
+
+ return RawMacAccessibilitySnapshotNode(
+ role: stringAttribute(kAXRoleAttribute as CFString, from: element),
+ title: stringAttribute(kAXTitleAttribute as CFString, from: element),
+ label: stringAttribute(kAXDescriptionAttribute as CFString, from: element),
+ valueSummary: valueSummaryAttribute(kAXValueAttribute as CFString, from: element),
+ frame: frame(from: element),
+ isEnabled: boolAttribute(kAXEnabledAttribute as CFString, from: element),
+ isFocused: boolAttribute(kAXFocusedAttribute as CFString, from: element),
+ actions: actionNames(from: element),
+ children: children
+ )
+ }
+
+ private func childNodes(
+ for element: AXUIElement,
+ depth: Int,
+ limits: MacAccessibilitySnapshotLimits,
+ remainingNodeCount: inout Int,
+ isTreeTruncated: inout Bool
+ ) -> [RawMacAccessibilitySnapshotNode] {
+ let childCount = elementArrayCount(
+ kAXChildrenAttribute as CFString,
+ from: element
+ )
+ guard depth < limits.maxDepth else {
+ if childCount > 0 {
+ isTreeTruncated = true
+ }
+ return []
+ }
+
+ if childCount > limits.maxChildrenPerNode {
+ isTreeTruncated = true
+ }
+ let rawChildren = elementArrayAttribute(
+ kAXChildrenAttribute as CFString,
+ from: element,
+ limit: min(childCount, limits.maxChildrenPerNode)
+ )
+
+ return rawChildren
+ .compactMap { child in
+ readRawNode(
+ child,
+ depth: depth + 1,
+ limits: limits,
+ remainingNodeCount: &remainingNodeCount,
+ isTreeTruncated: &isTreeTruncated
+ )
+ }
+ }
+
+ private func matches(
+ _ element: AXUIElement,
+ target: MacWindowTargetCandidate
+ ) -> Bool {
+ if let targetTitle = normalized(target.title),
+ normalized(stringAttribute(kAXTitleAttribute as CFString, from: element)) == targetTitle {
+ return true
+ }
+
+ guard let frame = frame(from: element) else {
+ return false
+ }
+
+ return abs(frame.x - target.bounds.x) <= 2
+ && abs(frame.y - target.bounds.y) <= 2
+ && abs(frame.width - target.bounds.width) <= 2
+ && abs(frame.height - target.bounds.height) <= 2
+ }
+
+ private func normalized(_ value: String?) -> String? {
+ guard let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !trimmed.isEmpty
+ else {
+ return nil
+ }
+
+ return trimmed
+ }
+
+ private func stringAttribute(
+ _ attribute: CFString,
+ from element: AXUIElement
+ ) -> String? {
+ guard let value = copyAttribute(attribute, from: element) else {
+ return nil
+ }
+
+ if let string = value as? String {
+ return string
+ }
+
+ if let number = value as? NSNumber {
+ return number.stringValue
+ }
+
+ return nil
+ }
+
+ private func valueSummaryAttribute(
+ _ attribute: CFString,
+ from element: AXUIElement
+ ) -> String? {
+ guard let value = copyAttribute(attribute, from: element) else {
+ return nil
+ }
+
+ if let string = value as? String {
+ return string
+ }
+
+ if let number = value as? NSNumber {
+ return number.stringValue
+ }
+
+ return String(describing: value)
+ }
+
+ private func boolAttribute(
+ _ attribute: CFString,
+ from element: AXUIElement
+ ) -> Bool? {
+ guard let value = copyAttribute(attribute, from: element) else {
+ return nil
+ }
+
+ if let bool = value as? Bool {
+ return bool
+ }
+
+ return (value as? NSNumber)?.boolValue
+ }
+
+ private func elementArrayCount(
+ _ attribute: CFString,
+ from element: AXUIElement
+ ) -> Int {
+ var count: CFIndex = 0
+ if AXUIElementGetAttributeValueCount(element, attribute, &count) == .success {
+ return max(0, count)
+ }
+
+ guard let value = copyAttribute(attribute, from: element) else {
+ return 0
+ }
+
+ return (value as? [AXUIElement])?.count ?? 0
+ }
+
+ private func elementAttribute(
+ _ attribute: CFString,
+ from element: AXUIElement
+ ) -> AXUIElement? {
+ guard let value = copyAttribute(attribute, from: element),
+ CFGetTypeID(value) == AXUIElementGetTypeID()
+ else {
+ return nil
+ }
+
+ return (value as! AXUIElement)
+ }
+
+ private func elementArrayAttribute(
+ _ attribute: CFString,
+ from element: AXUIElement,
+ limit: Int
+ ) -> [AXUIElement] {
+ guard limit > 0 else {
+ return []
+ }
+
+ var values: CFArray?
+ if AXUIElementCopyAttributeValues(
+ element,
+ attribute,
+ 0,
+ limit,
+ &values
+ ) == .success,
+ let elements = values as? [AXUIElement] {
+ return elements
+ }
+
+ guard let value = copyAttribute(attribute, from: element) else {
+ return []
+ }
+
+ return Array((value as? [AXUIElement] ?? []).prefix(limit))
+ }
+
+ private func actionNames(from element: AXUIElement) -> [String] {
+ var value: CFArray?
+ guard AXUIElementCopyActionNames(element, &value) == .success,
+ let actions = value as? [String]
+ else {
+ return []
+ }
+
+ return actions
+ }
+
+ private func frame(from element: AXUIElement) -> WindowTargetBounds? {
+ guard let position = pointAttribute(
+ kAXPositionAttribute as CFString,
+ from: element
+ ),
+ let size = sizeAttribute(
+ kAXSizeAttribute as CFString,
+ from: element
+ )
+ else {
+ return nil
+ }
+
+ return WindowTargetBounds(
+ x: position.x,
+ y: position.y,
+ width: size.width,
+ height: size.height
+ )
+ }
+
+ private func pointAttribute(
+ _ attribute: CFString,
+ from element: AXUIElement
+ ) -> CGPoint? {
+ guard let value = copyAttribute(attribute, from: element),
+ CFGetTypeID(value) == AXValueGetTypeID()
+ else {
+ return nil
+ }
+
+ let axValue = value as! AXValue
+ guard AXValueGetType(axValue) == .cgPoint else {
+ return nil
+ }
+
+ var point = CGPoint.zero
+ guard AXValueGetValue(axValue, .cgPoint, &point) else {
+ return nil
+ }
+
+ return point
+ }
+
+ private func sizeAttribute(
+ _ attribute: CFString,
+ from element: AXUIElement
+ ) -> CGSize? {
+ guard let value = copyAttribute(attribute, from: element),
+ CFGetTypeID(value) == AXValueGetTypeID()
+ else {
+ return nil
+ }
+
+ let axValue = value as! AXValue
+ guard AXValueGetType(axValue) == .cgSize else {
+ return nil
+ }
+
+ var size = CGSize.zero
+ guard AXValueGetValue(axValue, .cgSize, &size) else {
+ return nil
+ }
+
+ return size
+ }
+
+ private func copyAttribute(
+ _ attribute: CFString,
+ from element: AXUIElement
+ ) -> CFTypeRef? {
+ var value: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(element, attribute, &value) == .success else {
+ return nil
+ }
+
+ return value
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MacAccessibilitySnapshotCaptureServiceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MacAccessibilitySnapshotCaptureServiceTests.swift
new file mode 100644
index 00000000..09a35a0c
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MacAccessibilitySnapshotCaptureServiceTests.swift
@@ -0,0 +1,515 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct MacAccessibilitySnapshotCaptureServiceTests {
+ @Test
+ func snapshotTreeBuilderBoundsChildrenDepthTotalNodesAndRedactsLongText() {
+ let longText = "abcdefghijklmnopqrstuvwxyz"
+ let rawTree = RawMacAccessibilitySnapshotNode(
+ role: "AXWindow",
+ title: " Main Window ",
+ valueSummary: longText,
+ children: [
+ RawMacAccessibilitySnapshotNode(
+ role: "AXButton",
+ title: "First",
+ children: [
+ RawMacAccessibilitySnapshotNode(role: "AXStaticText", title: "Grandchild")
+ ]
+ ),
+ RawMacAccessibilitySnapshotNode(role: "AXButton", title: "Second"),
+ RawMacAccessibilitySnapshotNode(role: "AXButton", title: "Third")
+ ]
+ )
+
+ let tree = MacAccessibilitySnapshotTreeBuilder.build(
+ root: rawTree,
+ limits: MacAccessibilitySnapshotLimits(
+ maxDepth: 1,
+ maxChildrenPerNode: 2,
+ maxTotalNodes: 3,
+ maxTextLength: 8
+ )
+ )
+
+ #expect(tree.root.nodeID == "ax-1")
+ #expect(tree.root.title == "[redacted length=11]")
+ #expect(tree.root.valueSummary == "[redacted length=26]")
+ #expect(tree.root.children.map(\.nodeID) == ["ax-1.1", "ax-1.2"])
+ #expect(tree.root.children.map(\.title) == ["First", "Second"])
+ #expect(tree.root.isChildrenTruncated)
+ #expect(tree.root.children.first?.isChildrenTruncated == true)
+ #expect(tree.totalNodeCount == 3)
+ #expect(tree.isTreeTruncated)
+ }
+
+ @Test
+ func snapshotContractsRoundTripThroughJSON() throws {
+ let snapshot = MacAccessibilitySnapshot(
+ target: targetCandidate(windowID: 42, processID: 9001, appName: "Notes"),
+ limits: MacAccessibilitySnapshotLimits(maxDepth: 1),
+ root: MacAccessibilitySnapshotNode(
+ nodeID: "ax-1",
+ role: "AXWindow",
+ title: "Project",
+ actions: ["AXPress"]
+ ),
+ totalNodeCount: 1,
+ isTreeTruncated: false
+ )
+
+ let data = try JSONEncoder().encode(snapshot)
+ let decoded = try JSONDecoder().decode(
+ MacAccessibilitySnapshot.self,
+ from: data
+ )
+
+ #expect(decoded == snapshot)
+ }
+
+ @Test
+ func trustedCaptureWritesJsonAndRecordsArtifactMetadata() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ _ = try await store.prepareRun(
+ session: RunSession(id: "run-ax", userGoal: "capture", targetID: "target-1"),
+ traceID: "trace-ax"
+ )
+ let capturer = FakeMacAccessibilitySnapshotCapturer(
+ tree: MacAccessibilitySnapshotTreeBuilder.build(
+ root: RawMacAccessibilitySnapshotNode(
+ role: "AXWindow",
+ title: "Plan",
+ frame: WindowTargetBounds(x: 0, y: 0, width: 100, height: 100),
+ isEnabled: true,
+ isFocused: true,
+ actions: ["AXRaise"],
+ children: [
+ RawMacAccessibilitySnapshotNode(role: "AXButton", title: "OK")
+ ]
+ ),
+ limits: .default
+ )
+ )
+ let service = makeService(
+ store: store,
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Notes", title: "Plan")
+ ],
+ frontmostProcessID: 100,
+ capturer: capturer
+ )
+
+ let outcome = try await service.captureSnapshot(
+ runID: "run-ax",
+ artifactID: "accessibility-1"
+ )
+
+ guard case .captured(let result) = outcome else {
+ Issue.record("Expected captured outcome")
+ return
+ }
+
+ #expect(result.target.windowID == 10)
+ #expect(result.artifact.relativePath == "accessibility/accessibility-1.json")
+ #expect(result.artifact.kind == .accessibilitySnapshot)
+ #expect(result.artifact.contentType == "application/json")
+ #expect(result.snapshot.root.role == "AXWindow")
+ #expect(result.snapshot.root.children.first?.title == "OK")
+ #expect(capturer.capturedWindowIDs == [10])
+
+ let fileURL = root
+ .appendingPathComponent("run-ax", isDirectory: true)
+ .appendingPathComponent("accessibility/accessibility-1.json")
+ let storedSnapshot = try JSONDecoder().decode(
+ MacAccessibilitySnapshot.self,
+ from: Data(contentsOf: fileURL)
+ )
+ #expect(storedSnapshot == result.snapshot)
+
+ let summary = try await store.summary(runID: "run-ax")
+ #expect(summary.artifacts.count == 1)
+ #expect(summary.artifacts.first?.metadata["runID"] == "run-ax")
+ #expect(summary.artifacts.first?.metadata["traceID"] == "trace-ax")
+ #expect(summary.artifacts.first?.metadata["target.windowID"] == "10")
+ #expect(summary.artifacts.first?.metadata["target.appName"] == "Notes")
+ #expect(summary.artifacts.first?.metadata["accessibility.trustStatus"] == "trusted")
+ #expect(summary.artifacts.first?.metadata["accessibility.nodeCount"] == "2")
+ #expect(summary.eventCount == 0)
+ }
+
+ @Test
+ func explicitWindowSelectionIsPassedToAccessibilityCapturer() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ _ = try await store.prepareRun(
+ session: RunSession(id: "run-ax-explicit", userGoal: "capture", targetID: "target-1"),
+ traceID: "trace-ax-explicit"
+ )
+ let capturer = FakeMacAccessibilitySnapshotCapturer()
+ let service = makeService(
+ store: store,
+ windows: [
+ fixtureWindow(windowID: 1, processID: 100, appName: "Terminal"),
+ fixtureWindow(windowID: 2, processID: 200, appName: "Safari")
+ ],
+ frontmostProcessID: 100,
+ capturer: capturer
+ )
+
+ let outcome = try await service.captureSnapshot(
+ runID: "run-ax-explicit",
+ selection: MacWindowSelectionRequest(windowID: 2),
+ artifactID: "accessibility-explicit"
+ )
+
+ guard case .captured(let result) = outcome else {
+ Issue.record("Expected captured outcome")
+ return
+ }
+ #expect(result.target.windowID == 2)
+ #expect(capturer.capturedWindowIDs == [2])
+ }
+
+ @Test
+ func missingAccessibilityTrustAppendsPartialRunEventAndNoArtifact() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ _ = try await store.prepareRun(
+ session: RunSession(id: "run-ax-denied", userGoal: "capture", targetID: "target-1"),
+ traceID: "trace-ax-denied"
+ )
+ let capturer = FakeMacAccessibilitySnapshotCapturer(trustStatus: .notTrusted)
+ let service = makeService(
+ store: store,
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Notes")
+ ],
+ frontmostProcessID: 100,
+ capturer: capturer
+ )
+
+ let outcome = try await service.captureSnapshot(
+ runID: "run-ax-denied",
+ artifactID: "accessibility-denied"
+ )
+
+ guard case .permissionDenied(let result) = outcome else {
+ Issue.record("Expected permission denied outcome")
+ return
+ }
+
+ #expect(result.target.windowID == 10)
+ #expect(result.eventRecord.runID == "run-ax-denied")
+ #expect(result.eventRecord.traceID == "trace-ax-denied")
+ #expect(result.eventRecord.event.sequence == 1)
+ #expect(result.eventRecord.event.stream == .tool)
+ #expect(result.eventRecord.event.summary == "Accessibility permission is not granted")
+ #expect(result.eventRecord.event.metadata["target.windowID"] == "10")
+ #expect(capturer.capturedWindowIDs.isEmpty)
+
+ guard case .tool(let payload) = result.eventRecord.event.payload else {
+ Issue.record("Expected tool event payload")
+ return
+ }
+ #expect(payload.capability == .accessibility)
+ #expect(!payload.decision.isAllowed)
+ #expect(payload.toolName == "mac-accessibility-snapshot")
+
+ let summary = try await store.summary(runID: "run-ax-denied")
+ #expect(summary.eventCount == 1)
+ #expect(summary.artifacts.isEmpty)
+ #expect(!fileExists(root
+ .appendingPathComponent("run-ax-denied", isDirectory: true)
+ .appendingPathComponent("accessibility/accessibility-denied.json")))
+
+ let records = try jsonlRecords(from: root
+ .appendingPathComponent("run-ax-denied", isDirectory: true)
+ .appendingPathComponent("events.jsonl"))
+ #expect(records.map(\.event.sequence) == [1])
+ }
+
+ @Test
+ func unsafeTargetRefusesBeforeTrustCheckOrCapture() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ _ = try await store.prepareRun(
+ session: RunSession(id: "run-ax-unsafe", userGoal: "capture", targetID: "target-1"),
+ traceID: "trace-ax-unsafe"
+ )
+ let capturer = FakeMacAccessibilitySnapshotCapturer()
+ let service = makeService(
+ store: store,
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Safari", title: "Checkout Payment")
+ ],
+ frontmostProcessID: 100,
+ capturer: capturer
+ )
+
+ do {
+ _ = try await service.captureSnapshot(
+ runID: "run-ax-unsafe",
+ artifactID: "accessibility-unsafe"
+ )
+ Issue.record("Expected unsafe target to be refused")
+ } catch MacAccessibilitySnapshotCaptureError.unsafeTarget(let windowID, let status) {
+ #expect(windowID == 10)
+ #expect(status == .blocked)
+ } catch {
+ Issue.record("Unexpected error: \(error)")
+ }
+
+ let summary = try await store.summary(runID: "run-ax-unsafe")
+ #expect(summary.eventCount == 0)
+ #expect(summary.artifacts.isEmpty)
+ #expect(capturer.capturedWindowIDs.isEmpty)
+ }
+
+ @Test
+ func missingPreparedRunFailsWithoutWritingFile() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let capturer = FakeMacAccessibilitySnapshotCapturer()
+ let service = makeService(
+ store: store,
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Notes")
+ ],
+ frontmostProcessID: 100,
+ capturer: capturer
+ )
+
+ do {
+ _ = try await service.captureSnapshot(
+ runID: "missing-run",
+ artifactID: "accessibility-missing"
+ )
+ Issue.record("Expected missing prepared run to fail")
+ } catch MacAccessibilitySnapshotCaptureError.missingPreparedRun(let runID) {
+ #expect(runID == "missing-run")
+ } catch {
+ Issue.record("Unexpected error: \(error)")
+ }
+
+ #expect(capturer.capturedWindowIDs.isEmpty)
+ #expect(!fileExists(root
+ .appendingPathComponent("missing-run", isDirectory: true)
+ .appendingPathComponent("accessibility/accessibility-missing.json")))
+ }
+
+ @Test
+ func adapterCaptureFailureCreatesNoArtifactRecord() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ _ = try await store.prepareRun(
+ session: RunSession(id: "run-ax-failure", userGoal: "capture", targetID: "target-1"),
+ traceID: "trace-ax-failure"
+ )
+ let capturer = FakeMacAccessibilitySnapshotCapturer(
+ error: FixtureAccessibilityError.failed
+ )
+ let service = makeService(
+ store: store,
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Notes")
+ ],
+ frontmostProcessID: 100,
+ capturer: capturer
+ )
+
+ do {
+ _ = try await service.captureSnapshot(
+ runID: "run-ax-failure",
+ artifactID: "accessibility-failure"
+ )
+ Issue.record("Expected capture failure")
+ } catch MacAccessibilitySnapshotCaptureError.captureFailed(let windowID, let reason) {
+ #expect(windowID == 10)
+ #expect(reason.contains("failed"))
+ } catch {
+ Issue.record("Unexpected error: \(error)")
+ }
+
+ let summary = try await store.summary(runID: "run-ax-failure")
+ #expect(summary.artifacts.isEmpty)
+ #expect(capturer.capturedWindowIDs == [10])
+ }
+
+ private func makeService(
+ store: LocalRunArtifactStore,
+ windows: [MacWindowProviderWindow],
+ frontmostProcessID: Int32? = nil,
+ focusedWindowID: UInt32? = nil,
+ capturer: FakeMacAccessibilitySnapshotCapturer
+ ) -> MacAccessibilitySnapshotCaptureService {
+ MacAccessibilitySnapshotCaptureService(
+ artifactStore: store,
+ windowResolver: MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: windows,
+ frontmostProcessID: frontmostProcessID,
+ focusedWindowID: focusedWindowID
+ )
+ ),
+ capturer: capturer
+ )
+ }
+
+ private func fixtureWindow(
+ windowID: UInt32,
+ processID: Int32,
+ appName: String? = nil,
+ bundleIdentifier: String? = nil,
+ title: String? = nil,
+ bounds: WindowTargetBounds = WindowTargetBounds(
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 100
+ )
+ ) -> MacWindowProviderWindow {
+ MacWindowProviderWindow(
+ windowID: windowID,
+ processID: processID,
+ appName: appName,
+ bundleIdentifier: bundleIdentifier,
+ title: title,
+ bounds: bounds
+ )
+ }
+
+ private func targetCandidate(
+ windowID: UInt32,
+ processID: Int32,
+ appName: String
+ ) -> MacWindowTargetCandidate {
+ MacWindowTargetCandidate(
+ windowID: windowID,
+ processID: processID,
+ appName: appName,
+ 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: "No sensitive surface indicators detected"
+ )
+ )
+ }
+
+ private func temporaryDirectory() -> URL {
+ FileManager.default.temporaryDirectory.appendingPathComponent(
+ "DonkeyAccessibilitySnapshotTests-\(UUID().uuidString)",
+ isDirectory: true
+ )
+ }
+
+ private func fileExists(_ url: URL) -> Bool {
+ var isDirectory = ObjCBool(false)
+ let exists = FileManager.default.fileExists(
+ atPath: url.path,
+ isDirectory: &isDirectory
+ )
+ return exists && !isDirectory.boolValue
+ }
+
+ private func jsonlRecords(from url: URL) throws -> [RunTraceEventRecord] {
+ let data = try Data(contentsOf: url)
+ let text = String(decoding: data, as: UTF8.self)
+ return try text
+ .split(separator: "\n")
+ .map { line in
+ try JSONDecoder().decode(
+ RunTraceEventRecord.self,
+ from: Data(line.utf8)
+ )
+ }
+ }
+}
+
+private final class FakeMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing {
+ var trust: MacAccessibilityTrustStatus
+ var tree: MacAccessibilitySnapshotTree
+ var error: Error?
+ var capturedWindowIDs: [UInt32] = []
+
+ init(
+ trustStatus: MacAccessibilityTrustStatus = .trusted,
+ tree: MacAccessibilitySnapshotTree = MacAccessibilitySnapshotTreeBuilder.build(
+ root: RawMacAccessibilitySnapshotNode(role: "AXWindow", title: "Window"),
+ limits: .default
+ ),
+ error: Error? = nil
+ ) {
+ self.trust = trustStatus
+ self.tree = tree
+ self.error = error
+ }
+
+ func trustStatus() -> MacAccessibilityTrustStatus {
+ trust
+ }
+
+ func captureTree(
+ target: MacWindowTargetCandidate,
+ limits: MacAccessibilitySnapshotLimits
+ ) throws -> MacAccessibilitySnapshotTree {
+ capturedWindowIDs.append(target.windowID)
+ if let error {
+ throw error
+ }
+
+ return tree
+ }
+}
+
+private enum FixtureAccessibilityError: Error {
+ case failed
+}
+
+private struct FixtureWindowProvider: MacWindowMetadataProviding {
+ var fixtureWindows: [MacWindowProviderWindow]
+ var frontmostProcessID: Int32?
+ var focusedWindowID: UInt32?
+
+ init(
+ windows: [MacWindowProviderWindow],
+ frontmostProcessID: Int32? = nil,
+ focusedWindowID: UInt32? = nil
+ ) {
+ self.fixtureWindows = windows
+ self.frontmostProcessID = frontmostProcessID
+ self.focusedWindowID = focusedWindowID
+ }
+
+ func windows() -> [MacWindowProviderWindow] {
+ fixtureWindows
+ }
+
+ func frontmostProcessIdentifier() -> Int32? {
+ frontmostProcessID
+ }
+
+ func focusedWindowIdentifier() -> UInt32? {
+ focusedWindowID
+ }
+}
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
index 3d68ea8d..39eaa7e6 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -29,7 +29,9 @@ Donkey can also resolve visible macOS target-window metadata for the manual capt
Donkey can create a single read-only target-window screenshot artifact after a run folder has been prepared. The screenshot service resolves the target, refuses blocked or review-required safety surfaces, captures the selected window with ScreenCaptureKit's desktop-independent window path, writes PNG bytes under `screenshots/`, and records flattened target/capture metadata in `summary.json`. Overlap-sensitive fallback capture backends must refuse occluded targets instead of silently recording pixels from another window.
-This is a coordination, trace, target-metadata, and single-screenshot artifact foundation only. It does not dump Accessibility trees, run perception models, call LLMs, execute OS input, provide a manual capture UI, or wire coordinator events into disk persistence yet.
+Donkey can also create a shallow read-only Accessibility snapshot artifact after a run folder has been prepared. The Accessibility snapshot service resolves the same target-window selection, refuses blocked or review-required safety surfaces, checks Accessibility trust without prompting, writes a bounded JSON tree under `accessibility/` when trusted, and records artifact metadata in `summary.json`. If Accessibility trust is missing, the service appends a clear partial-run tool event to `events.jsonl` and does not create an artifact.
+
+This is a coordination, trace, target-metadata, single-screenshot artifact, and read-only Accessibility snapshot foundation only. It does not run perception models, call LLMs, execute OS input, perform Accessibility actions, provide a manual capture UI, or wire the full capture flow through `RunCoordinator` events yet.
## Technical Guidelines
@@ -39,6 +41,7 @@ This is a coordination, trace, target-metadata, and single-screenshot artifact f
- Treat `LocalRunArtifactStore` as a persistence sink for trace records and artifact metadata. It should not own lifecycle state or decide whether tool calls are allowed.
- Treat macOS window resolution as read-only metadata collection. Safety classifications should be conservative and used by later capture code to refuse or stop on sensitive surfaces.
- Treat target-window screenshot capture as a one-shot artifact write, not a continuous capture loop. ScreenCaptureKit desktop-independent window capture is preferred because overlapping windows do not contaminate the selected target artifact.
+- Treat Accessibility snapshot capture as read-only inspection. Keep trees bounded, redact long text values, avoid permission prompts in the capture service, and never perform AX actions from this path.
- Keep mutable installed-app run artifacts in Application Support, not inside the `.app` bundle and not relative to process working directory.
- Keep input actions denied unless a caller provides a policy that explicitly allows them.
- Preserve latest-request-wins behavior for live-control sessions so stale work cannot build up behind the reflex loop.
@@ -52,7 +55,7 @@ From `apps/Donkey/`:
swift test
```
-The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, unsafe target refusal, and overlap-sensitive capture refusal.
+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, and overlap-sensitive capture refusal.
## Source Entry Points
@@ -61,5 +64,7 @@ The runtime tests should cover lifecycle ordering, abort and timeout safety, lat
- Runtime coordination lives in `apps/Donkey/Sources/DonkeyRuntime/`.
- macOS window resolution lives in `apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift`.
- Target-window screenshot capture lives in `apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift`.
+- Accessibility snapshot contracts live in `apps/Donkey/Sources/DonkeyContracts/AccessibilitySnapshotContracts.swift`.
+- Read-only Accessibility snapshot capture lives in `apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift`.
- Local artifact persistence lives in `apps/Donkey/Sources/DonkeyRuntime/LocalRunArtifactStore.swift`.
- The manual capture source plan remains active in `plans/master-plan.md`.
diff --git a/plans/18-macos-accessibility.md b/plans/18-macos-accessibility.md
index 73e9e669..069297d8 100644
--- a/plans/18-macos-accessibility.md
+++ b/plans/18-macos-accessibility.md
@@ -51,6 +51,24 @@ Do not rely on macOS Accessibility for:
- latency-critical dodge/jump/shoot loops
- apps that expose incomplete or stale accessibility trees
+## Supported Read-Only Snapshot Boundary
+
+Donkey now supports bounded, read-only Accessibility snapshots for the manual target context capture milestone.
+
+Supported behavior:
+
+- check process Accessibility trust without prompting
+- resolve a selected target window by pid, title, focus, and frame metadata when possible
+- serialize a shallow tree with role, title/label, value summary, frame, enabled/focused state, and available action names
+- cap depth, children per node, total nodes, and text length
+- write trusted snapshots to the run artifact store under `accessibility/`
+- append a clear partial-run event when Accessibility trust is missing
+
+Current boundary:
+
+- The snapshot service records action names but does not perform actions.
+- Full app navigation, menu selection, value setting, focus changes, and setup/recovery flows remain future work.
+
## Operating Loop
Use the same inspect-act-verify pattern as PhoneAgent:
@@ -143,12 +161,18 @@ Accessibility APIs can block or return stale/incomplete data if the target app i
## First Milestones
-1. Check Accessibility trust status from the Mac synthetic controller.
-2. Find the focused window and dump basic AX attributes.
-3. Find the iPhone Mirroring window and read its bounds.
-4. Detect focus loss before sending synthetic input.
-5. Add an accessibility-backed window guard to the iPhone gameplay loop.
-6. Add tree/action/verify support for native Mac setup dialogs.
+Completed for the manual capture milestone:
+
+1. Check Accessibility trust status from the runtime capture path.
+2. Resolve a target app/window and dump bounded read-only AX attributes.
+3. Store shallow AX snapshots as local run artifacts.
+
+Remaining future milestones:
+
+1. Find the iPhone Mirroring window and read its bounds for calibration.
+2. Detect focus loss before sending synthetic input.
+3. Add an accessibility-backed window guard to the iPhone gameplay loop.
+4. Add tree/action/verify support for native Mac setup dialogs.
## Acceptance Criteria
@@ -157,4 +181,3 @@ Accessibility APIs can block or return stale/incomplete data if the target app i
- The system can read iPhone Mirroring window bounds for calibration.
- Accessibility calls are timed and never block the gameplay hot path.
- Native Mac dialogs can be detected as safety stops.
-
diff --git a/plans/master-plan.md b/plans/master-plan.md
index 31fe128a..14b9c120 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -112,20 +112,21 @@ Current boundaries:
### Accessibility Tree Snapshot
-- Add an Accessibility adapter that can:
- - check trust status
- - get frontmost/focused app and window
- - resolve a selected target window by pid/title/window metadata when possible
- - read a shallow AX tree with bounded depth and child count
- - serialize role, title/label, value summary, frame, enabled/focused state, and action names
-- Store AX snapshots under the prepared run folder:
+Supported as the fourth vertical slice. `MacAccessibilitySnapshotCaptureService` creates one read-only Accessibility snapshot artifact after a run folder has been prepared. It resolves a target from explicit `windowID` or focused/frontmost fallback, refuses blocked or review-required safety surfaces, checks Accessibility trust without prompting, captures a bounded AX tree when trusted, writes JSON through the local artifact store, records target/snapshot metadata, and appends a partial-run tool event when trust is missing.
+
+AX snapshots are stored under the prepared run folder:
```text
<run-folder>/accessibility/<artifact-id>.json
```
-- Keep the tree bounded. Do not dump arbitrarily large app trees.
-- Redact long text values by default and store summaries instead of full sensitive text.
+Current boundaries:
+
+- The snapshot path is read-only. It records available AX action names but never performs Accessibility actions.
+- Missing Accessibility trust creates an `events.jsonl` partial-run event and no artifact; the service does not open System Settings or request trust.
+- AX window matching is best effort by pid, title, focus, and frame metadata. Selection remains durable by `windowID` at the resolver/capture boundary.
+- Trees are bounded by depth, children per node, total nodes, and text length. Long text values are summarized with redaction markers.
+- The service does not publish ordered `RunCoordinator` events yet.
### Trace Artifact Store
@@ -185,12 +186,10 @@ accessibility/
## What Should Be Done Next
-Continue the read-only vertical slice from the completed local artifact writer, window resolver, candidate-list API, and screenshot artifact service:
+Continue the read-only vertical slice from the completed local artifact writer, window resolver, candidate-list API, screenshot artifact service, and Accessibility snapshot service:
-1. Add shallow Accessibility tree capture behind permission checks.
- - Serialize a bounded AX snapshot when trusted and record a clear partial-run event when not trusted.
-2. Wire the manual capture flow through `RunCoordinator` events.
+1. Wire the manual capture flow through `RunCoordinator` events.
- Emit ordered lifecycle/tool events for target resolution, screenshot capture, AX snapshot, artifact persistence, completion, and failure paths.
-3. Add integration tests and manual verification.
+2. Add integration tests and manual verification.
- Cover artifact metadata, bounded AX serialization, policy denial for input, and partial summaries.
- Manually verify against iPhone Mirroring and at least one other visible Mac app window, including an overlapped-window scenario.