Open source CapCut alternative.
TypeScript
Added screenshot capture
David Le1aaef3339edf
diff --git a/AGENTS.md b/AGENTS.mdindex 79c0f3db..fd4a145b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -3,9 +3,13 @@This repo has two kinds of written context:- `docs/`: supported product behavior and engineering guidance.-- `plans/`: exploratory or historical implementation planning.+- `plans/`: active, exploratory, or historical implementation planning.-Start with `docs/README.md` when changing supported behavior. Use `plans/` only for background unless the user explicitly asks to plan.+Start with `docs/README.md` when changing supported behavior.++Use `plans/master-plan.md` as the active implementation driver when it exists and is not in `plans/done/`. It exists to coordinate the current multi-step milestone: what is already supported, what remains next, and which older plans should be treated as background or cleanup targets. Before taking the next implementation slice, read the master plan, follow its "What Should Be Done Next" section, and update it when a slice becomes supported.++Use other `plans/` files only for background unless the user explicitly asks to plan from them or the master plan names them as cleanup targets. Do not let older plans override the current master plan.## Working Rules@@ -13,6 +17,7 @@ Start with `docs/README.md` when changing supported behavior. Use `plans/` only- Manage plans deliberately: move a plan to `plans/done/` when its work is complete, and create or keep plans only for work that remains.- Over time, prefer shrinking active `plans/` by completing work and moving finished plans to `plans/done/`.- When a completed capability changes, update the relevant guide in `docs/guides/`.+- When work completes a master-plan slice, update the master plan's supported/current-boundary language and next steps in the same change.- Keep guides explanatory. Describe supported behavior, boundaries, and engineering intent; do not duplicate code or maintain long file inventories.- Link to source paths only when a maintainer needs an entrypoint.- Keep this file stable and lightweight.diff --git a/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swiftnew file mode 100644index 00000000..c92757f3--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift@@ -0,0 +1,366 @@+import CoreGraphics+import DonkeyContracts+import Foundation+import ImageIO+import ScreenCaptureKit+import UniformTypeIdentifiers++public enum WindowScreenshotCaptureMethod: String, Codable, Equatable, Sendable {+ case screenCaptureKitDesktopIndependentWindow+ case boundsCrop+}++public enum WindowScreenshotOverlapStatus: String, Codable, Equatable, Sendable {+ case notRequired+ case clear+ case occluded+}++public enum WindowScreenshotCaptureError: Error, Equatable, Sendable {+ case missingPreparedRun(runID: String)+ case unsafeTarget(+ windowID: UInt32,+ status: WindowTargetSafetyStatus+ )+ case occludedTarget(+ windowID: UInt32,+ occludingWindowID: UInt32+ )+ case targetWindowUnavailable(windowID: UInt32)+ case captureFailed(windowID: UInt32, reason: String)+ case pngEncodingFailed(windowID: UInt32)+}++public struct WindowScreenshotCaptureResult: Equatable, Sendable {+ public var target: MacWindowTargetCandidate+ public var artifact: RunArtifactRecord+ public var imageWidth: Int+ public var imageHeight: Int+ public var captureMethod: WindowScreenshotCaptureMethod+ public var overlapStatus: WindowScreenshotOverlapStatus++ public init(+ target: MacWindowTargetCandidate,+ artifact: RunArtifactRecord,+ imageWidth: Int,+ imageHeight: Int,+ captureMethod: WindowScreenshotCaptureMethod,+ overlapStatus: WindowScreenshotOverlapStatus+ ) {+ self.target = target+ self.artifact = artifact+ self.imageWidth = imageWidth+ self.imageHeight = imageHeight+ self.captureMethod = captureMethod+ self.overlapStatus = overlapStatus+ }+}++struct CapturedWindowScreenshot: Equatable, Sendable {+ var pngData: Data+ var imageWidth: Int+ var imageHeight: Int+ var captureMethod: WindowScreenshotCaptureMethod+ var coordinateSpace: String++ init(+ pngData: Data,+ imageWidth: Int,+ imageHeight: Int,+ captureMethod: WindowScreenshotCaptureMethod,+ coordinateSpace: String+ ) {+ self.pngData = pngData+ self.imageWidth = imageWidth+ self.imageHeight = imageHeight+ self.captureMethod = captureMethod+ self.coordinateSpace = coordinateSpace+ }+}++protocol WindowScreenshotCapturing {+ var captureMethod: WindowScreenshotCaptureMethod { get }+ var requiresOverlapFreeTarget: Bool { get }++ func capture(+ target: MacWindowTargetCandidate+ ) async throws -> CapturedWindowScreenshot+}++public final class WindowScreenshotCaptureService {+ private let artifactStore: LocalRunArtifactStore+ private let windowResolver: MacWindowResolver+ private let capturer: any WindowScreenshotCapturing++ public convenience init(artifactStore: LocalRunArtifactStore) {+ self.init(+ artifactStore: artifactStore,+ windowResolver: MacWindowResolver(),+ capturer: ScreenCaptureKitWindowScreenshotCapturer()+ )+ }++ init(+ artifactStore: LocalRunArtifactStore,+ windowResolver: MacWindowResolver,+ capturer: any WindowScreenshotCapturing+ ) {+ self.artifactStore = artifactStore+ self.windowResolver = windowResolver+ self.capturer = capturer+ }++ public func captureScreenshot(+ runID: String,+ selection: MacWindowSelectionRequest = MacWindowSelectionRequest(),+ artifactID: String = "screenshot-\(UUID().uuidString)"+ ) async throws -> WindowScreenshotCaptureResult {+ let summary: RunTraceSummary+ do {+ summary = try await artifactStore.summary(runID: runID)+ } catch LocalRunArtifactStoreError.missingSummary {+ throw WindowScreenshotCaptureError.missingPreparedRun(runID: runID)+ }++ let candidates = windowResolver.enumerateCandidates()+ let target = try selectTarget(selection, from: candidates)+ guard target.safetyAssessment.status == .allowed else {+ throw WindowScreenshotCaptureError.unsafeTarget(+ windowID: target.windowID,+ status: target.safetyAssessment.status+ )+ }++ let overlapStatus = try validateOverlap(+ for: target,+ in: candidates+ )++ let screenshot: CapturedWindowScreenshot+ do {+ screenshot = try await capturer.capture(target: target)+ } catch let error as WindowScreenshotCaptureError {+ throw error+ } catch {+ throw WindowScreenshotCaptureError.captureFailed(+ windowID: target.windowID,+ reason: String(describing: error)+ )+ }++ let reservedPath = try await artifactStore.reserveArtifactPath(+ runID: runID,+ artifactID: artifactID,+ kind: .screenshot,+ fileExtension: "png"+ )+ try screenshot.pngData.write(to: reservedPath.fileURL, options: .atomic)++ let artifact = try await artifactStore.recordArtifact(+ runID: runID,+ artifactID: reservedPath.artifactID,+ kind: .screenshot,+ relativePath: reservedPath.relativePath,+ contentType: "image/png",+ byteCount: Int64(screenshot.pngData.count),+ metadata: metadata(+ runID: runID,+ traceID: summary.traceID,+ target: target,+ screenshot: screenshot,+ overlapStatus: overlapStatus+ )+ )++ return WindowScreenshotCaptureResult(+ target: target,+ artifact: artifact,+ imageWidth: screenshot.imageWidth,+ imageHeight: screenshot.imageHeight,+ captureMethod: screenshot.captureMethod,+ overlapStatus: overlapStatus+ )+ }++ private func selectTarget(+ _ selection: MacWindowSelectionRequest,+ from candidates: [MacWindowTargetCandidate]+ ) throws -> MacWindowTargetCandidate {+ guard !candidates.isEmpty else {+ throw MacWindowResolverError.noVisibleWindows+ }++ if let windowID = selection.windowID {+ guard let target = candidates.first(where: { $0.windowID == windowID }) else {+ throw MacWindowResolverError.windowNotFound(windowID: windowID)+ }++ return target+ }++ if let focused = candidates.first(where: \.isFocused) {+ return focused+ }++ if let frontmost = candidates.first(where: \.isFrontmost) {+ return frontmost+ }++ throw MacWindowResolverError.noFocusedWindow+ }++ private func validateOverlap(+ for target: MacWindowTargetCandidate,+ in candidates: [MacWindowTargetCandidate]+ ) throws -> WindowScreenshotOverlapStatus {+ guard capturer.requiresOverlapFreeTarget else {+ return .notRequired+ }++ guard let targetIndex = candidates.firstIndex(where: { $0.windowID == target.windowID }) else {+ return .clear+ }++ if let occludingWindow = candidates[..<targetIndex].first(where: { candidate in+ candidate.windowID != target.windowID+ && candidate.isVisible+ && candidate.isOnScreen+ && candidate.bounds.intersects(target.bounds)+ }) {+ throw WindowScreenshotCaptureError.occludedTarget(+ windowID: target.windowID,+ occludingWindowID: occludingWindow.windowID+ )+ }++ return .clear+ }++ private func metadata(+ runID: String,+ traceID: String,+ target: MacWindowTargetCandidate,+ screenshot: CapturedWindowScreenshot,+ overlapStatus: WindowScreenshotOverlapStatus+ ) -> [String: String] {+ var metadata = [+ "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: ","),+ "capture.method": screenshot.captureMethod.rawValue,+ "capture.coordinateSpace": screenshot.coordinateSpace,+ "capture.imageWidth": String(screenshot.imageWidth),+ "capture.imageHeight": String(screenshot.imageHeight),+ "capture.overlapStatus": overlapStatus.rawValue+ ]++ if let appName = target.appName {+ metadata["target.appName"] = appName+ }++ if let bundleIdentifier = target.bundleIdentifier {+ metadata["target.bundleIdentifier"] = bundleIdentifier+ }++ if let title = target.title {+ metadata["target.title"] = title+ }++ return metadata+ }+}++private final class ScreenCaptureKitWindowScreenshotCapturer: WindowScreenshotCapturing {+ var captureMethod: WindowScreenshotCaptureMethod {+ .screenCaptureKitDesktopIndependentWindow+ }++ var requiresOverlapFreeTarget: Bool {+ false+ }++ func capture(+ target: MacWindowTargetCandidate+ ) async throws -> CapturedWindowScreenshot {+ let content = try await SCShareableContent.current+ guard let window = content.windows.first(where: { $0.windowID == target.windowID }) else {+ throw WindowScreenshotCaptureError.targetWindowUnavailable(windowID: target.windowID)+ }++ let filter = SCContentFilter(desktopIndependentWindow: window)+ let contentInfo = SCShareableContent.info(for: filter)+ let scale = CGFloat(contentInfo.pointPixelScale)+ let configuration = SCStreamConfiguration()+ configuration.width = max(1, Int(ceil(contentInfo.contentRect.width * scale)))+ configuration.height = max(1, Int(ceil(contentInfo.contentRect.height * scale)))+ configuration.showsCursor = false+ configuration.capturesAudio = false+ configuration.ignoreShadowsSingleWindow = true+ configuration.ignoreGlobalClipSingleWindow = true++ let image = try await SCScreenshotManager.captureImage(+ contentFilter: filter,+ configuration: configuration+ )+ let pngData = try Self.pngData(+ for: image,+ windowID: target.windowID+ )++ return CapturedWindowScreenshot(+ pngData: pngData,+ imageWidth: image.width,+ imageHeight: image.height,+ captureMethod: .screenCaptureKitDesktopIndependentWindow,+ coordinateSpace: "screenCaptureKit.contentRect.points"+ )+ }++ private static func pngData(+ for image: CGImage,+ windowID: UInt32+ ) throws -> Data {+ let data = NSMutableData()+ guard let destination = CGImageDestinationCreateWithData(+ data,+ UTType.png.identifier as CFString,+ 1,+ nil+ ) else {+ throw WindowScreenshotCaptureError.pngEncodingFailed(windowID: windowID)+ }++ CGImageDestinationAddImage(destination, image, nil)+ guard CGImageDestinationFinalize(destination) else {+ throw WindowScreenshotCaptureError.pngEncodingFailed(windowID: windowID)+ }++ return data as Data+ }+}++private extension WindowTargetBounds {+ func intersects(_ other: WindowTargetBounds) -> Bool {+ let maxX = x + width+ let maxY = y + height+ let otherMaxX = other.x + other.width+ let otherMaxY = other.y + other.height++ return x < otherMaxX+ && maxX > other.x+ && y < otherMaxY+ && maxY > other.y+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/WindowScreenshotCaptureServiceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/WindowScreenshotCaptureServiceTests.swiftnew file mode 100644index 00000000..bedb5142--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/WindowScreenshotCaptureServiceTests.swift@@ -0,0 +1,440 @@+import DonkeyContracts+@testable import DonkeyRuntime+import Foundation+import Testing++@Suite+struct WindowScreenshotCaptureServiceTests {+ @Test+ func safeTargetCaptureWritesPngBytesAndRecordsArtifactMetadata() async throws {+ let root = temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: root) }++ let store = try LocalRunArtifactStore(baseDirectory: root)+ let session = RunSession(+ id: "run-screenshot",+ userGoal: "capture context",+ targetID: "target-1"+ )+ _ = try await store.prepareRun(session: session, traceID: "trace-screenshot")+ let capturer = FakeWindowScreenshotCapturer(+ pngData: pngBytes(),+ imageWidth: 320,+ imageHeight: 240,+ captureMethod: .screenCaptureKitDesktopIndependentWindow,+ requiresOverlapFreeTarget: false+ )+ let service = makeService(+ store: store,+ windows: [+ fixtureWindow(windowID: 10, processID: 100, appName: "Notes", title: "Plan")+ ],+ frontmostProcessID: 100,+ capturer: capturer+ )++ let result = try await service.captureScreenshot(+ runID: "run-screenshot",+ artifactID: "screenshot-1"+ )++ #expect(result.target.windowID == 10)+ #expect(result.artifact.relativePath == "screenshots/screenshot-1.png")+ #expect(result.artifact.contentType == "image/png")+ #expect(result.artifact.byteCount == Int64(pngBytes().count))+ #expect(result.imageWidth == 320)+ #expect(result.imageHeight == 240)+ #expect(result.captureMethod == .screenCaptureKitDesktopIndependentWindow)+ #expect(result.overlapStatus == .notRequired)+ #expect(capturer.capturedWindowIDs == [10])++ let fileURL = root+ .appendingPathComponent("run-screenshot", isDirectory: true)+ .appendingPathComponent("screenshots/screenshot-1.png")+ #expect(try Data(contentsOf: fileURL) == pngBytes())++ let summary = try await store.summary(runID: "run-screenshot")+ #expect(summary.artifacts.count == 1)+ #expect(summary.artifacts.first?.metadata["runID"] == "run-screenshot")+ #expect(summary.artifacts.first?.metadata["traceID"] == "trace-screenshot")+ #expect(summary.artifacts.first?.metadata["target.windowID"] == "10")+ #expect(summary.artifacts.first?.metadata["target.appName"] == "Notes")+ #expect(summary.artifacts.first?.metadata["target.title"] == "Plan")+ #expect(summary.artifacts.first?.metadata["capture.method"] == "screenCaptureKitDesktopIndependentWindow")+ #expect(summary.artifacts.first?.metadata["capture.imageWidth"] == "320")+ #expect(summary.artifacts.first?.metadata["capture.imageHeight"] == "240")+ #expect(summary.artifacts.first?.metadata["capture.overlapStatus"] == "notRequired")+ }++ @Test+ func explicitWindowSelectionIsPassedToCapturer() 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-explicit", userGoal: "capture", targetID: "target-1"),+ traceID: "trace-explicit"+ )+ let capturer = FakeWindowScreenshotCapturer()+ 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 result = try await service.captureScreenshot(+ runID: "run-explicit",+ selection: MacWindowSelectionRequest(windowID: 2),+ artifactID: "screenshot-explicit"+ )++ #expect(result.target.windowID == 2)+ #expect(capturer.capturedWindowIDs == [2])+ }++ @Test+ func unsafeTargetRefusesBeforeWritingFileOrArtifact() 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-unsafe", userGoal: "capture", targetID: "target-1"),+ traceID: "trace-unsafe"+ )+ let capturer = FakeWindowScreenshotCapturer()+ let service = makeService(+ store: store,+ windows: [+ fixtureWindow(windowID: 10, processID: 100, appName: "Safari", title: "Checkout Payment")+ ],+ frontmostProcessID: 100,+ capturer: capturer+ )++ do {+ _ = try await service.captureScreenshot(+ runID: "run-unsafe",+ artifactID: "screenshot-unsafe"+ )+ Issue.record("Expected unsafe target to be refused")+ } catch WindowScreenshotCaptureError.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-unsafe")+ #expect(summary.artifacts.isEmpty)+ #expect(capturer.capturedWindowIDs.isEmpty)+ #expect(!fileExists(root+ .appendingPathComponent("run-unsafe", isDirectory: true)+ .appendingPathComponent("screenshots/screenshot-unsafe.png")))+ }++ @Test+ func missingPreparedRunFailsWithoutWritingFile() async throws {+ let root = temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: root) }++ let store = try LocalRunArtifactStore(baseDirectory: root)+ let capturer = FakeWindowScreenshotCapturer()+ let service = makeService(+ store: store,+ windows: [+ fixtureWindow(windowID: 10, processID: 100, appName: "Notes")+ ],+ frontmostProcessID: 100,+ capturer: capturer+ )++ do {+ _ = try await service.captureScreenshot(+ runID: "missing-run",+ artifactID: "screenshot-missing"+ )+ Issue.record("Expected missing prepared run to fail")+ } catch WindowScreenshotCaptureError.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("screenshots/screenshot-missing.png")))+ }++ @Test+ func fakeCapturerRecordsImageDimensionsAndMethodMetadata() 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-method", userGoal: "capture", targetID: "target-1"),+ traceID: "trace-method"+ )+ let service = makeService(+ store: store,+ windows: [+ fixtureWindow(windowID: 10, processID: 100, appName: "Preview")+ ],+ frontmostProcessID: 100,+ capturer: FakeWindowScreenshotCapturer(+ imageWidth: 640,+ imageHeight: 480,+ captureMethod: .boundsCrop,+ requiresOverlapFreeTarget: true+ )+ )++ let result = try await service.captureScreenshot(+ runID: "run-method",+ artifactID: "screenshot-method"+ )++ #expect(result.captureMethod == .boundsCrop)+ #expect(result.overlapStatus == .clear)+ #expect(result.imageWidth == 640)+ #expect(result.imageHeight == 480)++ let summary = try await store.summary(runID: "run-method")+ #expect(summary.artifacts.first?.metadata["capture.method"] == "boundsCrop")+ #expect(summary.artifacts.first?.metadata["capture.imageWidth"] == "640")+ #expect(summary.artifacts.first?.metadata["capture.imageHeight"] == "480")+ #expect(summary.artifacts.first?.metadata["capture.overlapStatus"] == "clear")+ }++ @Test+ func overlapSensitiveBackendRefusesOccludedBoundsCropTarget() 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-occluded", userGoal: "capture", targetID: "target-1"),+ traceID: "trace-occluded"+ )+ let capturer = FakeWindowScreenshotCapturer(+ captureMethod: .boundsCrop,+ requiresOverlapFreeTarget: true+ )+ let service = makeService(+ store: store,+ windows: [+ fixtureWindow(+ windowID: 1,+ processID: 100,+ appName: "Occluder",+ bounds: WindowTargetBounds(x: 25, y: 25, width: 50, height: 50)+ ),+ fixtureWindow(+ windowID: 2,+ processID: 200,+ appName: "Target",+ bounds: WindowTargetBounds(x: 0, y: 0, width: 100, height: 100)+ )+ ],+ frontmostProcessID: 200,+ capturer: capturer+ )++ do {+ _ = try await service.captureScreenshot(+ runID: "run-occluded",+ selection: MacWindowSelectionRequest(windowID: 2),+ artifactID: "screenshot-occluded"+ )+ Issue.record("Expected occluded bounds crop target to be refused")+ } catch WindowScreenshotCaptureError.occludedTarget(let windowID, let occludingWindowID) {+ #expect(windowID == 2)+ #expect(occludingWindowID == 1)+ } catch {+ Issue.record("Unexpected error: \(error)")+ }++ #expect(capturer.capturedWindowIDs.isEmpty)+ let summary = try await store.summary(runID: "run-occluded")+ #expect(summary.artifacts.isEmpty)+ }++ @Test+ func trueWindowBackendAllowsOverlappedTarget() 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-overlap-allowed", userGoal: "capture", targetID: "target-1"),+ traceID: "trace-overlap-allowed"+ )+ let capturer = FakeWindowScreenshotCapturer(+ captureMethod: .screenCaptureKitDesktopIndependentWindow,+ requiresOverlapFreeTarget: false+ )+ let service = makeService(+ store: store,+ windows: [+ fixtureWindow(+ windowID: 1,+ processID: 100,+ appName: "Occluder",+ bounds: WindowTargetBounds(x: 25, y: 25, width: 50, height: 50)+ ),+ fixtureWindow(+ windowID: 2,+ processID: 200,+ appName: "Target",+ bounds: WindowTargetBounds(x: 0, y: 0, width: 100, height: 100)+ )+ ],+ frontmostProcessID: 200,+ capturer: capturer+ )++ let result = try await service.captureScreenshot(+ runID: "run-overlap-allowed",+ selection: MacWindowSelectionRequest(windowID: 2),+ artifactID: "screenshot-overlap-allowed"+ )++ #expect(result.target.windowID == 2)+ #expect(result.overlapStatus == .notRequired)+ #expect(capturer.capturedWindowIDs == [2])+ }++ private func makeService(+ store: LocalRunArtifactStore,+ windows: [MacWindowProviderWindow],+ frontmostProcessID: Int32? = nil,+ focusedWindowID: UInt32? = nil,+ capturer: FakeWindowScreenshotCapturer+ ) -> WindowScreenshotCaptureService {+ WindowScreenshotCaptureService(+ 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 temporaryDirectory() -> URL {+ FileManager.default.temporaryDirectory.appendingPathComponent(+ "DonkeyWindowScreenshotTests-\(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 pngBytes() -> Data {+ Data([0x89, 0x50, 0x4E, 0x47])+ }+}++private final class FakeWindowScreenshotCapturer: WindowScreenshotCapturing {+ var pngData: Data+ var imageWidth: Int+ var imageHeight: Int+ var captureMethod: WindowScreenshotCaptureMethod+ var requiresOverlapFreeTarget: Bool+ var capturedWindowIDs: [UInt32] = []++ init(+ pngData: Data = Data([0x89, 0x50, 0x4E, 0x47]),+ imageWidth: Int = 100,+ imageHeight: Int = 100,+ captureMethod: WindowScreenshotCaptureMethod = .screenCaptureKitDesktopIndependentWindow,+ requiresOverlapFreeTarget: Bool = false+ ) {+ self.pngData = pngData+ self.imageWidth = imageWidth+ self.imageHeight = imageHeight+ self.captureMethod = captureMethod+ self.requiresOverlapFreeTarget = requiresOverlapFreeTarget+ }++ func capture(+ target: MacWindowTargetCandidate+ ) async throws -> CapturedWindowScreenshot {+ capturedWindowIDs.append(target.windowID)+ return CapturedWindowScreenshot(+ pngData: pngData,+ imageWidth: imageWidth,+ imageHeight: imageHeight,+ captureMethod: captureMethod,+ coordinateSpace: "fixture.pixels"+ )+ }+}++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.mdindex 8a926150..687da103 100644--- a/docs/guides/minimal-run-coordinator.md+++ b/docs/guides/minimal-run-coordinator.md@@ -27,7 +27,9 @@ The artifact store can append ordered event records, reserve safe screenshot orDonkey 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.+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.## Technical Guidelines@@ -36,6 +38,7 @@ This is a coordination, trace, and target-metadata foundation only. It does not- 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.+- 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.- 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.@@ -49,7 +52,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, and deterministic window resolver behavior through fixture providers.+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, screenshot artifact metadata, unsafe target refusal, and overlap-sensitive capture refusal.## Source Entry Points@@ -57,5 +60,6 @@ The runtime tests should cover lifecycle ordering, abort and timeout safety, lat- 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`.+- Target-window screenshot capture lives in `apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.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/master-plan.md b/plans/master-plan.mdindex 7566b799..4403075d 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -95,26 +95,20 @@ Current boundaries:### Screenshot Capture-- Start with one manual screenshot per run.-- 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:+Supported as the third vertical slice. `WindowScreenshotCaptureService` creates one read-only screenshot 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, captures the selected window with ScreenCaptureKit desktop-independent window capture, writes PNG bytes through the local artifact store, and records flattened target/capture metadata.++Screenshots are stored under the prepared run folder:```text<run-folder>/screenshots/<artifact-id>.png```-- Write sidecar metadata:- - artifact id- - run id- - trace id- - monotonic and wall-clock timestamps- - target/window metadata- - coordinate space- - image size- - capture method- - occlusion/overlap validation result when available+Current boundaries:++- The production path uses true window capture, so overlapping windows do not contaminate the artifact.+- Bounds-crop fallback behavior is represented by an overlap-sensitive capturer abstraction and tests, but no production bounds-crop backend is installed.+- Screen Recording/TCC denial surfaces as a capture failure and must not create an artifact record.+- The service does not publish `RunCoordinator` events yet.### Accessibility Tree Snapshot@@ -191,23 +185,16 @@ accessibility/## What Should Be Done Next-Continue the read-only vertical slice from the completed local artifact writer and window resolver:+Continue the read-only vertical slice from the completed local artifact writer, window resolver, and screenshot artifact service:-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.+1. 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.+2. 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.+3. 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.+4. 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.