Skip to content

Open source CapCut alternative.

TypeScript

Add window target capture

David Leba8bccafe387
diff --git a/apps/Donkey/Sources/DonkeyContracts/WindowTargetContracts.swift b/apps/Donkey/Sources/DonkeyContracts/WindowTargetContracts.swift
new file mode 100644
index 00000000..6a531e79
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyContracts/WindowTargetContracts.swift
@@ -0,0 +1,106 @@
+import Foundation
+
+public struct WindowTargetBounds: Codable, Equatable, Sendable {
+ public var x: Double
+ public var y: Double
+ public var width: Double
+ public var height: Double
+
+ public init(
+ x: Double,
+ y: Double,
+ width: Double,
+ height: Double
+ ) {
+ self.x = x
+ self.y = y
+ self.width = width
+ self.height = height
+ }
+
+ public var hasPositiveArea: Bool {
+ width > 0 && height > 0
+ }
+}
+
+public enum WindowTargetSafetyStatus: String, Codable, Equatable, Sendable {
+ case allowed
+ case reviewRequired
+ case blocked
+}
+
+public enum WindowTargetSafetyReason: String, Codable, Equatable, Sendable {
+ case systemSurface
+ case loginSurface
+ case passwordSurface
+ case paymentSurface
+ case permissionSurface
+ case unknownSurface
+}
+
+public struct WindowTargetSafetyAssessment: Codable, Equatable, Sendable {
+ public var status: WindowTargetSafetyStatus
+ public var reasons: [WindowTargetSafetyReason]
+ public var summary: String
+
+ public init(
+ status: WindowTargetSafetyStatus,
+ reasons: [WindowTargetSafetyReason] = [],
+ summary: String
+ ) {
+ self.status = status
+ self.reasons = reasons
+ self.summary = summary
+ }
+}
+
+public struct MacWindowTargetCandidate: Codable, Equatable, Sendable {
+ public var windowID: UInt32
+ public var processID: Int32
+ public var appName: String?
+ public var bundleIdentifier: String?
+ public var title: String?
+ public var bounds: WindowTargetBounds
+ public var isVisible: Bool
+ public var isOnScreen: Bool
+ public var isFrontmost: Bool
+ public var isFocused: Bool
+ public var isIPhoneMirroring: Bool
+ public var safetyAssessment: WindowTargetSafetyAssessment
+
+ public init(
+ windowID: UInt32,
+ processID: Int32,
+ appName: String? = nil,
+ bundleIdentifier: String? = nil,
+ title: String? = nil,
+ bounds: WindowTargetBounds,
+ isVisible: Bool,
+ isOnScreen: Bool,
+ isFrontmost: Bool,
+ isFocused: Bool,
+ isIPhoneMirroring: Bool,
+ safetyAssessment: WindowTargetSafetyAssessment
+ ) {
+ self.windowID = windowID
+ self.processID = processID
+ self.appName = appName
+ self.bundleIdentifier = bundleIdentifier
+ self.title = title
+ self.bounds = bounds
+ self.isVisible = isVisible
+ self.isOnScreen = isOnScreen
+ self.isFrontmost = isFrontmost
+ self.isFocused = isFocused
+ self.isIPhoneMirroring = isIPhoneMirroring
+ self.safetyAssessment = safetyAssessment
+ }
+}
+
+public struct MacWindowSelectionRequest: Codable, Equatable, Sendable {
+ public var windowID: UInt32?
+
+ public init(windowID: UInt32? = nil) {
+ self.windowID = windowID
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift b/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift
new file mode 100644
index 00000000..aeacd9f7
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift
@@ -0,0 +1,345 @@
+@preconcurrency import AppKit
+import CoreGraphics
+import DonkeyContracts
+import Foundation
+
+public enum MacWindowResolverError: Error, Equatable, Sendable {
+ case noVisibleWindows
+ case noFocusedWindow
+ case windowNotFound(windowID: UInt32)
+}
+
+struct MacWindowProviderWindow: Equatable, Sendable {
+ var windowID: UInt32
+ var processID: Int32
+ var appName: String?
+ var bundleIdentifier: String?
+ var title: String?
+ var bounds: WindowTargetBounds
+ var alpha: Double
+ var layer: Int
+ var isOnScreen: Bool
+
+ init(
+ windowID: UInt32,
+ processID: Int32,
+ appName: String? = nil,
+ bundleIdentifier: String? = nil,
+ title: String? = nil,
+ bounds: WindowTargetBounds,
+ alpha: Double = 1,
+ layer: Int = 0,
+ isOnScreen: Bool = true
+ ) {
+ self.windowID = windowID
+ self.processID = processID
+ self.appName = appName
+ self.bundleIdentifier = bundleIdentifier
+ self.title = title
+ self.bounds = bounds
+ self.alpha = alpha
+ self.layer = layer
+ self.isOnScreen = isOnScreen
+ }
+}
+
+protocol MacWindowMetadataProviding {
+ func windows() -> [MacWindowProviderWindow]
+ func frontmostProcessIdentifier() -> Int32?
+ func focusedWindowIdentifier() -> UInt32?
+}
+
+public final class MacWindowResolver {
+ private let provider: any MacWindowMetadataProviding
+
+ public convenience init() {
+ self.init(provider: CoreGraphicsMacWindowMetadataProvider())
+ }
+
+ init(provider: any MacWindowMetadataProviding) {
+ self.provider = provider
+ }
+
+ public func enumerateCandidates() -> [MacWindowTargetCandidate] {
+ let frontmostProcessID = provider.frontmostProcessIdentifier()
+ let focusedWindowID = provider.focusedWindowIdentifier()
+ var assignedFocusedFallback = false
+
+ return provider.windows()
+ .filter(Self.isVisibleWindow)
+ .map { window in
+ let isFrontmost = window.processID == frontmostProcessID
+ let isFocused: Bool
+
+ if let focusedWindowID {
+ isFocused = window.windowID == focusedWindowID
+ } else if isFrontmost && !assignedFocusedFallback {
+ isFocused = true
+ assignedFocusedFallback = true
+ } else {
+ isFocused = false
+ }
+
+ return MacWindowTargetCandidate(
+ windowID: window.windowID,
+ processID: window.processID,
+ appName: Self.normalizedOptional(window.appName),
+ bundleIdentifier: Self.normalizedOptional(window.bundleIdentifier),
+ title: Self.normalizedOptional(window.title),
+ bounds: window.bounds,
+ isVisible: true,
+ isOnScreen: window.isOnScreen,
+ isFrontmost: isFrontmost,
+ isFocused: isFocused,
+ isIPhoneMirroring: Self.isIPhoneMirroring(window),
+ safetyAssessment: Self.safetyAssessment(for: window)
+ )
+ }
+ }
+
+ public func selectTarget(
+ _ request: MacWindowSelectionRequest = MacWindowSelectionRequest()
+ ) throws -> MacWindowTargetCandidate {
+ let candidates = enumerateCandidates()
+ guard !candidates.isEmpty else {
+ throw MacWindowResolverError.noVisibleWindows
+ }
+
+ if let windowID = request.windowID {
+ guard let match = candidates.first(where: { $0.windowID == windowID }) else {
+ throw MacWindowResolverError.windowNotFound(windowID: windowID)
+ }
+
+ return match
+ }
+
+ if let focused = candidates.first(where: \.isFocused) {
+ return focused
+ }
+
+ if let frontmost = candidates.first(where: \.isFrontmost) {
+ return frontmost
+ }
+
+ throw MacWindowResolverError.noFocusedWindow
+ }
+
+ private static func isVisibleWindow(_ window: MacWindowProviderWindow) -> Bool {
+ window.isOnScreen
+ && window.alpha > 0
+ && window.layer == 0
+ && window.bounds.hasPositiveArea
+ }
+
+ private static func isIPhoneMirroring(_ window: MacWindowProviderWindow) -> Bool {
+ let haystack = searchableText(for: window)
+ return haystack.contains("iphone mirroring")
+ || haystack.contains("iphone")
+ && haystack.contains("mirroring")
+ || haystack.contains("screencontinuity")
+ }
+
+ private static func safetyAssessment(
+ for window: MacWindowProviderWindow
+ ) -> WindowTargetSafetyAssessment {
+ var reasons: [WindowTargetSafetyReason] = []
+ let haystack = searchableText(for: window)
+
+ if haystack.contains("loginwindow")
+ || haystack.contains("sign in")
+ || haystack.contains("signin")
+ || haystack.contains("sign-in")
+ || haystack.contains("log in")
+ || haystack.contains("unlock")
+ || haystack.contains("authentication") {
+ reasons.append(.loginSurface)
+ }
+
+ if haystack.contains("password")
+ || haystack.contains("passcode")
+ || haystack.contains("credential")
+ || haystack.contains("keychain") {
+ reasons.append(.passwordSurface)
+ }
+
+ if haystack.contains("payment")
+ || haystack.contains("checkout")
+ || haystack.contains("billing")
+ || haystack.contains("credit card")
+ || haystack.contains("card number")
+ || haystack.contains("apple pay")
+ || haystack.contains("paypal")
+ || haystack.contains("purchase") {
+ reasons.append(.paymentSurface)
+ }
+
+ if haystack.contains("permission")
+ || haystack.contains("privacy & security")
+ || haystack.contains("screen recording")
+ || haystack.contains("accessibility") {
+ reasons.append(.permissionSurface)
+ }
+
+ if haystack.contains("system settings")
+ || haystack.contains("system preferences")
+ || haystack.contains("securityagent")
+ || haystack.contains("coreautha")
+ || haystack.contains("systemuiserver")
+ || haystack.contains("installer")
+ || haystack.contains("software update") {
+ reasons.append(.systemSurface)
+ }
+
+ if isUnderDescribed(window) {
+ reasons.append(.unknownSurface)
+ }
+
+ let uniqueReasons = reasons.uniqued()
+ if uniqueReasons.isEmpty {
+ return WindowTargetSafetyAssessment(
+ status: .allowed,
+ summary: "No sensitive surface indicators detected"
+ )
+ }
+
+ if uniqueReasons == [.unknownSurface] {
+ return WindowTargetSafetyAssessment(
+ status: .reviewRequired,
+ reasons: uniqueReasons,
+ summary: "Window metadata is too sparse for automatic capture"
+ )
+ }
+
+ return WindowTargetSafetyAssessment(
+ status: .blocked,
+ reasons: uniqueReasons,
+ summary: "Sensitive or system surface indicators detected"
+ )
+ }
+
+ private static func isUnderDescribed(_ window: MacWindowProviderWindow) -> Bool {
+ normalizedOptional(window.appName) == nil
+ && normalizedOptional(window.bundleIdentifier) == nil
+ && normalizedOptional(window.title) == nil
+ }
+
+ private static func searchableText(for window: MacWindowProviderWindow) -> String {
+ [
+ window.appName,
+ window.bundleIdentifier,
+ window.title
+ ]
+ .compactMap(normalizedOptional)
+ .joined(separator: " ")
+ .lowercased()
+ }
+
+ private static func normalizedOptional(_ value: String?) -> String? {
+ guard let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !trimmed.isEmpty
+ else {
+ return nil
+ }
+
+ return trimmed
+ }
+}
+
+private struct CoreGraphicsMacWindowMetadataProvider: MacWindowMetadataProviding {
+ func windows() -> [MacWindowProviderWindow] {
+ guard let rawWindows = CGWindowListCopyWindowInfo(
+ [.optionOnScreenOnly, .excludeDesktopElements],
+ kCGNullWindowID
+ ) as? [[String: Any]] else {
+ return []
+ }
+
+ return rawWindows.compactMap { rawWindow in
+ guard let windowID = rawWindow.uint32Value(for: kCGWindowNumber),
+ let processID = rawWindow.int32Value(for: kCGWindowOwnerPID),
+ let bounds = rawWindow.boundsValue(for: kCGWindowBounds)
+ else {
+ return nil
+ }
+
+ let bundleIdentifier = NSRunningApplication(
+ processIdentifier: processID
+ )?.bundleIdentifier
+
+ return MacWindowProviderWindow(
+ windowID: windowID,
+ processID: processID,
+ appName: rawWindow.stringValue(for: kCGWindowOwnerName),
+ bundleIdentifier: bundleIdentifier,
+ title: rawWindow.stringValue(for: kCGWindowName),
+ bounds: bounds,
+ alpha: rawWindow.doubleValue(for: kCGWindowAlpha) ?? 1,
+ layer: rawWindow.intValue(for: kCGWindowLayer) ?? 0,
+ isOnScreen: rawWindow.boolValue(for: kCGWindowIsOnscreen) ?? true
+ )
+ }
+ }
+
+ func frontmostProcessIdentifier() -> Int32? {
+ NSWorkspace.shared.frontmostApplication?.processIdentifier
+ }
+
+ func focusedWindowIdentifier() -> UInt32? {
+ nil
+ }
+}
+
+private extension Dictionary where Key == String, Value == Any {
+ func stringValue(for key: CFString) -> String? {
+ self[key as String] as? String
+ }
+
+ func boolValue(for key: CFString) -> Bool? {
+ if let value = self[key as String] as? Bool {
+ return value
+ }
+
+ return (self[key as String] as? NSNumber)?.boolValue
+ }
+
+ func intValue(for key: CFString) -> Int? {
+ (self[key as String] as? NSNumber)?.intValue
+ }
+
+ func int32Value(for key: CFString) -> Int32? {
+ (self[key as String] as? NSNumber)?.int32Value
+ }
+
+ func uint32Value(for key: CFString) -> UInt32? {
+ (self[key as String] as? NSNumber)?.uint32Value
+ }
+
+ func doubleValue(for key: CFString) -> Double? {
+ (self[key as String] as? NSNumber)?.doubleValue
+ }
+
+ func boundsValue(for key: CFString) -> WindowTargetBounds? {
+ guard let rawBounds = self[key as String] as? [String: Any],
+ let x = (rawBounds["X"] as? NSNumber)?.doubleValue,
+ let y = (rawBounds["Y"] as? NSNumber)?.doubleValue,
+ let width = (rawBounds["Width"] as? NSNumber)?.doubleValue,
+ let height = (rawBounds["Height"] as? NSNumber)?.doubleValue
+ else {
+ return nil
+ }
+
+ return WindowTargetBounds(
+ x: x,
+ y: y,
+ width: width,
+ height: height
+ )
+ }
+}
+
+private extension Array where Element: Hashable {
+ func uniqued() -> [Element] {
+ var seen = Set<Element>()
+ return filter { seen.insert($0).inserted }
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MacWindowResolverTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MacWindowResolverTests.swift
new file mode 100644
index 00000000..618c3aa3
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MacWindowResolverTests.swift
@@ -0,0 +1,280 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct MacWindowResolverTests {
+ @Test
+ func windowCandidateMetadataRoundTripsThroughJSON() throws {
+ let candidate = MacWindowTargetCandidate(
+ windowID: 42,
+ processID: 9001,
+ appName: "Notes",
+ bundleIdentifier: "com.apple.Notes",
+ title: "Project Notes",
+ bounds: WindowTargetBounds(x: 10, y: 20, width: 300, height: 400),
+ isVisible: true,
+ isOnScreen: true,
+ isFrontmost: true,
+ isFocused: true,
+ isIPhoneMirroring: false,
+ safetyAssessment: WindowTargetSafetyAssessment(
+ status: .allowed,
+ summary: "No sensitive surface indicators detected"
+ )
+ )
+
+ let data = try JSONEncoder().encode(candidate)
+ let decoded = try JSONDecoder().decode(
+ MacWindowTargetCandidate.self,
+ from: data
+ )
+
+ #expect(decoded == candidate)
+ #expect(decoded.bounds == WindowTargetBounds(x: 10, y: 20, width: 300, height: 400))
+ }
+
+ @Test
+ func explicitWindowSelectionUsesRequestedWindowID() throws {
+ let resolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(windowID: 1, processID: 100, appName: "Terminal"),
+ fixtureWindow(windowID: 2, processID: 200, appName: "Safari")
+ ],
+ frontmostProcessID: 100
+ )
+ )
+
+ let selected = try resolver.selectTarget(
+ MacWindowSelectionRequest(windowID: 2)
+ )
+
+ #expect(selected.windowID == 2)
+ #expect(selected.appName == "Safari")
+ }
+
+ @Test
+ func focusedWindowSelectionFallsBackToFrontmostCandidate() throws {
+ let resolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(windowID: 1, processID: 100, appName: "Terminal"),
+ fixtureWindow(windowID: 2, processID: 200, appName: "Safari"),
+ fixtureWindow(windowID: 3, processID: 200, appName: "Safari", title: "Background Tab")
+ ],
+ frontmostProcessID: 200
+ )
+ )
+
+ let candidates = resolver.enumerateCandidates()
+ let selected = try resolver.selectTarget()
+
+ #expect(selected.windowID == 2)
+ #expect(candidates.first(where: { $0.windowID == 2 })?.isFocused == true)
+ #expect(candidates.first(where: { $0.windowID == 3 })?.isFocused == false)
+ }
+
+ @Test
+ func focusedWindowIdentifierWinsWhenProvided() throws {
+ let resolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(windowID: 1, processID: 100, appName: "Terminal"),
+ fixtureWindow(windowID: 2, processID: 200, appName: "Safari"),
+ fixtureWindow(windowID: 3, processID: 200, appName: "Safari", title: "Focused Tab")
+ ],
+ frontmostProcessID: 200,
+ focusedWindowID: 3
+ )
+ )
+
+ let selected = try resolver.selectTarget()
+
+ #expect(selected.windowID == 3)
+ #expect(selected.isFocused)
+ #expect(selected.isFrontmost)
+ }
+
+ @Test
+ func missingExplicitWindowSelectionFailsDeterministically() {
+ let resolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(windowID: 1, processID: 100, appName: "Terminal")
+ ],
+ frontmostProcessID: 100
+ )
+ )
+
+ do {
+ _ = try resolver.selectTarget(MacWindowSelectionRequest(windowID: 999))
+ Issue.record("Expected missing window selection to fail")
+ } catch MacWindowResolverError.windowNotFound(let windowID) {
+ #expect(windowID == 999)
+ } catch {
+ Issue.record("Unexpected error: \(error)")
+ }
+ }
+
+ @Test
+ func iPhoneMirroringIsNormalVisibleCandidateWithHint() {
+ let resolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(
+ windowID: 7,
+ processID: 700,
+ appName: "iPhone Mirroring",
+ bundleIdentifier: "com.apple.ScreenContinuity",
+ title: "David's iPhone"
+ )
+ ],
+ frontmostProcessID: 700
+ )
+ )
+
+ let candidates = resolver.enumerateCandidates()
+
+ #expect(candidates.map(\.windowID) == [7])
+ #expect(candidates.first?.isIPhoneMirroring == true)
+ #expect(candidates.first?.safetyAssessment.status == .allowed)
+ }
+
+ @Test
+ func safetyClassificationMarksSensitiveAndUnknownSurfaces() {
+ let resolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(
+ windowID: 1,
+ processID: 100,
+ appName: "Notes",
+ bundleIdentifier: "com.apple.Notes",
+ title: "Shopping List"
+ ),
+ fixtureWindow(
+ windowID: 2,
+ processID: 200,
+ appName: "Safari",
+ title: "Password Sign In"
+ ),
+ fixtureWindow(
+ windowID: 3,
+ processID: 300,
+ appName: "Safari",
+ title: "Checkout Payment"
+ ),
+ fixtureWindow(
+ windowID: 4,
+ processID: 400,
+ appName: "System Settings",
+ bundleIdentifier: "com.apple.systempreferences",
+ title: "Privacy & Security Accessibility Permission"
+ ),
+ fixtureWindow(windowID: 5, processID: 500)
+ ],
+ frontmostProcessID: 100
+ )
+ )
+
+ let candidates = Dictionary(
+ uniqueKeysWithValues: resolver.enumerateCandidates().map {
+ ($0.windowID, $0.safetyAssessment)
+ }
+ )
+
+ #expect(candidates[1]?.status == .allowed)
+ #expect(candidates[2]?.status == .blocked)
+ #expect(candidates[2]?.reasons.contains(.loginSurface) == true)
+ #expect(candidates[2]?.reasons.contains(.passwordSurface) == true)
+ #expect(candidates[3]?.status == .blocked)
+ #expect(candidates[3]?.reasons.contains(.paymentSurface) == true)
+ #expect(candidates[4]?.status == .blocked)
+ #expect(candidates[4]?.reasons.contains(.systemSurface) == true)
+ #expect(candidates[4]?.reasons.contains(.permissionSurface) == true)
+ #expect(candidates[5]?.status == .reviewRequired)
+ #expect(candidates[5]?.reasons == [.unknownSurface])
+ }
+
+ @Test
+ func enumerationFiltersNonVisibleWindows() {
+ let resolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(windowID: 1, processID: 100, appName: "Visible"),
+ fixtureWindow(windowID: 2, processID: 200, appName: "Transparent", alpha: 0),
+ fixtureWindow(windowID: 3, processID: 300, appName: "Desktop", layer: 1),
+ fixtureWindow(windowID: 4, processID: 400, appName: "Offscreen", isOnScreen: false),
+ fixtureWindow(
+ windowID: 5,
+ processID: 500,
+ appName: "Zero Size",
+ bounds: WindowTargetBounds(x: 0, y: 0, width: 0, height: 100)
+ )
+ ],
+ frontmostProcessID: 100
+ )
+ )
+
+ #expect(resolver.enumerateCandidates().map(\.windowID) == [1])
+ }
+
+ 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
+ ),
+ alpha: Double = 1,
+ layer: Int = 0,
+ isOnScreen: Bool = true
+ ) -> MacWindowProviderWindow {
+ MacWindowProviderWindow(
+ windowID: windowID,
+ processID: processID,
+ appName: appName,
+ bundleIdentifier: bundleIdentifier,
+ title: title,
+ bounds: bounds,
+ alpha: alpha,
+ layer: layer,
+ isOnScreen: isOnScreen
+ )
+ }
+}
+
+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 ef8f6428..8a926150 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -25,7 +25,9 @@ accessibility/
The artifact store can append ordered event records, reserve safe screenshot or Accessibility artifact paths, record artifact metadata, and keep `summary.json` current.
-This is a coordination and trace foundation only. It does not capture the screen, run perception models, call LLMs, execute OS input, or wire coordinator events into disk persistence yet.
+Donkey can also resolve visible macOS target-window metadata for the manual capture path. The resolver enumerates on-screen app windows, describes window id, pid, app name, bundle id, title, bounds, focus/frontmost state, iPhone Mirroring hints, and conservative safety metadata. Callers can select an explicit window id or fall back to the focused/frontmost visible window.
+
+This is a coordination, trace, and target-metadata foundation only. It does not capture the screen, dump Accessibility trees, run perception models, call LLMs, execute OS input, or wire coordinator events into disk persistence yet.
## Technical Guidelines
@@ -33,6 +35,7 @@ This is a coordination and trace foundation only. It does not capture the screen
- Keep coordinator state and append ordering in `DonkeyRuntime`; UI code should read status through narrow provider boundaries.
- Treat `RunCoordinator` as the owner of lifecycle and event ordering, not as the owner of perception, controller internals, or input backends.
- 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.
- 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.
@@ -46,11 +49,13 @@ 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, and summary updates.
+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, and deterministic window resolver behavior through fixture providers.
## Source Entry Points
- Runtime contracts live in `apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift`.
+- Window target contracts live in `apps/Donkey/Sources/DonkeyContracts/WindowTargetContracts.swift`.
- Runtime coordination lives in `apps/Donkey/Sources/DonkeyRuntime/`.
+- macOS window resolution lives in `apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift`.
- Local artifact persistence lives in `apps/Donkey/Sources/DonkeyRuntime/LocalRunArtifactStore.swift`.
-- The source plan remains active in `plans/20-off-the-shelf-run-loop.md`.
+- The manual capture source plan remains active in `plans/master-plan.md`.
diff --git a/plans/master-plan.md b/plans/master-plan.md
index d9f53a4f..7566b799 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -84,21 +84,21 @@ Out of scope:
### Target Window Resolution
-- Add a macOS target resolver that can enumerate and describe candidate windows:
- - pid
- - app name or bundle id when available
- - window title
- - bounds in screen coordinates
- - focus/frontmost status
-- Support explicit targeting by window id, pid/title tuple, or selected candidate from a debug UI/command.
-- Use the focused window only as a default when no explicit target is provided.
-- Treat iPhone Mirroring as a normal candidate window with optional target-specific metadata.
-- Stop and record a safe failure if the target appears to be a system prompt, payment/login surface, or unknown sensitive window.
+Supported as the second vertical slice. `MacWindowResolver` enumerates visible on-screen macOS app windows, normalizes window metadata, supports explicit selection by window id, falls back to the focused/frontmost candidate, marks iPhone Mirroring as a normal candidate with a hint, and attaches conservative safety metadata.
+
+Current boundaries:
+
+- Window candidate numbering is not durable. A debug UI or command should map short labels like "window 1" to the candidate's macOS `windowID` at the time the user chooses.
+- Selection by pid/title tuple is still future-facing. Current deterministic selection is explicit window id or focused/frontmost fallback.
+- Safety classification is metadata-only. Later capture orchestration must refuse or safety-stop blocked/review-required targets before writing screenshots.
+- Overlap is not solved by metadata alone. Screenshot capture must avoid accidentally recording another window that visually covers the selected target.
### Screenshot Capture
- Start with one manual screenshot per run.
-- Capture the explicitly selected target window bounds, not the whole desktop by default.
+- Capture the explicitly selected target window, not the whole desktop by default.
+- Prefer a true window-scoped capture path when available so overlapping windows do not contaminate the artifact.
+- If the first implementation must use a bounds crop, validate that the selected target is frontmost/focused immediately before capture, record the capture method as overlap-sensitive, and safety-stop when another visible window appears to cover the target bounds.
- Store screenshots under the prepared run folder:
```text
@@ -114,6 +114,7 @@ Out of scope:
- coordinate space
- image size
- capture method
+ - occlusion/overlap validation result when available
### Accessibility Tree Snapshot
@@ -168,11 +169,12 @@ accessibility/
- The trace folder contains `events.jsonl`, `summary.json`, one screenshot artifact, and one Accessibility snapshot when permission is available.
- The capture flow records ordered `tool` and `lifecycle` events through `RunCoordinator`.
- Screenshot capture is target/window scoped by default.
+- Overlapping windows do not silently produce misleading target screenshots. The capture path either uses true window capture or records/refuses an overlap-sensitive bounds crop when the target is occluded.
- Accessibility tree capture is shallow, bounded, and serializable.
- Missing Accessibility permission produces a clear event and a partial run summary instead of crashing.
- Input and Accessibility actions remain disabled.
- Sensitive/system/payment/login windows are refused or marked as safety stops.
-- Unit tests cover metadata serialization, run artifact path generation, artifact summary updates, bounded AX tree serialization, and policy denial for input.
+- Unit tests cover metadata serialization, target selection rules, run artifact path generation, artifact summary updates, bounded AX tree serialization, overlap/occlusion safety behavior, and policy denial for input.
- Manual verification works against at least two different windows, such as iPhone Mirroring and a normal Mac app window.
## Handoff Notes For The Next LLM
@@ -189,20 +191,23 @@ accessibility/
## What Should Be Done Next
-Continue the read-only vertical slice from the completed local artifact writer:
-
-1. Add window enumeration and target selection metadata.
- - Add a macOS window resolver in `DonkeyRuntime` that returns visible candidate windows with window id, pid, app name or bundle id, title, bounds, and frontmost/focus metadata.
- - Support explicit selection by window id and a focused-window default when no explicit target is provided.
- - Treat iPhone Mirroring as a normal visible candidate, not a special-only path.
- - Add conservative safety metadata so later capture can refuse obvious system, login, payment, or unknown sensitive surfaces.
- - Add tests for metadata serialization, target selection rules, focused-window fallback, and safety classification.
-2. Add one target-scoped screenshot artifact.
- - Capture the selected target bounds, write PNG bytes through `LocalRunArtifactStore`, and record screenshot artifact metadata.
+Continue the read-only vertical slice from the completed local artifact writer and window resolver:
+
+1. Add one overlap-aware target screenshot artifact.
+ - Resolve a `MacWindowTargetCandidate` from an explicit `windowID` or the focused/frontmost fallback.
+ - Refuse or safety-stop before capture when the target safety status is blocked or review-required.
+ - Prefer true window capture over bounds cropping so overlapping windows do not contaminate the selected target artifact.
+ - If bounds cropping is the only available first implementation, add occlusion checks from the ordered window list and refuse/record a partial run when another visible window overlaps the selected target.
+ - Write PNG bytes through `LocalRunArtifactStore` and record screenshot artifact metadata, including target metadata, capture method, coordinate space, image size, and overlap validation result.
+ - Add tests with fixture window providers for safe capture, blocked target refusal, and occluded bounds-crop refusal.
+2. Add candidate-list support for manual/debug selection.
+ - Provide a small read-only API that returns ordered visible candidates with ephemeral labels such as `window 1`, `window 2`, and their durable `windowID` values.
+ - Make clear that labels are valid only for the current enumeration snapshot; follow-up commands should carry the durable `windowID`.
+ - Add tests that labels remain deterministic for one snapshot and that explicit `windowID` selection is used for multi-window flows.
3. 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.
4. 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.
5. 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.
+ - Manually verify against iPhone Mirroring and at least one other visible Mac app window, including an overlapped-window scenario.