Skip to content

Open source CapCut alternative.

TypeScript

Add manual capture debug entrypoint

David Le02fb792bba16
diff --git a/apps/Donkey/Package.swift b/apps/Donkey/Package.swift
index 95f6bcf6..b0cad930 100644
--- a/apps/Donkey/Package.swift
+++ b/apps/Donkey/Package.swift
@@ -38,6 +38,7 @@ let package = Package(
dependencies: [
"DonkeyAI",
"DonkeyContracts",
+ "DonkeyRuntime",
"DonkeyUI"
],
resources: [
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
index 5be96cdd..db4a5415 100644
--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
@@ -1,10 +1,22 @@
import AppKit
+import Darwin
@MainActor
final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
private var overlayController: PointerPromptOverlayController?
func applicationDidFinishLaunching(_ notification: Notification) {
+ if ManualCaptureDebugLaunchHandler.shouldHandle(arguments: CommandLine.arguments) {
+ NSApp.setActivationPolicy(.accessory)
+ Task {
+ let exitCode = await ManualCaptureDebugLaunchHandler().run(
+ arguments: CommandLine.arguments
+ )
+ Darwin.exit(exitCode)
+ }
+ return
+ }
+
NSApp.setActivationPolicy(.accessory)
let model = PointerPromptOverlayModel()
diff --git a/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift b/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift
new file mode 100644
index 00000000..9c84ef91
--- /dev/null
+++ b/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift
@@ -0,0 +1,73 @@
+import DonkeyContracts
+import DonkeyRuntime
+import Foundation
+
+@MainActor
+struct ManualCaptureDebugLaunchHandler {
+ static func shouldHandle(arguments: [String]) -> Bool {
+ ManualCaptureDebugCommandParser.containsDebugCommand(arguments: arguments)
+ }
+
+ func run(arguments: [String]) async -> Int32 {
+ do {
+ guard let command = try ManualCaptureDebugCommandParser.parse(arguments: arguments) else {
+ return 0
+ }
+
+ switch command {
+ case .listWindowCandidates:
+ printLines(
+ ManualCaptureDebugCommandFormatter.lines(
+ for: MacWindowResolver().enumerateCandidateList()
+ )
+ )
+ return 0
+ case .manualCapture(let options):
+ let artifactStore = try LocalRunArtifactStore()
+ let service = ManualTargetContextCaptureService(artifactStore: artifactStore)
+ let runID = options.runID ?? "manual-\(UUID().uuidString)"
+ let traceID = options.traceID ?? "trace-\(UUID().uuidString)"
+ let session = RunSession(
+ id: runID,
+ userGoal: "manual capture debug",
+ targetID: targetID(for: options.selection)
+ )
+ let result = try await service.capture(
+ session: session,
+ selection: options.selection,
+ traceID: traceID
+ )
+ let runDirectory = try await artifactStore.runDirectory(for: result.traceSummary.runID)
+
+ printLines(
+ ManualCaptureDebugCommandFormatter.lines(
+ for: result,
+ runDirectory: runDirectory
+ )
+ )
+ return 0
+ }
+ } catch {
+ printError(ManualCaptureDebugCommandFormatter.errorLine(for: error))
+ return 1
+ }
+ }
+
+ private func targetID(for selection: MacWindowSelectionRequest) -> String {
+ if let windowID = selection.windowID {
+ return "window-\(windowID)"
+ }
+
+ return "focused-or-frontmost-window"
+ }
+
+ private func printLines(_ lines: [String]) {
+ for line in lines {
+ print(line)
+ }
+ }
+
+ private func printError(_ line: String) {
+ FileHandle.standardError.write(Data("\(line)\n".utf8))
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift b/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift
new file mode 100644
index 00000000..0d62e675
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift
@@ -0,0 +1,266 @@
+import DonkeyContracts
+import Foundation
+
+public enum ManualCaptureDebugCommand: Equatable, Sendable {
+ case listWindowCandidates
+ case manualCapture(ManualCaptureDebugCaptureOptions)
+}
+
+public struct ManualCaptureDebugCaptureOptions: Equatable, Sendable {
+ public var selection: MacWindowSelectionRequest
+ public var runID: String?
+ public var traceID: String?
+
+ public init(
+ selection: MacWindowSelectionRequest = MacWindowSelectionRequest(),
+ runID: String? = nil,
+ traceID: String? = nil
+ ) {
+ self.selection = selection
+ self.runID = runID
+ self.traceID = traceID
+ }
+}
+
+public enum ManualCaptureDebugCommandParseError: Error, Equatable, Sendable, CustomStringConvertible {
+ case conflictingCommands
+ case missingCommand
+ case missingValue(String)
+ case invalidWindowID(String)
+ case invalidIdentifier(option: String, value: String)
+ case unsupportedOption(String)
+
+ public var description: String {
+ switch self {
+ case .conflictingCommands:
+ return "Use only one debug command: --list-window-candidates or --manual-capture."
+ case .missingCommand:
+ return "Use --list-window-candidates or --manual-capture before capture options."
+ case .missingValue(let option):
+ return "Missing value for \(option)."
+ case .invalidWindowID(let value):
+ return "Invalid --window-id value: \(value)."
+ case .invalidIdentifier(let option, let value):
+ return "Invalid \(option) value: \(value). Use letters, numbers, '.', '_', or '-'."
+ case .unsupportedOption(let option):
+ return "Unsupported manual capture debug option: \(option)."
+ }
+ }
+}
+
+public enum ManualCaptureDebugCommandParser {
+ public static func containsDebugCommand(arguments: [String]) -> Bool {
+ normalizedArguments(arguments).contains { argument in
+ argument == "--list-window-candidates"
+ || argument == "--manual-capture"
+ || argument == "--window-id"
+ || argument == "--run-id"
+ || argument == "--trace-id"
+ }
+ }
+
+ public static func parse(
+ arguments: [String]
+ ) throws -> ManualCaptureDebugCommand? {
+ let arguments = normalizedArguments(arguments)
+ guard containsDebugCommand(arguments: arguments) else {
+ return nil
+ }
+
+ var mode: ManualCaptureDebugCommandMode?
+ var windowID: UInt32?
+ var runID: String?
+ var traceID: String?
+ var index = 0
+
+ while index < arguments.count {
+ let argument = arguments[index]
+ switch argument {
+ case "--list-window-candidates":
+ try setMode(.listWindowCandidates, current: &mode)
+ index += 1
+ case "--manual-capture":
+ try setMode(.manualCapture, current: &mode)
+ index += 1
+ case "--window-id":
+ let value = try value(after: argument, in: arguments, at: index)
+ guard let parsed = UInt32(value) else {
+ throw ManualCaptureDebugCommandParseError.invalidWindowID(value)
+ }
+ windowID = parsed
+ index += 2
+ case "--run-id":
+ let value = try value(after: argument, in: arguments, at: index)
+ try validateIdentifier(value, option: argument)
+ runID = value
+ index += 2
+ case "--trace-id":
+ let value = try value(after: argument, in: arguments, at: index)
+ try validateIdentifier(value, option: argument)
+ traceID = value
+ index += 2
+ default:
+ throw ManualCaptureDebugCommandParseError.unsupportedOption(argument)
+ }
+ }
+
+ guard let mode else {
+ throw ManualCaptureDebugCommandParseError.missingCommand
+ }
+
+ switch mode {
+ case .listWindowCandidates:
+ guard windowID == nil, runID == nil, traceID == nil else {
+ throw ManualCaptureDebugCommandParseError.unsupportedOption(
+ "capture options require --manual-capture"
+ )
+ }
+ return .listWindowCandidates
+ case .manualCapture:
+ return .manualCapture(
+ ManualCaptureDebugCaptureOptions(
+ selection: MacWindowSelectionRequest(windowID: windowID),
+ runID: runID,
+ traceID: traceID
+ )
+ )
+ }
+ }
+
+ private static func setMode(
+ _ next: ManualCaptureDebugCommandMode,
+ current: inout ManualCaptureDebugCommandMode?
+ ) throws {
+ if let current, current != next {
+ throw ManualCaptureDebugCommandParseError.conflictingCommands
+ }
+
+ current = next
+ }
+
+ private static func value(
+ after option: String,
+ in arguments: [String],
+ at index: Int
+ ) throws -> String {
+ let valueIndex = index + 1
+ guard valueIndex < arguments.count else {
+ throw ManualCaptureDebugCommandParseError.missingValue(option)
+ }
+
+ let value = arguments[valueIndex]
+ guard !value.hasPrefix("--") else {
+ throw ManualCaptureDebugCommandParseError.missingValue(option)
+ }
+
+ return value
+ }
+
+ private static func validateIdentifier(
+ _ value: String,
+ option: String
+ ) throws {
+ let allowedScalars = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-")
+ let isSafe = !value.isEmpty
+ && value.count <= 128
+ && value != "."
+ && value != ".."
+ && value.unicodeScalars.allSatisfy { allowedScalars.contains($0) }
+
+ guard isSafe else {
+ throw ManualCaptureDebugCommandParseError.invalidIdentifier(
+ option: option,
+ value: value
+ )
+ }
+ }
+
+ private static func normalizedArguments(_ arguments: [String]) -> [String] {
+ var normalized = arguments
+ if let first = normalized.first, !first.hasPrefix("--") {
+ normalized.removeFirst()
+ }
+
+ if normalized.first == "--" {
+ normalized.removeFirst()
+ }
+
+ return normalized
+ }
+}
+
+public enum ManualCaptureDebugCommandFormatter {
+ public static func lines(
+ for snapshot: MacWindowCandidateListSnapshot
+ ) -> [String] {
+ guard !snapshot.candidates.isEmpty else {
+ return ["No visible window candidates found."]
+ }
+
+ return snapshot.candidates.map { labeled in
+ let candidate = labeled.candidate
+ return [
+ labeled.label,
+ "windowID=\(candidate.windowID)",
+ "app=\(candidate.appName ?? "-")",
+ "title=\(candidate.title ?? "-")",
+ "safety=\(candidate.safetyAssessment.status.rawValue)",
+ "iPhoneMirroring=\(candidate.isIPhoneMirroring)"
+ ]
+ .joined(separator: " | ")
+ }
+ }
+
+ public static func lines(
+ for result: ManualTargetContextCaptureResult,
+ runDirectory: URL
+ ) -> [String] {
+ var lines = [
+ "manual capture completed",
+ "runID=\(result.traceSummary.runID)",
+ "traceID=\(result.traceSummary.traceID)",
+ "runFolder=\(runDirectory.path)",
+ "target.windowID=\(result.target.windowID)",
+ "screenshot=\(artifactURL(runDirectory: runDirectory, relativePath: result.screenshot.artifact.relativePath).path)"
+ ]
+
+ switch result.accessibility {
+ case .captured(let accessibilityResult):
+ lines.append("accessibility=captured")
+ lines.append(
+ "accessibilityArtifact=\(artifactURL(runDirectory: runDirectory, relativePath: accessibilityResult.artifact.relativePath).path)"
+ )
+ case .permissionDenied:
+ lines.append("accessibility=permissionDenied")
+ case .skipped(let reason):
+ lines.append("accessibility=skipped")
+ lines.append("accessibilityReason=\(reason)")
+ }
+
+ return lines
+ }
+
+ public static func errorLine(for error: Error) -> String {
+ if let parseError = error as? ManualCaptureDebugCommandParseError {
+ return "manual capture debug error: \(parseError.description)"
+ }
+
+ return "manual capture debug error: \(String(describing: error))"
+ }
+
+ private static func artifactURL(
+ runDirectory: URL,
+ relativePath: String
+ ) -> URL {
+ relativePath
+ .split(separator: "/")
+ .reduce(runDirectory) { url, component in
+ url.appendingPathComponent(String(component), isDirectory: false)
+ }
+ }
+}
+
+private enum ManualCaptureDebugCommandMode {
+ case listWindowCandidates
+ case manualCapture
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift
new file mode 100644
index 00000000..352968b1
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift
@@ -0,0 +1,322 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct ManualCaptureDebugCommandTests {
+ @Test
+ func noArgumentsAreNotHandled() throws {
+ let command = try ManualCaptureDebugCommandParser.parse(arguments: [])
+
+ #expect(command == nil)
+ #expect(!ManualCaptureDebugCommandParser.containsDebugCommand(arguments: []))
+ }
+
+ @Test
+ func listWindowCandidatesSelectsListMode() throws {
+ let command = try ManualCaptureDebugCommandParser.parse(
+ arguments: ["Donkey", "--", "--list-window-candidates"]
+ )
+
+ #expect(command == .listWindowCandidates)
+ #expect(ManualCaptureDebugCommandParser.containsDebugCommand(
+ arguments: ["Donkey", "--", "--list-window-candidates"]
+ ))
+ }
+
+ @Test
+ func manualCaptureWindowIDBuildsDurableSelection() throws {
+ let command = try ManualCaptureDebugCommandParser.parse(
+ arguments: [
+ "Donkey",
+ "--manual-capture",
+ "--window-id",
+ "22",
+ "--run-id",
+ "run.debug-1",
+ "--trace-id",
+ "trace.debug-1"
+ ]
+ )
+
+ #expect(command == .manualCapture(
+ ManualCaptureDebugCaptureOptions(
+ selection: MacWindowSelectionRequest(windowID: 22),
+ runID: "run.debug-1",
+ traceID: "trace.debug-1"
+ )
+ ))
+ }
+
+ @Test
+ func invalidWindowIDReturnsCommandError() throws {
+ #expect(throws: ManualCaptureDebugCommandParseError.invalidWindowID("window 2")) {
+ _ = try ManualCaptureDebugCommandParser.parse(
+ arguments: ["--manual-capture", "--window-id", "window 2"]
+ )
+ }
+ }
+
+ @Test
+ func missingWindowIDValueReturnsCommandError() throws {
+ #expect(throws: ManualCaptureDebugCommandParseError.missingValue("--window-id")) {
+ _ = try ManualCaptureDebugCommandParser.parse(
+ arguments: ["--manual-capture", "--window-id"]
+ )
+ }
+ }
+
+ @Test
+ func invalidRunIDAndTraceIDReturnCommandErrors() throws {
+ #expect(throws: ManualCaptureDebugCommandParseError.invalidIdentifier(
+ option: "--run-id",
+ value: "../run"
+ )) {
+ _ = try ManualCaptureDebugCommandParser.parse(
+ arguments: ["--manual-capture", "--run-id", "../run"]
+ )
+ }
+
+ #expect(throws: ManualCaptureDebugCommandParseError.invalidIdentifier(
+ option: "--trace-id",
+ value: " "
+ )) {
+ _ = try ManualCaptureDebugCommandParser.parse(
+ arguments: ["--manual-capture", "--trace-id", " "]
+ )
+ }
+ }
+
+ @Test
+ func missingRunIDAndTraceIDValuesReturnCommandErrors() throws {
+ #expect(throws: ManualCaptureDebugCommandParseError.missingValue("--run-id")) {
+ _ = try ManualCaptureDebugCommandParser.parse(
+ arguments: ["--manual-capture", "--run-id"]
+ )
+ }
+
+ #expect(throws: ManualCaptureDebugCommandParseError.missingValue("--trace-id")) {
+ _ = try ManualCaptureDebugCommandParser.parse(
+ arguments: ["--manual-capture", "--trace-id"]
+ )
+ }
+ }
+
+ @Test
+ func listFormatterPrintsLabelsAndDurableWindowIDsInResolverOrder() {
+ let snapshot = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(windowID: 11, processID: 100, appName: "Terminal", title: "Shell"),
+ fixtureWindow(windowID: 22, processID: 200, appName: "Safari", title: "Docs")
+ ],
+ frontmostProcessID: 100
+ )
+ )
+ .enumerateCandidateList()
+
+ let lines = ManualCaptureDebugCommandFormatter.lines(for: snapshot)
+
+ #expect(lines == [
+ "window 1 | windowID=11 | app=Terminal | title=Shell | safety=allowed | iPhoneMirroring=false",
+ "window 2 | windowID=22 | app=Safari | title=Docs | safety=allowed | iPhoneMirroring=false"
+ ])
+ }
+
+ @Test
+ func manualCaptureModeCanDriveExistingServiceWithExplicitWindowID() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let command = try ManualCaptureDebugCommandParser.parse(
+ arguments: ["--manual-capture", "--window-id", "22"]
+ )
+ guard case .manualCapture(let options) = command else {
+ Issue.record("Expected manual capture command")
+ return
+ }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ let screenshotCapturer = FakeWindowScreenshotCapturer()
+ let accessibilityCapturer = FakeMacAccessibilitySnapshotCapturer()
+ let service = makeManualService(
+ store: store,
+ windows: [
+ fixtureWindow(windowID: 11, processID: 100, appName: "Terminal"),
+ fixtureWindow(windowID: 22, processID: 200, appName: "Safari")
+ ],
+ frontmostProcessID: 100,
+ screenshotCapturer: screenshotCapturer,
+ accessibilityCapturer: accessibilityCapturer
+ )
+
+ let result = try await service.capture(
+ session: RunSession(id: "run-debug-command", userGoal: "debug capture", targetID: "target-1"),
+ selection: options.selection,
+ traceID: "trace-debug-command",
+ screenshotArtifactID: "screenshot-debug-command",
+ accessibilityArtifactID: "accessibility-debug-command"
+ )
+
+ #expect(result.target.windowID == 22)
+ #expect(screenshotCapturer.capturedWindowIDs == [22])
+ #expect(accessibilityCapturer.capturedWindowIDs == [22])
+ }
+
+ private func makeManualService(
+ store: LocalRunArtifactStore,
+ windows: [MacWindowProviderWindow],
+ frontmostProcessID: Int32? = nil,
+ focusedWindowID: UInt32? = nil,
+ screenshotCapturer: FakeWindowScreenshotCapturer,
+ accessibilityCapturer: FakeMacAccessibilitySnapshotCapturer
+ ) -> ManualTargetContextCaptureService {
+ let provider = FixtureWindowProvider(
+ windows: windows,
+ frontmostProcessID: frontmostProcessID,
+ focusedWindowID: focusedWindowID
+ )
+ let screenshotService = WindowScreenshotCaptureService(
+ artifactStore: store,
+ windowResolver: MacWindowResolver(provider: provider),
+ capturer: screenshotCapturer
+ )
+ let accessibilityService = MacAccessibilitySnapshotCaptureService(
+ artifactStore: store,
+ windowResolver: MacWindowResolver(provider: provider),
+ capturer: accessibilityCapturer
+ )
+
+ return ManualTargetContextCaptureService(
+ coordinator: RunCoordinator(),
+ artifactStore: store,
+ windowResolver: MacWindowResolver(provider: provider),
+ screenshotService: screenshotService,
+ accessibilityService: accessibilityService
+ )
+ }
+
+ 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(
+ "DonkeyManualCaptureDebugCommandTests-\(UUID().uuidString)",
+ isDirectory: true
+ )
+ }
+}
+
+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 final class FakeMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing {
+ var trust: MacAccessibilityTrustStatus
+ var tree: MacAccessibilitySnapshotTree
+ var capturedWindowIDs: [UInt32] = []
+
+ init(
+ trustStatus: MacAccessibilityTrustStatus = .trusted,
+ tree: MacAccessibilitySnapshotTree = MacAccessibilitySnapshotTreeBuilder.build(
+ root: RawMacAccessibilitySnapshotNode(role: "AXWindow", title: "Window"),
+ limits: .default
+ )
+ ) {
+ self.trust = trustStatus
+ self.tree = tree
+ }
+
+ func trustStatus() -> MacAccessibilityTrustStatus {
+ trust
+ }
+
+ func captureTree(
+ target: MacWindowTargetCandidate,
+ limits: MacAccessibilitySnapshotLimits
+ ) throws -> MacAccessibilitySnapshotTree {
+ capturedWindowIDs.append(target.windowID)
+ return tree
+ }
+}
+
+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 b8dc3300..2142c5c8 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -33,7 +33,9 @@ Donkey can also create a shallow read-only Accessibility snapshot artifact after
Donkey supports a runtime-level manual target context capture service that wires one read-only capture run through `RunCoordinator`. The service prepares the run folder, starts the session, resolves the target once, passes explicit durable `windowID` selection to screenshot and Accessibility capture services, records coordinator-assigned lifecycle and tool events, persists those events to `events.jsonl`, and completes the run after screenshot success. Missing Accessibility trust is a partial completion: the coordinator records one permission-denied tool event, the screenshot artifact remains, and no Accessibility artifact is created.
-This is a coordination, trace, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run perception models, call LLMs, execute OS input, perform Accessibility actions, provide a manual capture UI, or perform manual verification against live apps yet.
+The installed executable also supports a developer-only launch-argument entrypoint for manual verification. `--list-window-candidates` prints the current candidate-list labels and durable `windowID` values. `--manual-capture` runs one manual capture, optionally with `--window-id <id>`, `--run-id <safe-id>`, and `--trace-id <safe-id>`, then prints the run folder and artifact paths. These commands are non-interactive and exit before showing the pointer prompt overlay.
+
+This is a coordination, trace, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run perception models, call LLMs, execute OS input, perform Accessibility actions, provide a manual capture UI, or complete live verification against the full target matrix yet.
## Technical Guidelines
@@ -45,6 +47,7 @@ This is a coordination, trace, target-metadata, single-screenshot artifact, read
- 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.
- Treat manual target context capture as orchestration. `RunCoordinator` owns event order and policy decisions, while screenshot, Accessibility, and artifact-store services remain capture/persistence workers.
+- Treat the launch-argument debug entrypoint as developer tooling. It should stay plain text, non-interactive, and should never accept ephemeral labels as capture input.
- 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.
@@ -58,7 +61,14 @@ 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, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, and manual capture event ordering through persisted coordinator events.
+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, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.
+
+Manual smoke commands:
+
+```sh
+swift run Donkey -- --list-window-candidates
+swift run Donkey -- --manual-capture --window-id <id>
+```
## Source Entry Points
@@ -70,5 +80,6 @@ The runtime tests should cover lifecycle ordering, abort and timeout safety, lat
- Accessibility snapshot contracts live in `apps/Donkey/Sources/DonkeyContracts/AccessibilitySnapshotContracts.swift`.
- Read-only Accessibility snapshot capture lives in `apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift`.
- Manual target context capture orchestration lives in `apps/Donkey/Sources/DonkeyRuntime/ManualTargetContextCaptureService.swift`.
+- Manual capture debug command parsing lives in `apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.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.md
index 90f53253..b770e4e8 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -1,203 +1,43 @@
# Manual Target Context Capture Master Plan
-## Goal
-
-Build the first read-only data capture milestone for Donkey runs.
-
-One manual command or UI action should create a run session, select any visible target window, capture a screenshot, dump a shallow macOS Accessibility tree, write trace artifacts, and publish ordered runtime events.
-
-This should prove the data path before continuous capture, perception models, or synthetic input are added.
-
-## Master Plan Role
-
-Use this document as the current active master plan for the next sequence of work.
-
-It coordinates the order of plan edits and implementation slices needed to move Donkey from a runtime coordinator shell into real target-window context capture. Start here before editing the older active plans.
-
-Edit sequence:
-
-1. Keep this plan as the implementation driver until manual target context capture is supported.
-2. Update [18-macos-accessibility.md](18-macos-accessibility.md) only for Accessibility details that are still future-facing after read-only AX snapshots exist.
-3. Update [02-capture-and-perception.md](02-capture-and-perception.md) only for capture/perception boundaries that remain after manual screenshots are supported.
-4. Update [06-benchmarking.md](06-benchmarking.md) only for trace/artifact measurement rules that remain broader than this milestone.
-5. Update [20-off-the-shelf-run-loop.md](20-off-the-shelf-run-loop.md) only for the larger runtime/perception loop that remains after the minimal coordinator and manual capture pieces are documented.
-6. When this milestone is implemented, write or update the supported guide in `docs/guides/`, then move this plan to `plans/done/`.
-
-Do not spread implementation instructions across multiple active plans while this one is still open. Use linked plans for background and cleanup targets, not as competing sources of truth.
-
-## Related Plans And Guides
-
-- [20-off-the-shelf-run-loop.md](20-off-the-shelf-run-loop.md): runtime shell, event streams, session lifecycle, and coordinator boundary
-- [18-macos-accessibility.md](18-macos-accessibility.md): Accessibility tree/action backend and iPhone Mirroring window guard
-- [02-capture-and-perception.md](02-capture-and-perception.md): screenshot capture and world-state direction
-- [06-benchmarking.md](06-benchmarking.md): trace events, timestamps, and run artifact shape
-- [12-iphone-mirroring.md](12-iphone-mirroring.md): first target surface for mobile-game capture
-- [../docs/guides/minimal-run-coordinator.md](../docs/guides/minimal-run-coordinator.md): supported run coordinator behavior
-
-## Scope
-
-Build a manual, read-only capture flow:
-
-```text
-prompt / debug command
- -> RunSession
- -> target window resolver
- -> screenshot capture
- -> Accessibility tree snapshot
- -> trace artifact write
- -> RunCoordinator tool/lifecycle events
- -> compact context summary
-```
-
-In scope:
-
-- enumeration and selection of any visible macOS window
-- active, focused, or explicitly selected window metadata
-- iPhone Mirroring as one supported target option, not a special-only path
-- screenshot artifact metadata and PNG output
-- shallow Accessibility tree snapshot with roles, labels/titles, values, frames, pid, and window metadata
-- local trace folder for one run, stored under Application Support by default
-- ordered runtime events for capture and persistence
-- privacy-oriented redaction boundaries for sensitive windows
-
-Out of scope:
-
-- continuous frame capture
-- OCR, object detection, SAM, or model inference
-- synthetic input or Accessibility actions
-- remote model calls
-- full desktop recording
-- hot-loop performance optimization
-
-## Implementation Plan
-
-### Runtime And Permission Integration
-
-Supported as the fifth vertical slice. `ManualTargetContextCaptureService` orchestrates one read-only capture run through `RunCoordinator`, `LocalRunArtifactStore`, target-window resolution, screenshot capture, and Accessibility snapshot capture.
-
-The service prepares the run folder, starts the session, resolves the target once, passes explicit durable `windowID` selection to capture services, records coordinator-assigned lifecycle/tool events, persists those events to `events.jsonl`, and completes the run after screenshot success. Missing Accessibility trust is treated as partial completion: the coordinator records one permission-denied tool event, no Accessibility artifact is written, and the screenshot artifact remains.
-
-Current boundaries:
-
-- The API is runtime-level only. No manual command shell or UI entrypoint has been added yet.
-- Screenshot success is required for completion. Target-resolution, screenshot, persistence, and safety-stop failures fail the run.
-- Accessibility trust denial is the only supported partial-completion AX failure. Other AX capture failures fail the run.
-- Input/action capabilities remain denied by default, and the manual capture service emits no input tool events.
-- Standalone screenshot and Accessibility capture services remain usable independently; standalone missing-AX-trust behavior still records its own partial event unless the orchestrator asks it not to.
-
-### Target Window Resolution
-
-Supported as the second vertical slice. `MacWindowResolver` enumerates visible on-screen macOS app windows, normalizes window metadata, returns candidate-list snapshots with ephemeral labels for manual/debug selection, 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. Candidate-list snapshots map short labels like "window 1" to the candidate's macOS `windowID` only for the current enumeration; follow-up commands should carry the durable `windowID`.
-- 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
-
-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
-```
-
-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
-
-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
-```
-
-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.
-- Manual capture orchestration can suppress the standalone permission event so missing trust is recorded once through `RunCoordinator`.
-- 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.
-- Ordered `RunCoordinator` events are published by the manual capture orchestrator, not by the standalone AX snapshot service.
-
-### Trace Artifact Store
-
-Supported as the first vertical slice. `LocalRunArtifactStore` prepares durable run folders, appends JSONL event records, reserves safe artifact paths, records artifact metadata, and updates summaries.
-
-Installed Donkey stores runs under:
-
-```text
-~/Library/Application Support/Donkey/Runs/<run-id>/
-```
-
-Tests and development tools may pass an explicit base directory override. Each run folder contains:
-
-```text
-events.jsonl
-summary.json
-screenshots/
-accessibility/
-```
-
-- Keep the artifact store simple and local for this milestone. It can become async or buffered after coordinator capture events are wired to disk.
-
-### Context Assembly
-
-- Feed compact artifact references into context assembly:
- - screenshot artifact ids and target metadata
- - Accessibility tree summary
- - recent capture failures
- - run goal and target id
-- Do not pass raw screenshots or full AX trees to an LLM yet.
-
-## Acceptance Criteria
-
-- A manual command or prompt action creates a run session and one trace folder.
-- 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, 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
-
-- Before implementing, re-read `docs/README.md`, `docs/guides/minimal-run-coordinator.md`, `plans/18-macos-accessibility.md`, and `plans/20-off-the-shelf-run-loop.md`.
-- Keep this plan active while manual capture is incomplete.
-- When this milestone is complete, create or update a supported guide in `docs/guides/` for data capture and Accessibility snapshots.
-- After the guide exists and tests/manual verification pass, move this plan to `plans/done/`.
-- Clean up overlapping completed details in active plans:
- - keep `plans/20-off-the-shelf-run-loop.md` focused on future off-the-shelf perception and runtime direction
- - avoid duplicating the already-supported minimal coordinator behavior from `docs/guides/minimal-run-coordinator.md`
- - keep `plans/18-macos-accessibility.md` focused on future AX actions/window guards once read-only AX capture is documented
-- Prefer shrinking active `plans/` when a capability becomes supported. Completed implementation facts should live in `docs/guides/`, not in long active plan sections.
-
-## What Should Be Done Next
-
-Continue from the completed local artifact writer, window resolver, candidate-list API, screenshot artifact service, Accessibility snapshot service, and runtime-level manual capture event wiring:
-
-1. Add an integration/manual verification entrypoint.
- - Provide a small debug command, developer hook, or equivalent UI action that invokes the existing runtime-level manual capture service without adding synthetic input.
-2. Manually verify against real windows.
- - Test at least iPhone Mirroring and one normal Mac app window.
- - Include an overlapped-window scenario and an Accessibility-trust-missing scenario.
- - Confirm the trace folder contains ordered coordinator events, one screenshot artifact, and an Accessibility artifact only when permission is available.
-3. Close out the milestone after verification.
- - Keep the supported guide current.
- - Move this plan to `plans/done/` once the manual entrypoint and verification are complete.
+This file is the active task queue for the manual target context capture milestone.
+Supported behavior and engineering guidance belong in `docs/guides/minimal-run-coordinator.md`.
+
+## Completed Tasks
+
+- [x] Add local run artifact storage for `events.jsonl`, `summary.json`, screenshots, and Accessibility artifacts.
+- [x] Add visible-window target resolution with focused/frontmost fallback and conservative safety metadata.
+- [x] Add snapshot-scoped candidate labels such as `window 1`, mapped to durable `windowID` selection requests.
+- [x] Add read-only target-window screenshot artifact capture.
+- [x] Add bounded read-only Accessibility snapshot artifact capture.
+- [x] Wire manual capture through `RunCoordinator` lifecycle/tool events and persisted trace events.
+- [x] Add developer launch arguments for manual verification:
+ - `--list-window-candidates`
+ - `--manual-capture`
+ - `--window-id <UInt32>`
+ - `--run-id <safe-id>`
+ - `--trace-id <safe-id>`
+- [x] Update the supported behavior guide for the completed runtime, capture, Accessibility, and debug-entrypoint slices.
+
+## Remaining Tasks
+
+1. Manually verify the debug entrypoint against real windows.
+ - Run `swift run Donkey -- --list-window-candidates`.
+ - Run `swift run Donkey -- --manual-capture --window-id <id>` against one normal Mac app window.
+ - Run the same flow against iPhone Mirroring when available.
+ - Verify an overlapped-window scenario does not produce misleading capture behavior.
+ - Verify an Accessibility-trust-missing scenario completes partially with one screenshot artifact and one coordinator permission event.
+ - Confirm the run folder contains ordered coordinator events, one screenshot artifact, and an Accessibility artifact only when permission is available.
+
+2. Close out the milestone.
+ - Update `docs/guides/minimal-run-coordinator.md` with any findings from live verification.
+ - Keep active plans focused on future work only:
+ - `plans/18-macos-accessibility.md`
+ - `plans/02-capture-and-perception.md`
+ - `plans/06-benchmarking.md`
+ - `plans/20-off-the-shelf-run-loop.md`
+ - Move this file to `plans/done/` after verification and guide cleanup.
+
+## Next Item
+
+Manual verification against real windows.