Skip to content

Open source CapCut alternative.

TypeScript

refactor(app): remove unused vision/guidance/smoke/keyboard-backend code

David Lec3eedc3ec488
diff --git a/apps/Donkey/Sources/DonkeyAI/VisionGroundingFlow.swift b/apps/Donkey/Sources/DonkeyAI/VisionGroundingFlow.swift
deleted file mode 100644
index ed593404..00000000
--- a/apps/Donkey/Sources/DonkeyAI/VisionGroundingFlow.swift
+++ /dev/null
@@ -1,133 +0,0 @@
-import CoreGraphics
-import DonkeyContracts
-import DonkeyRuntime
-import Foundation
-
-/// Grounds a target control by VISION when accessibility can't: screenshot the app window, ask the
-/// hosted UI-inspection model for clickable elements, resolve the requested one by text, and map its
-/// screenshot bounding box back to a screen point. This is the fallback for apps whose accessibility
-/// tree is too sparse to ground by text (e.g. Spotify and other Electron apps).
-@MainActor
-public enum VisionGroundingFlow {
- public struct Outcome: Sendable {
- public var screenPoint: CGPoint?
- public var reason: String
- public var matchedLabel: String?
- public var resolvedAppName: String?
-
- public init(screenPoint: CGPoint?, reason: String, matchedLabel: String? = nil, resolvedAppName: String? = nil) {
- self.screenPoint = screenPoint
- self.reason = reason
- self.matchedLabel = matchedLabel
- self.resolvedAppName = resolvedAppName
- }
- }
-
- public typealias ScreenshotCapture = @Sendable (MacWindowTargetCandidate) async throws -> CapturedWindowScreenshot
-
- public static func locate(
- appName: String?,
- bundleIdentifier: String?,
- targetQuery: String,
- analyzer: DebugUIInspectionAnalyzing,
- minConfidence: Double = 0.25,
- capture: ScreenshotCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: $0) },
- windowResolver: MacWindowResolver = MacWindowResolver()
- ) async -> Outcome {
- guard let target = AccessibilityObserver.resolveTarget(
- appName: appName,
- bundleIdentifier: bundleIdentifier,
- resolver: windowResolver
- ) else {
- return Outcome(screenPoint: nil, reason: "noWindowForApp")
- }
-
- let shot: CapturedWindowScreenshot
- do {
- shot = try await capture(target)
- } catch {
- return Outcome(screenPoint: nil, reason: "screenshotFailed", resolvedAppName: target.appName)
- }
- guard shot.imageWidth > 0, shot.imageHeight > 0 else {
- return Outcome(screenPoint: nil, reason: "emptyScreenshot", resolvedAppName: target.appName)
- }
-
- // Compress (downscale + JPEG) through the shared helper so this request matches every other
- // hosted-vision request; the model's coordinates then map back through the COMPRESSED size.
- let compressed = ScreenshotCompression.compressedForModel(shot)
- // The hosted vision model occasionally returns malformed JSON; retry a few times.
- let request = DebugUIInspectionRequest(
- imageDataURL: compressed.base64DataURL,
- pixelSize: compressed.pixelSize,
- minConfidence: minConfidence
- )
- var frame: DebugUIInspectionFrame?
- var lastError: Error?
- for _ in 0..<3 {
- do {
- frame = try await analyzer.inspect(request)
- break
- } catch {
- lastError = error
- }
- }
- guard let frame else {
- return Outcome(screenPoint: nil, reason: "visionInspectionFailed: \(lastError.map { "\($0)" } ?? "unknown")", resolvedAppName: target.appName)
- }
-
- guard let element = resolveElement(targetQuery, in: frame.elements) else {
- return Outcome(screenPoint: nil, reason: "elementNotFound", resolvedAppName: target.appName)
- }
- let point = screenPoint(
- bbox: element.bbox,
- imageWidth: Int(compressed.pixelSize.width.rounded()),
- imageHeight: Int(compressed.pixelSize.height.rounded()),
- window: target.bounds
- )
- return Outcome(screenPoint: point, reason: "ok", matchedLabel: element.label, resolvedAppName: target.appName)
- }
-
- /// Resolves the best inspected element for `query` by text relevance over its label/description/type.
- nonisolated static func resolveElement(_ query: String, in elements: [DebugUIElement]) -> DebugUIElement? {
- let normalizedQuery = query.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
- guard !normalizedQuery.isEmpty else { return nil }
- let queryTokens = ControlTextRelevance.tokens(in: normalizedQuery)
-
- var best: (element: DebugUIElement, score: Double)?
- for element in elements where element.bbox.hasPositiveArea {
- let candidates = [element.label, element.description, element.type.rawValue]
- .map { $0.lowercased() }
- .filter { !$0.isEmpty }
- let score = ControlTextRelevance.score(
- normalizedQuery: normalizedQuery,
- queryTokens: queryTokens,
- candidates: candidates
- )
- guard score > 0 else { continue }
- // Tie-break toward higher model confidence.
- let composite = score * 1_000 + element.confidence
- if best == nil || composite > best!.score {
- best = (element, composite)
- }
- }
- return best?.element
- }
-
- /// Maps a screenshot-pixel bounding box center to a screen point, given the window's screen
- /// bounds and the screenshot pixel size (handles Retina scaling between the two).
- nonisolated static func screenPoint(
- bbox: DebugUIBoundingBox,
- imageWidth: Int,
- imageHeight: Int,
- window: WindowTargetBounds
- ) -> CGPoint {
- let scaleX = window.width / Double(imageWidth)
- let scaleY = window.height / Double(imageHeight)
- let centerX = bbox.x + bbox.width / 2
- let centerY = bbox.y + bbox.height / 2
- return CGPoint(
- x: window.x + centerX * scaleX,
- y: window.y + centerY * scaleY
- )
- }
-}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/GuardedLiveActionSmoke.swift b/apps/Donkey/Sources/DonkeyRuntime/GuardedLiveActionSmoke.swift
deleted file mode 100644
index f02b31c7..00000000
--- a/apps/Donkey/Sources/DonkeyRuntime/GuardedLiveActionSmoke.swift
+++ /dev/null
@@ -1,157 +0,0 @@
-import DonkeyContracts
-import Foundation
-
-public enum GuardedLiveActionSmokeStatus: String, Codable, Equatable, Sendable {
- case executed
- case skipped
- case denied
-}
-
-public struct GuardedLiveActionSmokeResult: Equatable, Sendable {
- public var status: GuardedLiveActionSmokeStatus
- public var reason: String
- public var commandTrace: ActionEngineCommandTrace?
- public var metadata: [String: String]
-
- public init(
- status: GuardedLiveActionSmokeStatus,
- reason: String,
- commandTrace: ActionEngineCommandTrace? = nil,
- metadata: [String: String] = [:]
- ) {
- self.status = status
- self.reason = reason
- self.commandTrace = commandTrace
- self.metadata = metadata
- }
-}
-
-public struct GuardedLiveActionSmokeRunner: Sendable {
- public var actionEngine: ActionEngineGuardrail
-
- public init(actionEngine: ActionEngineGuardrail) {
- self.actionEngine = actionEngine
- }
-
- public func run(
- dryRunResult: DryRunReflexLoopResult,
- latencyReport: ReflexLatencyReport,
- session: RunSession,
- issuedAt: RunTraceTimestamp
- ) async -> GuardedLiveActionSmokeResult {
- guard latencyReport.traceCount > 0,
- latencyReport.softwareLoopMS.p95 != nil
- else {
- return GuardedLiveActionSmokeResult(
- status: .skipped,
- reason: "dry-run latency report is missing p95 evidence",
- metadata: reportMetadata(latencyReport)
- )
- }
-
- guard let state = dryRunResult.latestWorldState,
- let action = dryRunResult.latestAction
- else {
- return GuardedLiveActionSmokeResult(
- status: .skipped,
- reason: "dry-run loop did not produce state and action"
- )
- }
-
- guard action.metadata["fallback"] != "true" else {
- return GuardedLiveActionSmokeResult(
- status: .skipped,
- reason: "latest dry-run action is a fallback",
- metadata: [
- "fallbackReason": action.metadata["fallbackReason"] ?? "unknown"
- ]
- )
- }
-
- guard let command = Self.command(
- for: action,
- state: state,
- targetID: session.targetID,
- issuedAt: issuedAt
- ) else {
- return GuardedLiveActionSmokeResult(
- status: .skipped,
- reason: "latest dry-run action cannot be mapped to a live command",
- metadata: [
- "action.kind": action.kind.rawValue
- ]
- )
- }
-
- let trace = await actionEngine.handle(
- command,
- permissionPolicy: session.permissionPolicy
- )
-
- switch trace.decision {
- case .executedLive:
- return GuardedLiveActionSmokeResult(
- status: .executed,
- reason: "guarded live action executed",
- commandTrace: trace,
- metadata: reportMetadata(latencyReport)
- )
- case .skippedNoLiveInput:
- return GuardedLiveActionSmokeResult(
- status: .skipped,
- reason: "action engine skipped live input",
- commandTrace: trace,
- metadata: reportMetadata(latencyReport)
- )
- case .denied(let reason):
- return GuardedLiveActionSmokeResult(
- status: .denied,
- reason: reason,
- commandTrace: trace,
- metadata: reportMetadata(latencyReport)
- )
- }
- }
-
- public static func command(
- for action: HotLoopControllerAction,
- state: HotLoopWorldState,
- targetID: String,
- issuedAt: RunTraceTimestamp
- ) -> ActionEngineCommand? {
- switch action.kind {
- case .tapTarget, .focusWindow, .switchTab, .activateCandidate:
- guard let target = action.target else { return nil }
- return ActionEngineCommand(
- id: "live-smoke-\(action.id)",
- traceID: action.traceID,
- targetID: targetID,
- stateID: state.id,
- actionID: action.id,
- kind: .tap,
- issuedAt: issuedAt,
- targetBounds: target,
- metadata: [
- "sourceActionKind": action.kind.rawValue,
- "smoke": "guardedLiveAction"
- ].merging(action.metadata) { current, _ in current }
- )
- case .observe, .wait, .openAppSwitcher:
- return nil
- }
- }
-
- private func reportMetadata(_ report: ReflexLatencyReport) -> [String: String] {
- [
- "dryRun.traceCount": String(report.traceCount),
- "dryRun.softwareLoopP95MS": format(report.softwareLoopMS.p95),
- "dryRun.droppedFrameCount": String(report.droppedFrameCount),
- "dryRun.staleActionCount": String(report.staleActionCount)
- ]
- }
-
- private func format(_ value: Double?) -> String {
- guard let value else { return "unknown" }
- return String(format: "%.2f", value)
- }
-}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/GuidanceOverlayFlow.swift b/apps/Donkey/Sources/DonkeyRuntime/GuidanceOverlayFlow.swift
deleted file mode 100644
index b04d816f..00000000
--- a/apps/Donkey/Sources/DonkeyRuntime/GuidanceOverlayFlow.swift
+++ /dev/null
@@ -1,70 +0,0 @@
-@preconcurrency import ApplicationServices
-import DonkeyContracts
-import Foundation
-
-/// Produces an accessibility-grounded cursor overlay for a guidance request ("show me where X is").
-///
-/// Visualization-only: it captures the target app's accessibility tree, grounds the requested
-/// controls to a cursor path, and returns an overlay request. It never performs input
-/// (`realPointerMoved` stays false). Because it relies only on the accessibility tree, it works on
-/// any app that exposes one — native or Electron (Chromium) — which is exactly the case where
-/// AppleScript cannot help.
-@MainActor
-public enum GuidanceOverlayFlow {
- public struct Outcome: Sendable {
- public var request: PointerCoachCursorGuideRequest?
- public var reason: String
- public var resolvedAppName: String?
-
- public init(request: PointerCoachCursorGuideRequest?, reason: String, resolvedAppName: String?) {
- self.request = request
- self.reason = reason
- self.resolvedAppName = resolvedAppName
- }
- }
-
- public static func cursorGuide(
- appName: String?,
- bundleIdentifier: String?,
- targets: [AccessibilityCursorPathTarget],
- title: String,
- traceID: String,
- windowResolver: MacWindowResolver = MacWindowResolver()
- ) -> Outcome {
- guard AXIsProcessTrusted() else {
- return Outcome(request: nil, reason: "accessibilityNotTrusted", resolvedAppName: nil)
- }
- guard !targets.isEmpty else {
- return Outcome(request: nil, reason: "noTargets", resolvedAppName: nil)
- }
- guard let observation = AccessibilityObserver.observe(
- appName: appName,
- bundleIdentifier: bundleIdentifier,
- resolver: windowResolver
- ) else {
- return Outcome(request: nil, reason: "accessibilityObservationUnavailable", resolvedAppName: nil)
- }
- let target = observation.target
- let steps = AccessibilityCursorPathBuilder.buildSteps(
- targetApp: target.appName ?? appName ?? "",
- windowBounds: target.bounds,
- controls: observation.controls,
- targets: targets,
- phaseID: "guidance"
- )
- guard !steps.isEmpty else {
- return Outcome(request: nil, reason: "noGroundedTargets", resolvedAppName: target.appName)
- }
- let trace = AgentPathTrace(
- taskID: traceID,
- title: title,
- sourceTraceID: traceID,
- steps: steps,
- metadata: ["mode": "guidance", "realPointerMoved": "false"]
- )
- guard let request = trace.visualizationPlan()?.cursorOverlayRequest() else {
- return Outcome(request: nil, reason: "noOverlayRequest", resolvedAppName: target.appName)
- }
- return Outcome(request: request, reason: "ok", resolvedAppName: target.appName)
- }
-}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacKeyboardActionEngineInputBackend.swift b/apps/Donkey/Sources/DonkeyRuntime/MacKeyboardActionEngineInputBackend.swift
deleted file mode 100644
index 4ad4958f..00000000
--- a/apps/Donkey/Sources/DonkeyRuntime/MacKeyboardActionEngineInputBackend.swift
+++ /dev/null
@@ -1,375 +0,0 @@
-import AppKit
-import CoreGraphics
-import DonkeyContracts
-import Foundation
-
-struct MacKeyboardTextEntryExecution: Equatable, Sendable {
- var executed: Bool
- var inputMode: String
- var metadata: [String: String]
-
- init(
- executed: Bool,
- inputMode: String,
- metadata: [String: String] = [:]
- ) {
- self.executed = executed
- self.inputMode = inputMode
- self.metadata = metadata
- }
-}
-
-public struct MacKeyboardActionEngineInputBackend: ActionEngineInputBackend {
- private let keyCommandPoster: @Sendable (String) -> Bool
- private let mouseClickPoster: @Sendable (CGPoint) -> Bool
- private let textEntryExecutor: @Sendable (
- String,
- @escaping @Sendable (String) -> Bool
- ) async -> MacKeyboardTextEntryExecution
-
- public init() {
- self.keyCommandPoster = Self.postKeyCommand
- self.mouseClickPoster = Self.postMouseClick
- self.textEntryExecutor = Self.pasteText
- }
-
- init(
- keyCommandPoster: @escaping @Sendable (String) -> Bool,
- mouseClickPoster: @escaping @Sendable (CGPoint) -> Bool = Self.postMouseClick,
- textEntryExecutor: @escaping @Sendable (
- String,
- @escaping @Sendable (String) -> Bool
- ) async -> MacKeyboardTextEntryExecution
- ) {
- self.keyCommandPoster = keyCommandPoster
- self.mouseClickPoster = mouseClickPoster
- self.textEntryExecutor = textEntryExecutor
- }
-
- public func execute(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult {
- if command.kind == .tap {
- return await executeTap(command)
- }
-
- guard command.kind == .key, let key = command.key else {
- return result(
- command: command,
- executed: false,
- metadata: [
- "liveInputBackend": "mac-keyboard",
- "inputMode": "keyboard",
- "elementClick": "false",
- "reason": "unsupportedCommandKind"
- ]
- )
- }
-
- let executed: Bool
- let inputMode: String
- var inputMetadata: [String: String] = [:]
- if command.metadata["inputRole"] == "textEntry" {
- let textResult = await textEntryExecutor(key, keyCommandPoster)
- executed = textResult.executed
- inputMode = textResult.inputMode
- inputMetadata = textResult.metadata
- } else {
- executed = keyCommandPoster(key)
- inputMode = "keyCommand"
- }
-
- if executed {
- try? await Task.sleep(nanoseconds: 80_000_000)
- }
-
- return result(
- command: command,
- executed: executed,
- metadata: [
- "liveInputBackend": "mac-keyboard",
- "inputMode": inputMode,
- "elementClick": "false",
- "key": key
- ].merging(inputMetadata) { current, _ in current }
- )
- }
-
- private func executeTap(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult {
- guard let point = screenCenter(of: command.targetBounds) else {
- return result(
- command: command,
- executed: false,
- metadata: [
- "liveInputBackend": "mac-keyboard",
- "inputMode": "coordinateClick",
- "elementClick": "true",
- "reason": "missingScreenTargetBounds"
- ]
- )
- }
-
- let executed = mouseClickPoster(point)
- if executed {
- try? await Task.sleep(nanoseconds: 80_000_000)
- }
- return result(
- command: command,
- executed: executed,
- metadata: [
- "liveInputBackend": "mac-keyboard",
- "inputMode": "coordinateClick",
- "elementClick": "true",
- "targetPoint.x": String(Double(point.x)),
- "targetPoint.y": String(Double(point.y)),
- "controlID": command.metadata["controlID"] ?? "",
- "visualFallback": command.metadata["visualFallback"] ?? ""
- ]
- )
- }
-
- private func screenCenter(of rect: HotLoopRect?) -> CGPoint? {
- guard let rect,
- rect.hasPositiveArea,
- rect.space == .screen
- else {
- return nil
- }
- return CGPoint(
- x: rect.origin.x + rect.size.width / 2,
- y: rect.origin.y + rect.size.height / 2
- )
- }
-
- private func result(
- command: ActionEngineCommand,
- executed: Bool,
- metadata: [String: String]
- ) -> ActionEngineInputBackendResult {
- ActionEngineInputBackendResult(
- executed: executed,
- completedAt: Self.now(),
- metadata: metadata
- )
- }
-
- private static func pasteText(
- _ text: String,
- postKeyCommand: @escaping @Sendable (String) -> Bool
- ) async -> MacKeyboardTextEntryExecution {
- guard !text.isEmpty else {
- return MacKeyboardTextEntryExecution(
- executed: false,
- inputMode: "pasteboardText",
- metadata: ["reason": "emptyText"]
- )
- }
-
- let pasteboard = NSPasteboard.general
- let snapshot = PasteboardSnapshot.capture(from: pasteboard)
- pasteboard.clearContents()
- guard pasteboard.setString(text, forType: .string) else {
- snapshot.restore(to: pasteboard)
- return MacKeyboardTextEntryExecution(
- executed: false,
- inputMode: "pasteboardText",
- metadata: ["reason": "pasteboardWriteFailed"]
- )
- }
- let textChangeCount = pasteboard.changeCount
-
- try? await Task.sleep(nanoseconds: 30_000_000)
- let pasted = postKeyCommand("Command+V")
- try? await Task.sleep(nanoseconds: 400_000_000)
- if pasteboard.changeCount == textChangeCount {
- snapshot.restore(to: pasteboard)
- }
-
- return MacKeyboardTextEntryExecution(
- executed: pasted,
- inputMode: "pasteboardText",
- metadata: [
- "textEntry.method": "pasteboard",
- "textEntry.shortcut": "Command+V",
- "textEntry.characterCount": String(text.count)
- ]
- )
- }
-
- private static func postKeyCommand(_ command: String) -> Bool {
- let parts = command
- .split(separator: "+")
- .map { String($0).trimmingCharacters(in: .whitespacesAndNewlines) }
- .filter { !$0.isEmpty }
- guard let keyName = parts.last,
- let keyCode = Self.keyCode(for: keyName),
- let source = CGEventSource(stateID: .hidSystemState)
- else {
- return false
- }
-
- let flags = Self.flags(for: Array(parts.dropLast()))
- guard let keyDown = CGEvent(keyboardEventSource: source, virtualKey: keyCode, keyDown: true),
- let keyUp = CGEvent(keyboardEventSource: source, virtualKey: keyCode, keyDown: false)
- else {
- return false
- }
-
- keyDown.flags = flags
- keyUp.flags = flags
- keyDown.post(tap: .cghidEventTap)
- keyUp.post(tap: .cghidEventTap)
- return true
- }
-
- private static func postMouseClick(at point: CGPoint) -> Bool {
- guard let source = CGEventSource(stateID: .hidSystemState),
- let mouseDown = CGEvent(
- mouseEventSource: source,
- mouseType: .leftMouseDown,
- mouseCursorPosition: point,
- mouseButton: .left
- ),
- let mouseUp = CGEvent(
- mouseEventSource: source,
- mouseType: .leftMouseUp,
- mouseCursorPosition: point,
- mouseButton: .left
- )
- else {
- return false
- }
- mouseDown.post(tap: .cghidEventTap)
- mouseUp.post(tap: .cghidEventTap)
- return true
- }
-
- private static func flags(for modifiers: [String]) -> CGEventFlags {
- var flags: CGEventFlags = []
- for modifier in modifiers.map({ $0.lowercased() }) {
- switch modifier {
- case "command", "cmd", "⌘":
- flags.insert(.maskCommand)
- case "shift", "⇧":
- flags.insert(.maskShift)
- case "option", "alt", "⌥":
- flags.insert(.maskAlternate)
- case "control", "ctrl", "⌃":
- flags.insert(.maskControl)
- default:
- continue
- }
- }
- return flags
- }
-
- private static func keyCode(for keyName: String) -> CGKeyCode? {
- switch keyName.lowercased() {
- case "return", "enter":
- return 36
- case "tab":
- return 48
- case "escape", "esc":
- return 53
- case "space":
- return 49
- case "a":
- return 0
- case "b":
- return 11
- case "c":
- return 8
- case "d":
- return 2
- case "e":
- return 14
- case "f":
- return 3
- case "g":
- return 5
- case "h":
- return 4
- case "i":
- return 34
- case "j":
- return 38
- case "k":
- return 40
- case "l":
- return 37
- case "m":
- return 46
- case "n":
- return 45
- case "o":
- return 31
- case "p":
- return 35
- case "q":
- return 12
- case "r":
- return 15
- case "s":
- return 1
- case "t":
- return 17
- case "u":
- return 32
- case "v":
- return 9
- case "w":
- return 13
- case "x":
- return 7
- case "y":
- return 16
- case "z":
- return 6
- default:
- return nil
- }
- }
-
- private static func now() -> RunTraceTimestamp {
- RunTraceTimestamp(
- wallClock: Date(),
- monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)
- )
- }
-}
-
-private struct PasteboardSnapshot {
- var items: [Item]
-
- struct Item {
- var representations: [(type: String, data: Data)]
- }
-
- static func capture(from pasteboard: NSPasteboard) -> PasteboardSnapshot {
- PasteboardSnapshot(
- items: (pasteboard.pasteboardItems ?? []).map { item in
- Item(
- representations: item.types.compactMap { type in
- guard let data = item.data(forType: type) else { return nil }
- return (type.rawValue, data)
- }
- )
- }
- )
- }
-
- func restore(to pasteboard: NSPasteboard) {
- pasteboard.clearContents()
- let pasteboardItems = items.compactMap { item -> NSPasteboardItem? in
- let pasteboardItem = NSPasteboardItem()
- var wroteRepresentation = false
- for representation in item.representations {
- let type = NSPasteboard.PasteboardType(representation.type)
- wroteRepresentation = pasteboardItem.setData(representation.data, forType: type)
- || wroteRepresentation
- }
- return wroteRepresentation ? pasteboardItem : nil
- }
- if !pasteboardItems.isEmpty {
- pasteboard.writeObjects(pasteboardItems)
- }
- }
-}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GuardedLiveActionSmokeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GuardedLiveActionSmokeTests.swift
deleted file mode 100644
index 31f8c8fc..00000000
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GuardedLiveActionSmokeTests.swift
+++ /dev/null
@@ -1,326 +0,0 @@
-import DonkeyContracts
-@testable import DonkeyRuntime
-import Foundation
-import Testing
-
-@Suite
-struct GuardedLiveActionSmokeTests {
- @Test
- func localNavigationLiveSmokeRequiresDryRunReportPolicyAndFocusGuard() async {
- let dryRunCoordinator = RunCoordinator()
- let dryRunSession = RunSession(
- id: "dry-run-session",
- userGoal: "focus Code",
- targetID: "local-navigation"
- )
- 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-smoke",
- requestedBundleIdentifier: "com.microsoft.VSCode"
- )
- )
- let dryRunLoop = DryRunReflexLoop(
- coordinator: dryRunCoordinator,
- frameSource: source,
- perceptionAdapter: LocalNavigationDryRunPerceptionAdapter(),
- worldStateProjector: LocalNavigationDryRunWorldStateProjector(),
- controllerPolicy: LocalNavigationDryRunControllerPolicy()
- )
-
- let dryRunResult = await dryRunLoop.run(session: dryRunSession)
- let report = await ReflexLatencyReportBuilder.build(
- from: dryRunCoordinator.reflexTraces(),
- droppedFrameCount: dryRunResult.droppedFrameCount
- )
-
- #expect(dryRunSession.permissionPolicy.decision(for: .input).isAllowed == false)
- #expect(report.traceCount == 1)
- #expect(report.softwareLoopMS.p95 != nil)
- #expect(dryRunResult.latestAction?.kind == .focusWindow)
-
- let backend = RecordingSmokeInputBackend()
- let runner = GuardedLiveActionSmokeRunner(
- actionEngine: ActionEngineGuardrail(
- configuration: ActionEngineConfiguration(liveInputEnabled: true),
- focusGuard: AllowingFocusGuard(),
- inputBackend: backend
- )
- )
- let liveSession = RunSession(
- id: "live-smoke-session",
- userGoal: "focus Code",
- targetID: "local-navigation",
- permissionPolicy: ToolCallPolicy(deniedCapabilities: [])
- )
-
- let smoke = await runner.run(
- dryRunResult: dryRunResult,
- latencyReport: report,
- session: liveSession,
- issuedAt: timestamp(100)
- )
-
- #expect(smoke.status == .executed)
- #expect(smoke.commandTrace?.decision == .executedLive)
- #expect(smoke.commandTrace?.executed == true)
- #expect(smoke.commandTrace?.focusGuardPassed == true)
- #expect(smoke.commandTrace?.command.kind == .tap)
- #expect(smoke.commandTrace?.command.metadata["sourceActionKind"] == "focusWindow")
- #expect(await backend.executedCommandIDs() == ["live-smoke-action-local-nav-state-trace-local-nav-smoke"])
- }
-
- @Test
- func liveSmokeIsDeniedWithoutExplicitInputPolicy() async {
- let state = worldState()
- let action = action(state: state)
- let result = DryRunReflexLoopResult(
- processedFrameCount: 1,
- droppedFrameCount: 0,
- latestWorldState: state,
- latestAction: action
- )
- let report = reportForDryRun()
- let backend = RecordingSmokeInputBackend()
- let runner = GuardedLiveActionSmokeRunner(
- actionEngine: ActionEngineGuardrail(
- configuration: ActionEngineConfiguration(liveInputEnabled: true),
- inputBackend: backend
- )
- )
-
- let smoke = await runner.run(
- dryRunResult: result,
- latencyReport: report,
- session: RunSession(id: "session-denied", userGoal: "focus", targetID: "target-1"),
- issuedAt: timestamp(100)
- )
-
- #expect(smoke.status == .denied)
- #expect(smoke.commandTrace?.decision == .denied(reason: "input permission denied"))
- #expect(await backend.executedCommandIDs().isEmpty)
- }
-
- @Test
- func liveSmokeIsDeniedWhenFocusGuardFailsAndReleasesHeldInputOnAbort() async {
- let state = worldState()
- let action = action(state: state)
- let engine = ActionEngineGuardrail(
- configuration: ActionEngineConfiguration(liveInputEnabled: true),
- focusGuard: DenyingSmokeFocusGuard(),
- inputBackend: RecordingSmokeInputBackend()
- )
- let runner = GuardedLiveActionSmokeRunner(actionEngine: engine)
- let liveSession = RunSession(
- id: "session-focus-denied",
- userGoal: "focus",
- targetID: "target-1",
- permissionPolicy: ToolCallPolicy(deniedCapabilities: [])
- )
-
- let smoke = await runner.run(
- dryRunResult: DryRunReflexLoopResult(
- processedFrameCount: 1,
- droppedFrameCount: 0,
- latestWorldState: state,
- latestAction: action
- ),
- latencyReport: reportForDryRun(),
- session: liveSession,
- issuedAt: timestamp(100)
- )
- #expect(smoke.status == .denied)
- #expect(smoke.commandTrace?.decision == .denied(reason: "focus guard failed"))
-
- let holdingEngine = ActionEngineGuardrail(
- configuration: ActionEngineConfiguration(liveInputEnabled: true),
- inputBackend: RecordingSmokeInputBackend()
- )
- _ = await holdingEngine.handle(
- ActionEngineCommand(
- id: "hold-1",
- traceID: "trace-1",
- targetID: "target-1",
- kind: .key,
- issuedAt: timestamp(110),
- key: "Command",
- holdDurationMS: 50
- ),
- permissionPolicy: ToolCallPolicy(deniedCapabilities: [])
- )
- #expect(await holdingEngine.heldInputCount() == 1)
-
- let release = await holdingEngine.releaseAll(
- traceID: "trace-1",
- targetID: "target-1",
- issuedAt: timestamp(120)
- )
-
- #expect(release.releaseAll == true)
- #expect(release.metadata["heldInputReleased"] == "true")
- #expect(await holdingEngine.heldInputCount() == 0)
- }
-
- private func worldState() -> HotLoopWorldState {
- HotLoopWorldState(
- id: "state-1",
- traceID: "trace-1",
- frameID: "frame-1",
- targetID: "target-1",
- observedAt: timestamp(10),
- signalSummaries: [
- HotLoopPerceptionSignalSummary(
- id: "signal-1",
- kind: "localNavigationMetadata",
- confidence: 0.9,
- observationCount: 1
- )
- ],
- actionAffordances: [],
- confidence: 0.9
- )
- }
-
- private func action(state: HotLoopWorldState) -> HotLoopControllerAction {
- HotLoopControllerAction(
- id: "action-1",
- traceID: state.traceID,
- frameID: state.frameID,
- stateID: state.id,
- kind: .focusWindow,
- target: HotLoopRect(x: 10, y: 20, width: 300, height: 200, space: .screen),
- policyName: "local-navigation-controller-v1",
- confidence: 0.9,
- rationale: "focus target",
- metadata: ["fallback": "false"]
- )
- }
-
- private func reportForDryRun() -> ReflexLatencyReport {
- ReflexLatencyReport(
- mode: .endToEndDryRun,
- traceCount: 1,
- softwareLoopMS: ReflexLatencyPercentiles(p50: 4, p95: 4, p99: 4),
- captureMS: ReflexLatencyPercentiles(p50: 0, p95: 0, p99: 0),
- perceptionMS: ReflexLatencyPercentiles(p50: 1, p95: 1, p99: 1),
- decisionMS: ReflexLatencyPercentiles(p50: 1, p95: 1, p99: 1),
- inputMS: ReflexLatencyPercentiles(p50: 0, p95: 0, p99: 0)
- )
- }
-
- 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),
- monotonicUptimeNanoseconds: milliseconds * 1_000_000
- )
- }
-}
-
-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
- }
-}
-
-private struct AllowingFocusGuard: ActionEngineFocusGuard {
- func targetIsSafeForInput(targetID: String) async -> Bool {
- true
- }
-}
-
-private struct DenyingSmokeFocusGuard: ActionEngineFocusGuard {
- func targetIsSafeForInput(targetID: String) async -> Bool {
- false
- }
-}
-
-private actor RecordingSmokeInputBackend: ActionEngineInputBackend {
- private var commandIDs: [String] = []
-
- func execute(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult {
- commandIDs.append(command.id)
- return ActionEngineInputBackendResult(
- executed: true,
- completedAt: command.issuedAt,
- metadata: ["liveInputBackend": "recording-smoke"]
- )
- }
-
- func executedCommandIDs() -> [String] {
- commandIDs
- }
-}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GuidanceOverlayLiveSmokeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GuidanceOverlayLiveSmokeTests.swift
deleted file mode 100644
index 96e03042..00000000
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GuidanceOverlayLiveSmokeTests.swift
+++ /dev/null
@@ -1,61 +0,0 @@
-import AppKit
-@testable import Donkey
-import DonkeyContracts
-import DonkeyRuntime
-import DonkeyUI
-import Foundation
-import Testing
-
-/// Live, env-gated smoke test for the guidance overlay (plan phase 2): capture a running app's
-/// accessibility tree, ground a named control, and animate the pointer to it — visualization only,
-/// no input. Works on any app with an accessibility tree (native or Electron).
-///
-/// env DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer DONKEY_LIVE_SMOKE=1 \
-/// [DONKEY_GUIDE_APP=Spotify] [DONKEY_GUIDE_TARGET=Search] \
-/// swift test --filter GuidanceOverlayLiveSmokeTests
-@Suite
-struct GuidanceOverlayLiveSmokeTests {
- @Test
- @MainActor
- func showsPointerAtAControlInARunningApp() {
- let env = ProcessInfo.processInfo.environment
- guard env["DONKEY_LIVE_SMOKE"] == "1" else { return }
-
- let appName = env["DONKEY_GUIDE_APP"] ?? "Music"
- let targetText = env["DONKEY_GUIDE_TARGET"] ?? "Search"
-
- // Bring the app to the front so the overlay is visible over it.
- NSWorkspace.shared.launchApplication(appName)
- pump(0.8)
-
- let outcome = GuidanceOverlayFlow.cursorGuide(
- appName: appName,
- bundleIdentifier: nil,
- targets: [
- AccessibilityCursorPathTarget(query: targetText, label: "Here: \(targetText)", kind: .targetControl)
- ],
- title: "Where is \(targetText)",
- traceID: "guidance-smoke"
- )
-
- guard let request = outcome.request else {
- Issue.record("No grounded overlay (reason=\(outcome.reason), app=\(outcome.resolvedAppName ?? "nil")). Grant Accessibility + ensure \(appName) is running with a '\(targetText)' control.")
- return
- }
-
- #expect(!request.steps.isEmpty)
-
- if NSApplication.shared.activationPolicy() == .prohibited {
- NSApplication.shared.setActivationPolicy(.accessory)
- }
- let overlay = PointerCoachCursorOverlayController()
- overlay.show(request: request)
- let duration = request.steps.reduce(1.5) { $0 + $1.travelDuration + $1.holdDuration }
- pump(duration)
- }
-
- @MainActor
- private func pump(_ seconds: TimeInterval) {
- RunLoop.main.run(until: Date().addingTimeInterval(seconds))
- }
-}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MacKeyboardActionEngineInputBackendTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MacKeyboardActionEngineInputBackendTests.swift
deleted file mode 100644
index b7e3b761..00000000
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/MacKeyboardActionEngineInputBackendTests.swift
+++ /dev/null
@@ -1,156 +0,0 @@
-@testable import DonkeyRuntime
-import DonkeyContracts
-import CoreGraphics
-import Foundation
-import Testing
-
-@Suite
-struct MacKeyboardActionEngineInputBackendTests {
- @Test
- func textEntryUsesPasteboardBackedPasteCommand() async {
- let recorder = KeyboardCommandRecorder()
- let backend = MacKeyboardActionEngineInputBackend(
- keyCommandPoster: { command in
- recorder.append(command)
- return true
- },
- textEntryExecutor: { text, postKeyCommand in
- let pasted = postKeyCommand("Command+V")
- return MacKeyboardTextEntryExecution(
- executed: pasted,
- inputMode: "pasteboardText",
- metadata: [
- "textEntry.method": "pasteboard",
- "textEntry.shortcut": "Command+V",
- "textEntry.characterCount": String(text.count)
- ]
- )
- }
- )
-
- let result = await backend.execute(command(
- key: "Sample Result",
- metadata: ["inputRole": "textEntry"]
- ))
-
- #expect(result.executed == true)
- #expect(result.metadata["inputMode"] == "pasteboardText")
- #expect(result.metadata["textEntry.method"] == "pasteboard")
- #expect(result.metadata["textEntry.shortcut"] == "Command+V")
- #expect(result.metadata["textEntry.characterCount"] == "13")
- #expect(recorder.commands() == ["Command+V"])
- }
-
- @Test
- func ordinaryKeyCommandsDoNotUseTextEntryPastePath() async {
- let recorder = KeyboardCommandRecorder()
- let backend = MacKeyboardActionEngineInputBackend(
- keyCommandPoster: { command in
- recorder.append(command)
- return true
- },
- textEntryExecutor: { _, _ in
- MacKeyboardTextEntryExecution(
- executed: false,
- inputMode: "pasteboardText",
- metadata: ["reason": "unexpectedTextEntry"]
- )
- }
- )
-
- let result = await backend.execute(command(key: "Command+F"))
-
- #expect(result.executed == true)
- #expect(result.metadata["inputMode"] == "keyCommand")
- #expect(result.metadata["reason"] == nil)
- #expect(recorder.commands() == ["Command+F"])
- }
-
- @Test
- func tapCommandsClickCenterOfScreenTargetBounds() async {
- let recorder = MouseClickRecorder()
- let backend = MacKeyboardActionEngineInputBackend(
- keyCommandPoster: { _ in false },
- mouseClickPoster: { point in
- recorder.append(point)
- return true
- },
- textEntryExecutor: { _, _ in
- MacKeyboardTextEntryExecution(executed: false, inputMode: "pasteboardText")
- }
- )
-
- let result = await backend.execute(ActionEngineCommand(
- id: "tap-visual-send",
- traceID: "trace-coordinate-click",
- targetID: "local-app-task-test",
- kind: .tap,
- issuedAt: RunTraceTimestamp(
- wallClock: Date(timeIntervalSince1970: 0),
- monotonicUptimeNanoseconds: 0
- ),
- targetBounds: HotLoopRect(x: 100, y: 200, width: 80, height: 40, space: .screen),
- metadata: ["controlID": "send", "visualFallback": "aiOrObservedBounds"]
- ))
-
- #expect(result.executed == true)
- #expect(result.metadata["inputMode"] == "coordinateClick")
- #expect(result.metadata["elementClick"] == "true")
- #expect(result.metadata["controlID"] == "send")
- #expect(recorder.points() == [CGPoint(x: 140, y: 220)])
- }
-
- private func command(
- key: String,
- metadata: [String: String] = [:]
- ) -> ActionEngineCommand {
- ActionEngineCommand(
- id: "keyboard-\(key)",
- traceID: "trace-keyboard",
- targetID: "local-app-task-test",
- kind: .key,
- issuedAt: RunTraceTimestamp(
- wallClock: Date(timeIntervalSince1970: 0),
- monotonicUptimeNanoseconds: 0
- ),
- key: key,
- metadata: metadata
- )
- }
-}
-
-private final class KeyboardCommandRecorder: @unchecked Sendable {
- private let lock = NSLock()
- private var recordedCommands: [String] = []
-
- func append(_ command: String) {
- lock.lock()
- recordedCommands.append(command)
- lock.unlock()
- }
-
- func commands() -> [String] {
- lock.lock()
- let commands = recordedCommands
- lock.unlock()
- return commands
- }
-}
-
-private final class MouseClickRecorder: @unchecked Sendable {
- private let lock = NSLock()
- private var recordedPoints: [CGPoint] = []
-
- func append(_ point: CGPoint) {
- lock.lock()
- recordedPoints.append(point)
- lock.unlock()
- }
-
- func points() -> [CGPoint] {
- lock.lock()
- let points = recordedPoints
- lock.unlock()
- return points
- }
-}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionGroundingFlowTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionGroundingFlowTests.swift
deleted file mode 100644
index ec52b3d9..00000000
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionGroundingFlowTests.swift
+++ /dev/null
@@ -1,58 +0,0 @@
-@testable import DonkeyAI
-import DonkeyContracts
-import Foundation
-import Testing
-
-@Suite
-struct VisionGroundingFlowTests {
- private func element(
- id: String,
- type: DebugUIElementType,
- label: String,
- description: String = "",
- x: Double, y: Double, width: Double, height: Double,
- confidence: Double = 0.9
- ) -> DebugUIElement {
- DebugUIElement(
- id: id,
- type: type,
- label: label,
- description: description,
- bbox: DebugUIBoundingBox(x: x, y: y, width: width, height: height),
- confidence: confidence,
- visualStyle: DebugUIOverlayStyle(overlayColor: "#000", borderColor: "#000", labelColor: "#fff"),
- metadata: [:]
- )
- }
-
- @Test
- func mapsScreenshotPixelBoxToScreenWithRetinaScaling() {
- // 2x Retina screenshot (1600x1200) of a 800x600 window at screen (100, 50).
- let window = WindowTargetBounds(x: 100, y: 50, width: 800, height: 600)
- let bbox = DebugUIBoundingBox(x: 700, y: 100, width: 200, height: 60) // center (800, 130) in image px
- let point = VisionGroundingFlow.screenPoint(bbox: bbox, imageWidth: 1600, imageHeight: 1200, window: window)
- // scaleX=800/1600=0.5, scaleY=600/1200=0.5 → screen (100+400, 50+65) = (500, 115)
- #expect(point.x == 500)
- #expect(point.y == 115)
- }
-
- @Test
- func resolvesElementByLabelPreferringExactThenConfidence() {
- let elements = [
- element(id: "a", type: .button, label: "Search the web", x: 0, y: 0, width: 10, height: 10, confidence: 0.6),
- element(id: "b", type: .input, label: "Search", x: 20, y: 0, width: 10, height: 10, confidence: 0.9),
- element(id: "c", type: .button, label: "Settings", x: 40, y: 0, width: 10, height: 10)
- ]
- #expect(VisionGroundingFlow.resolveElement("Search", in: elements)?.id == "b")
- }
-
- @Test
- func ignoresZeroAreaAndUnrelatedElements() {
- let elements = [
- element(id: "ghost", type: .input, label: "Search", x: 0, y: 0, width: 0, height: 0),
- element(id: "other", type: .button, label: "Play", x: 10, y: 10, width: 30, height: 20)
- ]
- #expect(VisionGroundingFlow.resolveElement("Search", in: elements) == nil)
- #expect(VisionGroundingFlow.resolveElement("Play", in: elements)?.id == "other")
- }
-}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionGroundingLiveSmokeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionGroundingLiveSmokeTests.swift
deleted file mode 100644
index df48a95e..00000000
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionGroundingLiveSmokeTests.swift
+++ /dev/null
@@ -1,54 +0,0 @@
-import AppKit
-import DonkeyAI
-import DonkeyContracts
-import DonkeyRuntime
-import Foundation
-import Testing
-
-/// Live, env-gated test that hosted VISION can ground a control AX can't (e.g. Spotify's search
-/// box). Captures the app window, sends it to the hosted UI-inspection model, and maps the located
-/// element to a screen point.
-///
-/// env DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer \
-/// DONKEY_LIVE_SMOKE=1 DONKEY_WEB_BASE_URL=http://localhost:3000 DONKEY_DEV_AUTH_BYPASS=1 \
-/// [DONKEY_GUIDE_APP=Spotify] [DONKEY_GUIDE_TARGET=Search] \
-/// swift test --filter VisionGroundingLiveSmokeTests
-@Suite
-struct VisionGroundingLiveSmokeTests {
- @Test
- @MainActor
- func hostedVisionLocatesAControl() async {
- let env = ProcessInfo.processInfo.environment
- guard env["DONKEY_LIVE_SMOKE"] == "1" else { return }
- guard env["DONKEY_WEB_BASE_URL"]?.isEmpty == false else {
- Issue.record("DONKEY_WEB_BASE_URL not set")
- return
- }
- guard let config = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {
- Issue.record("could not load backend configuration")
- return
- }
-
- let app = env["DONKEY_GUIDE_APP"] ?? "Spotify"
- let target = env["DONKEY_GUIDE_TARGET"] ?? "Search"
- NSWorkspace.shared.launchApplication(app)
- try? await Task.sleep(nanoseconds: 1_200_000_000)
-
- let analyzer = HostedDebugUIInspectionAnalyzer(
- backend: DonkeyBackendInferenceClient(configuration: config, httpClient: URLSessionAIHTTPClient())
- )
- let outcome = await VisionGroundingFlow.locate(
- appName: app,
- bundleIdentifier: nil,
- targetQuery: target,
- analyzer: analyzer
- )
-
- guard let point = outcome.screenPoint else {
- Issue.record("Hosted vision did not locate '\(target)' in \(app): reason=\(outcome.reason) app=\(outcome.resolvedAppName ?? "nil"). Needs Screen Recording permission + a reachable backend.")
- return
- }
- #expect(point.x > 0 && point.y > 0)
- #expect(outcome.matchedLabel != nil)
- }
-}