Open source CapCut alternative.
TypeScript
Integrate local navigation dry-run loop
David Le9b160f8ee7a0
diff --git a/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift b/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swiftindex 2006da4b..81b83dda 100644--- a/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/HotLoopContracts.swift@@ -246,6 +246,7 @@ public enum HotLoopFrameSourceKind: String, Codable, Equatable, Sendable {case syntheticcase recordedcase targetWindow+ case localNavigationMetadata}public struct HotLoopFrame: Codable, Equatable, Sendable {@@ -384,19 +385,22 @@ public struct HotLoopActionAffordance: Codable, Equatable, Sendable {public var targetBounds: HotLoopRect?public var confidence: Doublepublic var sourceSignalID: String+ public var metadata: [String: String]public init(id: String,kind: HotLoopActionKind,targetBounds: HotLoopRect? = nil,confidence: Double,- sourceSignalID: String+ sourceSignalID: String,+ metadata: [String: String] = [:]) {self.id = idself.kind = kindself.targetBounds = targetBoundsself.confidence = confidenceself.sourceSignalID = sourceSignalID+ self.metadata = metadata}}diff --git a/apps/Donkey/Sources/DonkeyContracts/LocalNavigationContracts.swift b/apps/Donkey/Sources/DonkeyContracts/LocalNavigationContracts.swiftindex cc58db7c..5dd08283 100644--- a/apps/Donkey/Sources/DonkeyContracts/LocalNavigationContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/LocalNavigationContracts.swift@@ -50,6 +50,52 @@ public struct LocalNavigationCandidate: Codable, Equatable, Sendable {}}+public struct LocalNavigationBrowserTabMetadata: Codable, Equatable, Sendable {+ public var id: String+ public var appName: String?+ public var bundleIdentifier: String?+ public var title: String?+ public var url: String?+ public var windowID: UInt32?+ public var bounds: HotLoopRect?+ public var isActive: Bool+ public var isFrontmost: Bool+ public var isFocused: Bool+ public var safetyStatus: WindowTargetSafetyStatus+ public var confidence: Double+ public var metadata: [String: String]++ public init(+ id: String,+ appName: String? = nil,+ bundleIdentifier: String? = nil,+ title: String? = nil,+ url: String? = nil,+ windowID: UInt32? = nil,+ bounds: HotLoopRect? = nil,+ isActive: Bool = false,+ isFrontmost: Bool = false,+ isFocused: Bool = false,+ safetyStatus: WindowTargetSafetyStatus = .allowed,+ confidence: Double = 0.8,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.appName = appName+ self.bundleIdentifier = bundleIdentifier+ self.title = title+ self.url = url+ self.windowID = windowID+ self.bounds = bounds+ self.isActive = isActive+ self.isFrontmost = isFrontmost+ self.isFocused = isFocused+ self.safetyStatus = safetyStatus+ self.confidence = min(max(confidence, 0), 1)+ self.metadata = metadata+ }+}+public struct LocalNavigationWorldState: Codable, Equatable, Sendable {public var id: Stringpublic var traceID: String@@ -114,14 +160,26 @@ public struct LocalNavigationWorldState: Codable, Equatable, Sendable {kind: candidate.kind == .browserTab ? .switchTab : .focusWindow,targetBounds: candidate.bounds,confidence: candidate.confidence,- sourceSignalID: "signal-\(id)"+ sourceSignalID: "signal-\(id)",+ metadata: candidate.metadata.merging([+ "localNavigation.candidateID": candidate.id,+ "localNavigation.candidateKind": candidate.kind.rawValue,+ "localNavigation.isFrontmost": String(candidate.isFrontmost),+ "localNavigation.isFocused": String(candidate.isFocused),+ "localNavigation.safetyStatus": candidate.safetyStatus.rawValue,+ "localNavigation.appName": candidate.appName ?? "",+ "localNavigation.bundleIdentifier": candidate.bundleIdentifier ?? "",+ "localNavigation.title": candidate.title ?? ""+ ]) { current, _ in current })},confidence: confidence,metadata: metadata.merging(["localNavigation.candidateCount": String(candidates.count),"localNavigation.focusedCandidateID": focusedCandidateID ?? "",- "localNavigation.frontmostCandidateID": frontmostCandidateID ?? ""+ "localNavigation.frontmostCandidateID": frontmostCandidateID ?? "",+ "localNavigation.requestedBundleIdentifier": requestedBundleIdentifier ?? "",+ "localNavigation.requestedTitleContains": requestedTitleContains ?? ""]) { current, _ in current })}diff --git a/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift b/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swiftindex 748dc4b0..23b8858b 100644--- a/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift@@ -315,9 +315,13 @@ public struct ReflexTraceTimeline: Codable, Equatable, Sendable {public var modelEnd: RunTraceTimestamp?public var perceptionStart: RunTraceTimestamp?public var perceptionEnd: RunTraceTimestamp?+ public var stateUpdateStart: RunTraceTimestamp?+ public var stateUpdateEnd: RunTraceTimestamp?public var statePublished: RunTraceTimestamp?public var controllerStart: RunTraceTimestamp?public var controllerEnd: RunTraceTimestamp?+ public var actionProjectionStart: RunTraceTimestamp?+ public var actionProjectionEnd: RunTraceTimestamp?public var actionEnqueued: RunTraceTimestamp?public var inputExecuted: RunTraceTimestamp?@@ -330,9 +334,13 @@ public struct ReflexTraceTimeline: Codable, Equatable, Sendable {modelEnd: RunTraceTimestamp? = nil,perceptionStart: RunTraceTimestamp? = nil,perceptionEnd: RunTraceTimestamp? = nil,+ stateUpdateStart: RunTraceTimestamp? = nil,+ stateUpdateEnd: RunTraceTimestamp? = nil,statePublished: RunTraceTimestamp? = nil,controllerStart: RunTraceTimestamp? = nil,controllerEnd: RunTraceTimestamp? = nil,+ actionProjectionStart: RunTraceTimestamp? = nil,+ actionProjectionEnd: RunTraceTimestamp? = nil,actionEnqueued: RunTraceTimestamp? = nil,inputExecuted: RunTraceTimestamp? = nil) {@@ -344,9 +352,13 @@ public struct ReflexTraceTimeline: Codable, Equatable, Sendable {self.modelEnd = modelEndself.perceptionStart = perceptionStartself.perceptionEnd = perceptionEnd+ self.stateUpdateStart = stateUpdateStart+ self.stateUpdateEnd = stateUpdateEndself.statePublished = statePublishedself.controllerStart = controllerStartself.controllerEnd = controllerEnd+ self.actionProjectionStart = actionProjectionStart+ self.actionProjectionEnd = actionProjectionEndself.actionEnqueued = actionEnqueuedself.inputExecuted = inputExecuted}@@ -357,7 +369,9 @@ public struct ReflexTraceTimeline: Codable, Equatable, Sendable {preprocessMS: milliseconds(from: preprocessStart, to: preprocessEnd),modelInferenceMS: milliseconds(from: modelStart, to: modelEnd),perceptionMS: milliseconds(from: perceptionStart, to: perceptionEnd),+ stateUpdateMS: milliseconds(from: stateUpdateStart, to: stateUpdateEnd),decisionMS: milliseconds(from: controllerStart, to: controllerEnd),+ actionProjectionMS: milliseconds(from: actionProjectionStart, to: actionProjectionEnd),inputMS: milliseconds(from: actionEnqueued, to: inputExecuted),softwareLoopMS: milliseconds(from: captureEnd, to: inputExecuted),frameAgeMS: milliseconds(from: captureEnd, to: controllerStart),@@ -379,7 +393,9 @@ public struct ReflexLatencyBreakdown: Codable, Equatable, Sendable {public var preprocessMS: Double?public var modelInferenceMS: Double?public var perceptionMS: Double?+ public var stateUpdateMS: Double?public var decisionMS: Double?+ public var actionProjectionMS: Double?public var inputMS: Double?public var softwareLoopMS: Double?public var frameAgeMS: Double?@@ -390,7 +406,9 @@ public struct ReflexLatencyBreakdown: Codable, Equatable, Sendable {preprocessMS: Double? = nil,modelInferenceMS: Double? = nil,perceptionMS: Double? = nil,+ stateUpdateMS: Double? = nil,decisionMS: Double? = nil,+ actionProjectionMS: Double? = nil,inputMS: Double? = nil,softwareLoopMS: Double? = nil,frameAgeMS: Double? = nil,@@ -400,7 +418,9 @@ public struct ReflexLatencyBreakdown: Codable, Equatable, Sendable {self.preprocessMS = preprocessMSself.modelInferenceMS = modelInferenceMSself.perceptionMS = perceptionMS+ self.stateUpdateMS = stateUpdateMSself.decisionMS = decisionMS+ self.actionProjectionMS = actionProjectionMSself.inputMS = inputMSself.softwareLoopMS = softwareLoopMSself.frameAgeMS = frameAgeMSdiff --git a/apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift b/apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swiftindex 9a618a4c..4965dcce 100644--- a/apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/CheapPerceptionAndController.swift@@ -90,7 +90,7 @@ public struct CheapPerceptionAdapter: DryRunPerceptionAdapting {}}-public struct HotLoopWorldStateProjector: Sendable {+public struct HotLoopWorldStateProjector: DryRunWorldStateProjecting {public var staleSignalThresholdMS: Doublepublic init(staleSignalThresholdMS: Double = 250) {@@ -101,7 +101,7 @@ public struct HotLoopWorldStateProjector: Sendable {frame: HotLoopFrame,signals: [HotLoopPerceptionSignal],observedAt: RunTraceTimestamp- ) -> HotLoopWorldState {+ ) async -> HotLoopWorldState {HotLoopWorldState.build(id: "state-\(frame.id)",frame: frame,diff --git a/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift b/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swiftindex 69448a6e..dd603bfb 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift@@ -9,6 +9,14 @@ public protocol DryRunPerceptionAdapting: Sendable {func perceive(frame: HotLoopFrame) async -> [HotLoopPerceptionSignal]}+public protocol DryRunWorldStateProjecting: Sendable {+ func project(+ frame: HotLoopFrame,+ signals: [HotLoopPerceptionSignal],+ observedAt: RunTraceTimestamp+ ) async -> HotLoopWorldState+}+public protocol DryRunControllerPolicy: Sendable {var name: String { get }func decide(state: HotLoopWorldState) async -> HotLoopControllerAction@@ -78,13 +86,14 @@ public struct DryRunReflexLoop: Sendable {public var perceptionAdapter: any DryRunPerceptionAdaptingpublic var controllerPolicy: any DryRunControllerPolicypublic var actionProjector: any DryRunActionProjecting- public var worldStateProjector: HotLoopWorldStateProjector+ public var worldStateProjector: any DryRunWorldStateProjectingpublic var staleSignalThresholdMS: Doublepublic init(coordinator: RunCoordinator,frameSource: any DryRunFrameSource,perceptionAdapter: any DryRunPerceptionAdapting = CheapPerceptionAdapter(),+ worldStateProjector: (any DryRunWorldStateProjecting)? = nil,controllerPolicy: any DryRunControllerPolicy = DeterministicControllerPolicy(),actionProjector: any DryRunActionProjecting = DryRunActionProjector(),staleSignalThresholdMS: Double = 250@@ -94,7 +103,8 @@ public struct DryRunReflexLoop: Sendable {self.perceptionAdapter = perceptionAdapterself.controllerPolicy = controllerPolicyself.actionProjector = actionProjector- self.worldStateProjector = HotLoopWorldStateProjector(staleSignalThresholdMS: staleSignalThresholdMS)+ self.worldStateProjector = worldStateProjector+ ?? HotLoopWorldStateProjector(staleSignalThresholdMS: staleSignalThresholdMS)self.staleSignalThresholdMS = staleSignalThresholdMS}@@ -151,29 +161,78 @@ public struct DryRunReflexLoop: Sendable {) async -> (worldState: HotLoopWorldState, action: HotLoopControllerAction) {let signals = await perceptionAdapter.perceive(frame: frame)let observedAt = signals.map(\.observedAt).maxByMonotonicUptime() ?? frame.capturedAt.addingMilliseconds(2)- let worldState = worldStateProjector.project(+ let stateUpdateStart = observedAt+ let worldState = await worldStateProjector.project(frame: frame,signals: signals,observedAt: observedAt,)- let controllerStart = observedAt.addingMilliseconds(1)+ let stateUpdateEnd = stateUpdateStart.addingMilliseconds(+ latencyMilliseconds(+ named: "latency.stateUpdateMS",+ frame: frame,+ signals: signals,+ defaultValue: 1+ ) ?? 1+ )+ let controllerStart = stateUpdateEndlet action = await controllerPolicy.decide(state: worldState)let result = await actionProjector.project(action: action, state: worldState)+ let controllerEnd = controllerStart.addingMilliseconds(+ latencyMilliseconds(+ named: "latency.controllerDecisionMS",+ frame: frame,+ signals: signals,+ defaultValue: 1+ ) ?? 1+ )+ let actionProjectionStart = controllerEnd+ let actionProjectionEnd = actionProjectionStart.addingMilliseconds(+ latencyMilliseconds(+ named: "latency.actionProjectionMS",+ frame: frame,+ signals: signals,+ defaultValue: 0+ ) ?? 0+ )+ let captureStart = captureStart(for: frame)+ let preprocess = stageWindow(+ named: "latency.preprocessMS",+ frame: frame,+ signals: signals,+ defaultValue: frame.crop == nil ? 0 : nil,+ after: frame.capturedAt+ )+ let model = stageWindow(+ named: "latency.modelInferenceMS",+ frame: frame,+ signals: signals,+ defaultValue: nil,+ after: preprocess.end ?? frame.capturedAt+ )let trace = ReflexTraceRecord(traceID: frame.traceID,frameID: frame.id,stateID: worldState.id,actionID: action.id,timestamps: ReflexTraceTimeline(- captureStart: frame.capturedAt,+ captureStart: captureStart,captureEnd: frame.capturedAt,+ preprocessStart: preprocess.start,+ preprocessEnd: preprocess.end,+ modelStart: model.start,+ modelEnd: model.end,perceptionStart: frame.capturedAt,perceptionEnd: observedAt,- statePublished: observedAt,+ stateUpdateStart: stateUpdateStart,+ stateUpdateEnd: stateUpdateEnd,+ statePublished: stateUpdateEnd,controllerStart: controllerStart,- controllerEnd: result.enqueuedAt,- actionEnqueued: result.enqueuedAt,- inputExecuted: result.completedAt+ controllerEnd: controllerEnd,+ actionProjectionStart: actionProjectionStart,+ actionProjectionEnd: actionProjectionEnd,+ actionEnqueued: actionProjectionEnd,+ inputExecuted: actionProjectionEnd),controllerPolicy: action.policyName,confidence: action.confidence,@@ -184,7 +243,17 @@ public struct DryRunReflexLoop: Sendable {"dryRun.summary": result.summary,"action.kind": action.kind.rawValue,"action.rationale": action.rationale,- "action.fallback": action.metadata["fallback"] ?? "false"+ "action.fallback": action.metadata["fallback"] ?? "false",+ "latency.metadataReadMS": formatLatency(+ latencyMilliseconds(+ named: "latency.metadataReadMS",+ frame: frame,+ signals: signals,+ defaultValue: nil+ )+ ),+ "latency.stateUpdateMS": formatLatency(stateUpdateStart.milliseconds(until: stateUpdateEnd)),+ "latency.actionProjectionMS": formatLatency(actionProjectionStart.milliseconds(until: actionProjectionEnd))].merging(action.metadata, uniquingKeysWith: { current, _ in current }))@@ -193,6 +262,60 @@ public struct DryRunReflexLoop: Sendable {return (worldState, action)}+ private func captureStart(for frame: HotLoopFrame) -> RunTraceTimestamp {+ guard let latency = Double(frame.metadata["capture.latencyMS"] ?? ""),+ latency >= 0+ else {+ return frame.capturedAt+ }++ return frame.capturedAt.addingMilliseconds(-latency)+ }++ private func stageWindow(+ named key: String,+ frame: HotLoopFrame,+ signals: [HotLoopPerceptionSignal],+ defaultValue: Double?,+ after start: RunTraceTimestamp+ ) -> (start: RunTraceTimestamp?, end: RunTraceTimestamp?) {+ guard let latency = latencyMilliseconds(+ named: key,+ frame: frame,+ signals: signals,+ defaultValue: defaultValue+ ) else {+ return (nil, nil)+ }++ let end = start.addingMilliseconds(latency)+ return (start, end)+ }++ private func latencyMilliseconds(+ named key: String,+ frame: HotLoopFrame,+ signals: [HotLoopPerceptionSignal],+ defaultValue: Double?+ ) -> Double? {+ if let value = Double(frame.metadata[key] ?? "") {+ return max(0, value)+ }++ for signal in signals {+ if let value = Double(signal.metadata[key] ?? "") {+ return max(0, value)+ }+ }++ return defaultValue+ }++ private func formatLatency(_ value: Double?) -> String {+ guard let value else { return "unknown" }+ return String(format: "%.2f", value)+ }+private func finish(_ completion: DryRunReflexLoopCompletion) async {switch completion {case .complete(let reason):@@ -240,10 +363,15 @@ public typealias SyntheticPerceptionAdapter = CheapPerceptionAdapterpublic typealias InspectableDryRunControllerPolicy = DeterministicControllerPolicyprivate extension RunTraceTimestamp {- func addingMilliseconds(_ milliseconds: UInt64) -> RunTraceTimestamp {+ func addingMilliseconds(_ milliseconds: Double) -> RunTraceTimestamp {RunTraceTimestamp(wallClock: wallClock.addingTimeInterval(Double(milliseconds) / 1_000),- monotonicUptimeNanoseconds: monotonicUptimeNanoseconds + milliseconds * 1_000_000+ monotonicUptimeNanoseconds: UInt64(+ max(+ 0,+ Double(monotonicUptimeNanoseconds) + milliseconds * 1_000_000+ )+ ))}}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalNavigationController.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalNavigationController.swiftindex ed22b124..2e463ba3 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalNavigationController.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalNavigationController.swift@@ -15,15 +15,20 @@ public struct LocalNavigationMetadataProjector: Sendable {observedAt: RunTraceTimestamp,sourceCapturedAt: RunTraceTimestamp,requestedBundleIdentifier: String? = nil,- requestedTitleContains: String? = nil+ requestedTitleContains: String? = nil,+ browserTabs: [LocalNavigationBrowserTabMetadata] = []) -> LocalNavigationWorldState {let sourceAgeMS = sourceCapturedAt.milliseconds(until: observedAt)- let candidates = snapshot.candidates.map { labeled in+ let windowCandidates = snapshot.candidates.map { labeled incandidate(labeled: labeled,sourceAgeMS: sourceAgeMS)}+ let tabCandidates = browserTabs.map { tab in+ candidate(tab: tab, sourceAgeMS: sourceAgeMS)+ }+ let candidates = windowCandidates + tabCandidateslet usableCandidates = candidates.filter { $0.safetyStatus == .allowed }let confidence = usableCandidates.isEmpty? 0@@ -44,6 +49,9 @@ public struct LocalNavigationMetadataProjector: Sendable {metadata: ["projector": "local-navigation-metadata-projector","rawPixelsExposed": "false",+ "browserTabMetadataAvailable": String(!browserTabs.isEmpty),+ "browserTabCandidateCount": String(browserTabs.count),+ "windowCandidateCount": String(windowCandidates.count),"sourceAgeMS": sourceAgeMS.map { String($0) } ?? "unknown","stale": String((sourceAgeMS ?? Double.greatestFiniteMagnitude) > staleSourceThresholdMS)]@@ -83,6 +91,31 @@ public struct LocalNavigationMetadataProjector: Sendable {)}+ private func candidate(+ tab: LocalNavigationBrowserTabMetadata,+ sourceAgeMS: Double?+ ) -> LocalNavigationCandidate {+ LocalNavigationCandidate(+ id: "browser-tab-\(tab.id)",+ kind: .browserTab,+ appName: tab.appName,+ bundleIdentifier: tab.bundleIdentifier,+ title: tab.title,+ bounds: tab.bounds,+ isFrontmost: tab.isFrontmost,+ isFocused: tab.isFocused || tab.isActive,+ safetyStatus: tab.safetyStatus,+ confidence: tab.safetyStatus == .allowed ? min(max(tab.confidence, 0), 1) : 0,+ sourceAgeMS: sourceAgeMS,+ metadata: tab.metadata.merging([+ "browserTabID": tab.id,+ "browserTabURL": tab.url ?? "",+ "browserTabWindowID": tab.windowID.map(String.init) ?? "",+ "browserTabActive": String(tab.isActive)+ ]) { current, _ in current }+ )+ }+private func confidence(for window: MacWindowTargetCandidate) -> Double {guard window.isVisible, window.isOnScreen else { return 0 }diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalNavigationDryRunLoop.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalNavigationDryRunLoop.swiftnew file mode 100644index 00000000..3fe5e7d5--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalNavigationDryRunLoop.swift@@ -0,0 +1,437 @@+import DonkeyContracts+import Foundation++public struct LocalNavigationMetadataFrameRequest: Equatable, Sendable {+ public var targetID: String+ public var traceID: String+ public var frameIDPrefix: String+ public var maxFrameCount: Int+ public var requestedBundleIdentifier: String?+ public var requestedTitleContains: String?+ public var browserTabs: [LocalNavigationBrowserTabMetadata]++ public init(+ targetID: String = "local-navigation",+ traceID: String,+ frameIDPrefix: String = "local-navigation-frame",+ maxFrameCount: Int = 1,+ requestedBundleIdentifier: String? = nil,+ requestedTitleContains: String? = nil,+ browserTabs: [LocalNavigationBrowserTabMetadata] = []+ ) {+ self.targetID = targetID+ self.traceID = traceID+ self.frameIDPrefix = frameIDPrefix+ self.maxFrameCount = max(0, maxFrameCount)+ self.requestedBundleIdentifier = requestedBundleIdentifier+ self.requestedTitleContains = requestedTitleContains+ self.browserTabs = browserTabs+ }+}++public struct LocalNavigationMetadataFrameSource: DryRunFrameSource {+ private let windowResolver: MacWindowResolver+ private let timestampProvider: any RunTraceTimestampProviding+ private let request: LocalNavigationMetadataFrameRequest++ public init(request: LocalNavigationMetadataFrameRequest) {+ self.init(+ windowResolver: MacWindowResolver(),+ timestampProvider: SystemLocalNavigationTimestampProvider(),+ request: request+ )+ }++ init(+ windowResolver: MacWindowResolver,+ timestampProvider: any RunTraceTimestampProviding = SystemLocalNavigationTimestampProvider(),+ request: LocalNavigationMetadataFrameRequest+ ) {+ self.windowResolver = windowResolver+ self.timestampProvider = timestampProvider+ self.request = request+ }++ public func frameBatches() async -> [[HotLoopFrame]] {+ let frameCount = max(0, request.maxFrameCount)+ guard frameCount > 0 else { return [] }++ return (0..<frameCount).map { index in+ [frame(index: index)]+ }+ }++ private func frame(index: Int) -> HotLoopFrame {+ let metadataStart = timestampProvider.now()+ let snapshot = windowResolver.enumerateCandidateList()+ let capturedAt = timestampProvider.now()+ var metadata = LocalNavigationFrameMetadataCodec.encode(+ snapshot: snapshot,+ browserTabs: request.browserTabs,+ requestedBundleIdentifier: request.requestedBundleIdentifier,+ requestedTitleContains: request.requestedTitleContains+ )+ metadata["latency.metadataReadMS"] = String(metadataStart.milliseconds(until: capturedAt) ?? 0)+ metadata["capture.latencyMS"] = "0"+ metadata["capture.encoded"] = "false"+ metadata["capture.artifactWritten"] = "false"+ metadata["localNavigation.frameSource"] = "metadata"++ let bounds = snapshot.candidates.first(where: \.candidate.isFocused)?.candidate.bounds+ ?? snapshot.candidates.first(where: \.candidate.isFrontmost)?.candidate.bounds+ ?? snapshot.candidates.first?.candidate.bounds+ ?? WindowTargetBounds(x: 0, y: 0, width: 1, height: 1)++ return HotLoopFrame(+ id: "\(request.frameIDPrefix)-\(index + 1)",+ traceID: request.traceID,+ targetID: request.targetID,+ capturedAt: capturedAt,+ sourceKind: .localNavigationMetadata,+ windowBounds: HotLoopRect(+ x: bounds.x,+ y: bounds.y,+ width: bounds.width,+ height: bounds.height,+ space: .screen+ ),+ pixelSize: HotLoopSize(+ width: max(1, bounds.width),+ height: max(1, bounds.height),+ space: .window+ ),+ metadata: metadata+ )+ }+}++public struct LocalNavigationDryRunPerceptionAdapter: DryRunPerceptionAdapting {+ public var adapterName: String+ public var observationDelayMS: Double++ public init(+ adapterName: String = "local-navigation-metadata-perception",+ observationDelayMS: Double = 1+ ) {+ self.adapterName = adapterName+ self.observationDelayMS = observationDelayMS+ }++ public func perceive(frame: HotLoopFrame) async -> [HotLoopPerceptionSignal] {+ let metadataReadMS = Double(frame.metadata["latency.metadataReadMS"] ?? "") ?? observationDelayMS+ let observedAt = frame.capturedAt.addingMilliseconds(max(metadataReadMS, observationDelayMS))+ let candidateCount = Int(frame.metadata["localNavigation.window.count"] ?? "") ?? 0+ let browserTabCount = Int(frame.metadata["localNavigation.browserTab.count"] ?? "") ?? 0++ return [+ HotLoopPerceptionSignal(+ id: "signal-\(frame.id)",+ traceID: frame.traceID,+ frameID: frame.id,+ kind: "localNavigationMetadata",+ capturedAt: frame.capturedAt,+ observedAt: observedAt,+ confidence: candidateCount + browserTabCount > 0 ? 1 : 0,+ plannerHintID: frame.plannerHintID,+ metadata: [+ "adapter": adapterName,+ "rawPixelsExposed": "false",+ "latency.metadataReadMS": String(metadataReadMS),+ "latency.preprocessMS": frame.metadata["latency.preprocessMS"] ?? "0",+ "latency.modelInferenceMS": frame.metadata["latency.modelInferenceMS"] ?? "0",+ "localNavigation.windowCandidateCount": String(candidateCount),+ "localNavigation.browserTabCandidateCount": String(browserTabCount)+ ]+ )+ ]+ }+}++public struct LocalNavigationDryRunWorldStateProjector: DryRunWorldStateProjecting {+ public var projector: LocalNavigationMetadataProjector++ public init(projector: LocalNavigationMetadataProjector = LocalNavigationMetadataProjector()) {+ self.projector = projector+ }++ public func project(+ frame: HotLoopFrame,+ signals: [HotLoopPerceptionSignal],+ observedAt: RunTraceTimestamp+ ) async -> HotLoopWorldState {+ let navigationState = projector.project(+ snapshot: LocalNavigationFrameMetadataCodec.decodeWindowSnapshot(from: frame.metadata),+ traceID: frame.traceID,+ targetID: frame.targetID,+ observedAt: observedAt,+ sourceCapturedAt: frame.capturedAt,+ requestedBundleIdentifier: nonEmpty(frame.metadata["localNavigation.requestedBundleIdentifier"]),+ requestedTitleContains: nonEmpty(frame.metadata["localNavigation.requestedTitleContains"]),+ browserTabs: LocalNavigationFrameMetadataCodec.decodeBrowserTabs(from: frame.metadata)+ )+ var state = navigationState.hotLoopWorldState()+ state.metadata.merge([+ "projector": "local-navigation-dry-run-world-state-projector",+ "perceptionSignalIDs": signals.map(\.id).joined(separator: ",")+ ]) { current, _ in current }+ return state+ }++ private func nonEmpty(_ value: String?) -> String? {+ guard let value, !value.isEmpty else { return nil }+ return value+ }+}++public struct LocalNavigationDryRunControllerPolicy: DryRunControllerPolicy {+ public var name: String { policy.name }+ public var policy: LocalNavigationControllerPolicy++ public init(policy: LocalNavigationControllerPolicy = LocalNavigationControllerPolicy()) {+ self.policy = policy+ }++ public func decide(state: HotLoopWorldState) async -> HotLoopControllerAction {+ policy.decide(state: localNavigationState(from: state))+ }++ private func localNavigationState(from state: HotLoopWorldState) -> LocalNavigationWorldState {+ let candidates = state.actionAffordances.map { affordance in+ LocalNavigationCandidate(+ id: value("localNavigation.candidateID", in: affordance) ?? affordance.id,+ kind: LocalNavigationCandidateKind(rawValue: value("localNavigation.candidateKind", in: affordance) ?? "")+ ?? .window,+ appName: nonEmpty(value("localNavigation.appName", in: affordance)),+ bundleIdentifier: nonEmpty(value("localNavigation.bundleIdentifier", in: affordance)),+ title: nonEmpty(value("localNavigation.title", in: affordance)),+ bounds: affordance.targetBounds,+ isFrontmost: boolValue("localNavigation.isFrontmost", in: affordance),+ isFocused: boolValue("localNavigation.isFocused", in: affordance),+ safetyStatus: WindowTargetSafetyStatus(rawValue: value("localNavigation.safetyStatus", in: affordance) ?? "")+ ?? .reviewRequired,+ confidence: affordance.confidence,+ sourceAgeMS: state.signalSummaries.first?.sourceAgeMS,+ metadata: affordance.metadata+ )+ }++ return LocalNavigationWorldState(+ id: state.id,+ traceID: state.traceID,+ frameID: state.frameID,+ targetID: state.targetID,+ observedAt: state.observedAt,+ candidates: candidates,+ focusedCandidateID: nonEmpty(state.metadata["localNavigation.focusedCandidateID"]),+ frontmostCandidateID: nonEmpty(state.metadata["localNavigation.frontmostCandidateID"]),+ requestedBundleIdentifier: nonEmpty(state.metadata["localNavigation.requestedBundleIdentifier"]),+ requestedTitleContains: nonEmpty(state.metadata["localNavigation.requestedTitleContains"]),+ confidence: state.confidence,+ metadata: state.metadata+ )+ }++ private func value(_ key: String, in affordance: HotLoopActionAffordance) -> String? {+ affordance.metadata[key]+ }++ private func boolValue(_ key: String, in affordance: HotLoopActionAffordance) -> Bool {+ value(key, in: affordance) == "true"+ }++ private func nonEmpty(_ value: String?) -> String? {+ guard let value, !value.isEmpty else { return nil }+ return value+ }+}++enum LocalNavigationFrameMetadataCodec {+ static func encode(+ snapshot: MacWindowCandidateListSnapshot,+ browserTabs: [LocalNavigationBrowserTabMetadata],+ requestedBundleIdentifier: String?,+ requestedTitleContains: String?+ ) -> [String: String] {+ var metadata = [+ "localNavigation.metadataEncoded": "true",+ "localNavigation.rawPixelsExposed": "false",+ "localNavigation.window.count": String(snapshot.candidates.count),+ "localNavigation.browserTab.count": String(browserTabs.count),+ "localNavigation.requestedBundleIdentifier": requestedBundleIdentifier ?? "",+ "localNavigation.requestedTitleContains": requestedTitleContains ?? ""+ ]++ for (index, labeled) in snapshot.candidates.enumerated() {+ let prefix = "localNavigation.window.\(index)."+ let candidate = labeled.candidate+ metadata[prefix + "label"] = labeled.label+ metadata[prefix + "windowID"] = String(candidate.windowID)+ metadata[prefix + "processID"] = String(candidate.processID)+ metadata[prefix + "appName"] = candidate.appName ?? ""+ metadata[prefix + "bundleIdentifier"] = candidate.bundleIdentifier ?? ""+ metadata[prefix + "title"] = candidate.title ?? ""+ metadata[prefix + "bounds.x"] = String(candidate.bounds.x)+ metadata[prefix + "bounds.y"] = String(candidate.bounds.y)+ metadata[prefix + "bounds.width"] = String(candidate.bounds.width)+ metadata[prefix + "bounds.height"] = String(candidate.bounds.height)+ metadata[prefix + "isVisible"] = String(candidate.isVisible)+ metadata[prefix + "isOnScreen"] = String(candidate.isOnScreen)+ metadata[prefix + "isFrontmost"] = String(candidate.isFrontmost)+ metadata[prefix + "isFocused"] = String(candidate.isFocused)+ metadata[prefix + "isIPhoneMirroring"] = String(candidate.isIPhoneMirroring)+ metadata[prefix + "safetyStatus"] = candidate.safetyAssessment.status.rawValue+ metadata[prefix + "safetySummary"] = candidate.safetyAssessment.summary+ metadata[prefix + "safetyReasons"] = candidate.safetyAssessment.reasons.map(\.rawValue).joined(separator: ",")+ }++ for (index, tab) in browserTabs.enumerated() {+ let prefix = "localNavigation.browserTab.\(index)."+ metadata[prefix + "id"] = tab.id+ metadata[prefix + "appName"] = tab.appName ?? ""+ metadata[prefix + "bundleIdentifier"] = tab.bundleIdentifier ?? ""+ metadata[prefix + "title"] = tab.title ?? ""+ metadata[prefix + "url"] = tab.url ?? ""+ metadata[prefix + "windowID"] = tab.windowID.map(String.init) ?? ""+ metadata[prefix + "isActive"] = String(tab.isActive)+ metadata[prefix + "isFrontmost"] = String(tab.isFrontmost)+ metadata[prefix + "isFocused"] = String(tab.isFocused)+ metadata[prefix + "safetyStatus"] = tab.safetyStatus.rawValue+ metadata[prefix + "confidence"] = String(tab.confidence)+ if let bounds = tab.bounds {+ metadata[prefix + "bounds.x"] = String(bounds.origin.x)+ metadata[prefix + "bounds.y"] = String(bounds.origin.y)+ metadata[prefix + "bounds.width"] = String(bounds.size.width)+ metadata[prefix + "bounds.height"] = String(bounds.size.height)+ metadata[prefix + "bounds.space"] = bounds.space.rawValue+ }+ }++ return metadata+ }++ static func decodeWindowSnapshot(from metadata: [String: String]) -> MacWindowCandidateListSnapshot {+ let count = Int(metadata["localNavigation.window.count"] ?? "") ?? 0+ let candidates = (0..<count).compactMap { index -> LabeledMacWindowTargetCandidate? in+ let prefix = "localNavigation.window.\(index)."+ guard let windowID = UInt32(metadata[prefix + "windowID"] ?? ""),+ let processID = Int32(metadata[prefix + "processID"] ?? ""),+ let x = Double(metadata[prefix + "bounds.x"] ?? ""),+ let y = Double(metadata[prefix + "bounds.y"] ?? ""),+ let width = Double(metadata[prefix + "bounds.width"] ?? ""),+ let height = Double(metadata[prefix + "bounds.height"] ?? "")+ else {+ return nil+ }++ return LabeledMacWindowTargetCandidate(+ label: metadata[prefix + "label"] ?? "window \(index + 1)",+ candidate: MacWindowTargetCandidate(+ windowID: windowID,+ processID: processID,+ appName: nonEmpty(metadata[prefix + "appName"]),+ bundleIdentifier: nonEmpty(metadata[prefix + "bundleIdentifier"]),+ title: nonEmpty(metadata[prefix + "title"]),+ bounds: WindowTargetBounds(x: x, y: y, width: width, height: height),+ isVisible: bool(metadata[prefix + "isVisible"], defaultValue: true),+ isOnScreen: bool(metadata[prefix + "isOnScreen"], defaultValue: true),+ isFrontmost: bool(metadata[prefix + "isFrontmost"], defaultValue: false),+ isFocused: bool(metadata[prefix + "isFocused"], defaultValue: false),+ isIPhoneMirroring: bool(metadata[prefix + "isIPhoneMirroring"], defaultValue: false),+ safetyAssessment: WindowTargetSafetyAssessment(+ status: WindowTargetSafetyStatus(rawValue: metadata[prefix + "safetyStatus"] ?? "")+ ?? .reviewRequired,+ reasons: safetyReasons(metadata[prefix + "safetyReasons"]),+ summary: metadata[prefix + "safetySummary"] ?? "Decoded from local-navigation frame metadata"+ )+ )+ )+ }++ return MacWindowCandidateListSnapshot(labeledCandidates: candidates)+ }++ static func decodeBrowserTabs(from metadata: [String: String]) -> [LocalNavigationBrowserTabMetadata] {+ let count = Int(metadata["localNavigation.browserTab.count"] ?? "") ?? 0+ return (0..<count).compactMap { index in+ let prefix = "localNavigation.browserTab.\(index)."+ guard let id = nonEmpty(metadata[prefix + "id"]) else { return nil }++ return LocalNavigationBrowserTabMetadata(+ id: id,+ appName: nonEmpty(metadata[prefix + "appName"]),+ bundleIdentifier: nonEmpty(metadata[prefix + "bundleIdentifier"]),+ title: nonEmpty(metadata[prefix + "title"]),+ url: nonEmpty(metadata[prefix + "url"]),+ windowID: UInt32(metadata[prefix + "windowID"] ?? ""),+ bounds: bounds(prefix: prefix, metadata: metadata),+ isActive: bool(metadata[prefix + "isActive"], defaultValue: false),+ isFrontmost: bool(metadata[prefix + "isFrontmost"], defaultValue: false),+ isFocused: bool(metadata[prefix + "isFocused"], defaultValue: false),+ safetyStatus: WindowTargetSafetyStatus(rawValue: metadata[prefix + "safetyStatus"] ?? "")+ ?? .reviewRequired,+ confidence: Double(metadata[prefix + "confidence"] ?? "") ?? 0.8+ )+ }+ }++ private static func bounds(+ prefix: String,+ metadata: [String: String]+ ) -> HotLoopRect? {+ guard let x = Double(metadata[prefix + "bounds.x"] ?? ""),+ let y = Double(metadata[prefix + "bounds.y"] ?? ""),+ let width = Double(metadata[prefix + "bounds.width"] ?? ""),+ let height = Double(metadata[prefix + "bounds.height"] ?? "")+ else {+ return nil+ }++ return HotLoopRect(+ x: x,+ y: y,+ width: width,+ height: height,+ space: HotLoopCoordinateSpace(rawValue: metadata[prefix + "bounds.space"] ?? "") ?? .screen+ )+ }++ private static func safetyReasons(_ value: String?) -> [WindowTargetSafetyReason] {+ value?+ .split(separator: ",")+ .compactMap { WindowTargetSafetyReason(rawValue: String($0)) }+ ?? []+ }++ private static func bool(_ value: String?, defaultValue: Bool) -> Bool {+ guard let value else { return defaultValue }+ return value == "true"+ }++ private static func nonEmpty(_ value: String?) -> String? {+ guard let value, !value.isEmpty else { return nil }+ return value+ }+}++private struct SystemLocalNavigationTimestampProvider: RunTraceTimestampProviding {+ func now() -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: Date(),+ monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)+ )+ }+}++private extension RunTraceTimestamp {+ func addingMilliseconds(_ milliseconds: Double) -> RunTraceTimestamp {+ RunTraceTimestamp(+ wallClock: wallClock.addingTimeInterval(milliseconds / 1_000),+ monotonicUptimeNanoseconds: UInt64(+ max(+ 0,+ Double(monotonicUptimeNanoseconds) + milliseconds * 1_000_000+ )+ )+ )+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift b/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swiftindex 3f0ac3de..39c45b1c 100644--- a/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift@@ -49,7 +49,7 @@ protocol MacWindowMetadataProviding {func focusedWindowIdentifier() -> UInt32?}-public final class MacWindowResolver {+public final class MacWindowResolver: @unchecked Sendable {private let provider: any MacWindowMetadataProvidingpublic convenience init() {diff --git a/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift b/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swiftindex 2e77c445..2f73fa61 100644--- a/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift@@ -36,8 +36,12 @@ public struct ReflexLatencyReport: Codable, Equatable, Sendable {public var traceCount: Intpublic var softwareLoopMS: ReflexLatencyPercentilespublic var captureMS: ReflexLatencyPercentiles+ public var preprocessMS: ReflexLatencyPercentiles+ public var modelInferenceMS: ReflexLatencyPercentilespublic var perceptionMS: ReflexLatencyPercentiles+ public var stateUpdateMS: ReflexLatencyPercentilespublic var decisionMS: ReflexLatencyPercentiles+ public var actionProjectionMS: ReflexLatencyPercentilespublic var inputMS: ReflexLatencyPercentilespublic var captureFPS: Double?public var perceptionFPS: Double?@@ -52,8 +56,12 @@ public struct ReflexLatencyReport: Codable, Equatable, Sendable {traceCount: Int,softwareLoopMS: ReflexLatencyPercentiles,captureMS: ReflexLatencyPercentiles,+ preprocessMS: ReflexLatencyPercentiles = ReflexLatencyPercentiles(),+ modelInferenceMS: ReflexLatencyPercentiles = ReflexLatencyPercentiles(),perceptionMS: ReflexLatencyPercentiles,+ stateUpdateMS: ReflexLatencyPercentiles = ReflexLatencyPercentiles(),decisionMS: ReflexLatencyPercentiles,+ actionProjectionMS: ReflexLatencyPercentiles = ReflexLatencyPercentiles(),inputMS: ReflexLatencyPercentiles,captureFPS: Double? = nil,perceptionFPS: Double? = nil,@@ -67,8 +75,12 @@ public struct ReflexLatencyReport: Codable, Equatable, Sendable {self.traceCount = traceCountself.softwareLoopMS = softwareLoopMSself.captureMS = captureMS+ self.preprocessMS = preprocessMS+ self.modelInferenceMS = modelInferenceMSself.perceptionMS = perceptionMS+ self.stateUpdateMS = stateUpdateMSself.decisionMS = decisionMS+ self.actionProjectionMS = actionProjectionMSself.inputMS = inputMSself.captureFPS = captureFPSself.perceptionFPS = perceptionFPS@@ -108,8 +120,12 @@ public enum ReflexLatencyReportBuilder {traceCount: traces.count,softwareLoopMS: percentiles(traces.compactMap(\.latencyBreakdown.softwareLoopMS)),captureMS: percentiles(traces.compactMap(\.latencyBreakdown.captureMS)),+ preprocessMS: percentiles(traces.compactMap(\.latencyBreakdown.preprocessMS)),+ modelInferenceMS: percentiles(traces.compactMap(\.latencyBreakdown.modelInferenceMS)),perceptionMS: percentiles(traces.compactMap(\.latencyBreakdown.perceptionMS)),+ stateUpdateMS: percentiles(traces.compactMap(\.latencyBreakdown.stateUpdateMS)),decisionMS: percentiles(traces.compactMap(\.latencyBreakdown.decisionMS)),+ actionProjectionMS: percentiles(traces.compactMap(\.latencyBreakdown.actionProjectionMS)),inputMS: percentiles(traces.compactMap(\.latencyBreakdown.inputMS)),captureFPS: rate(count: traces.count,@@ -206,8 +222,12 @@ public enum ReflexLatencyReportFormatter {"traceCount=\(report.traceCount)","softwareLoopMS=\(format(report.softwareLoopMS))","captureMS=\(format(report.captureMS))",+ "preprocessMS=\(format(report.preprocessMS))",+ "modelInferenceMS=\(format(report.modelInferenceMS))","perceptionMS=\(format(report.perceptionMS))",+ "stateUpdateMS=\(format(report.stateUpdateMS))","decisionMS=\(format(report.decisionMS))",+ "actionProjectionMS=\(format(report.actionProjectionMS))","inputMS=\(format(report.inputMS))","captureFPS=\(format(report.captureFPS))","perceptionFPS=\(format(report.perceptionFPS))",diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/CheapPerceptionAndControllerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/CheapPerceptionAndControllerTests.swiftindex f31f28d9..5b5c52a8 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/CheapPerceptionAndControllerTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/CheapPerceptionAndControllerTests.swift@@ -38,7 +38,7 @@ struct CheapPerceptionAndControllerTests {let frame = fixtureFrame()let signals = await CheapPerceptionAdapter().perceive(frame: frame)- let state = HotLoopWorldStateProjector(staleSignalThresholdMS: 250).project(+ let state = await HotLoopWorldStateProjector(staleSignalThresholdMS: 250).project(frame: frame,signals: signals,observedAt: timestamp(12)diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalNavigationControllerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalNavigationControllerTests.swiftindex bc2c465a..f578e92a 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalNavigationControllerTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalNavigationControllerTests.swift@@ -43,6 +43,46 @@ struct LocalNavigationControllerTests {#expect(state.hotLoopWorldState().metadata["localNavigation.candidateCount"] == "2")}+ @Test+ func metadataProjectorIncludesBrowserTabsWhenAvailable() {+ let state = LocalNavigationMetadataProjector().project(+ snapshot: MacWindowCandidateListSnapshot(candidates: [+ window(+ id: 200,+ appName: "Safari",+ bundleIdentifier: "com.apple.Safari",+ title: "Docs Window",+ isFrontmost: true,+ isFocused: true+ )+ ]),+ traceID: "trace-tabs",+ targetID: "local-navigation",+ observedAt: timestamp(20),+ sourceCapturedAt: timestamp(10),+ requestedTitleContains: "Install",+ browserTabs: [+ LocalNavigationBrowserTabMetadata(+ id: "safari-tab-1",+ appName: "Safari",+ bundleIdentifier: "com.apple.Safari",+ title: "Install Guide",+ url: "https://example.test/install",+ windowID: 200,+ isActive: false,+ isFrontmost: true,+ confidence: 0.9+ )+ ]+ )++ #expect(state.candidates.map(\.kind) == [.window, .browserTab])+ #expect(state.metadata["browserTabMetadataAvailable"] == "true")+ #expect(state.metadata["browserTabCandidateCount"] == "1")+ #expect(state.hotLoopWorldState().actionAffordances.last?.kind == .switchTab)+ #expect(state.hotLoopWorldState().actionAffordances.last?.metadata["browserTabID"] == "safari-tab-1")+ }+@Testfunc controllerSelectsRequestedWindowFocusAction() {let state = navigationState(@@ -135,6 +175,81 @@ struct LocalNavigationControllerTests {#expect(action.metadata["fallbackReason"] == "targetNotFound")}+ @Test+ func dryRunLoopUsesLocalNavigationMetadataProjectionAndController() async {+ let coordinator = RunCoordinator()+ let source = LocalNavigationMetadataFrameSource(+ windowResolver: MacWindowResolver(+ provider: FixtureWindowProvider(+ windows: [+ providerWindow(+ windowID: 100,+ processID: 1000,+ appName: "Code",+ bundleIdentifier: "com.microsoft.VSCode",+ title: "Donkey"+ ),+ providerWindow(+ windowID: 200,+ processID: 2000,+ appName: "Safari",+ bundleIdentifier: "com.apple.Safari",+ title: "Docs"+ )+ ],+ frontmostProcessID: 2000,+ focusedWindowID: 200+ )+ ),+ timestampProvider: FixtureTimestampProvider(),+ request: LocalNavigationMetadataFrameRequest(+ traceID: "trace-local-nav-loop",+ requestedTitleContains: "Install",+ browserTabs: [+ LocalNavigationBrowserTabMetadata(+ id: "tab-install",+ appName: "Safari",+ bundleIdentifier: "com.apple.Safari",+ title: "Install Guide",+ url: "https://example.test/install",+ windowID: 200,+ isActive: false,+ isFrontmost: true,+ confidence: 0.95+ )+ ]+ )+ )+ let loop = DryRunReflexLoop(+ coordinator: coordinator,+ frameSource: source,+ perceptionAdapter: LocalNavigationDryRunPerceptionAdapter(),+ worldStateProjector: LocalNavigationDryRunWorldStateProjector(),+ controllerPolicy: LocalNavigationDryRunControllerPolicy()+ )++ let result = await loop.run(+ session: RunSession(+ id: "session-local-nav-loop",+ userGoal: "switch to install guide tab",+ targetID: "local-navigation"+ )+ )++ #expect(result.processedFrameCount == 1)+ #expect(result.latestWorldState?.metadata["browserTabMetadataAvailable"] == "true")+ #expect(result.latestAction?.kind == .switchTab)+ #expect(result.latestAction?.metadata["candidateKind"] == "browserTab")+ #expect(result.latestAction?.metadata["browserTabID"] == "tab-install")++ let trace = await coordinator.latestReflexTrace()+ #expect(trace?.metadata["latency.metadataReadMS"] == "5.00")+ #expect(trace?.latencyBreakdown.preprocessMS == 0)+ #expect(trace?.latencyBreakdown.modelInferenceMS == 0)+ #expect(trace?.latencyBreakdown.stateUpdateMS == 1)+ #expect(trace?.metadata["action.kind"] == "switchTab")+ }+private func navigationState(requestedBundleIdentifier: String?,windows: [MacWindowTargetCandidate]@@ -178,6 +293,23 @@ struct LocalNavigationControllerTests {)}+ private func providerWindow(+ windowID: UInt32,+ processID: Int32,+ appName: String,+ bundleIdentifier: String,+ title: String+ ) -> MacWindowProviderWindow {+ MacWindowProviderWindow(+ windowID: windowID,+ processID: processID,+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ title: title,+ bounds: WindowTargetBounds(x: 10, y: 20, width: 300, height: 200)+ )+ }+private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {RunTraceTimestamp(wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),@@ -185,3 +317,44 @@ struct LocalNavigationControllerTests {)}}++private final class FixtureTimestampProvider: RunTraceTimestampProviding, @unchecked Sendable {+ private var nextMilliseconds: UInt64 = 0++ func now() -> RunTraceTimestamp {+ let timestamp = RunTraceTimestamp(+ wallClock: Date(timeIntervalSince1970: Double(nextMilliseconds) / 1_000),+ monotonicUptimeNanoseconds: nextMilliseconds * 1_000_000+ )+ nextMilliseconds += 5+ return timestamp+ }+}++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/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swiftindex 968196c8..90364100 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swift@@ -26,8 +26,12 @@ struct ReflexLatencyReportTests {#expect(report.softwareLoopMS.p95 == 30)#expect(report.softwareLoopMS.p99 == 30)#expect(report.captureMS.p50 == 1)+ #expect(report.preprocessMS.p50 == 1)+ #expect(report.modelInferenceMS.p50 == 3)#expect(report.perceptionMS.p50 == 2)+ #expect(report.stateUpdateMS.p50 == 1)#expect(report.decisionMS.p50 == 1)+ #expect(report.actionProjectionMS.p50 == 1)#expect(report.inputMS.p50 == 1)#expect(isClose(report.captureFPS, to: 100))#expect(isClose(report.perceptionFPS, to: 100))@@ -111,11 +115,19 @@ struct ReflexLatencyReportTests {timestamps: ReflexTraceTimeline(captureStart: timestamp(baseMS),captureEnd: timestamp(baseMS + 1),+ preprocessStart: timestamp(baseMS + 1),+ preprocessEnd: timestamp(baseMS + 2),+ modelStart: timestamp(baseMS + 2),+ modelEnd: timestamp(baseMS + 5),perceptionStart: timestamp(baseMS + 1),perceptionEnd: timestamp(baseMS + 3),+ stateUpdateStart: timestamp(baseMS + 3),+ stateUpdateEnd: timestamp(baseMS + 4),statePublished: timestamp(baseMS + 3),controllerStart: timestamp(baseMS + 3),controllerEnd: timestamp(baseMS + 4),+ actionProjectionStart: timestamp(baseMS + 4),+ actionProjectionEnd: timestamp(baseMS + 5),actionEnqueued: timestamp(baseMS + softwareLoopMS),inputExecuted: timestamp(baseMS + softwareLoopMS + 1)),diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.mdindex fe300a8e..323cc003 100644--- a/docs/guides/minimal-run-coordinator.md+++ b/docs/guides/minimal-run-coordinator.md@@ -18,7 +18,7 @@ Donkey also supports the first real reflex trace shape for the off-the-shelf runDonkey also supports shared hot-loop contracts for deterministic reflex-loop slices. Frames, crops, coordinate spaces, perception signals, compact world states, controller actions, and action results are typed, Codable, Sendable contracts. Coordinate spaces are explicit across screen, window, crop, and normalized target space. Perception signals carry confidence and monotonic source age, and stale signals are marked on world state instead of being silently reused.-Donkey also supports a deterministic dry-run reflex loop skeleton. The loop consumes synthetic or recorded frame batches through a latest-frame-wins buffer with queue depth 1, counts dropped frames, converts signals into compact world state, chooses an inspectable semantic action, projects the action in dry-run mode without OS input, and publishes `ReflexTraceRecord` samples through `RunCoordinator`. This skeleton is for contract validation and replayable tests only; target-window continuous capture and live input are not supported yet.+Donkey also supports a deterministic dry-run reflex loop skeleton. The loop consumes synthetic, recorded, target-window, or local-navigation metadata frame batches through a latest-frame-wins buffer with queue depth 1, counts dropped frames, converts signals into compact world state through a swappable projector, chooses an inspectable semantic action, projects the action in dry-run mode without OS input, and publishes `ReflexTraceRecord` samples through `RunCoordinator`. This skeleton is for contract validation and replayable tests only; continuous streaming capture and live input are not supported yet.Donkey also supports a bounded target-window frame source for the dry-run hot-loop boundary. The frame source reuses macOS window selection and safety checks, captures selected windows through ScreenCaptureKit's desktop-independent window path, returns `HotLoopFrame` metadata for a caller-provided maximum frame count, and records capture latency and copy cost with monotonic timestamps. This path does not write screenshot artifacts and does not PNG/JPEG encode or decode frames. High-resolution manual screenshot artifacts remain separate from reflex frames.@@ -26,9 +26,9 @@ Donkey also supports the first cheap perception and deterministic controller sliDonkey also supports the first action-engine guardrail boundary. `ActionEngineGuardrail` accepts typed tap, swipe, key, mouse, controller, and `releaseAll` commands; checks input permission policy, focus guard status, command rate, and maximum hold duration; tracks held-input state; and records replayable command traces. Live OS input is not implemented and remains disabled by default. Allowed commands are projected as dry-run traces, denied commands include explicit denial reasons, and `releaseAll` clears held-input state even before live input exists.-Donkey also supports reflex latency reports and a synthetic replay benchmark. `ReflexLatencyReportBuilder` summarizes reflex traces into p50/p95/p99 latency, capture/perception/controller rates, dropped frames, stale actions, and worst traces. `ReflexReplayBenchmark` can generate deterministic dry-run traces for capture-only, controller-only, or end-to-end dry-run report modes. The installed debug entrypoint can print a CLI-friendly dry-run latency report with `--dry-run-latency-report`.+Donkey also supports reflex latency reports and a synthetic replay benchmark. `ReflexLatencyReportBuilder` summarizes reflex traces into p50/p95/p99 latency for software-loop, capture, preprocess/crop-normalize, model inference, perception, state update, controller decision, action projection, and input stages, plus capture/perception/controller rates, dropped frames, stale actions, and worst traces. `ReflexReplayBenchmark` can generate deterministic dry-run traces for capture-only, controller-only, or end-to-end dry-run report modes. The installed debug entrypoint can print a CLI-friendly dry-run latency report with `--dry-run-latency-report`.-Donkey also supports the first fast local-navigation dry-run slice. `LocalNavigationMetadataProjector` turns macOS window candidate metadata into typed local-navigation world state with frontmost/focused candidates, safe focus candidates, confidence, source age, and no raw pixels. `LocalNavigationControllerPolicy` can choose traceable dry-run semantic actions such as `focusWindow`, `activateCandidate`, `switchTab`, `wait`, or `observe` from that typed state. This slice is metadata-only and side-effect free; browser-tab metadata adapters, live input, and richer visual inference remain future work.+Donkey also supports the first fast local-navigation dry-run slice end to end through the dry-run reflex loop. `LocalNavigationMetadataFrameSource` can turn macOS window candidate metadata and optional browser-tab metadata supplied by callers into metadata-only hot-loop frames. `LocalNavigationDryRunPerceptionAdapter` and `LocalNavigationDryRunWorldStateProjector` keep the local-navigation path swappable while preserving the no-remote-model fallback. `LocalNavigationControllerPolicy` can choose traceable dry-run semantic actions such as `focusWindow`, `activateCandidate`, `switchTab`, `wait`, or `observe` from typed state. This slice is metadata-only and side-effect free; live input and richer visual inference remain future work.Donkey also supports slow-path planner hint contracts. `StructuredPlannerHint` carries a goal, policy, priorities, regions of interest, preferred and avoided semantic actions, confidence, expiry, and source trace/frame/state/model-call ids. Planner hints are advisory only; they are validated for unknown actions, unsafe actions, stale state references, low-confidence replacement, and expiry before selection. `PlannerHintSelector` chooses the latest valid hint, and the reflex loop remains able to run without any planner hint.@@ -79,6 +79,7 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic- Preserve latest-request-wins behavior for live-control sessions so stale work cannot build up behind the reflex loop.- Keep hot-loop data flowing through `DonkeyContracts` types. Controllers should consume `HotLoopWorldState`, not raw screenshots, detector tensors, or untyped metadata.- Keep dry-run action projection side-effect free. It records semantic action intent and trace evidence, but never calls the input capability.+- Keep dry-run world-state projection swappable. Local-navigation metadata, cheap template metadata, and future local inference adapters should share the loop boundary instead of requiring planner or remote-model output.- Keep reflex frame buffers at queue depth 1. Dropped frames are expected under pressure and should be counted.- Keep target-window reflex frames bounded by caller-provided frame count until a streaming capture loop exists.- Keep manual screenshot artifacts and high-resolution planner snapshots separate from reflex frames. The reflex frame source should not encode PNG/JPEG or write screenshot artifacts.@@ -89,7 +90,7 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic- Keep live OS input disabled until a later smoke slice explicitly wires a real backend. The guardrail boundary may project dry-run commands and release held state, but should not synthesize OS events.- Use monotonic timestamps for latency math. Wall-clock timestamps are for human labels and trace correlation only.- Use latency reports for any p50/p95/p99 claim. Reports should include dropped frames, stale actions, tick rates, and worst traces.-- Keep local-navigation decisions typed and side-effect free until the guarded live-action slice. Metadata projectors may use window and Accessibility facts, but controllers should emit semantic actions only.+- Keep local-navigation decisions typed and side-effect free until the guarded live-action slice. Metadata projectors may use window, browser-tab, and Accessibility facts when available, but controllers should emit semantic actions only.- Treat planner hints as validated, expiring advice. Controllers may use the latest valid hint, but planner output must never become direct input.- Keep model selection in `AIModelRegistry` data. Do not scatter provider model ids through planner code.- Keep privacy-sensitive Responses API calls configured with `store: false` unless an explicit later policy changes that default.@@ -108,7 +109,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, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, OpenAI Responses request shaping and failure handling, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, 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.+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, OpenAI Responses request shaping and failure handling, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, 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:@@ -138,6 +139,7 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi- Reflex latency reports and synthetic replay benchmarks live in `apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift`.- Local-navigation contracts live in `apps/Donkey/Sources/DonkeyContracts/LocalNavigationContracts.swift`.- Local-navigation metadata projection and dry-run action selection live in `apps/Donkey/Sources/DonkeyRuntime/LocalNavigationController.swift`.+- Local-navigation dry-run frame source, loop adapter, world-state projector, and generic controller wrapper live in `apps/Donkey/Sources/DonkeyRuntime/LocalNavigationDryRunLoop.swift`.- AI model registry and routing live in `apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift`.- The first OpenAI Responses planner-hint adapter lives in `apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift`.- Memory contracts live in `apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift`.diff --git a/plans/master-plan.md b/plans/master-plan.mdindex 0f183c1f..85a468e8 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -49,8 +49,8 @@ The hot path must continue to work with the AI harness disabled.## Supported Boundary-- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, in-memory reflex trace retention, and latency reports are supported.-- Reflex hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, deterministic controller, metadata-only local-navigation dry-run action selection, and dry-run action projection are supported. Live OS input is not supported.+- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, in-memory reflex trace retention, and stage-split latency reports are supported.+- Reflex hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, swappable world-state projection, deterministic controller, loop-integrated metadata-only local-navigation dry-run action selection, optional caller-supplied browser-tab metadata, and dry-run action projection are supported. Live OS input is not supported.- Safety boundary: action-engine command contracts, permission/focus/rate/hold/release guardrails, and replayable command traces are supported before live input.- Slow AI boundary: structured planner hints, validation/expiry/latest-valid selection, model registry/router, an OpenAI Responses structured-output adapter, source-linked memory, and replay/eval scaffolding are supported as optional sidecar pieces. The hot loop still runs without AI output.- Source of truth: detailed supported behavior lives in `docs/guides/minimal-run-coordinator.md`; historical implementation details should be found with search in `docs/`, `plans/`, and git history, not duplicated here.@@ -68,27 +68,20 @@ The hot path must continue to work with the AI harness disabled.## Active Queue-1. Finish fast local navigation dry-run closeout.- - Wire local-navigation metadata projection into the dry-run reflex loop instead of testing it only as a standalone projector/controller.- - Add browser-tab metadata where available and keep window metadata as the no-remote-model fallback.- - Add a swappable local perception adapter for fast inference experiments, but keep navigation working without remote models or chat LLMs.- - Measure metadata read, crop/resize/normalize if used, inference if used, world-state update, controller decision, and action projection separately with p50/p95/p99 latency.- - Keep the reflex queue latest-frame/latest-state-wins with queue depth 1, stale-result dropping, and no PNG/JPEG encode/decode in the hot path.--2. Integrate slow planner beside the dry-run loop.+1. Integrate slow planner beside the dry-run loop.- Trigger planner calls on scene change, low confidence, repeated failure, goal completion, or user instruction.- Build compact snapshots from world state, trace summaries, optional screenshots, and memory.- Publish only validated hints to the controller.- Prove planner latency does not move p95 reflex latency.-3. Enable guarded live-action smoke only after dry-run closeout.+2. Enable guarded live-action smoke only after dry-run closeout.- Use fast local navigation as the first target behavior.- Run end-to-end dry-run with input disabled and latency report passing.- Enable live input only with explicit policy allowance and focus guard.- Verify abort and timeout release held input.- Record trace evidence for every action.-4. Close out the primary plans.+3. Close out the primary plans.- Update supported behavior guides in `docs/guides/`.- Move `plans/20-off-the-shelf-run-loop.md` to `plans/done/` when the reflex loop acceptance criteria are supported.- Move `plans/19-ai-harness.md` to `plans/done/` when the AI harness acceptance criteria are supported.@@ -97,9 +90,9 @@ The hot path must continue to work with the AI harness disabled.## What Should Be Done Next-Start with active task 1: finish fast local navigation dry-run closeout.+Start with active task 1: integrate the slow planner beside the dry-run loop.-This is the right next slice because the first metadata-only local-navigation projector and controller can now choose traceable dry-run focus actions with the AI harness disabled. It still needs loop integration, browser-tab metadata where available, and measured local-navigation latency before guarded live input is considered.+This is the right next slice because the metadata-only local-navigation path now runs through the dry-run loop with browser-tab metadata when available, no remote-model dependency, queue depth 1, no hot-path image encoding, and stage-split latency traces. The next gap is proving optional planner calls can publish validated hints without moving reflex p95 latency.## Closeout Criteria