Open source CapCut alternative.
TypeScript
Run typed queries through computer-use harness
David Le91d1249d9257
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swiftindex b026c7cc..c6daf113 100644--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift@@ -1,6 +1,7 @@import AppKitimport Carbon.HIToolboximport Darwin+import DonkeyAIimport Foundation@MainActor@@ -13,6 +14,7 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {private var debugInspectionCoordinator: DebugUIInspectionCoordinator?#endifprivate var runtimeOnboardingController: LocalRuntimeOnboardingWindowController?+ private var frontmostVisionWarmCache: FrontmostVisionWarmCache?func applicationDidFinishLaunching(_ notification: Notification) {if ManualCaptureDebugLaunchHandler.shouldHandle(arguments: CommandLine.arguments) {@@ -70,6 +72,7 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {andEventID: AEEventID(kAEGetURL))overlayController?.stop()+ frontmostVisionWarmCache?.stop()#if DONKEY_DEBUG_OVERLAYdebugInspectionCoordinator?.stop()#endif@@ -127,6 +130,13 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {let runtimeOnboardingController = LocalRuntimeOnboardingWindowController()self.runtimeOnboardingController = runtimeOnboardingControllerruntimeOnboardingController.showIfSetupNeeded()++ // Keep ParsedVisionStore warm: watch the frontmost window and re-parse on big changes, so a+ // typed vision command reuses a fresh parse instead of paying for one inline. No-ops when the+ // vision backend isn't configured.+ let frontmostVisionWarmCache = FrontmostVisionWarmCache.fromEnvironment()+ self.frontmostVisionWarmCache = frontmostVisionWarmCache+ frontmostVisionWarmCache?.start()}private func registerAuthCallbackHandler() {diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swiftindex 697b8753..7cfa9c33 100644--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift@@ -266,8 +266,24 @@ final class DebugUIInspectionCoordinator {return}+ // Carry the already-detected vision/AI elements into this fast accessibility render. The+ // element tracker is shared across every render path, so feeding it an accessibility-ONLY+ // frame here would mark the vision boxes "missing" and age them out within+ // `disappearanceTolerance` cycles — which, once the vision parse is skipped for an unchanged+ // window, makes the boxes flicker (appear, vanish, reappear on the next real parse). Fusing+ // the carried AI elements keeps them present every cycle, matching the active-accessibility+ // path's behavior.+ let carriedAIFrame = DebugUIInspectionFrame(+ elements: (lastRenderedFrames[screen.screenID]?.elements ?? [])+ .filter { !Self.isAccessibilityEvidence($0) }+ )+ let fusedFrame = DebugUIInspectionFrameFusion.fused(+ accessibilityFrame: frame,+ aiFrame: carriedAIFrame+ )+var tracker = trackers[screen.screenID] ?? Self.makeElementTracker()- let trackedFrame = tracker.update(with: frame)+ let trackedFrame = tracker.update(with: fusedFrame, renderNewElementsImmediately: true)trackers[screen.screenID] = trackerguard force|| lastRenderedFrames[screen.screenID]?.isOverlayRenderEquivalent(to: trackedFrame) != truediff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 6487d6c0..271ac6a7 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -27,26 +27,6 @@ private enum VisionGroundingLog {}}-/// Configurable, env-gated "vision navigation" route. When enabled, a typed query is grounded-/// straight into on-screen actions by `VisionActionDriver` against the FRONTMOST user app —-/// bypassing the intent/AppleScript pipeline entirely. Gated by `DONKEY_VISION_NAV` so it is-/// trivial to turn off and revert to the standard route; the value is injectable so callers and-/// tests can force it on or off without touching the environment.-struct VisionNavigationMode: Equatable, Sendable {- var isEnabled: Bool-- static let disabled = VisionNavigationMode(isEnabled: false)-- static func fromEnvironment(- _ environment: [String: String] = ProcessInfo.processInfo.environment- ) -> VisionNavigationMode {- let raw = (environment["DONKEY_VISION_NAV"] ?? "")- .trimmingCharacters(in: .whitespacesAndNewlines)- .lowercased()- return VisionNavigationMode(isEnabled: ["1", "true", "yes", "on"].contains(raw))- }-}-struct UserQueryCommandHandlingResult: Equatable, Sendable {var status: LocalAppTaskLiveRunStatusvar threadStatus: UserQueryTaskStatus@@ -90,11 +70,6 @@ struct DocumentFormFillReviewRequest: Equatable, Sendable {var traceID: String}-private struct UserQueryModelIntentInput: Equatable, Sendable {- var command: String- var contextSnippets: [String]-}-struct UserQueryCommandContext: Sendable {var task: UserQueryNotchTaskvar recentEvents: [UserQueryTaskEvent]@@ -122,47 +97,21 @@ extension UserQueryCommandHandling {}struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {- var catalog: LocalAppTaskCatalog- var taskIntentAdapter: any TaskIntentParsingAdapter- var appController: any LocalAppTaskAppControlling- var actionEngineFactory: LocalAppHarnessStepExecutor.ActionEngineFactoryvar permissionPolicy: ToolCallPolicy- var redactor: AIHarnessRedactor- var memoryRetriever: SemanticRunMemoryRetrievervar coordinatorRegistry: UserQueryRunCoordinatorRegistryvar genericHarnessLifecycle: AppHarnessGenericLifecycle- var memoryStore: SQLiteAgentMemoryStore?- var visionNavigationMode: VisionNavigationModeinit(- catalog: LocalAppTaskCatalog = .defaultLocal(),- taskIntentAdapter: (any TaskIntentParsingAdapter)? = nil,- appController: any LocalAppTaskAppControlling = MacLocalAppTaskController(- uiUnderstandingRunner: DonkeyUIUnderstandingRunnerFactory.defaultRunner()- ),- actionEngineFactory: @escaping LocalAppHarnessStepExecutor.ActionEngineFactory = LocalAppTaskActionEngines.keyboardOrAutomation(for:),permissionPolicy: ToolCallPolicy = ToolCallPolicy(allowedCapabilities: ToolCallPolicy.defaultAllowedCapabilities.union([.input]),deniedCapabilities: []),- redactor: AIHarnessRedactor = AIHarnessRedactor(),- memoryRetriever: SemanticRunMemoryRetriever = SemanticRunMemoryRetriever(),coordinatorRegistry: UserQueryRunCoordinatorRegistry = UserQueryRunCoordinatorRegistry(),- genericHarnessLifecycle: AppHarnessGenericLifecycle = AppHarnessGenericLifecycle(),- memoryStore: SQLiteAgentMemoryStore? = .shared,- visionNavigationMode: VisionNavigationMode = .fromEnvironment()+ genericHarnessLifecycle: AppHarnessGenericLifecycle = AppHarnessGenericLifecycle()) {- self.catalog = catalog- self.coordinatorRegistry = coordinatorRegistry- self.taskIntentAdapter = taskIntentAdapter ?? HostedTaskIntentParsingAdapter()- self.appController = appController- self.actionEngineFactory = actionEngineFactoryself.permissionPolicy = permissionPolicy- self.redactor = redactor- self.memoryRetriever = memoryRetriever+ self.coordinatorRegistry = coordinatorRegistryself.genericHarnessLifecycle = genericHarnessLifecycle- self.memoryStore = memoryStore- self.visionNavigationMode = visionNavigationMode}func handleSubmittedCommand(@@ -186,7 +135,11 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {traceID: String,taskID: String) async -> UserQueryCommandHandlingResult {- let harnessRequest = Self.harnessRequest(command: command, context: context)+ // Redact PII/secrets before the command becomes the task goal: the hosted planner forwards the+ // goal to the backend on every step, and the goal is the only user text this route sends to a+ // model, so redacting here keeps secrets on-device without touching the planner.+ let redactedCommand = AIHarnessRedactor().redact(command, surface: .modelContext).redactedText+ let harnessRequest = Self.harnessRequest(command: redactedCommand, context: context)let genericPreparedTurn = await genericHarnessLifecycle.prepareUserQueryTurn(request: harnessRequest,pointerTask: context?.task,@@ -224,240 +177,14 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {return result}- let coordinator = await coordinatorRegistry.coordinator(for: taskID)-- // Vision-navigation route (env-gated by `DONKEY_VISION_NAV`): ground the typed query- // directly into on-screen actions against the frontmost app, skipping intent parsing and- // the AppleScript pipeline. Configurable so we can revert to the standard route below.- if visionNavigationMode.isEnabled {- return await handleVisionNavigation(- command: command,- traceID: traceID,- taskID: taskID,- preparedTurnMetadata: Self.genericHarnessMetadata(preparedTurn: genericPreparedTurn)- )- }-- let modelInput = Self.modelInput(- for: command,- context: context,- compactedContext: genericPreparedTurn.compactedContext- )- let commandRedaction = redactor.redact(modelInput.command, surface: .modelContext)- let contextRedactions = modelInput.contextSnippets.map {- redactor.redact($0, surface: .modelContext)- }- let redactedContextSnippets = contextRedactions.map(\.redactedText)- let redactionCount = commandRedaction.redactionCount- + contextRedactions.reduce(0) { $0 + $1.redactionCount }- let memoryProposalDecisions = (try? ProviderDecodedMemoryProposalHandler.decisions(- from: Data("[]".utf8),- decidedAt: Self.now()- )) ?? []- let parseStartedAt = Self.uptimeMilliseconds()- let taskIntentResult = await resolveTaskIntent(- command: commandRedaction.redactedText,- contextSnippets: redactedContextSnippets,- availableToolNames: Self.genericHarnessToolNames(),- sourceTraceID: traceID- )- let resolution = taskIntentResult.resolution- let parseLatencyMS = Self.uptimeMilliseconds() - parseStartedAt- logModelResolution(- command: commandRedaction.redactedText,- traceID: traceID,- resolution: resolution,- trace: taskIntentResult.trace,- latencyMS: parseLatencyMS- )- let semanticMemoryResults = await retrieveSemanticMemory(- command: commandRedaction.redactedText,- resolution: resolution- )- let modelObservability = AIModelObservabilityReportBuilder.build(from: [taskIntentResult.trace])- let modelMetadata = [- "appHarness.router": "genericHarnessPlanner",- "appHarness.context.promptCharacters": String(genericPreparedTurn.compactedContext.promptText.count),- "appHarness.context.redactionCount": String(redactionCount),- "intentParser": "hostedHarnessPlanner",- "latency.commandParseMS": Self.formatLatency(parseLatencyMS),- "modelCallID": taskIntentResult.trace.id,- "modelCallStatus": taskIntentResult.trace.status.rawValue,- "modelValidationStatus": taskIntentResult.trace.validationStatus,- "modelObservability.callCount": String(modelObservability.callCount),- "modelObservability.acceptedCount": String(modelObservability.acceptedCount),- "modelObservability.recoverySuccessCount": String(modelObservability.recoverySuccessCount),- "redaction.modelContext.count": String(redactionCount),- "semanticMemory.resultCount": String(semanticMemoryResults.count),- "semanticMemory.recordIDs": semanticMemoryResults.map(\.record.id).joined(separator: ","),- "semanticMemory.targetID": semanticMemoryTargetID(for: resolution) ?? "",- "memoryProposal.decisionCount": String(memoryProposalDecisions.count)- ]- .merging(Self.contextMetadata(context)) { current, _ in current }- .merging(Self.genericHarnessMetadata(preparedTurn: genericPreparedTurn)) { current, _ in current }-- await coordinator.recordToolEvent(- capability: .model,- decision: .allow,- toolName: "generic-harness-planner",- summary: "Planned user query turn",- traceID: traceID,- metadata: [- "modelCallID": taskIntentResult.trace.id,- "modelCallStatus": taskIntentResult.trace.status.rawValue,- "modelValidationStatus": taskIntentResult.trace.validationStatus- ]- )-- if taskIntentResult.trace.metadata["genericHarness.intent.route"] == "guidance" {- return await handleGuidance(- trace: taskIntentResult.trace, traceID: traceID, taskID: taskID,- modelMetadata: modelMetadata- )- }-- if Self.shouldFailSafelyWithoutLocalTask(resolution) {- return await handleFailSafe(- resolution: resolution, traceID: traceID, taskID: taskID,- modelMetadata: modelMetadata- )- }-- if Self.shouldAskClarificationBeforeLocalTask(resolution) {- return await handleClarification(- resolution: resolution, traceID: traceID, taskID: taskID,- modelMetadata: modelMetadata- )- }-- if Self.shouldRespondWithoutLocalTask(resolution) {- return await handleConversation(- resolution: resolution, traceID: traceID, taskID: taskID,- modelMetadata: modelMetadata- )- }-- // Execution-strategy router: for a non-scriptable target app (Electron, no dictionary), the- // AppleScript/skill path can't act — drive it by vision instead. Scriptable/unknown apps fall- // through to the AppleScript-first generic harness loop below.- if let visionResult = await handleVisionActionIfNonScriptable(- resolution: resolution,- trace: taskIntentResult.trace,- command: commandRedaction.redactedText,- traceID: traceID,- taskID: taskID,- modelMetadata: modelMetadata- ) {- return visionResult- }-- let decision = AppHarnessDecision(- kind: .runLocalTask,- taskIntentID: resolution.intent?.intentID,+ // Every typed query runs the generic harness loop against the frontmost app: the planner+ // re-plans per observation and picks AX/vision to see and AX/vision/scripts to act.+ return await runHarnessLoop(+ command: redactedCommand,traceID: traceID,- metadata: [- "structuredDecision": "true",- "router": "modelLocalAppTask",- "resolution.status": resolution.status.rawValue- ]- )- _ = await genericHarnessLifecycle.planLocalTaskRun(- taskID: taskID,- resolution: resolution,- fallbackGoal: commandRedaction.redactedText,- traceID: traceID,- availableToolNames: Self.genericHarnessToolNames()- )- var harnessServices = LocalAppUserQueryHarnessServices.builtInSkillBackedServices()- let appleScriptGenerationAdapter = HostedAppleScriptGenerationAdapter()- harnessServices.appleScriptGenerator = { request in- await appleScriptGenerationAdapter.generateAppleScript(request)- }- let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(- services: harnessServices- )- let localStepExecutor = LocalAppHarnessStepExecutor(- command: commandRedaction.redactedText,- traceID: traceID,- resolution: resolution,- metadata: modelMetadata.merging([- "appHarness.decision": AppHarnessDecisionKind.runLocalTask.rawValue,- "genericHarness.taskID": taskID- ]) { current, _ in current },- appController: appController,- actionEngineFactory: actionEngineFactory,- permissionPolicy: permissionPolicy,- coordinator: coordinator- )- await localStepExecutor.registerTools(in: registry)- let genericRuntime = GenericHarnessRuntime(- coordinator: genericHarnessLifecycle.coordinator,- registry: registry- )- let runSteps = await executeGenericHarnessLoop(- taskID: taskID,- runtime: genericRuntime- )- Self.recordAppleScriptScriptability(resolution: resolution, runSteps: runSteps)- let runStep = runSteps.last- let verificationStep = runSteps.last { step in- step.toolResult?.toolName == LocalAppActionPlanTool.verifyCommand.rawValue- || step.toolResult?.toolName == LocalAppActionPlanTool.verifyVisibleText.rawValue- }- let result = Self.integratingGenericToolOutcome(- into: await localStepExecutor.currentResult(),- runSteps: runSteps- )- let finalized = await finalizeGenericHarnessTask(taskID: taskID,- result: result,- runStep: runStep,- verificationStep: verificationStep,- runtime: genericRuntime- )- let finalizedTask = await genericHarnessLifecycle.taskState(taskID: taskID)- logActionTraces(for: result)-- let agentVisualizationPlan = Self.agentVisualizationPlan(from: runSteps)- ?? LocalAppTaskAgentVisualizationBuilder.plan(- for: result,- sourceTraceID: traceID- ).map(groundAgentVisualizationPlan)- let localTaskMetadata = Self.genericHarnessTaskMetadata(finalizedTask ?? runStep?.task)- .merging(result.metadata) { current, _ in current }- .merging([- "appHarness.decision": AppHarnessDecisionKind.runLocalTask.rawValue,- "appHarness.router": "modelLocalAppTask"- ]) { current, _ in current }- .merging(Self.genericHarnessMetadata(- preparedTurn: genericPreparedTurn,- runStep: runStep,- verificationStep: finalized.verificationStep,- recoveryStep: finalized.recoveryStep- )) { current, _ in current }- let handlingResult = UserQueryCommandHandlingResult(- status: result.status,- threadStatus: Self.userQueryStatus(for: finalizedTask)- ?? threadStatus(for: result, runStep: runStep),- decision: decision,- summary: summary(for: result, task: finalizedTask, runStep: runStep),- traceID: traceID,- metadata: localTaskMetadata,- taskLabel: taskLabel(for: result),- documentReviewRequest: documentReviewRequest(- traceID: traceID,- result: result- ),- agentVisualizationPlan: agentVisualizationPlan,- cursorOverlayRequest: agentVisualizationPlan?.cursorOverlayRequest()+ preparedTurnMetadata: Self.genericHarnessMetadata(preparedTurn: genericPreparedTurn))- await coordinatorRegistry.finish(taskID: taskID)- logHandlingResult(- handlingResult,- stage: "localTask",- hint: runHint(for: result)- )- return handlingResult}func pauseCommand(taskID: String) async -> Bool {@@ -481,1371 +208,311 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {) != nil}- // MARK: - Non-Local-Task Routing+ // MARK: - Harness Run (frontmost app)- private func handleFailSafe(- resolution: LocalAppTaskCatalogResolution,+ /// The only route: satisfies the typed query by running the generic harness loop+ /// (`GenericHarnessRuntime.run`) against the frontmost app. The loop re-plans after every+ /// observation via `HostedHarnessStepPlanner`, which picks the next tool — AX or vision to see,+ /// AX/vision/keyboard/AppleScript to act — and console-logs the grounding latency for telemetry.+ ///+ /// `@MainActor` because window resolution, the tools, and the timing accumulators all run on the+ /// main actor.+ @MainActor+ private func runHarnessLoop(+ command: String,traceID: String,taskID: String,- modelMetadata: [String: String]+ preparedTurnMetadata: [String: String]) async -> UserQueryCommandHandlingResult {- let response = Self.modelUnavailableResponse(for: resolution)- let decision = AppHarnessDecision(- kind: .respond,- message: response,- traceID: traceID,- metadata: [- "structuredDecision": "true",- "router": "modelUnavailable",- "resolution.status": resolution.status.rawValue- ]- )- let result = UserQueryCommandHandlingResult(- status: .failedSafe,- threadStatus: .failed,- decision: decision,- summary: response,- traceID: traceID,- metadata: modelMetadata.merging([- "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,- "router": "modelUnavailable",- "resolution.status": resolution.status.rawValue,- "resolution.reason": resolution.metadata["reason"] ?? ""- ]) { _, new in new }+ guard permissionPolicy.allowedCapabilities.contains(.input) else {+ return await failHarnessRun(+ response: "Vision navigation needs input permission, which isn't granted.",+ reason: "inputNotPermitted",+ appName: "",+ traceID: traceID,+ taskID: taskID,+ preparedTurnMetadata: preparedTurnMetadata+ )+ }+ guard let target = MacWindowResolver().frontmostUserAppTarget() else {+ return await failHarnessRun(+ response: "I couldn't find a frontmost app window to navigate. Focus the app you want, then type your request.",+ reason: "noFrontmostApp",+ appName: "",+ traceID: traceID,+ taskID: taskID,+ preparedTurnMetadata: preparedTurnMetadata+ )+ }+ let appName = target.appName ?? "the frontmost app"+ let bundleIdentifier = target.bundleIdentifier++ guard let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {+ return await failHarnessRun(+ response: "The vision backend isn't configured (set DONKEY_WEB_BASE_URL), so I couldn't navigate by vision.",+ reason: "visionBackendUnavailable",+ appName: appName,+ traceID: traceID,+ taskID: taskID,+ preparedTurnMetadata: preparedTurnMetadata+ )+ }+ let backend = DonkeyBackendInferenceClient(configuration: configuration)+ let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(+ forApp: appName,+ bundleIdentifier: bundleIdentifier)- _ = await genericHarnessLifecycle.coordinator.failSafe(- taskID: taskID,- reason: "Hosted command parser did not produce a safe action plan"++ // Drive the frontmost app through the GENERIC HARNESS LOOP: the harness re-plans after every+ // observation, consulting `HostedHarnessStepPlanner` (the model boundary) to pick the next+ // tool. The planner chooses how to SEE (ax.observe vs. vision.capture) and how to ACT (ax.click,+ // vision.click, keyboard/text input, generated AppleScript), or `run.complete` when done —+ // vision is just one tool among many. The always-on warm-cache monitor is suspended for the+ // duration so it never races us on a parse.+ let analyzer = HostedDebugUIInspectionAnalyzer(backend: backend)+ let appKey = (bundleIdentifier?.isEmpty == false ? bundleIdentifier! : appName)++ // Built-in action/lifecycle/skill tools, minus the placeholder see/act tools that the real AX ++ // vision tools below replace, and restricted to what this turn is permitted to run.+ var harnessServices = LocalAppUserQueryHarnessServices.builtInSkillBackedServices()+ let appleScriptGenerationAdapter = HostedAppleScriptGenerationAdapter()+ harnessServices.appleScriptGenerator = { request in+ await appleScriptGenerationAdapter.generateAppleScript(request)+ }+ let granted = Self.userQueryGrantedPermissions+ let replacedBuiltIns: Set<String> = ["screen.observe", "elements.get", "element.perform", "text.enter", "keyboard.press"]+ let builtInDescriptors = BuiltInHarnessToolCatalog.descriptors.filter { descriptor in+ !replacedBuiltIns.contains(descriptor.name)+ && Set(descriptor.requiredPermissions).isSubset(of: granted)+ }+ let registry = HarnessToolRegistry(+ tools: BuiltInHarnessToolExecutors.tools(descriptors: builtInDescriptors, services: harnessServices))- await coordinatorRegistry.finish(taskID: taskID)- logHandlingResult(- result,- stage: "modelUnavailable",- hint: "The hosted planner failed before producing executable intent; no local task was run."+ let axProvider = AXComputerUseToolProvider(appName: appName, bundleIdentifier: bundleIdentifier)+ let visionProvider = VisionComputerUseToolProvider(+ appName: appName,+ appKey: appKey,+ bundleIdentifier: bundleIdentifier,+ analyzer: analyzer)- return result- }-- private func handleClarification(- resolution: LocalAppTaskCatalogResolution,- traceID: String,- taskID: String,- modelMetadata: [String: String]- ) async -> UserQueryCommandHandlingResult {- let question = Self.clarificationQuestion(for: resolution)- let decision = AppHarnessDecision(- kind: .askClarification,- message: question,- missingDetail: resolution.metadata["reason"],- traceID: traceID,- metadata: [- "structuredDecision": "true",- "router": "modelClarification",- "resolution.status": resolution.status.rawValue- ]+ // Register the AX/vision see/act tools only when this turn holds their permissions, mirroring+ // the built-in descriptor filter so the planner is never offered a tool it can't run.+ for tool in axProvider.makeTools() + visionProvider.makeTools()+ where Set(tool.descriptor.requiredPermissions).isSubset(of: granted) {+ await registry.register(tool)+ }+ let runtime = GenericHarnessRuntime(+ coordinator: genericHarnessLifecycle.coordinator,+ registry: registry)- let result = UserQueryCommandHandlingResult(- status: .needsConfirmation,- threadStatus: .waitingForClarification,- decision: decision,- summary: question,- traceID: traceID,- metadata: modelMetadata.merging([- "appHarness.decision": AppHarnessDecisionKind.askClarification.rawValue,- "router": "modelClarification",- "resolution.status": resolution.status.rawValue,- "resolution.reason": resolution.metadata["reason"] ?? ""- ]) { _, new in new }+ let plannerDescriptors = await registry.descriptors()+ let planner = HostedHarnessStepPlanner(+ backend: backend,+ descriptors: plannerDescriptors,+ appName: appName,+ appGuidance: appGuidance)- _ = await genericHarnessLifecycle.coordinator.waitForUser(+ _ = await genericHarnessLifecycle.coordinator.startRunning(taskID: taskID,- question: question,- reason: "Generic harness planner requested clarification"+ reason: "User query harness run")- await coordinatorRegistry.finish(taskID: taskID)- logHandlingResult(- result,- stage: "clarification",- hint: "The harness planner asked for a missing detail before selecting an action tool."++ VisionGroundingLog.emit(+ "start traceID=\(traceID) app=\(appName) goal=\"\(command)\"")- return result- }+ let e2eStartMS = Self.uptimeMilliseconds()+ // Suspend the warm-cache monitor for the whole drive so it never races us writing the same+ // app's parse. The run between these calls has no early exit, so resume always pairs with it.+ VisionWarmCacheActivity.shared.suspend()+ let runSteps = await runtime.run(taskID: taskID, planner: planner, maxSteps: 8)+ VisionWarmCacheActivity.shared.resume()++ let finalTask = await genericHarnessLifecycle.coordinator.task(id: taskID)+ let finalStatus = finalTask?.status+ let completed = finalStatus == .completed+ let awaitingUser = finalStatus == .waitingForUser+ let outcomeReason = completed ? "ok"+ : (awaitingUser ? "awaitingUser"+ : (finalStatus == .failedSafe ? "failedSafe" : "maxStepsReached"))+ let turns = runSteps.count+ let anyTurnUsedCache = runSteps.contains { $0.toolResult?.metadata["usedCache"] == "true" }+ let totalParseMS = runSteps.reduce(0.0) { $0 + ($1.toolResult?.metadata["parseMS"].flatMap(Double.init) ?? 0) }+ let timeToFirstActionMS = planner.firstActionUptimeMS.map { $0 - e2eStartMS }+ let e2eTotalMS = Self.uptimeMilliseconds() - e2eStartMS+ let averagePerTurnMS = turns > 0 ? e2eTotalMS / Double(turns) : 0+ if let timeToFirstActionMS {+ VisionGroundingLog.emit(+ "time-to-first-action traceID=\(traceID) app=\(appName) ms=\(Self.formatLatency(timeToFirstActionMS))"+ )+ }+ VisionGroundingLog.emit(+ "complete traceID=\(traceID) app=\(appName) completed=\(completed) reason=\(outcomeReason) turns=\(turns) usedCache=\(anyTurnUsedCache) parseMS=\(Self.formatLatency(totalParseMS)) e2eTotalMS=\(Self.formatLatency(e2eTotalMS)) timeToFirstActionMS=\(Self.formatLatency(timeToFirstActionMS ?? 0)) avgPerTurnMS=\(Self.formatLatency(averagePerTurnMS))"+ )++ let baseMetadata = preparedTurnMetadata.merging([+ "appHarness.router": "harness",+ "harness.app": appName,+ "harness.completed": String(completed),+ "harness.turns": String(turns),+ "harness.reason": outcomeReason,+ "grounding.e2eTotalMS": Self.formatLatency(e2eTotalMS),+ "grounding.timeToFirstActionMS": Self.formatLatency(timeToFirstActionMS ?? 0),+ "grounding.avgPerTurnMS": Self.formatLatency(averagePerTurnMS),+ "grounding.usedCache": String(anyTurnUsedCache),+ "grounding.parseMS": Self.formatLatency(totalParseMS)+ ]) { _, new in new }++ // The planner can end a turn three ways: ask the user (user.clarify → waitingForUser), answer+ // conversationally (conversation.respond), or finish an action (run.complete). Surface whichever+ // happened rather than always reporting "Done".+ if awaitingUser {+ let question = finalTask?.pendingContinuation?.question.flatMap { $0.isEmpty ? nil : $0 }+ ?? "Could you clarify what you'd like me to do?"+ let decision = AppHarnessDecision(+ kind: .askClarification,+ message: question,+ traceID: traceID,+ metadata: ["structuredDecision": "true", "router": "harness"]+ )+ let result = UserQueryCommandHandlingResult(+ status: .needsConfirmation,+ threadStatus: .waitingForClarification,+ decision: decision,+ summary: question,+ traceID: traceID,+ metadata: baseMetadata.merging([+ "appHarness.decision": AppHarnessDecisionKind.askClarification.rawValue+ ]) { _, new in new }+ )+ await coordinatorRegistry.finish(taskID: taskID)+ logHandlingResult(result, stage: "harness", hint: "Asked the user to clarify.")+ return result+ }- private func handleConversation(- resolution: LocalAppTaskCatalogResolution,- traceID: String,- taskID: String,- modelMetadata: [String: String]- ) async -> UserQueryCommandHandlingResult {- let response = Self.conversationResponse(for: resolution)+ let conversationMessage = finalTask?.toolHistory.last { $0.call.name == "conversation.respond" }+ .flatMap { $0.call.input["response"] ?? $0.call.input["message"] }+ .flatMap { $0.isEmpty ? nil : $0 }+ let response = conversationMessage+ ?? planner.lastNarration+ ?? (completed ? "Done." : "I tried operating \(appName) but couldn't confirm the goal was finished.")let decision = AppHarnessDecision(kind: .respond,message: response,traceID: traceID,- metadata: [- "structuredDecision": "true",- "router": "modelConversation",- "resolution.status": resolution.status.rawValue- ]+ metadata: ["structuredDecision": "true", "router": "harness", "harness.completed": String(completed)])let result = UserQueryCommandHandlingResult(- status: .completed,- threadStatus: .chatting,+ status: completed ? .completed : .failedSafe,+ threadStatus: completed ? .completed : .failed,decision: decision,summary: response,traceID: traceID,- metadata: modelMetadata.merging([- "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,- "router": "modelConversation",- "resolution.status": resolution.status.rawValue,- "resolution.reason": resolution.metadata["reason"] ?? ""+ metadata: baseMetadata.merging([+ "appHarness.decision": AppHarnessDecisionKind.respond.rawValue]) { _, new in new })- _ = await genericHarnessLifecycle.coordinator.complete(- taskID: taskID,- reason: "User query conversation response"- )+ // The planner ends the run via run.complete/run.failSafe, so the task status is usually already+ // terminal; finalize defensively for the maxSteps-reached case.+ if completed {+ _ = await genericHarnessLifecycle.coordinator.complete(+ taskID: taskID,+ reason: "User query harness run completed"+ )+ } else {+ _ = await genericHarnessLifecycle.coordinator.failSafe(+ taskID: taskID,+ reason: "User query harness run did not confirm completion"+ )+ }await coordinatorRegistry.finish(taskID: taskID)logHandlingResult(result,- stage: "conversation",- hint: "No local task intent was produced; responded in the thread."+ stage: "harness",+ hint: completed ? "Operated \(appName)." : "Harness run stopped: \(outcomeReason).")return result}- /// Guidance route: show the user where something is by grounding the requested controls in the- /// target app's accessibility tree and presenting a cursor overlay. Visualization only — no- /// input, no app state change. Works for any app with an accessibility tree (native or Electron).- private func handleGuidance(- trace: AIModelCallTrace,+ /// Fail-safe exit for the vision-navigation route when it can't even start (no frontmost app,+ /// backend unconfigured, input not permitted). Mirrors the other non-local routes' lifecycle.+ private func failHarnessRun(+ response: String,+ reason: String,+ appName: String,traceID: String,taskID: String,- modelMetadata: [String: String]+ preparedTurnMetadata: [String: String]) async -> UserQueryCommandHandlingResult {- let appName = trace.metadata["genericHarness.intent.targetApp"].flatMap { $0.isEmpty ? nil : $0 }- let targets = Self.guidanceTargets(from: trace.metadata["guidanceTargets"] ?? "")- let title = trace.metadata["genericHarness.intent.goal"].flatMap { $0.isEmpty ? nil : $0 } ?? "Here you go"- let outcome = await MainActor.run {- GuidanceOverlayFlow.cursorGuide(- appName: appName,- bundleIdentifier: nil,- targets: targets,- title: title,- traceID: traceID- )- }- let located = outcome.request != nil- // Prefer the model's own narration; fall back only when it didn't provide one (or when we- // couldn't actually ground the control at runtime, which the planner can't know up front).- let modelResponse = trace.metadata["assistantResponse"].flatMap { $0.isEmpty ? nil : $0 }- let response = located- ? (modelResponse ?? "Here it is — follow the pointer.")- : "I couldn't locate that on screen right now."+ VisionGroundingLog.emit("aborted traceID=\(traceID) reason=\(reason) app=\(appName)")let decision = AppHarnessDecision(kind: .respond,message: response,traceID: traceID,metadata: ["structuredDecision": "true",- "router": "modelGuidance",- "guidance.reason": outcome.reason+ "router": "harness",+ "harness.abortReason": reason])let result = UserQueryCommandHandlingResult(- status: .completed,- threadStatus: .chatting,+ status: .failedSafe,+ threadStatus: .failed,decision: decision,summary: response,traceID: traceID,- metadata: modelMetadata.merging([+ metadata: preparedTurnMetadata.merging(["appHarness.decision": AppHarnessDecisionKind.respond.rawValue,- "router": "modelGuidance",- "guidance.reason": outcome.reason,- "guidance.targetCount": String(targets.count),- "guidance.resolvedApp": outcome.resolvedAppName ?? ""- ]) { _, new in new },- cursorOverlayRequest: outcome.request+ "appHarness.router": "harness",+ "harness.abortReason": reason+ ]) { _, new in new })- _ = await genericHarnessLifecycle.coordinator.complete(+ _ = await genericHarnessLifecycle.coordinator.failSafe(taskID: taskID,- reason: "User query guidance overlay"+ reason: "User query harness run could not start: \(reason)")await coordinatorRegistry.finish(taskID: taskID)- logHandlingResult(- result,- stage: "guidance",- hint: located ? "Guided with a pointer overlay." : "No grounded control to point at."- )+ logHandlingResult(result, stage: "harness", hint: response)return result}- /// Parses planner `guidanceTargets` into ordered path targets. The planner emits a JSON array of- /// `{label, query}` objects — robust to labels/queries that contain punctuation (`:`, `;`, …),- /// which a delimiter-based format would mis-split. A legacy `"Label::query; …"` string is still- /// accepted as a fallback for older planner output.- private static func guidanceTargets(from raw: String) -> [AccessibilityCursorPathTarget] {- let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)- guard !trimmed.isEmpty else { return [] }+ // MARK: - Generic Harness Task Execution- if let data = trimmed.data(using: .utf8),- let decoded = try? JSONDecoder().decode([GuidanceTargetWire].self, from: data) {- return decoded.compactMap(\.pathTarget)- }+ private func logSubmittedCommand(+ _ command: String,+ traceID: String,+ taskID: String,+ context: UserQueryCommandContext?+ ) {+ guard UserQueryLog.isEnabled else { return }- return trimmed.components(separatedBy: ";").compactMap { entry in- let parts = entry.components(separatedBy: "::")- .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }- let query = (parts.count > 1 ? parts[1] : parts.first ?? "")- guard !query.isEmpty else { return nil }- let label = (parts.count > 1 && !parts[0].isEmpty) ? parts[0] : query- return AccessibilityCursorPathTarget(query: query, label: label, kind: .targetControl)- }+ let source = context?.turnSource.rawValue ?? AppHarnessTurnSource.typedPrompt.rawValue+ let isFollowUp = context?.isFollowUp ?? false+ UserQueryLog.commands.notice(+ "command submitted traceID=\(traceID, privacy: .public) taskID=\(taskID, privacy: .public) source=\(source, privacy: .public) followUp=\(String(isFollowUp), privacy: .public) command=\(command, privacy: .public)"+ )}- private struct GuidanceTargetWire: Decodable {- var label: String?- var query: String+ private func logHandlingResult(+ _ result: UserQueryCommandHandlingResult,+ stage: String,+ hint: String+ ) {+ guard UserQueryLog.isEnabled else { return }- var pathTarget: AccessibilityCursorPathTarget? {- let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)- guard !trimmedQuery.isEmpty else { return nil }- let trimmedLabel = (label ?? "").trimmingCharacters(in: .whitespacesAndNewlines)- return AccessibilityCursorPathTarget(- query: trimmedQuery,- label: trimmedLabel.isEmpty ? trimmedQuery : trimmedLabel,- kind: .targetControl- )- }+ let taskLabel = result.taskLabel ?? ""+ UserQueryLog.commands.notice(+ "command finished traceID=\(result.traceID, privacy: .public) stage=\(stage, privacy: .public) status=\(result.status.rawValue, privacy: .public) threadStatus=\(result.threadStatus.rawValue, privacy: .public) summary=\(result.summary, privacy: .public) taskLabel=\(taskLabel, privacy: .public) hint=\(hint, privacy: .public)"+ )}- // MARK: - Vision Action Route (non-scriptable apps)-- /// If the resolved target app genuinely can't be driven by AppleScript/keystrokes — an Electron app,- /// or one this machine has LEARNED fails AppleScript — drive it by vision via the shared- /// `VisionActionDriver`. Returns nil (use the normal AppleScript/keystroke path) when the app is- /// scriptable, when it merely lacks a dictionary (System-Events keystrokes still work), when input- /// isn't permitted, or when the hosted backend can't be reached. Honors the planner's confirm- /// request: an action flagged `needsConfirmation` asks the user first rather than auto-driving.- private func handleVisionActionIfNonScriptable(- resolution: LocalAppTaskCatalogResolution,- trace: AIModelCallTrace,- command: String,- traceID: String,- taskID: String,- modelMetadata: [String: String]- ) async -> UserQueryCommandHandlingResult? {- guard permissionPolicy.allowedCapabilities.contains(.input) else { return nil }- guard let intent = resolution.intent else { return nil }- let appName = intent.targetApp.appName- guard !appName.isEmpty, appName.lowercased() != "none" else { return nil }- let bundleIdentifier = intent.targetApp.bundleIdentifier-- let scriptability = AppCapabilityService.shared.scriptability(- bundleIdentifier: bundleIdentifier,- appName: appName- )- guard ExecutionStrategySelector.strategy(scriptability: scriptability) == .accessibilityUI else {- return nil- }- // Only pre-empt the AppleScript/keystroke path for apps that truly can't use it: Electron- // (Chromium-rendered, no usable dictionary/keystroke automation) or apps that have actually- // failed AppleScript here. A native app that merely lacks a scripting dictionary can still be- // driven by System-Events keystrokes, so leave it on the existing path.- let isElectron = MacAppScriptabilityProbe().facts(- bundleIdentifier: bundleIdentifier,- appName: appName- ).isElectron- let learnedFailure = AppCapabilityService.shared.hasLearnedAppleScriptFailure(bundleIdentifier: bundleIdentifier)- guard isElectron || learnedFailure else { return nil }-- guard let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {- return nil- }-- // Never auto-drive the real pointer/keyboard for an action the planner asked to confirm; ask.- if intent.needsConfirmation {- return await confirmVisionAction(- appName: appName,- trace: trace,- traceID: traceID,- taskID: taskID,- modelMetadata: modelMetadata- )- }-- let backend = DonkeyBackendInferenceClient(configuration: configuration)- let goal = trace.metadata["genericHarness.intent.goal"]- .flatMap { $0.isEmpty ? nil : $0 } ?? command- let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(- forApp: appName,- bundleIdentifier: bundleIdentifier- )-- let outcome = await VisionActionDriver.drive(- appName: appName,- bundleIdentifier: bundleIdentifier,- goal: goal,- appGuidance: appGuidance,- backend: backend- )-- let response = outcome.completed- ? (outcome.lastNarration ?? "Done.")- : "I tried operating \(appName) but couldn't confirm the goal was finished."- let decision = AppHarnessDecision(- kind: .respond,- message: response,- traceID: traceID,- metadata: [- "structuredDecision": "true",- "router": "modelVisionAction",- "visionAction.completed": String(outcome.completed)- ]- )- let result = UserQueryCommandHandlingResult(- status: outcome.completed ? .completed : .failedSafe,- threadStatus: outcome.completed ? .completed : .failed,- decision: decision,- summary: response,- traceID: traceID,- metadata: modelMetadata.merging([- "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,- "appHarness.router": "modelVisionAction",- "visionAction.app": appName,- "visionAction.completed": String(outcome.completed),- "visionAction.turns": String(outcome.turns),- "visionAction.reason": outcome.reason- ]) { _, new in new }- )- if outcome.completed {- _ = await genericHarnessLifecycle.coordinator.complete(- taskID: taskID,- reason: "User query vision action completed"- )- } else {- _ = await genericHarnessLifecycle.coordinator.failSafe(- taskID: taskID,- reason: "User query vision action did not confirm completion"- )- }- await coordinatorRegistry.finish(taskID: taskID)- logHandlingResult(- result,- stage: "visionAction",- hint: outcome.completed ? "Drove \(appName) by vision." : "Vision action stopped: \(outcome.reason)."- )- return result- }-- /// Asks the user before driving an app by vision, when the planner flagged the action for- /// confirmation. Mirrors the clarification route — no input is performed.- private func confirmVisionAction(- appName: String,- trace: AIModelCallTrace,- traceID: String,- taskID: String,- modelMetadata: [String: String]- ) async -> UserQueryCommandHandlingResult {- let goal = trace.metadata["genericHarness.intent.goal"].flatMap { $0.isEmpty ? nil : $0 }- let question = goal.map { "I can do that in \(appName) by controlling it directly (\($0)). Want me to go ahead?" }- ?? "I can do that in \(appName) by controlling it directly. Want me to go ahead?"- let decision = AppHarnessDecision(- kind: .askClarification,- message: question,- traceID: traceID,- metadata: [- "structuredDecision": "true",- "router": "modelVisionActionConfirm"- ]- )- let result = UserQueryCommandHandlingResult(- status: .needsConfirmation,- threadStatus: .waitingForClarification,- decision: decision,- summary: question,- traceID: traceID,- metadata: modelMetadata.merging([- "appHarness.decision": AppHarnessDecisionKind.askClarification.rawValue,- "appHarness.router": "modelVisionActionConfirm",- "visionAction.app": appName- ]) { _, new in new }- )- _ = await genericHarnessLifecycle.coordinator.waitForUser(- taskID: taskID,- question: question,- reason: "Vision action requires confirmation before driving the app"- )- await coordinatorRegistry.finish(taskID: taskID)- logHandlingResult(- result,- stage: "visionActionConfirm",- hint: "Asked before driving \(appName) by vision."- )- return result- }-- // MARK: - Vision Navigation Route (frontmost app, env-gated)-- /// Drives the FRONTMOST user app by vision to satisfy the typed query, end to end: resolve the- /// frontmost window, ground the query into a screenshot→action loop with `VisionActionDriver`,- /// and console-log the grounding latency (time-to-first-action and total) for telemetry.- ///- /// `@MainActor` because window resolution, the driver, and the per-turn timing closure all run on- /// the main actor — keeping it isolated lets the timing accumulators stay plain locals.- @MainActor- private func handleVisionNavigation(- command: String,- traceID: String,- taskID: String,- preparedTurnMetadata: [String: String]- ) async -> UserQueryCommandHandlingResult {- guard permissionPolicy.allowedCapabilities.contains(.input) else {- return await failVisionNavigation(- response: "Vision navigation needs input permission, which isn't granted.",- reason: "inputNotPermitted",- appName: "",- traceID: traceID,- taskID: taskID,- preparedTurnMetadata: preparedTurnMetadata- )- }- guard let target = Self.frontmostUserAppTarget() else {- return await failVisionNavigation(- response: "I couldn't find a frontmost app window to navigate. Focus the app you want, then type your request.",- reason: "noFrontmostApp",- appName: "",- traceID: traceID,- taskID: taskID,- preparedTurnMetadata: preparedTurnMetadata- )- }- let appName = target.appName ?? "the frontmost app"- let bundleIdentifier = target.bundleIdentifier-- guard let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {- return await failVisionNavigation(- response: "The vision backend isn't configured (set DONKEY_WEB_BASE_URL), so I couldn't navigate by vision.",- reason: "visionBackendUnavailable",- appName: appName,- traceID: traceID,- taskID: taskID,- preparedTurnMetadata: preparedTurnMetadata- )- }- let backend = DonkeyBackendInferenceClient(configuration: configuration)- let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(- forApp: appName,- bundleIdentifier: bundleIdentifier- )-- VisionGroundingLog.emit(- "start traceID=\(traceID) app=\(appName) goal=\"\(command)\""- )- let e2eStartMS = Self.uptimeMilliseconds()- var timeToFirstActionMS: Double?- let outcome = await VisionActionDriver.drive(- appName: appName,- bundleIdentifier: bundleIdentifier,- goal: command,- appGuidance: appGuidance,- backend: backend,- onTurn: { info in- // Time-to-first-grounded-action: from query submit to the first on-screen action the- // model grounded from the screenshot + query. This is the headline grounding number.- guard timeToFirstActionMS == nil else { return }- let elapsed = Self.uptimeMilliseconds() - e2eStartMS- timeToFirstActionMS = elapsed- VisionGroundingLog.emit(- "time-to-first-action traceID=\(traceID) app=\(appName) ms=\(Self.formatLatency(elapsed)) action=\(info.action.action)"- )- }- )- let e2eTotalMS = Self.uptimeMilliseconds() - e2eStartMS- let averagePerTurnMS = outcome.turns > 0 ? e2eTotalMS / Double(outcome.turns) : 0- VisionGroundingLog.emit(- "complete traceID=\(traceID) app=\(appName) completed=\(outcome.completed) reason=\(outcome.reason) turns=\(outcome.turns) e2eTotalMS=\(Self.formatLatency(e2eTotalMS)) timeToFirstActionMS=\(Self.formatLatency(timeToFirstActionMS ?? 0)) avgPerTurnMS=\(Self.formatLatency(averagePerTurnMS))"- )-- let response = outcome.completed- ? (outcome.lastNarration ?? "Done.")- : "I tried navigating \(appName) by vision but couldn't confirm the goal was finished."- let decision = AppHarnessDecision(- kind: .respond,- message: response,- traceID: traceID,- metadata: [- "structuredDecision": "true",- "router": "visionNavigation",- "visionNavigation.completed": String(outcome.completed)- ]- )- let result = UserQueryCommandHandlingResult(- status: outcome.completed ? .completed : .failedSafe,- threadStatus: outcome.completed ? .completed : .failed,- decision: decision,- summary: response,- traceID: traceID,- metadata: preparedTurnMetadata.merging([- "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,- "appHarness.router": "visionNavigation",- "visionNavigation.app": appName,- "visionNavigation.completed": String(outcome.completed),- "visionNavigation.turns": String(outcome.turns),- "visionNavigation.reason": outcome.reason,- "grounding.e2eTotalMS": Self.formatLatency(e2eTotalMS),- "grounding.timeToFirstActionMS": Self.formatLatency(timeToFirstActionMS ?? 0),- "grounding.avgPerTurnMS": Self.formatLatency(averagePerTurnMS)- ]) { _, new in new }- )- if outcome.completed {- _ = await genericHarnessLifecycle.coordinator.complete(- taskID: taskID,- reason: "User query vision navigation completed"- )- } else {- _ = await genericHarnessLifecycle.coordinator.failSafe(- taskID: taskID,- reason: "User query vision navigation did not confirm completion"- )- }- await coordinatorRegistry.finish(taskID: taskID)- logHandlingResult(- result,- stage: "visionNavigation",- hint: outcome.completed ? "Navigated \(appName) by vision." : "Vision navigation stopped: \(outcome.reason)."- )- return result- }-- /// Fail-safe exit for the vision-navigation route when it can't even start (no frontmost app,- /// backend unconfigured, input not permitted). Mirrors the other non-local routes' lifecycle.- private func failVisionNavigation(- response: String,- reason: String,- appName: String,- traceID: String,- taskID: String,- preparedTurnMetadata: [String: String]- ) async -> UserQueryCommandHandlingResult {- VisionGroundingLog.emit("aborted traceID=\(traceID) reason=\(reason) app=\(appName)")- let decision = AppHarnessDecision(- kind: .respond,- message: response,- traceID: traceID,- metadata: [- "structuredDecision": "true",- "router": "visionNavigation",- "visionNavigation.abortReason": reason- ]- )- let result = UserQueryCommandHandlingResult(- status: .failedSafe,- threadStatus: .failed,- decision: decision,- summary: response,- traceID: traceID,- metadata: preparedTurnMetadata.merging([- "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,- "appHarness.router": "visionNavigation",- "visionNavigation.abortReason": reason- ]) { _, new in new }- )- _ = await genericHarnessLifecycle.coordinator.failSafe(- taskID: taskID,- reason: "User query vision navigation could not start: \(reason)"- )- await coordinatorRegistry.finish(taskID: taskID)- logHandlingResult(result, stage: "visionNavigation", hint: response)- return result- }-- /// Resolves the user's frontmost real window for vision navigation. Donkey's own overlay panels- /// float above layer 0 and are already excluded by the window enumerator, but we also skip our- /// own process so we never drive Donkey's UI. Candidates come back in front-to-back z-order, so- /// the first match is the app the user was last working in.- @MainActor- private static func frontmostUserAppTarget() -> MacWindowTargetCandidate? {- let ownProcessID = ProcessInfo.processInfo.processIdentifier- let ownBundleID = Bundle.main.bundleIdentifier- return MacWindowResolver().enumerateCandidates().first { candidate in- if candidate.processID == ownProcessID { return false }- if let ownBundleID, let candidateBundle = candidate.bundleIdentifier,- candidateBundle.caseInsensitiveCompare(ownBundleID) == .orderedSame {- return false- }- return true- }- }-- /// Records whether the AppleScript path actually worked for the target app, so the strategy router- /// learns per machine: repeated failures flip an app to the accessibility/vision path, a success- /// keeps it on AppleScript. Best-effort — only fires when the run executed an AppleScript action- /// and we know the app's bundle identifier.- private static func recordAppleScriptScriptability(- resolution: LocalAppTaskCatalogResolution,- runSteps: [HarnessStepExecutionResult]- ) {- guard let bundleIdentifier = (resolution.definition?.targetApp.bundleIdentifier- ?? resolution.intent?.targetApp.bundleIdentifier),- !bundleIdentifier.isEmpty- else {- return- }- let appName = resolution.definition?.targetApp.appName ?? resolution.intent?.targetApp.appName-- var sawAppleScript = false- var anySucceeded = false- for step in runSteps {- guard let toolResult = step.toolResult else { continue }- let isAppleScript = toolResult.metadata["liveInputBackend"] == "mac-apple-script"- || toolResult.metadata["appleScript.output"] != nil- || toolResult.toolName == "automation.applescript.execute"- guard isAppleScript else { continue }- sawAppleScript = true- if toolResult.status == .succeeded { anySucceeded = true }- }- guard sawAppleScript else { return }- AppCapabilityService.shared.recordAppleScriptOutcome(- bundleIdentifier: bundleIdentifier,- appName: appName,- succeeded: anySucceeded- )- }-- // MARK: - Generic Harness Task Execution-- private func finalizeGenericHarnessTask(- taskID: String,- result: LocalAppTaskLiveRunResult,- runStep: HarnessStepExecutionResult?,- verificationStep: HarnessStepExecutionResult?,- runtime: GenericHarnessRuntime- ) async -> UserQueryGenericFinalizeResult {- switch result.status {- case .completed:- if verificationStep?.toolResult?.status == .failed {- let recoveryStep = await recoverGenericHarnessTask(- taskID: taskID,- reason: verificationStep?.toolResult?.summary ?? "Verification failed",- traceID: result.traceID,- runtime: runtime- )- _ = await genericHarnessLifecycle.coordinator.failSafe(- taskID: taskID,- reason: "User query verification failed"- )- return UserQueryGenericFinalizeResult(- verificationStep: verificationStep,- recoveryStep: recoveryStep- )- }-- _ = await genericHarnessLifecycle.coordinator.complete(- taskID: taskID,- reason: "User query local task completed"- )- return UserQueryGenericFinalizeResult(verificationStep: verificationStep)- case .needsUserReview:- _ = await genericHarnessLifecycle.coordinator.waitForUser(- taskID: taskID,- question: "Review the local app result before I continue.",- reason: "User query local app verification needs review"- )- return UserQueryGenericFinalizeResult(verificationStep: verificationStep)- case .needsConfirmation, .unsupportedCommand:- _ = await genericHarnessLifecycle.coordinator.waitForUser(- taskID: taskID,- question: summary(for: result, task: runStep?.task, runStep: runStep),- reason: "User query local app task needs clarification"- )- return UserQueryGenericFinalizeResult()- case .appUnavailable, .failedSafe:- let recoveryStep = await recoverGenericHarnessTask(- taskID: taskID,- reason: summary(for: result, task: runStep?.task, runStep: runStep),- traceID: result.traceID,- runtime: runtime- )- _ = await genericHarnessLifecycle.coordinator.failSafe(- taskID: taskID,- reason: summary(for: result, task: runStep?.task, runStep: runStep)- )- return UserQueryGenericFinalizeResult(- recoveryStep: recoveryStep- )- }- }-- private func recoverGenericHarnessTask(- taskID: String,- reason: String,- traceID: String,- runtime: GenericHarnessRuntime- ) async -> HarnessStepExecutionResult? {- _ = await genericHarnessLifecycle.planRecovery(- taskID: taskID,- reason: reason,- traceID: traceID- )- return await runtime.executeNextPlannedStep(taskID: taskID)- }-- private func executeGenericHarnessLoop(- taskID: String,- runtime: GenericHarnessRuntime,- maxSteps: Int = 16- ) async -> [HarnessStepExecutionResult] {- var results: [HarnessStepExecutionResult] = []- for _ in 0..<maxSteps {- guard let result = await runtime.executeNextPlannedStep(taskID: taskID) else {- break- }- results.append(result)- if result.stoppedForGate || Self.shouldStopHarnessLoop(after: result.toolResult) {- break- }- }- return results- }-- private static func shouldStopHarnessLoop(after result: HarnessToolResult?) -> Bool {- switch result?.status {- case .failed, .unknownTool, .invalidInput, .permissionDenied, .waitingForUser, .waitingForPermission:- return true- case .succeeded, nil:- return false- }- }-- private static func integratingGenericToolOutcome(- into result: LocalAppTaskLiveRunResult,- runSteps: [HarnessStepExecutionResult]- ) -> LocalAppTaskLiveRunResult {- guard result.actionTraces.isEmpty,- result.status == .failedSafe- else {- return result- }-- let toolResults = runSteps.compactMap(\.toolResult)- guard let toolResult = toolResults.last else {- return result- }- let completedGenericAction = toolResults.last { result in- result.status == .succeeded- && (- result.toolName == "skill.script.execute"- || result.toolName == "automation.applescript.execute"- )- }-- switch toolResult.status {- case .succeeded where completedGenericAction != nil:- var completed = result- let actionResult = completedGenericAction ?? toolResult- completed.status = .completed- completed.metadata = result.metadata- .merging(actionResult.metadata) { current, _ in current }- .merging(toolResult.metadata) { current, _ in current }- completed.metadata["reason"] = "genericToolCompleted"- completed.metadata["genericTool.completed"] = actionResult.toolName- return completed- case .waitingForUser:- var waiting = result- waiting.status = .needsConfirmation- waiting.metadata = result.metadata.merging(toolResult.metadata) { current, _ in current }- waiting.metadata["reason"] = "genericToolNeedsUser"- waiting.metadata["genericTool.waiting"] = toolResult.toolName- return waiting- default:- return result- }- }-- private static func agentVisualizationPlan(- from runSteps: [HarnessStepExecutionResult]- ) -> AgentVisualizationPlan? {- for step in runSteps.reversed() {- guard step.toolResult?.toolName == AppHarnessGenericLifecycleToolNames.agentPathVisualize,- let text = step.toolResult?.metadata["agentVisualization.planJSON"],- let data = text.data(using: .utf8),- let plan = try? JSONDecoder().decode(AgentVisualizationPlan.self, from: data)- else {- continue- }- return plan- }- return nil- }-- private func groundAgentVisualizationPlan(_ plan: AgentVisualizationPlan) -> AgentVisualizationPlan {- let candidates = MacWindowResolver().enumerateCandidates()- guard !candidates.isEmpty else { return plan }-- return AgentVisualizationGrounder().ground(- plan: plan,- targetAppName: plan.metadata["targetApp"],- candidates: candidates- )- }-- private func logSubmittedCommand(- _ command: String,- traceID: String,- taskID: String,- context: UserQueryCommandContext?- ) {- guard UserQueryLog.isEnabled else { return }-- let source = context?.turnSource.rawValue ?? AppHarnessTurnSource.typedPrompt.rawValue- let isFollowUp = context?.isFollowUp ?? false- UserQueryLog.commands.notice(- "command submitted traceID=\(traceID, privacy: .public) taskID=\(taskID, privacy: .public) source=\(source, privacy: .public) followUp=\(String(isFollowUp), privacy: .public) command=\(command, privacy: .public)"- )- }-- private func resolveTaskIntent(- command: String,- contextSnippets: [String],- availableToolNames: [String],- sourceTraceID: String- ) async -> (resolution: LocalAppTaskCatalogResolution, trace: AIModelCallTrace) {- let request = TaskIntentAdapterRequest(- command: command,- taskDefinitions: catalog.taskDefinitions,- contextSnippets: contextSnippets,- appFinderCatalog: catalog.appFinderCatalogEntries(),- availableToolNames: availableToolNames,- sourceTraceID: sourceTraceID- )- let result = await taskIntentAdapter.parseTaskIntent(request)-- guard let intent = result.intent else {- var metadata = [- "reason": "hostedModelIntentUnavailable",- "modelCallStatus": result.trace.status.rawValue,- "modelValidationStatus": result.trace.validationStatus- ]- if result.trace.validationStatus == "noTaskIntent" {- metadata["reason"] = "noSupportedTaskIntent"- metadata["responseMode"] = "conversation"- metadata["assistantResponse"] = "I'm here. What would you like to work on?"- }- Self.mergeNonEmpty(- from: result.trace.metadata,- keys: ["responseMode", "assistantResponse"],- into: &metadata- )- Self.mergeNonEmpty(- from: result.trace.metadata,- keys: [- "reason", "detail", "error", "backend.provider",- "http.status", "http.bodyPreview",- "modelOutput.empty", "modelOutput.preview",- "fallback.status", "fallback.validation", "fallback.reason",- "fallback.http.status", "fallback.http.bodyPreview",- "provider", "privacy.store"- ],- into: &metadata,- keyPrefix: "model."- )- return (- LocalAppTaskCatalogResolution(- status: .needsConfirmation,- metadata: metadata- ),- result.trace- )- }-- return (catalog.resolve(intent: intent), result.trace)- }-- private func logModelResolution(- command: String,- traceID: String,- resolution: LocalAppTaskCatalogResolution,- trace: AIModelCallTrace,- latencyMS: Double- ) {- guard UserQueryLog.isEnabled else { return }-- let taskType = resolution.definition?.taskType ?? resolution.intent?.taskType ?? ""- let reason = resolution.metadata["reason"] ?? ""- let modelReason = Self.metadataValue(- in: resolution.metadata,- keys: ["model.reason", "model.fallback.reason"]- )- ?? Self.metadataValue(- in: trace.metadata,- keys: ["reason", "fallback.reason"]- )- ?? ""- let modelDetail = Self.metadataValue(- in: resolution.metadata,- keys: [- "model.detail",- "model.error",- "model.http.bodyPreview",- "model.fallback.http.bodyPreview",- "model.sidecar.outputPreview"- ]- )- ?? Self.metadataValue(- in: trace.metadata,- keys: [- "detail",- "error",- "http.bodyPreview",- "fallback.http.bodyPreview",- "sidecar.outputPreview"- ]- )- ?? ""- let fallbackStatus = trace.metadata["fallback.status"] ?? ""- let latency = Self.formatLatency(latencyMS)- UserQueryLog.commands.notice(- "intent resolved traceID=\(traceID, privacy: .public) resolution=\(resolution.status.rawValue, privacy: .public) taskType=\(taskType, privacy: .public) reason=\(reason, privacy: .public) modelStatus=\(trace.status.rawValue, privacy: .public) validation=\(trace.validationStatus, privacy: .public) modelReason=\(modelReason, privacy: .public) modelDetail=\(modelDetail, privacy: .public) fallbackStatus=\(fallbackStatus, privacy: .public) latencyMS=\(latency, privacy: .public) command=\(command, privacy: .public)"- )- }-- private func logHandlingResult(- _ result: UserQueryCommandHandlingResult,- stage: String,- hint: String- ) {- guard UserQueryLog.isEnabled else { return }-- let taskLabel = result.taskLabel ?? ""- UserQueryLog.commands.notice(- "command finished traceID=\(result.traceID, privacy: .public) stage=\(stage, privacy: .public) status=\(result.status.rawValue, privacy: .public) threadStatus=\(result.threadStatus.rawValue, privacy: .public) summary=\(result.summary, privacy: .public) taskLabel=\(taskLabel, privacy: .public) hint=\(hint, privacy: .public)"- )- }-- private func logActionTraces(for result: LocalAppTaskLiveRunResult) {- guard UserQueryLog.isEnabled else { return }-- for trace in result.actionTraces {- let command = trace.command- let backend = trace.metadata["liveInputBackend"] ?? "unknown"- let inputMode = trace.metadata["inputMode"] ?? inputModeDescription(- backend: backend,- commandKind: command.kind- )- let workflowStepID = command.metadata["workflowStepID"] ?? ""- let controlID = command.metadata["controlID"] ?? ""- let target = actionTargetDescription(for: command)- let elementClick = isElementClick(command)- let appleScriptAction = trace.metadata["appleScript.action"] ?? command.metadata["appleScript.action"] ?? ""- let appleScriptOutput = trace.metadata["appleScript.output"] ?? ""- let accessibilityResult = trace.metadata["accessibility.result"] ?? ""- let overlayPointer = backend == "mac-apple-script" ? "fallbackOnly" : "visualOnly"-- UserQueryLog.commands.notice(- "local action traceID=\(result.traceID, privacy: .public) commandID=\(command.id, privacy: .public) workflowStepID=\(workflowStepID, privacy: .public) kind=\(command.kind.rawValue, privacy: .public) backend=\(backend, privacy: .public) inputMode=\(inputMode, privacy: .public) executed=\(String(trace.executed), privacy: .public) decision=\(decisionDescription(trace.decision), privacy: .public) elementClick=\(String(elementClick), privacy: .public) controlID=\(controlID, privacy: .public) target=\(target, privacy: .public) overlayPointer=\(overlayPointer, privacy: .public) appleScriptAction=\(appleScriptAction, privacy: .public) appleScriptOutput=\(appleScriptOutput, privacy: .public) accessibilityResult=\(accessibilityResult, privacy: .public)"- )- }- }-- private static func metadataValue(in metadata: [String: String], keys: [String]) -> String? {- for key in keys {- if let value = metadata[key] {- return value- }- }- return nil- }-- private static func mergeNonEmpty(- from source: [String: String],- keys: [String],- into target: inout [String: String],- keyPrefix: String = ""- ) {- for key in keys {- if let value = source[key], !value.isEmpty {- target["\(keyPrefix)\(key)"] = value- }- }- }-- private func runHint(for result: LocalAppTaskLiveRunResult) -> String {- if let reason = result.metadata["reason"], !reason.isEmpty {- if reason == "missingModelPlannedCommand",- let missingTool = result.metadata["missingTool"],- !missingTool.isEmpty {- return "Run reason: \(reason) at \(missingTool)."- }- return "Run reason: \(reason)."- }- if let automationBackend = result.metadata["automation.backend"],- !automationBackend.isEmpty {- let automationAction = result.metadata["automation.action"] ?? ""- return "Automation \(automationBackend) \(automationAction) finished with status \(result.status.rawValue)."- }- if let verificationStatus = result.metadata["verification.status"],- let verificationSummary = result.metadata["verification.summary"] {- return "Verification \(verificationStatus): \(verificationSummary)."- }- return "Local app workflow finished with status \(result.status.rawValue)."- }-- private func inputModeDescription(- backend: String,- commandKind: ActionEngineCommandKind- ) -> String {- if backend.contains("apple-script") { return "appAutomation" }- if backend.contains("accessibility") { return "accessibilityElement" }- if backend.contains("keyboard") { return "keyboard" }- return commandKind.rawValue- }-- private func actionTargetDescription(for command: ActionEngineCommand) -> String {- if let controlID = command.metadata["controlID"],- !controlID.isEmpty {- return "control:\(controlID)"- }-- guard let bounds = command.targetBounds else {- return "none"- }- return String(- format: "bounds:x=%.3f,y=%.3f,w=%.3f,h=%.3f,space=%@",- bounds.origin.x,- bounds.origin.y,- bounds.size.width,- bounds.size.height,- bounds.space.rawValue- )- }-- private func isElementClick(_ command: ActionEngineCommand) -> Bool {- (command.kind == .tap || command.kind == .mouse) &&- (command.targetBounds != nil || command.metadata["controlID"]?.isEmpty == false)- }-- private func decisionDescription(_ decision: ActionEngineCommandDecision) -> String {- switch decision {- case .skippedNoLiveInput:- return "skippedNoLiveInput"- case .executedLive:- return "executedLive"- case .denied(let reason):- return "denied:\(reason)"- }- }-- private static func shouldRespondWithoutLocalTask(_ resolution: LocalAppTaskCatalogResolution) -> Bool {- guard resolution.status == .needsConfirmation else { return false }- if resolution.metadata["responseMode"] == "conversation",- resolution.metadata["assistantResponse"]?.isEmpty == false {- return true- }- return resolution.metadata["reason"] == "lowConfidenceIntent"- && resolution.metadata["assistantResponse"]?.isEmpty == false- }-- private static func shouldFailSafelyWithoutLocalTask(_ resolution: LocalAppTaskCatalogResolution) -> Bool {- guard resolution.status == .needsConfirmation,- resolution.intent == nil,- resolution.metadata["reason"] == "hostedModelIntentUnavailable"- else {- return false- }- return resolution.metadata["responseMode"] != "conversation"- }-- private static func shouldAskClarificationBeforeLocalTask(_ resolution: LocalAppTaskCatalogResolution) -> Bool {- guard resolution.status == .needsConfirmation,- shouldRespondWithoutLocalTask(resolution) == false- else {- return false- }- return resolution.intent == nil- || resolution.intent?.needsConfirmation == true- || resolution.metadata["responseMode"] == "clarification"- }-- private static func clarificationQuestion(for resolution: LocalAppTaskCatalogResolution) -> String {- if let assistantResponse = resolution.metadata["assistantResponse"],- !assistantResponse.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- return assistantResponse- }- if let reason = resolution.metadata["reason"],- !reason.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- let readableDetail = reason- .split(separator: "_")- .joined(separator: " ")- return "What \(readableDetail) should I use?"- }- return "What detail should I use?"- }-- private static func conversationResponse(for resolution: LocalAppTaskCatalogResolution) -> String {- if let assistantResponse = resolution.metadata["assistantResponse"],- !assistantResponse.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- return assistantResponse- }- if resolution.metadata["reason"] == "hostedModelIntentUnavailable" {- let modelStatus = resolution.metadata["modelCallStatus"] ?? ""- if modelStatus == AIModelCallStatus.missingCredentials.rawValue {- return "The hosted command parser is not configured yet, so I couldn't safely run that action."- }- if modelStatus == AIModelCallStatus.providerOutage.rawValue- || modelStatus == AIModelCallStatus.timeout.rawValue {- return "The hosted command parser is not available right now, so I couldn't safely run that action."- }- }- return "I can help, but I need a clearer request before opening an app."- }-- private static func modelUnavailableResponse(for resolution: LocalAppTaskCatalogResolution) -> String {- let modelStatus = resolution.metadata["modelCallStatus"] ?? ""- if modelStatus == AIModelCallStatus.missingCredentials.rawValue {- return "The hosted command parser is not configured yet, so I couldn't safely run that action."- }- if modelStatus == AIModelCallStatus.providerOutage.rawValue- || modelStatus == AIModelCallStatus.timeout.rawValue- || modelStatus == AIModelCallStatus.rateLimited.rawValue {- return "The hosted command parser is not available right now, so I couldn't safely run that action."- }- return "The hosted command parser failed before it produced a safe action plan, so I didn't run anything."- }-- private func retrieveSemanticMemory(- command: String,- resolution: LocalAppTaskCatalogResolution- ) async -> [RunMemorySemanticResult] {- guard let memoryStore,- let targetID = semanticMemoryTargetID(for: resolution)- else {- return []- }-- return (try? memoryStore.search(query: AgentMemoryQuery(- text: command,- targetID: targetID,- scope: .target,- kinds: [.targetFact, .workflowMemory, .userInstruction],- budget: RunMemoryRetrievalBudget(maxRecords: 3, maxPromptCharacters: 800)- ))) ?? []- }-- private func semanticMemoryTargetID(- for resolution: LocalAppTaskCatalogResolution- ) -> String? {- guard let definition = resolution.definition else { return nil }- return LocalAppTaskAdapter(definition: definition).targetID- }-- private func documentReviewRequest(- traceID: String,- result: LocalAppTaskLiveRunResult- ) -> DocumentFormFillReviewRequest? {- guard result.status == .needsUserReview,- let plan = result.documentFormFillPlan,- let definition = result.resolution.definition- else {- return nil- }-- return DocumentFormFillReviewRequest(- plan: plan,- definition: definition,- traceID: traceID- )- }-- private func statusSummary(for result: LocalAppTaskLiveRunResult) -> String {- switch result.status {- case .completed:- return "Done"- case .needsUserReview:- if let proposalCount = result.documentFormFillPlan?.proposals.count,- proposalCount > 0 {- return "Review \(proposalCount) fields"- }- return "Needs review"- case .needsConfirmation:- if let reason = result.resolution.metadata["reason"] {- guard reason != "hostedModelIntentUnavailable",- reason != "needsConfirmation"- else {- return "Need more detail"- }- return "Need \(reason)"- }- return "Need more detail"- case .appUnavailable:- if let appName = result.resolution.metadata["targetApp"] ?? result.resolution.availability?.target.appName {- return "\(appName) not found"- }- return "App not found"- case .unsupportedCommand:- return "Need more detail"- case .failedSafe:- return "Stopped safely"- }- }-- private func summary(- for result: LocalAppTaskLiveRunResult,- task: HarnessTaskState?,- runStep: HarnessStepExecutionResult?- ) -> String {- if let task,- task.status == .waitingForPermission {- return Self.permissionGateSummary(for: task)- }-- if let task,- task.status == .interrupted {- return Self.interruptionSummary(for: task)- }-- if let question = task?.pendingContinuation?.question,- !question.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- return question- }-- if let task = runStep?.task,- task.status == .waitingForPermission {- return Self.permissionGateSummary(for: task)- }-- if let task = runStep?.task,- task.status == .interrupted {- return Self.interruptionSummary(for: task)- }-- if let question = runStep?.task.pendingContinuation?.question,- !question.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- return question- }-- return statusSummary(for: result)- }-- private func threadStatus(- for result: LocalAppTaskLiveRunResult,- runStep: HarnessStepExecutionResult? = nil- ) -> UserQueryTaskStatus {- if let status = Self.userQueryStatus(for: runStep?.task) {- return status- }-- switch result.status {- case .completed:- return .completed- case .needsUserReview:- return .waitingForReview- case .needsConfirmation, .unsupportedCommand:- return .waitingForClarification- case .appUnavailable, .failedSafe:- return .failed- }- }-- private func taskLabel(for result: LocalAppTaskLiveRunResult) -> String? {- guard result.status == .completed || result.status == .needsUserReview,- let definition = result.resolution.definition- else {- return nil- }-- let entities = result.resolution.intent?.normalizedEntities ?? [:]- if let template = definition.metadata["taskLabelTemplate"],- let label = Self.renderTemplate(template, entities: entities),- !label.isEmpty {- return label- }-- return Self.displayTitle(for: definition)- }-- private static func displayTitle(for definition: LocalAppTaskDefinition) -> String {- if let displayTitle = definition.metadata["displayTitle"], !displayTitle.isEmpty {- return displayTitle- .split(separator: " ")- .map { word in word.prefix(1).uppercased() + word.dropFirst() }- .joined(separator: " ")- }-- return definition.taskType- .split(separator: "_")- .map { word in word.prefix(1).uppercased() + word.dropFirst() }- .joined(separator: " ")- }-- private static func renderTemplate(- _ template: String,- entities: [String: String]- ) -> String? {- var rendered = template- for (name, value) in entities {- rendered = rendered.replacingOccurrences(of: "{\(name)}", with: value)- }- guard !rendered.contains("{") else { return nil }- return rendered.trimmingCharacters(in: .whitespacesAndNewlines)- }-- private static func uptimeMilliseconds() -> Double {- ProcessInfo.processInfo.systemUptime * 1_000- }+ private static func uptimeMilliseconds() -> Double {+ ProcessInfo.processInfo.systemUptime * 1_000+ }private static func formatLatency(_ milliseconds: Double) -> String {String(format: "%.3f", max(0, milliseconds))}- private static func now() -> RunTraceTimestamp {- RunTraceTimestamp(- wallClock: Date(),- monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)- )- }-- private static func modelInput(- for command: String,- context: UserQueryCommandContext?,- compactedContext: HarnessCompactedThreadContext- ) -> UserQueryModelIntentInput {- let modelCommand = compactedContext.currentTurn?.text ?? command- let compactedPrompt = compactedContext.promptText- guard let context, context.isFollowUp else {- return UserQueryModelIntentInput(- command: modelCommand,- contextSnippets: [compactedPrompt].filter { !$0.isEmpty }- )- }-- let taskContext = [- "Existing task title: \(context.task.title)",- "Existing task original request: \(context.task.commandText)",- "Existing task status: \(context.task.status.rawValue)"- ]- .compactMap(\.self)- .joined(separator: "\n\n")-- return UserQueryModelIntentInput(- command: modelCommand,- contextSnippets: [- taskContext,- compactedPrompt- ].filter { !$0.isEmpty }- )- }-- private static func runtimeCapabilities(for catalog: LocalAppTaskCatalog) -> [String] {- catalog.taskDefinitions- .map { definition in- let title = displayTitle(for: definition)- let entities = definition.entityRules.map(\.name).joined(separator: ",")- return "\(definition.taskType): \(title) app=\(definition.targetApp.appName) entities=\(entities)"- }- .sorted()- }-private static var userQueryGrantedPermissions: Set<HarnessPermission> {[.conversation,@@ -1879,69 +546,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {)).sorted()}- private static func userQueryStatus(for task: HarnessTaskState?) -> UserQueryTaskStatus? {- guard let task else { return nil }-- switch task.status {- case .running, .resuming:- return nil- case .paused:- return .paused- case .waitingForUser:- return .waitingForClarification- case .waitingForPermission:- return .waitingForPermission- case .interrupted:- return .interrupted- case .completed:- return .completed- case .failedSafe, .cancelled:- return .failed- }- }-- private static func genericHarnessTaskMetadata(_ task: HarnessTaskState?) -> [String: String] {- guard let task else { return [:] }-- var metadata: [String: String] = [- "genericHarness.taskStatus": task.status.rawValue- ]- if let continuation = task.pendingContinuation {- metadata["genericHarness.pendingReason"] = continuation.reason- metadata["genericHarness.pendingStage"] = continuation.stage.rawValue- metadata["genericHarness.pendingToolName"] = continuation.pendingToolCall?.name ?? ""- metadata["genericHarness.pendingToolCallID"] = continuation.pendingToolCall?.id ?? ""- metadata["genericHarness.pendingQuestion"] = continuation.question ?? ""- metadata["genericHarness.missingPermissions"] = continuation.missingPermissions- .map(\.rawValue)- .joined(separator: ",")- metadata["genericHarness.newGoal"] = continuation.metadata["newGoal"] ?? ""- }- return metadata- }-- private static func permissionGateSummary(for task: HarnessTaskState) -> String {- let permissions = task.pendingContinuation?.missingPermissions ?? []- let permissionText = permissions.isEmpty- ? "permission"- : permissions.map(\.rawValue).joined(separator: ", ")- let pendingTool = task.pendingContinuation?.pendingToolCall?.name- if let pendingTool, !pendingTool.isEmpty {- return "Approve \(permissionText) for \(pendingTool)"- }-- return "Approve \(permissionText)"- }-- private static func interruptionSummary(for task: HarnessTaskState) -> String {- if let newGoal = task.pendingContinuation?.metadata["newGoal"],- !newGoal.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- return "Changed course: \(newGoal)"- }-- return "Changed course"- }-private static func harnessRequest(command: String,context: UserQueryCommandContext?@@ -1982,30 +586,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {"genericHarness.pendingQuestion": runStep?.task.pendingContinuation?.question ?? ""]}-- private static func contextMetadata(_ context: UserQueryCommandContext?) -> [String: String] {- guard let context else { return [:] }-- return [- "taskContext.taskID": context.task.id,- "taskContext.isFollowUp": String(context.isFollowUp),- "taskContext.eventCount": String(context.recentEvents.count),- "taskContext.assetCount": String(context.assets.count)- ]- }-}--private struct UserQueryGenericFinalizeResult: Equatable, Sendable {- var verificationStep: HarnessStepExecutionResult?- var recoveryStep: HarnessStepExecutionResult?-- init(- verificationStep: HarnessStepExecutionResult? = nil,- recoveryStep: HarnessStepExecutionResult? = nil- ) {- self.verificationStep = verificationStep- self.recoveryStep = recoveryStep- }}actor UserQueryRunCoordinatorRegistry {diff --git a/apps/Donkey/Sources/DonkeyAI/FrontmostVisionWarmCache.swift b/apps/Donkey/Sources/DonkeyAI/FrontmostVisionWarmCache.swiftnew file mode 100644index 00000000..25ab2c43--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/FrontmostVisionWarmCache.swift@@ -0,0 +1,189 @@+import AppKit+import DonkeyContracts+import DonkeyRuntime+import Foundation++/// Decision the warm-cache monitor makes each tick. Pure and separate from the monitor so the+/// big-change / debounce logic is unit-testable without capture or network.+public enum VisionWarmCacheDecision: String, Equatable, Sendable {+ case parse+ case skipUnchanged+ case skipDebounced+}++public enum VisionWarmCachePolicy {+ /// Parse when this is the first sighting of an app, or when the screen changed by at least+ /// `bigChangeThreshold` of its cells AND we haven't parsed this app within+ /// `minReparseIntervalMS`. The threshold is deliberately higher than the reuse threshold: the+ /// reuse check asks "is this the same screen?", this asks "did something big happen?".+ public static func decide(+ previous: ScreenshotSignature?,+ next: ScreenshotSignature,+ bigChangeThreshold: Double,+ lastParseUptimeMS: Double?,+ nowUptimeMS: Double,+ minReparseIntervalMS: Double+ ) -> VisionWarmCacheDecision {+ guard let previous else { return .parse }+ let changed = next.changedFraction(from: previous)+ guard changed >= bigChangeThreshold else { return .skipUnchanged }+ if let lastParseUptimeMS, nowUptimeMS - lastParseUptimeMS < minReparseIntervalMS {+ return .skipDebounced+ }+ return .parse+ }+}++/// Process-wide gate that lets an active vision drive pause the warm-cache monitor, so the two never+/// race to parse and write the same app's entry in `ParsedVisionStore` at the same time.+public final class VisionWarmCacheActivity: @unchecked Sendable {+ public static let shared = VisionWarmCacheActivity()++ private let lock = NSLock()+ private var depth = 0++ public init() {}++ public var isSuspended: Bool {+ lock.lock(); defer { lock.unlock() }+ return depth > 0+ }++ public func suspend() {+ lock.lock(); depth += 1; lock.unlock()+ }++ public func resume() {+ lock.lock(); depth = max(0, depth - 1); lock.unlock()+ }+}++/// Always-on, non-LLM monitor that keeps `ParsedVisionStore` warm: it watches the frontmost user+/// window's screenshot fingerprint and, when a *big* change happens, captures + parses once and+/// stores the result. So when the model later calls `screen.captureAndAnalyze`, the window is usually+/// unchanged since the last big change and the parse is reused instantly instead of paid for inline.+///+/// This is detection-driven, not action-driven: it fires on any large on-screen change (a navigation,+/// a new dialog), independent of whether the agent caused it.+@MainActor+public final class FrontmostVisionWarmCache {+ private let analyzer: any DebugUIInspectionAnalyzing+ private let store: ParsedVisionStore+ private let capture: VisionActionDriver.ScreenshotCapture+ private let permissionChecker: any ScreenRecordingPermissionChecking+ private let cadenceNanoseconds: UInt64+ private let bigChangeThreshold: Double+ private let minReparseIntervalMS: Double+ private let minConfidence: Double+ private let uptimeMS: @Sendable () -> Double++ private var task: Task<Void, Never>?+ private var lastSignatureByApp: [String: ScreenshotSignature] = [:]+ private var lastParseUptimeMSByApp: [String: Double] = [:]++ public init(+ analyzer: any DebugUIInspectionAnalyzing,+ store: ParsedVisionStore = .shared,+ capture: @escaping VisionActionDriver.ScreenshotCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: $0) },+ permissionChecker: any ScreenRecordingPermissionChecking = CoreGraphicsScreenRecordingPermissionChecker(),+ cadenceNanoseconds: UInt64 = 700_000_000,+ bigChangeThreshold: Double = 0.10,+ minReparseIntervalMS: Double = 1_500,+ minConfidence: Double = 0.25,+ uptimeMS: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime * 1_000 }+ ) {+ self.analyzer = analyzer+ self.store = store+ self.capture = capture+ self.permissionChecker = permissionChecker+ self.cadenceNanoseconds = cadenceNanoseconds+ self.bigChangeThreshold = bigChangeThreshold+ self.minReparseIntervalMS = minReparseIntervalMS+ self.minConfidence = minConfidence+ self.uptimeMS = uptimeMS+ }++ /// Builds the monitor from the environment-configured vision backend, or returns nil when the+ /// backend isn't configured (so the app simply doesn't run it).+ public static func fromEnvironment() -> FrontmostVisionWarmCache? {+ guard let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {+ return nil+ }+ let backend = DonkeyBackendInferenceClient(configuration: configuration)+ return FrontmostVisionWarmCache(analyzer: HostedDebugUIInspectionAnalyzer(backend: backend))+ }++ public func start() {+ guard task == nil else { return }+ task = Task { [weak self] in+ await self?.loop()+ }+ }++ public func stop() {+ task?.cancel()+ task = nil+ }++ private func loop() async {+ while !Task.isCancelled {+ await tick()+ try? await Task.sleep(nanoseconds: cadenceNanoseconds)+ }+ }++ func tick() async {+ guard !VisionWarmCacheActivity.shared.isSuspended else { return }+ guard permissionChecker.hasScreenRecordingAccess() else { return }+ guard let target = MacWindowResolver().frontmostUserAppTarget() else { return }+ let appKey = target.bundleIdentifier.flatMap { $0.isEmpty ? nil : $0 } ?? target.appName ?? ""+ guard !appKey.isEmpty else { return }+ guard let shot = try? await capture(target),+ let signature = ScreenshotSignature.make(fromImageData: shot.pngData) else {+ return+ }++ let decision = VisionWarmCachePolicy.decide(+ previous: lastSignatureByApp[appKey],+ next: signature,+ bigChangeThreshold: bigChangeThreshold,+ lastParseUptimeMS: lastParseUptimeMSByApp[appKey],+ nowUptimeMS: uptimeMS(),+ minReparseIntervalMS: minReparseIntervalMS+ )++ // On debounce keep the OLD fingerprint so the next eligible tick still sees the big change and+ // can parse once the debounce window clears. Otherwise record what we just saw.+ if decision != .skipDebounced {+ lastSignatureByApp[appKey] = signature+ }+ guard decision == .parse else { return }++ let compressed = ScreenshotCompression.compressedForModel(shot)+ let imageWidth = max(1, Int(compressed.pixelSize.width.rounded()))+ let imageHeight = max(1, Int(compressed.pixelSize.height.rounded()))+ guard let frame = try? await analyzer.inspect(+ DebugUIInspectionRequest(+ imageDataURL: compressed.base64DataURL,+ pixelSize: compressed.pixelSize,+ minConfidence: minConfidence+ )+ ) else {+ return+ }+ // A drive may have suspended us while we were capturing and parsing. Re-check before writing so+ // a warm parse that started before the drive cannot overwrite the drive's fresher entry.+ guard !VisionWarmCacheActivity.shared.isSuspended else { return }+ store.store(+ appKey: appKey,+ entry: ParsedVisionStore.Entry(+ signature: signature,+ elements: frame.elements,+ imagePixelWidth: imageWidth,+ imagePixelHeight: imageHeight,+ capturedAtUptimeMS: uptimeMS()+ )+ )+ lastParseUptimeMSByApp[appKey] = uptimeMS()+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swiftnew file mode 100644index 00000000..813164eb--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift@@ -0,0 +1,256 @@+import DonkeyContracts+import DonkeyHarness+import Foundation++/// The general model boundary that plans the harness loop one step at a time. The harness calls+/// `planNextStep(for:)` after every observation; this makes one inference over the task's current+/// world model (the evidence the last tool produced) plus the catalog of available tools, and returns+/// the next tool call to run — or `run.complete` when the goal is met.+///+/// It is tool-agnostic: it does not know about vision or Accessibility specifically. It is handed the+/// descriptors of whatever tools are registered (AX see/act, vision see/act, keyboard/text, scripts,+/// lifecycle, conversation) and lets the model choose among them. That is the whole point of the+/// harness — the model picks how to SEE (AX vs. vision) and how to ACT (AX, vision, scripts) per step.+@MainActor+public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {+ private let backend: DonkeyBackendInferenceClient+ private let descriptors: [HarnessToolDescriptor]+ private let appName: String+ private let appGuidance: String?+ private let uptimeMS: @Sendable () -> Double++ /// Uptime (ms) at which the planner first chose an *action* tool (something that changes app+ /// state, i.e. not a read-only observation). The route turns this into the "time to first action"+ /// telemetry; nil until the first action is planned.+ public private(set) var firstActionUptimeMS: Double?+ /// Most recent one-line rationale, surfaced to the user as the run's narration.+ public private(set) var lastNarration: String?++ /// At most this many world-model elements are described to the model (highest-signal first).+ private static let maxElementsInPrompt = 150+ /// Names of the registered read-only tools (observe/verify/respond/lifecycle), derived from each+ /// descriptor's safety class. A tool counts as an "action" for first-action timing exactly when it+ /// is NOT read-only, so this stays in sync with the tools instead of a hand-maintained name list.+ private let readOnlyToolNames: Set<String>++ public init(+ backend: DonkeyBackendInferenceClient,+ descriptors: [HarnessToolDescriptor],+ appName: String,+ appGuidance: String?,+ uptimeMS: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime * 1_000 }+ ) {+ self.backend = backend+ self.descriptors = descriptors+ self.appName = appName+ self.appGuidance = appGuidance+ self.uptimeMS = uptimeMS+ self.readOnlyToolNames = Set(descriptors.filter { $0.safetyClass == .readOnly }.map(\.name))+ }++ public func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {+ let decision: Decision+ do {+ decision = try await decide(task: task)+ } catch {+ return HarnessToolCall(name: "run.failSafe", input: ["reason": "harnessPlanFailed"])+ }+ lastNarration = decision.reason.flatMap { $0.isEmpty ? nil : $0 } ?? lastNarration+ guard let toolName = decision.tool.flatMap({ $0.isEmpty ? nil : $0 }) else {+ return HarnessToolCall(name: "run.complete", input: ["reason": decision.reason ?? "Goal satisfied."])+ }+ if !readOnlyToolNames.contains(toolName), firstActionUptimeMS == nil {+ firstActionUptimeMS = uptimeMS()+ }+ return HarnessToolCall(name: toolName, input: decision.input ?? [:])+ }++ // MARK: - Model call++ private struct Decision: Sendable {+ var tool: String?+ var input: [String: String]?+ var reason: String?+ }++ private struct DecisionWire: Decodable {+ var tool: String?+ var input: [String: String]?+ var reason: String?++ private enum CodingKeys: String, CodingKey { case tool, input, reason }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ tool = try container.decodeIfPresent(String.self, forKey: .tool)+ reason = try container.decodeIfPresent(String.self, forKey: .reason)+ // The response schema is non-strict, so the model can emit a numeric or boolean input value+ // (e.g. {"elementID": 3}). Coerce scalars to strings instead of failing the whole turn.+ input = try container.decodeIfPresent([String: ScalarString].self, forKey: .input)?+ .mapValues(\.value)+ }+ }++ /// A JSON scalar (string, number, boolean, or null) decoded into its string form.+ private struct ScalarString: Decodable {+ let value: String++ init(from decoder: Decoder) throws {+ let container = try decoder.singleValueContainer()+ if let string = try? container.decode(String.self) {+ value = string+ } else if let bool = try? container.decode(Bool.self) {+ value = String(bool)+ } else if let int = try? container.decode(Int.self) {+ value = String(int)+ } else if let double = try? container.decode(Double.self) {+ value = String(double)+ } else if container.decodeNil() {+ value = ""+ } else {+ throw DecodingError.dataCorruptedError(+ in: container,+ debugDescription: "Tool input value is not a JSON scalar"+ )+ }+ }+ }++ public enum PlanningError: Error, CustomStringConvertible {+ case missingOutputText(String)+ public var description: String {+ switch self {+ case let .missingOutputText(raw): return "missingOutputText raw=\(raw)"+ }+ }+ }++ private func decide(task: HarnessTaskState) async throws -> Decision {+ let response = try await backend.createResponse(responseRequest(task: task))+ guard let text = RemoteInferenceResponseHelpers.outputText(from: response), !text.isEmpty else {+ let raw = (try? JSONEncoder().encode(response)).flatMap { String(data: $0, encoding: .utf8) } ?? "<unencodable>"+ throw PlanningError.missingOutputText(String(raw.prefix(2_000)))+ }+ let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)+ let wire = try JSONDecoder().decode(DecisionWire.self, from: Data(json.utf8))+ return Decision(tool: wire.tool, input: wire.input, reason: wire.reason)+ }++ private func responseRequest(task: HarnessTaskState) -> RemoteInferenceResponseCreateRequest {+ let toolNames = descriptors.map(\.name)+ return RemoteInferenceResponseCreateRequest(+ input: .array([+ .object([+ "role": .string("user"),+ "content": .array([+ .object([+ "type": .string("input_text"),+ "text": .string(prompt(task: task))+ ])+ ])+ ])+ ]),+ store: false,+ text: [+ "format": .object([+ "type": .string("json_schema"),+ "name": .string("harness_step_v1"),+ "strict": .bool(false),+ "schema": .object([+ "type": .string("object"),+ "additionalProperties": .bool(false),+ "required": .array([.string("tool"), .string("reason")]),+ "properties": .object([+ "tool": .object([+ "type": .string("string"),+ "enum": .array(toolNames.map(RemoteInferenceJSONValue.string))+ ]),+ "input": .object([+ "type": .string("object"),+ "additionalProperties": .object(["type": .string("string")])+ ]),+ "reason": .object(["type": .string("string")])+ ])+ ])+ ])+ ],+ metadata: ["source": "hosted-harness-step-planner", "prompt_version": "harness-step-v1"],+ parameters: [+ "temperature": .number(0),+ "max_output_tokens": .number(2_000),+ "thinking_budget": .number(0)+ ]+ )+ }++ private func prompt(task: HarnessTaskState) -> String {+ let elements = task.worldModel.elements+ let elementsBlock: String+ if elements.isEmpty {+ elementsBlock = "Nothing has been observed yet. Use a SEE tool (e.g. ax.observe or vision.capture) before acting on an element."+ } else {+ let lines = elements.prefix(Self.maxElementsInPrompt).map { element -> String in+ " \(element.id): [\(element.role)] \"\(element.label)\""+ }.joined(separator: "\n")+ elementsBlock = "Elements currently observed (id: [role] \"label\"):\n\(lines)"+ }++ let factsBlock = task.worldModel.facts.isEmpty+ ? ""+ : "\nKnown state:\n" + task.worldModel.facts.sorted { $0.key < $1.key }+ .map { " \($0.key) = \($0.value)" }.joined(separator: "\n") + "\n"++ let history = task.toolHistory.suffix(12).map { " \($0.call.name): \($0.summary)" }+ let historyBlock = history.isEmpty+ ? "Nothing has been done yet."+ : "Steps already taken (most recent last):\n" + history.joined(separator: "\n")++ let toolsBlock = descriptors+ .sorted { $0.name < $1.name }+ .map { descriptor -> String in+ let inputs = descriptor.inputSchema.keys.sorted().map { key -> String in+ let optional = descriptor.optionalInputKeys.contains(key)+ return "\(key)\(optional ? "?" : "")"+ }+ let inputsText = inputs.isEmpty ? "" : " (input: \(inputs.joined(separator: ", ")))"+ return " - \(descriptor.name): \(descriptor.summary)\(inputsText)"+ }+ .joined(separator: "\n")++ let guidanceBlock: String+ if let appGuidance, !appGuidance.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ guidanceBlock = "\nAPP-SPECIFIC OPERATING GUIDE for \"\(appName)\":\n\(appGuidance)\n"+ } else {+ guidanceBlock = ""+ }++ return """+ You operate the macOS app "\(appName)" by choosing ONE tool to run next, then you will see the+ result and choose again. Work toward the goal in small, verifiable steps.+ GOAL: \(task.goal)++ \(historyBlock)+ \(factsBlock)\(guidanceBlock)+ \(elementsBlock)++ AVAILABLE TOOLS:+ \(toolsBlock)++ Guidance:+ - SEE before you act. Prefer ax.observe (fast, structured) for native apps; use vision.capture+ when Accessibility is missing or insufficient (e.g. canvas/Electron content).+ - To act on a specific element, pass its id from the list above in "input".+ - Before an irreversible or destructive action (sending, deleting, purchasing, posting, moving+ to trash, or overwriting), first ask the user to confirm with user.clarify (set+ input.question), and only perform it after they approve.+ - If the request is a question or chit-chat rather than a desktop action, answer with+ conversation.respond (set input.response), then run.complete.+ - If a required detail is missing and you cannot safely proceed, use user.clarify+ (set input.question).+ - Verification must be evidence-backed: after acting, re-observe (ax.observe/vision.capture) or+ state.verify and confirm the effect BEFORE choosing run.complete. A focused app is not+ evidence; only complete once the goal is confirmed by what you can see.+ Return JSON: {"tool": "<one tool name>", "input": {"key": "value", ...}, "reason": "<one sentence>"}.+ """+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swiftnew file mode 100644index 00000000..fa7a4f2c--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift@@ -0,0 +1,417 @@+import AppKit+import CoreGraphics+import DonkeyContracts+import DonkeyHarness+import DonkeyRuntime+import Foundation++/// Vision computer-use tools registered into a `HarnessToolRegistry` so the model can drive the+/// FRONTMOST app by *choosing* when to look and when to act — capture and analyze the screen on+/// demand, then click / type / press a key against the elements that capture detected.+///+/// These are real harness tools (descriptors, permissions, safety class, guarded execution), but+/// unlike the catalog's placeholder `element.perform`/`text.enter` they perform real input. They are+/// scoped to one frontmost target and built fresh per drive, so they live in the vision loop's own+/// registry rather than the global `BuiltInHarnessToolCatalog` (whose upfront planner would otherwise+/// emit them with no executor on non-vision paths).+///+/// Safety mirrors `VisionActionDriver`: every input action re-checks that the target is frontmost at+/// the instant of the click/keystroke, so input never lands on a window the user switched to during a+/// model round-trip. Click coordinates are mapped from the parse image's pixel space through the+/// window's *current* bounds, re-resolved at action time in case the window moved between turns.+@MainActor+public final class VisionComputerUseToolProvider {+ /// Tool names this provider registers. Stable identifiers the loop's planner names per turn.+ public enum ToolName {+ public static let captureAndAnalyze = "vision.capture"+ public static let click = "vision.click"+ // Keyboard input is modality-agnostic (shared by AX and vision), so it keeps generic names.+ public static let typeText = "text.enter"+ public static let pressKey = "keyboard.press"+ }++ public struct CaptureMetrics: Sendable {+ public var usedCache: Bool+ public var parseMS: Double+ public var elementCount: Int+ }++ let appName: String+ let appKey: String+ let bundleIdentifier: String?+ let analyzer: any DebugUIInspectionAnalyzing+ let store: ParsedVisionStore+ let minConfidence: Double+ let reuseChangedFractionThreshold: Double+ let capture: VisionActionDriver.ScreenshotCapture+ let uptimeMS: @Sendable () -> Double++ /// Metrics from the most recent `screen.captureAndAnalyze`, so the loop can roll up parse time+ /// and cache-hit telemetry without re-parsing the tool result.+ public private(set) var lastCaptureMetrics: CaptureMetrics?++ public init(+ appName: String,+ appKey: String,+ bundleIdentifier: String?,+ analyzer: any DebugUIInspectionAnalyzing,+ store: ParsedVisionStore = .shared,+ minConfidence: Double = 0.25,+ reuseChangedFractionThreshold: Double = VisionComputerUseToolProvider.reuseChangedFractionThreshold,+ capture: @escaping VisionActionDriver.ScreenshotCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: $0) },+ uptimeMS: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime * 1_000 }+ ) {+ self.appName = appName+ self.appKey = appKey+ self.bundleIdentifier = bundleIdentifier+ self.analyzer = analyzer+ self.store = store+ self.minConfidence = minConfidence+ self.reuseChangedFractionThreshold = reuseChangedFractionThreshold+ self.capture = capture+ self.uptimeMS = uptimeMS+ }++ public static var descriptors: [HarnessToolDescriptor] {+ [+ HarnessToolDescriptor(+ name: ToolName.captureAndAnalyze,+ pluginID: "core.computer-use.vision",+ summary: "Screenshot the frontmost window and detect its UI elements with vision. Use when Accessibility is missing or insufficient (canvas/Electron content).",+ outputSchema: ["elements": "Detected element IDs, labels, roles, and click eligibility."],+ requiredPermissions: [.screenCapture],+ safetyClass: .readOnly,+ verificationHints: ["fresh capture reflects the current on-screen state"]+ ),+ HarnessToolDescriptor(+ name: ToolName.click,+ pluginID: "core.computer-use.vision",+ summary: "Click one element returned by vision.capture.",+ inputSchema: ["elementID": "Element ID from the latest screen.captureAndAnalyze."],+ requiredPermissions: [.input],+ safetyClass: .guardedInput,+ requiredContext: ["frontmost target", "captured element"],+ verificationHints: ["re-capture to confirm the click changed the screen"]+ ),+ HarnessToolDescriptor(+ name: ToolName.typeText,+ pluginID: "core.computer-use.vision",+ summary: "Type text into the currently focused field.",+ inputSchema: ["text": "Text to type into the focused field."],+ requiredPermissions: [.input],+ safetyClass: .guardedInput,+ requiredContext: ["frontmost target", "focused field"]+ ),+ HarnessToolDescriptor(+ name: ToolName.pressKey,+ pluginID: "core.computer-use.vision",+ summary: "Press one key, e.g. return to submit.",+ inputSchema: ["key": "Key name such as return, tab, escape, or an arrow."],+ requiredPermissions: [.input],+ safetyClass: .guardedInput,+ requiredContext: ["frontmost target"]+ )+ ]+ }++ public func makeTools() -> [HarnessTool] {+ Self.descriptors.map { descriptor in+ HarnessTool(descriptor: descriptor) { context in+ await self.execute(context)+ }+ }+ }++ private func execute(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ switch context.call.name {+ case ToolName.captureAndAnalyze: return await captureAndAnalyze(context)+ case ToolName.click: return await click(context)+ case ToolName.typeText: return await typeText(context)+ case ToolName.pressKey: return await pressKey(context)+ default:+ return result(context, status: .unknownTool, summary: "Unknown vision tool.", reason: "unknownVisionTool")+ }+ }++ // MARK: - Capture + analyze++ private func captureAndAnalyze(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {+ return result(context, status: .failed, summary: "No window for \(appName).", reason: "noWindowForApp")+ }+ let shot: CapturedWindowScreenshot+ do {+ shot = try await capture(target)+ } catch {+ return result(context, status: .failed, summary: "Screenshot failed.", reason: "screenshotFailed")+ }++ let signature = ScreenshotSignature.make(fromImageData: shot.pngData)++ var usedCache = false+ var parseMS = 0.0+ let elements: [DebugUIElement]+ let elementImageWidth: Int+ let elementImageHeight: Int++ if let signature,+ let reusable = store.reusableEntry(+ appKey: appKey,+ signature: signature,+ changedFractionThreshold: reuseChangedFractionThreshold+ ) {+ usedCache = true+ elements = reusable.elements+ elementImageWidth = reusable.imagePixelWidth+ elementImageHeight = reusable.imagePixelHeight+ } else {+ // Compress only on a cache miss: a reused parse never sends the image, so encoding it+ // before the reuse check would be wasted work on the common warm-cache path.+ let compressed = ScreenshotCompression.compressedForModel(shot)+ let imageWidth = max(1, Int(compressed.pixelSize.width.rounded()))+ let imageHeight = max(1, Int(compressed.pixelSize.height.rounded()))+ let started = uptimeMS()+ let frame: DebugUIInspectionFrame+ do {+ frame = try await analyzer.inspect(+ DebugUIInspectionRequest(+ imageDataURL: compressed.base64DataURL,+ pixelSize: compressed.pixelSize,+ minConfidence: minConfidence+ )+ )+ } catch {+ return result(context, status: .failed, summary: "Vision parse failed.", reason: "visionParseFailed")+ }+ parseMS = uptimeMS() - started+ elements = frame.elements+ elementImageWidth = imageWidth+ elementImageHeight = imageHeight+ if let signature {+ store.store(+ appKey: appKey,+ entry: ParsedVisionStore.Entry(+ signature: signature,+ elements: frame.elements,+ imagePixelWidth: imageWidth,+ imagePixelHeight: imageHeight,+ capturedAtUptimeMS: uptimeMS()+ )+ )+ }+ }++ let actionable = elements.filter { $0.bbox.hasPositiveArea }+ let worldElements = actionable.map {+ Self.worldElement(from: $0, imageWidth: elementImageWidth, imageHeight: elementImageHeight)+ }+ lastCaptureMetrics = CaptureMetrics(usedCache: usedCache, parseMS: parseMS, elementCount: worldElements.count)++ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: "Captured \(worldElements.count) element(s) in \(appName).",+ observations: HarnessObservationDelta(+ focusedApp: appName,+ elements: worldElements,+ facts: [+ "vision.capture.usedCache": String(usedCache),+ "vision.capture.parseMS": String(format: "%.0f", parseMS),+ "vision.capture.elementCount": String(worldElements.count),+ "lastAcceptedTool": context.call.name+ ]+ ),+ metadata: [+ "usedCache": String(usedCache),+ "parseMS": String(format: "%.0f", parseMS),+ "elementCount": String(worldElements.count)+ ]+ )+ }++ // MARK: - Guarded input++ private func click(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ guard let elementID = trimmed(context.call.input["elementID"]) else {+ return result(context, status: .invalidInput, summary: "element.click requires an elementID.", reason: "missingElementID")+ }+ guard let element = context.worldModel.elements.first(where: { $0.id == elementID }) else {+ return result(context, status: .failed, summary: "Element \(elementID) is not in the latest capture.", reason: "elementNotFound")+ }+ guard element.isActionEligible,+ let geometry = Self.geometry(from: element.metadata) else {+ return result(context, status: .failed, summary: "Element \(elementID) cannot be clicked.", reason: "elementNotClickable")+ }+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {+ return result(context, status: .failed, summary: "No window for \(appName).", reason: "noWindowForApp")+ }+ guard isFrontmost(target) else {+ return result(context, status: .failed, summary: "\(appName) is not frontmost.", reason: "targetNotFrontmost")+ }+ let normalized = Self.normalizedCenter(+ bbox: geometry.bbox,+ imageWidth: geometry.imageWidth,+ imageHeight: geometry.imageHeight+ )+ let plan = VisionActionPlanner.PlannedAction(+ action: "click", x: normalized.x, y: normalized.y, text: nil, reason: nil, screenPoint: nil+ )+ guard let point = VisionActionPlanner.screenPoint(action: plan, window: target.bounds) else {+ return result(context, status: .failed, summary: "Could not map element \(elementID) to a screen point.", reason: "unmappablePoint")+ }+ MacPointerInput.moveAndClick(at: point)+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: "Clicked \(element.label.isEmpty ? elementID : element.label).",+ observations: HarnessObservationDelta(facts: ["lastAcceptedTool": context.call.name]),+ metadata: [+ "elementID": elementID,+ "label": element.label,+ "screenPoint": "\(Int(point.x)),\(Int(point.y))"+ ]+ )+ }++ private func typeText(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ guard let text = context.call.input["text"], !text.isEmpty else {+ return result(context, status: .invalidInput, summary: "text.enter requires non-empty text.", reason: "missingText")+ }+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier),+ isFrontmost(target) else {+ return result(context, status: .failed, summary: "\(appName) is not frontmost.", reason: "targetNotFrontmost")+ }+ MacKeyboardInput.type(text)+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: "Typed \(text.count) character(s).",+ observations: HarnessObservationDelta(facts: ["lastAcceptedTool": context.call.name]),+ metadata: ["characterCount": String(text.count)]+ )+ }++ private func pressKey(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ guard let key = trimmed(context.call.input["key"]) else {+ return result(context, status: .invalidInput, summary: "keyboard.press requires a key.", reason: "missingKey")+ }+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier),+ isFrontmost(target) else {+ return result(context, status: .failed, summary: "\(appName) is not frontmost.", reason: "targetNotFrontmost")+ }+ MacKeyboardInput.pressKey(key)+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: "Pressed \(key).",+ observations: HarnessObservationDelta(facts: ["lastAcceptedTool": context.call.name]),+ metadata: ["key": key]+ )+ }++ // MARK: - Element ⇄ world-model mapping++ /// Maps a vision-detected element into a world-model element, stashing the bbox and parse-image+ /// pixel size in metadata so a later `element.click` can re-derive the screen point against the+ /// window's current bounds.+ nonisolated static func worldElement(+ from element: DebugUIElement,+ imageWidth: Int,+ imageHeight: Int+ ) -> HarnessWorldElement {+ HarnessWorldElement(+ id: element.id,+ label: element.label,+ role: element.type.rawValue,+ isActionEligible: element.bbox.hasPositiveArea,+ actions: ["click"],+ metadata: [+ "vision.bbox.x": String(element.bbox.x),+ "vision.bbox.y": String(element.bbox.y),+ "vision.bbox.width": String(element.bbox.width),+ "vision.bbox.height": String(element.bbox.height),+ "vision.image.width": String(imageWidth),+ "vision.image.height": String(imageHeight),+ "vision.confidence": String(element.confidence)+ ]+ )+ }++ struct ElementGeometry: Sendable {+ var bbox: DebugUIBoundingBox+ var imageWidth: Int+ var imageHeight: Int+ }++ nonisolated static func geometry(from metadata: [String: String]) -> ElementGeometry? {+ guard let x = metadata["vision.bbox.x"].flatMap(Double.init),+ let y = metadata["vision.bbox.y"].flatMap(Double.init),+ let width = metadata["vision.bbox.width"].flatMap(Double.init),+ let height = metadata["vision.bbox.height"].flatMap(Double.init),+ let imageWidth = metadata["vision.image.width"].flatMap(Int.init),+ let imageHeight = metadata["vision.image.height"].flatMap(Int.init) else {+ return nil+ }+ return ElementGeometry(+ bbox: DebugUIBoundingBox(x: x, y: y, width: width, height: height),+ imageWidth: imageWidth,+ imageHeight: imageHeight+ )+ }++ // MARK: - Vision-grounding geometry++ /// Below this fraction of changed screenshot grid cells we treat the window as unchanged and reuse+ /// the cached parse instead of paying for another vision call.+ public static let reuseChangedFractionThreshold = 0.02++ /// The element box center expressed in Gemini's 0–1000 normalized image space, so the shared+ /// `VisionActionPlanner.screenPoint` maps it into the window exactly as it does for raw-coordinate+ /// planning. Pure mapping, extracted so it is unit-testable without any capture or network.+ nonisolated static func normalizedCenter(+ bbox: DebugUIBoundingBox,+ imageWidth: Int,+ imageHeight: Int+ ) -> (x: Double, y: Double) {+ let width = Double(max(1, imageWidth))+ let height = Double(max(1, imageHeight))+ let centerX = bbox.x + bbox.width / 2+ let centerY = bbox.y + bbox.height / 2+ return (+ x: centerX / width * VisionActionPlanner.normalizedCoordinateScale,+ y: centerY / height * VisionActionPlanner.normalizedCoordinateScale+ )+ }++ // MARK: - Helpers++ private func isFrontmost(_ target: MacWindowTargetCandidate) -> Bool {+ NSWorkspace.shared.frontmostApplication?.processIdentifier == pid_t(target.processID)+ }++ private func trimmed(_ value: String?) -> String? {+ guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {+ return nil+ }+ return value+ }++ private func result(+ _ context: HarnessToolExecutionContext,+ status: HarnessToolResultStatus,+ summary: String,+ reason: String+ ) -> HarnessToolResult {+ HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: status,+ summary: summary,+ metadata: ["reason": reason]+ )+ }+}diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swiftindex f0af7575..71db0416 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift@@ -16,6 +16,14 @@ public struct HarnessStepExecutionResult: Equatable, Sendable {}}+/// The model boundary the harness consults to choose the next tool call. This is the planning step of+/// the harness loop: it is asked again after every observation, with the task's world model already+/// updated by the previous tool's result, and returns the next call (or nil to stop). It expresses+/// completion by returning a `run.complete` lifecycle call, which ends the loop.+public protocol HarnessNextStepPlanning: Sendable {+ func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall?+}+public struct GenericHarnessRuntime: Sendable {public var coordinator: HarnessTaskCoordinatorpublic var registry: HarnessToolRegistry@@ -28,6 +36,37 @@ public struct GenericHarnessRuntime: Sendable {self.registry = registry}+ /// Runs the harness loop driven by per-observation re-planning: observe → plan one step → execute+ /// → record observation → re-plan, repeating until the planner stops, a gate stops the task, the+ /// task becomes non-executable (e.g. `run.complete`/`run.failSafe`), or `maxSteps` is reached.+ ///+ /// The planner is consulted with the *current* task each iteration, so it sees the world model the+ /// previous tool produced — that is what makes this a real harness loop rather than a fixed plan.+ @discardableResult+ public func run(+ taskID: String,+ planner: any HarnessNextStepPlanning,+ maxSteps: Int = 16+ ) async -> [HarnessStepExecutionResult] {+ var results: [HarnessStepExecutionResult] = []+ for _ in 0..<maxSteps {+ guard let task = await coordinator.task(id: taskID), task.status.canExecuteTools else {+ break+ }+ guard let call = await planner.planNextStep(for: task) else {+ break+ }+ guard let step = await executeToolCall(taskID: taskID, call: call) else {+ break+ }+ results.append(step)+ if step.stoppedForGate || !step.task.status.canExecuteTools {+ break+ }+ }+ return results+ }+public func executeToolCall(taskID: String,call: HarnessToolCalldiff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swiftindex b00e5350..f2085de0 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift@@ -153,7 +153,8 @@ public enum BuiltInHarnessToolCatalog {descriptor("conversation.respond",pluginID: "core.conversation",- summary: "Respond conversationally without taking external action.",+ summary: "Answer the user or chat when the request needs a reply rather than an action. Set 'response' to the message.",+ input: ["response": "The message to say to the user."],permissions: [.conversation],safety: .readOnly),diff --git a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swiftnew file mode 100644index 00000000..561c923e--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift@@ -0,0 +1,225 @@+import AppKit+import CoreGraphics+import DonkeyContracts+import DonkeyHarness+import Foundation++/// Accessibility computer-use tools registered into a `HarnessToolRegistry`: a "see" tool that reads+/// the frontmost app's Accessibility tree into the world model, and an "act" tool that clicks one of+/// those elements. These are the AX counterparts to the vision tools — the harness planner chooses+/// between AX (fast, structured, native apps) and vision (any pixels) per step.+///+/// Acting clicks the AX element's reported screen frame center, guarded so the target must be+/// frontmost at the instant of the click (mirrors the vision/`VisionActionDriver` safety rule).+@MainActor+public final class AXComputerUseToolProvider {+ public enum ToolName {+ public static let observe = "ax.observe"+ public static let click = "ax.click"+ }++ private let appName: String+ private let bundleIdentifier: String?++ public init(appName: String, bundleIdentifier: String?) {+ self.appName = appName+ self.bundleIdentifier = bundleIdentifier+ }++ public static var descriptors: [HarnessToolDescriptor] {+ [+ HarnessToolDescriptor(+ name: ToolName.observe,+ pluginID: "core.computer-use.ax",+ summary: "Read the frontmost app's Accessibility tree and return its actionable controls. Fast and structured; prefer this for native apps.",+ outputSchema: ["elements": "Accessibility control IDs, labels, roles, and click eligibility."],+ requiredPermissions: [.accessibility],+ safetyClass: .readOnly,+ verificationHints: ["fresh observation reflects the current control state"]+ ),+ HarnessToolDescriptor(+ name: ToolName.click,+ pluginID: "core.computer-use.ax",+ summary: "Click one control returned by ax.observe.",+ inputSchema: ["elementID": "Element ID from the latest ax.observe."],+ requiredPermissions: [.input],+ safetyClass: .guardedInput,+ requiredContext: ["frontmost target", "observed control"],+ verificationHints: ["re-observe to confirm the click changed state"]+ )+ ]+ }++ public func makeTools() -> [HarnessTool] {+ Self.descriptors.map { descriptor in+ HarnessTool(descriptor: descriptor) { context in+ await self.execute(context)+ }+ }+ }++ private func execute(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ switch context.call.name {+ case ToolName.observe: return observe(context)+ case ToolName.click: return await click(context)+ default:+ return result(context, status: .unknownTool, summary: "Unknown AX tool.", reason: "unknownAXTool")+ }+ }++ private func observe(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ guard let observation = AccessibilityObserver.observe(appName: appName, bundleIdentifier: bundleIdentifier) else {+ return result(context, status: .failed, summary: "Accessibility is unavailable for \(appName).", reason: "axUnavailable")+ }+ let worldElements = observation.controls.compactMap { Self.worldElement(from: $0) }+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: "Observed \(worldElements.count) Accessibility control(s) in \(appName).",+ observations: HarnessObservationDelta(+ focusedApp: observation.target.appName,+ focusedWindowTitle: observation.target.title,+ elements: worldElements,+ facts: [+ "ax.observe.controlCount": String(worldElements.count),+ "lastAcceptedTool": context.call.name+ ]+ ),+ metadata: ["elementCount": String(worldElements.count), "source": "accessibility"]+ )+ }++ private func click(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ guard let elementID = trimmed(context.call.input["elementID"]) else {+ return result(context, status: .invalidInput, summary: "ax.click requires an elementID.", reason: "missingElementID")+ }+ guard let element = context.worldModel.elements.first(where: { $0.id == elementID }) else {+ return result(context, status: .failed, summary: "Control \(elementID) is not in the latest observation.", reason: "elementNotFound")+ }+ guard element.isActionEligible, let center = Self.screenCenter(from: element.metadata) else {+ return result(context, status: .failed, summary: "Control \(elementID) cannot be clicked.", reason: "elementNotClickable")+ }+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {+ return result(context, status: .failed, summary: "No window for \(appName).", reason: "noWindowForApp")+ }+ guard isFrontmost(target) else {+ return result(context, status: .failed, summary: "\(appName) is not frontmost.", reason: "targetNotFrontmost")+ }+ let label = element.label.isEmpty ? elementID : element.label++ // Prefer a native Accessibility press (AXPress): it activates the control directly, so it works+ // even when a coordinate click would miss (partially obscured, scrolled, zero-size hit area).+ // Falls back to a guarded coordinate click on the element's frame center when AX press isn't+ // available (no bundle id, control doesn't support AXPress) or doesn't land.+ if let bundleIdentifier, !bundleIdentifier.isEmpty, element.actions.contains("AXPress"),+ await axPress(nodeID: element.id, bundleIdentifier: bundleIdentifier) {+ return clickSucceeded(context, elementID: elementID, label: label, strategy: "ax-press", point: nil)+ }+ MacPointerInput.moveAndClick(at: center)+ return clickSucceeded(context, elementID: elementID, label: label, strategy: "coordinate", point: center)+ }++ /// Performs an `AXPress` on the control identified by `nodeID` via the Accessibility action backend,+ /// which re-checks that `bundleIdentifier` is the frontmost app before acting. Returns whether the+ /// press landed.+ private func axPress(nodeID: String, bundleIdentifier: String) async -> Bool {+ let command = ActionEngineCommand(+ id: UUID().uuidString,+ traceID: "ax-click",+ targetID: nodeID,+ kind: .tap,+ issuedAt: RunTraceTimestamp(+ wallClock: Date(),+ monotonicUptimeNanoseconds: DispatchTime.now().uptimeNanoseconds+ ),+ metadata: [+ "accessibility.nodeID": nodeID,+ "accessibility.action": "AXPress",+ "bundleIdentifier": bundleIdentifier,+ "controlID": nodeID+ ]+ )+ let outcome = await MacAccessibilityActionEngineInputBackend().execute(command)+ return outcome.executed+ }++ private func clickSucceeded(+ _ context: HarnessToolExecutionContext,+ elementID: String,+ label: String,+ strategy: String,+ point: CGPoint?+ ) -> HarnessToolResult {+ var metadata = ["elementID": elementID, "label": label, "inputStrategy": strategy]+ if let point { metadata["screenPoint"] = "\(Int(point.x)),\(Int(point.y))" }+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: strategy == "ax-press" ? "Pressed \(label) via Accessibility." : "Clicked \(label).",+ observations: HarnessObservationDelta(facts: ["lastAcceptedTool": context.call.name]),+ metadata: metadata+ )+ }++ // MARK: - Control ⇄ world-model mapping++ /// Maps an Accessibility control into a world-model element, stashing its screen frame so a later+ /// `ax.click` can click the frame center. Returns nil for controls without a usable frame.+ nonisolated static func worldElement(from control: LocalAppDiscoveredControl) -> HarnessWorldElement? {+ guard let frame = control.frame, frame.width > 0, frame.height > 0 else { return nil }+ return HarnessWorldElement(+ id: control.id,+ label: control.label,+ role: control.role ?? control.kind.rawValue,+ isActionEligible: control.isEnabled,+ actions: control.actions.isEmpty ? ["click"] : control.actions,+ metadata: [+ "ax.frame.x": String(frame.x),+ "ax.frame.y": String(frame.y),+ "ax.frame.width": String(frame.width),+ "ax.frame.height": String(frame.height),+ "ax.kind": control.kind.rawValue,+ "ax.value": control.valueSummary ?? ""+ ]+ )+ }++ nonisolated static func screenCenter(from metadata: [String: String]) -> CGPoint? {+ guard let x = metadata["ax.frame.x"].flatMap(Double.init),+ let y = metadata["ax.frame.y"].flatMap(Double.init),+ let width = metadata["ax.frame.width"].flatMap(Double.init),+ let height = metadata["ax.frame.height"].flatMap(Double.init),+ width > 0, height > 0 else {+ return nil+ }+ return CGPoint(x: x + width / 2, y: y + height / 2)+ }++ // MARK: - Helpers++ private func isFrontmost(_ target: MacWindowTargetCandidate) -> Bool {+ NSWorkspace.shared.frontmostApplication?.processIdentifier == pid_t(target.processID)+ }++ private func trimmed(_ value: String?) -> String? {+ guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { return nil }+ return value+ }++ private func result(+ _ context: HarnessToolExecutionContext,+ status: HarnessToolResultStatus,+ summary: String,+ reason: String+ ) -> HarnessToolResult {+ HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: status,+ summary: summary,+ metadata: ["reason": reason]+ )+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift b/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swiftindex 89a5830e..4ab08166 100644--- a/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift@@ -127,6 +127,23 @@ public final class MacWindowResolver: @unchecked Sendable {MacWindowCandidateListSnapshot(candidates: enumerateCandidates())}+ /// The user's frontmost real window, skipping Donkey's own process and bundle so the agent never+ /// targets its own overlay. Candidates come back front-to-back, so the first non-Donkey match is+ /// the app the user was last working in. Shared by the harness run and the warm-cache monitor so+ /// the two always agree on which window is "frontmost".+ public func frontmostUserAppTarget() -> MacWindowTargetCandidate? {+ let ownProcessID = ProcessInfo.processInfo.processIdentifier+ let ownBundleID = Bundle.main.bundleIdentifier+ return enumerateCandidates().first { candidate in+ if candidate.processID == ownProcessID { return false }+ if let ownBundleID, let candidateBundle = candidate.bundleIdentifier,+ candidateBundle.caseInsensitiveCompare(ownBundleID) == .orderedSame {+ return false+ }+ return true+ }+ }+public func selectTarget(_ request: MacWindowSelectionRequest = MacWindowSelectionRequest()) throws -> MacWindowTargetCandidate {diff --git a/apps/Donkey/Sources/DonkeyRuntime/ParsedVisionStore.swift b/apps/Donkey/Sources/DonkeyRuntime/ParsedVisionStore.swiftnew file mode 100644index 00000000..b6c45c4f--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/ParsedVisionStore.swift@@ -0,0 +1,74 @@+import DonkeyContracts+import Foundation++/// Process-wide cache of the most recent vision parse per app, so a typed command can reuse the+/// elements that were already detected instead of paying for another `/api/inference/vision` parse+/// on every turn. Keyed by a stable app key (bundle identifier, falling back to app name).+///+/// Reuse is gated by `ScreenshotSignature`: a fresh capture is fingerprinted and compared to the+/// cached one; only when the window looks unchanged (below the change threshold) do we reuse the+/// stored elements. Elements are stored in the parse image's pixel space together with that pixel+/// size, so the caller can map a box back to the *current* window bounds even if the window moved.+public final class ParsedVisionStore: @unchecked Sendable {+ public static let shared = ParsedVisionStore()++ public struct Entry: Sendable {+ public var signature: ScreenshotSignature+ /// Detected elements with `bbox` in the parse image's pixel space (NOT screen points).+ public var elements: [DebugUIElement]+ public var imagePixelWidth: Int+ public var imagePixelHeight: Int+ public var capturedAtUptimeMS: Double++ public init(+ signature: ScreenshotSignature,+ elements: [DebugUIElement],+ imagePixelWidth: Int,+ imagePixelHeight: Int,+ capturedAtUptimeMS: Double+ ) {+ self.signature = signature+ self.elements = elements+ self.imagePixelWidth = imagePixelWidth+ self.imagePixelHeight = imagePixelHeight+ self.capturedAtUptimeMS = capturedAtUptimeMS+ }+ }++ private let lock = NSLock()+ private var entries: [String: Entry] = [:]++ public init() {}++ public func store(appKey: String, entry: Entry) {+ let key = Self.normalize(appKey)+ guard !key.isEmpty else { return }+ lock.lock()+ defer { lock.unlock() }+ entries[key] = entry+ }++ public func latest(appKey: String) -> Entry? {+ let key = Self.normalize(appKey)+ guard !key.isEmpty else { return nil }+ lock.lock()+ defer { lock.unlock() }+ return entries[key]+ }++ /// Returns the cached entry only when its fingerprint is close enough to `signature` to treat the+ /// window as unchanged, so the caller can reuse its elements without re-parsing.+ public func reusableEntry(+ appKey: String,+ signature: ScreenshotSignature,+ changedFractionThreshold: Double+ ) -> Entry? {+ guard let entry = latest(appKey: appKey) else { return nil }+ let changed = signature.changedFraction(from: entry.signature)+ return changed <= changedFractionThreshold ? entry : nil+ }++ private static func normalize(_ key: String) -> String {+ key.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AXComputerUseToolsTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AXComputerUseToolsTests.swiftnew file mode 100644index 00000000..3f55a16a--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AXComputerUseToolsTests.swift@@ -0,0 +1,60 @@+import CoreGraphics+import DonkeyContracts+import DonkeyHarness+@testable import DonkeyRuntime+import Testing++/// Coverage for the AX-control → world-element mapping and the frame → click-point math that decides+/// where `ax.click` lands. Observation/click execution touches the live window server and is covered+/// by the live path.+@Suite+struct AXComputerUseToolsTests {+ private func control(+ id: String,+ frame: WindowTargetBounds?,+ isEnabled: Bool = true,+ actions: [String] = ["AXPress"]+ ) -> LocalAppDiscoveredControl {+ LocalAppDiscoveredControl(+ id: id,+ kind: .button,+ role: "AXButton",+ label: "Play",+ frame: frame,+ isEnabled: isEnabled,+ actions: actions+ )+ }++ @Test+ func worldElementCarriesScreenFrameForClick() {+ let element = try! #require(+ AXComputerUseToolProvider.worldElement(+ from: control(id: "ax-1.2", frame: WindowTargetBounds(x: 100, y: 200, width: 40, height: 20))+ )+ )+ #expect(element.id == "ax-1.2")+ #expect(element.role == "AXButton")+ #expect(element.isActionEligible)+ #expect(element.actions == ["AXPress"])++ // Frame center: (100+20, 200+10) = (120, 210), in absolute screen coordinates.+ let center = try! #require(AXComputerUseToolProvider.screenCenter(from: element.metadata))+ #expect(center.x == 120)+ #expect(center.y == 210)+ }++ @Test+ func controlWithoutUsableFrameIsDropped() {+ #expect(AXComputerUseToolProvider.worldElement(from: control(id: "x", frame: nil)) == nil)+ #expect(AXComputerUseToolProvider.worldElement(+ from: control(id: "y", frame: WindowTargetBounds(x: 0, y: 0, width: 0, height: 0))+ ) == nil)+ }++ @Test+ func screenCenterIsNilWhenMetadataIncomplete() {+ #expect(AXComputerUseToolProvider.screenCenter(from: ["ax.frame.x": "1"]) == nil)+ #expect(AXComputerUseToolProvider.screenCenter(from: [:]) == nil)+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex a525087f..2ce82cee 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -162,6 +162,55 @@ struct GenericHarnessTests {#expect(toolResult.metadata["realPointerMoved"] == "false")}+ @Test+ func runReplansAfterEachObservation() async {+ // The harness loop must re-plan with the world model the previous tool produced. The planner+ // observes once, then — seeing the observation now recorded — completes. Proves planning is+ // driven by observations, not a fixed up-front plan.+ struct StubReplanningPlanner: HarnessNextStepPlanning {+ func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {+ if task.worldModel.facts["observed"] == "true" {+ return HarnessToolCall(name: "run.complete", input: ["reason": "done"])+ }+ return HarnessToolCall(name: "test.observe")+ }+ }++ let coordinator = HarnessTaskCoordinator()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ await registry.register(+ HarnessTool(+ descriptor: HarnessToolDescriptor(+ name: "test.observe",+ pluginID: "test",+ summary: "Stub observation tool.",+ safetyClass: .readOnly+ )+ ) { context in+ HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: "observed",+ observations: HarnessObservationDelta(facts: ["observed": "true"])+ )+ }+ )+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)+ let task = await coordinator.createTask(+ id: "task-replan",+ threadID: "thread-replan",+ goal: "observe then finish",+ grantedPermissions: [.lifecycle]+ )++ let steps = await runtime.run(taskID: task.id, planner: StubReplanningPlanner(), maxSteps: 5)++ #expect(steps.map { $0.toolResult?.toolName } == ["test.observe", "run.complete"])+ let finalTask = await coordinator.task(id: task.id)+ #expect(finalTask?.status == .completed)+ }+@Testfunc skillRegistryCanRegisterAndSearchSkills() async {let registry = HarnessSkillRegistry()diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GuidanceRouteLiveSmokeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GuidanceRouteLiveSmokeTests.swiftdeleted file mode 100644index 73904abd..00000000--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GuidanceRouteLiveSmokeTests.swift+++ /dev/null@@ -1,57 +0,0 @@-import AppKit-@testable import Donkey-import DonkeyContracts-import DonkeyUI-import Foundation-import Testing--/// Live, env-gated end-to-end test for the guidance route (plan phase 2): a natural-language-/// "show me where X is" goes through the real handler → hosted planner classifies `guidance` →-/// GuidanceOverlayFlow grounds the control → a cursor overlay is produced and presented.-///-/// env DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer DONKEY_LIVE_SMOKE=1 \-/// DONKEY_WEB_BASE_URL=http://localhost:3000 DONKEY_DEV_AUTH_BYPASS=1 \-/// swift test --filter GuidanceRouteLiveSmokeTests-@Suite-struct GuidanceRouteLiveSmokeTests {- @Test- @MainActor- func showMeWhereRoutesToGuidanceAndOverlays() async {- let env = ProcessInfo.processInfo.environment- guard env["DONKEY_LIVE_SMOKE"] == "1" else { return }- if env["DONKEY_WEB_BASE_URL"]?.isEmpty != false {- Issue.record("DONKEY_WEB_BASE_URL not set")- return- }-- let appName = env["DONKEY_GUIDE_APP"] ?? "Music"- NSWorkspace.shared.launchApplication(appName)- try? await Task.sleep(nanoseconds: 800_000_000)-- let handler = LocalAppUserQueryCommandHandler()- let result = await handler.handleSubmittedCommand("show me where the search field is in \(appName)")-- // The planner should have classified this as the guidance route.- #expect(result.metadata["router"] == "modelGuidance")- if result.cursorOverlayRequest == nil {- Issue.record("Guidance produced no overlay: reason=\(result.metadata["guidance.reason"] ?? "?") app=\(result.metadata["guidance.resolvedApp"] ?? "?") targets=\(result.metadata["guidance.targetCount"] ?? "?")")- return- }-- let request = result.cursorOverlayRequest!- #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 }- Self.pump(forSeconds: duration)- }-- @MainActor- private static func pump(forSeconds seconds: TimeInterval) {- RunLoop.main.run(until: Date().addingTimeInterval(seconds))- }-}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaybackLiveSmokeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaybackLiveSmokeTests.swiftdeleted file mode 100644index f4d066ac..00000000--- a/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaybackLiveSmokeTests.swift+++ /dev/null@@ -1,78 +0,0 @@-import AppKit-@testable import Donkey-import DonkeyContracts-import DonkeyRuntime-import DonkeyUI-import Foundation-import Testing--/// Live, end-to-end smoke test for playing music through the real Donkey agent harness.-///-/// This intentionally does almost nothing itself: it hands the raw query to the production-/// `LocalAppUserQueryCommandHandler`, which does ALL of the work — parse intent against the real-/// hosted backend, plan the task, execute it through the harness runtime (launching the resolved-/// media app and playing the track), and derive the cursor-path visualization from the actual run.-/// The test only requests Accessibility (so the harness can drive the app) and presents the-/// harness-produced cursor overlay so the pointer is visible.-///-/// Because it makes real network calls and can launch a media app, it is gated behind-/// `DONKEY_LIVE_SMOKE=1` and no-ops in normal `swift test` runs. To run it live:-///-/// env DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer \-/// DONKEY_LIVE_SMOKE=1 DONKEY_WEB_BASE_URL=http://localhost:3000 DONKEY_DEV_AUTH_BYPASS=1 \-/// swift test --filter MusicPlaybackLiveSmokeTests-@Suite-struct MusicPlaybackLiveSmokeTests {- private static let query = "play some cold play"-- @Test- @MainActor- func playsColdplayThroughRealHarnessAndVisualizesPointerPath() async throws {- let environment = ProcessInfo.processInfo.environment- guard environment["DONKEY_LIVE_SMOKE"] == "1" else {- // Skipped by default: this is a live smoke test, not a CI unit test.- return- }- if environment["DONKEY_WEB_BASE_URL"]?.isEmpty != false {- Issue.record("DONKEY_LIVE_SMOKE=1 but DONKEY_WEB_BASE_URL is not set; cannot reach a backend.")- return- }-- // Request Accessibility via the app's real requester so the harness can drive the media app- // (the planned UI-control steps need it). Shows the system prompt / opens System Settings.- _ = await SystemMacPermissionRequester().request(.accessibility)-- // Hand the raw query to the real handler. It parses, plans, executes (plays the music), and- // builds the agent-visualization plan from the run — nothing is hand-authored here. The- // music-media skill is responsible for picking a representative song for a vague request- // and acting directly (no clarification gate), so this should run to completion.- let handler = LocalAppUserQueryCommandHandler()- let result = await handler.handleSubmittedCommand(Self.query)-- // The harness should have routed this to a local app task and completed it.- #expect(result.decision.kind == .runLocalTask)- if result.status != .completed {- Issue.record("Harness run did not complete: status=\(result.status) summary=\(result.summary) metadata=\(result.metadata)")- }-- // Present the harness-derived cursor path so the pointer is visible during playback.- let cursorRequest = try #require(- result.cursorOverlayRequest,- "Harness produced no cursor overlay request for the run (no grounded agent path)."- )- if NSApplication.shared.activationPolicy() == .prohibited {- NSApplication.shared.setActivationPolicy(.accessory)- }- let overlay = PointerCoachCursorOverlayController()- overlay.show(request: cursorRequest)- let overlayDuration = cursorRequest.steps.reduce(1.0) { $0 + $1.travelDuration + $1.holdDuration }- Self.pumpMainRunLoop(forSeconds: overlayDuration)- }-- /// Runs the main run loop for `seconds` so the AppKit overlay panel renders/animates. Lives in- /// a synchronous method because `RunLoop.run(until:)` is unavailable directly in async contexts.- @MainActor- private static func pumpMainRunLoop(forSeconds seconds: TimeInterval) {- RunLoop.main.run(until: Date().addingTimeInterval(seconds))- }-}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ParsedVisionStoreTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ParsedVisionStoreTests.swiftnew file mode 100644index 00000000..10c4398b--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ParsedVisionStoreTests.swift@@ -0,0 +1,73 @@+import DonkeyContracts+import DonkeyRuntime+import Testing++/// Coverage for the per-app parsed-vision cache: a fresh capture reuses the stored elements only when+/// the window looks unchanged, and the app key matches case- and whitespace-insensitively. (The+/// parse-pixel → normalized click mapping is covered in `VisionComputerUseToolsTests`.)+@Suite+struct ParsedVisionStoreTests {+ private func signature(fill: UInt8) -> ScreenshotSignature {+ ScreenshotSignature(+ pixels: [UInt8](repeating: fill, count: 64 * 64),+ dimension: 64+ )+ }++ private func element(id: String, label: String, bbox: DebugUIBoundingBox) -> DebugUIElement {+ DebugUIElement(id: id, type: .button, label: label, bbox: bbox, confidence: 0.9)+ }++ @Test+ func reusesCacheWhenWindowUnchanged() {+ let store = ParsedVisionStore()+ let element = element(id: "1", label: "Discover Weekly", bbox: DebugUIBoundingBox(x: 0, y: 0, width: 10, height: 10))+ store.store(appKey: "com.spotify.client", entry: ParsedVisionStore.Entry(+ signature: signature(fill: 100),+ elements: [element],+ imagePixelWidth: 800,+ imagePixelHeight: 600,+ capturedAtUptimeMS: 0+ ))++ // An identical fingerprint is reused.+ let reused = store.reusableEntry(+ appKey: "com.spotify.client",+ signature: signature(fill: 100),+ changedFractionThreshold: 0.02+ )+ #expect(reused?.elements.first?.label == "Discover Weekly")+ }++ @Test+ func reparsesWhenWindowChangedBeyondThreshold() {+ let store = ParsedVisionStore()+ store.store(appKey: "spotify", entry: ParsedVisionStore.Entry(+ signature: signature(fill: 0),+ elements: [element(id: "1", label: "X", bbox: DebugUIBoundingBox(x: 0, y: 0, width: 1, height: 1))],+ imagePixelWidth: 10,+ imagePixelHeight: 10,+ capturedAtUptimeMS: 0+ ))+ // A wholly different image (every cell maxed) is far above the change threshold → no reuse.+ let reused = store.reusableEntry(+ appKey: "spotify",+ signature: signature(fill: 255),+ changedFractionThreshold: 0.02+ )+ #expect(reused == nil)+ }++ @Test+ func appKeyMatchingIsCaseAndWhitespaceInsensitive() {+ let store = ParsedVisionStore()+ store.store(appKey: "Com.Spotify.Client", entry: ParsedVisionStore.Entry(+ signature: signature(fill: 5),+ elements: [],+ imagePixelWidth: 1,+ imagePixelHeight: 1,+ capturedAtUptimeMS: 0+ ))+ #expect(store.latest(appKey: " com.spotify.client ") != nil)+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerUseToolsTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerUseToolsTests.swiftnew file mode 100644index 00000000..8eb95c3b--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerUseToolsTests.swift@@ -0,0 +1,73 @@+import CoreGraphics+@testable import DonkeyAI+import DonkeyContracts+import DonkeyHarness+import DonkeyRuntime+import Testing++/// Coverage for the pure mapping pieces that decide WHERE a vision-detected element gets clicked and+/// WHICH tool the model's per-turn decision invokes. The capture/click execution itself touches the+/// real window server and is exercised by the live path.+@Suite+struct VisionComputerUseToolsTests {+ private func element(+ id: String,+ bbox: DebugUIBoundingBox,+ confidence: Double = 0.9+ ) -> DebugUIElement {+ DebugUIElement(id: id, type: .button, label: "Play", bbox: bbox, confidence: confidence)+ }++ @Test+ func worldElementCarriesGeometryForLaterClickMapping() {+ let detected = element(id: "e1", bbox: DebugUIBoundingBox(x: 350, y: 250, width: 100, height: 100))+ let world = VisionComputerUseToolProvider.worldElement(from: detected, imageWidth: 800, imageHeight: 600)++ #expect(world.id == "e1")+ #expect(world.role == "button")+ #expect(world.isActionEligible)+ #expect(world.actions == ["click"])++ // The stored geometry round-trips back through `geometry(from:)` so a click can re-derive the+ // box center against the window's current bounds.+ let geometry = VisionComputerUseToolProvider.geometry(from: world.metadata)+ #expect(geometry?.imageWidth == 800)+ #expect(geometry?.imageHeight == 600)+ #expect(geometry?.bbox.width == 100)++ // Same parse-pixel → 0–1000 normalized mapping the image planner uses: center (400,300) in an+ // 800x600 image → (500, 500).+ if let geometry {+ let normalized = VisionComputerUseToolProvider.normalizedCenter(+ bbox: geometry.bbox,+ imageWidth: geometry.imageWidth,+ imageHeight: geometry.imageHeight+ )+ #expect(abs(normalized.x - 500) < 0.001)+ #expect(abs(normalized.y - 500) < 0.001)+ }+ }++ @Test+ func zeroAreaElementIsNotActionEligible() {+ let detected = element(id: "e2", bbox: DebugUIBoundingBox(x: 0, y: 0, width: 0, height: 0))+ let world = VisionComputerUseToolProvider.worldElement(from: detected, imageWidth: 100, imageHeight: 100)+ #expect(!world.isActionEligible)+ }++ @Test+ func geometryIsNilWhenMetadataIncomplete() {+ #expect(VisionComputerUseToolProvider.geometry(from: ["vision.bbox.x": "1"]) == nil)+ #expect(VisionComputerUseToolProvider.geometry(from: [:]) == nil)+ }++ @Test+ func visionToolNamesAreNamespaced() {+ // Vision is one tool family among several in the registry; its see/act tools are namespaced so+ // the planner can tell them apart from the AX tools. Keyboard input stays generic (shared).+ #expect(VisionComputerUseToolProvider.ToolName.captureAndAnalyze == "vision.capture")+ #expect(VisionComputerUseToolProvider.ToolName.click == "vision.click")+ #expect(VisionComputerUseToolProvider.ToolName.typeText == "text.enter")+ #expect(VisionComputerUseToolProvider.ToolName.pressKey == "keyboard.press")+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionNavigationModeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionNavigationModeTests.swiftdeleted file mode 100644index 1e8851fb..00000000--- a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionNavigationModeTests.swift+++ /dev/null@@ -1,30 +0,0 @@-@testable import Donkey-import Testing--/// Unit coverage for the configurable, env-gated vision-navigation route flag. The route itself-/// drives real input/screenshots (covered by the live smoke pattern), but the on/off parsing is-/// pure and must stay reliable so the path is easy to enable and revert.-@Suite-struct VisionNavigationModeTests {- @Test- func enabledForTruthyValues() {- for value in ["1", "true", "TRUE", "Yes", "on"] {- let mode = VisionNavigationMode.fromEnvironment(["DONKEY_VISION_NAV": value])- #expect(mode.isEnabled, "expected \"\(value)\" to enable vision navigation")- }- }-- @Test- func disabledByDefaultAndForFalsyValues() {- #expect(VisionNavigationMode.fromEnvironment([:]).isEnabled == false)- for value in ["", "0", "false", "off", "no", " "] {- let mode = VisionNavigationMode.fromEnvironment(["DONKEY_VISION_NAV": value])- #expect(mode.isEnabled == false, "expected \"\(value)\" to leave vision navigation off")- }- }-- @Test- func toleratesSurroundingWhitespaceAndCase() {- #expect(VisionNavigationMode.fromEnvironment(["DONKEY_VISION_NAV": " On "]).isEnabled)- }-}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionWarmCacheTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionWarmCacheTests.swiftnew file mode 100644index 00000000..72858749--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionWarmCacheTests.swift@@ -0,0 +1,77 @@+@testable import DonkeyAI+import DonkeyRuntime+import Testing++/// Coverage for the always-on warm-cache monitor's pure change/debounce decision and the activity+/// gate that pauses it during an active drive. The capture+parse side effects are integration-only.+@Suite+struct VisionWarmCacheTests {+ private func signature(fill: UInt8) -> ScreenshotSignature {+ ScreenshotSignature(pixels: [UInt8](repeating: fill, count: 64 * 64), dimension: 64)+ }++ @Test+ func firstSightingAlwaysParses() {+ let decision = VisionWarmCachePolicy.decide(+ previous: nil,+ next: signature(fill: 100),+ bigChangeThreshold: 0.10,+ lastParseUptimeMS: nil,+ nowUptimeMS: 0,+ minReparseIntervalMS: 1_500+ )+ #expect(decision == .parse)+ }++ @Test+ func unchangedScreenSkips() {+ let decision = VisionWarmCachePolicy.decide(+ previous: signature(fill: 100),+ next: signature(fill: 100),+ bigChangeThreshold: 0.10,+ lastParseUptimeMS: 0,+ nowUptimeMS: 10_000,+ minReparseIntervalMS: 1_500+ )+ #expect(decision == .skipUnchanged)+ }++ @Test+ func bigChangeWithinDebounceIsDeferred() {+ let decision = VisionWarmCachePolicy.decide(+ previous: signature(fill: 0),+ next: signature(fill: 255),+ bigChangeThreshold: 0.10,+ lastParseUptimeMS: 500,+ nowUptimeMS: 1_000, // 500ms since last parse, under the 1500ms window+ minReparseIntervalMS: 1_500+ )+ #expect(decision == .skipDebounced)+ }++ @Test+ func bigChangeAfterDebounceParses() {+ let decision = VisionWarmCachePolicy.decide(+ previous: signature(fill: 0),+ next: signature(fill: 255),+ bigChangeThreshold: 0.10,+ lastParseUptimeMS: 500,+ nowUptimeMS: 5_000,+ minReparseIntervalMS: 1_500+ )+ #expect(decision == .parse)+ }++ @Test+ func activityGateTracksSuspendDepth() {+ let gate = VisionWarmCacheActivity()+ #expect(!gate.isSuspended)+ gate.suspend()+ gate.suspend()+ #expect(gate.isSuspended)+ gate.resume()+ #expect(gate.isSuspended) // still one suspend outstanding+ gate.resume()+ #expect(!gate.isSuspended)+ }+}diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 91439936..d66434df 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -4,15 +4,16 @@User turn|v-Model boundary -> structured intent, risk, plan, verification- |- v-Generic harness task state- |- v+Generic harness task state (goal, world model, history) <--++ | |+ v |+Model boundary -> the single next tool call |+ | (see, act, verify, respond, clarify, or complete) |+ v |Tool registry -> guarded executor -> structured observation- | |- +----------- verify / recover / gate --++ | |+ +-- update world model, then re-plan ---------------------++ (or hard-stop at a permission / clarification gate)```The agent harness is Donkey's app-agnostic runtime boundary for turning a user@@ -28,28 +29,29 @@ conditionals.## Runtime ShapeA user-query turn enters the generic lifecycle before any local-app executor is-selected. The model boundary returns structured intent, risk/ambiguity, context-needs, plan steps, verification criteria, fallback policy, and clarification-policy. Deterministic Swift then validates the structured plan against the tool-registry, permissions, supported app catalog, and task state.+selected. The harness compacts context into task state, then runs a loop: each+step it asks the model boundary for the single next tool call given the current+world model, validates and executes that one call deterministically, records the+resulting observation, and asks again. Planning happens per observation, not as+one upfront plan.The loop is:```textintake--> intent analysis--> context gathering--> world model update--> planning+-> compact context into task state+-> ask the model boundary for the next tool call+-> validate against registry, permissions, and task state-> execute one guarded tool step--> verify--> recover, continue, clarify, ask permission, or complete+-> record the structured observation into the world model+-> re-plan, or hard-stop at a clarification / permission gate```-Desktop work is not a single model completion. The harness observes, acts,-records evidence, verifies, and may replan. Models choose structured tool calls;-Swift owns task state, tool validation, focus checks, permission gates,-execution, and result recording.+Desktop work is not a single model completion. The harness observes, acts, and+records evidence one step at a time, re-planning after each observation. The+model chooses the next tool — including when to see, verify, respond, clarify,+or complete — while Swift owns task state, tool validation, focus checks,+permission gates, execution, and result recording.## Task State@@ -94,7 +96,7 @@ Waiting states are hard stops:- missing permission moves the task to `waitingForPermission`- missing required user detail moves the task to `waitingForUser`- dangerous ambiguity asks before acting-- verification failure chooses recovery, review, or failed-safe state+- on verification failure the planner re-plans to recover, clarify, or fail safeCore tool families cover conversation, clarification, permission requests,memory, skills, app lookup, observation, UI element actions, text/keyboard@@ -103,10 +105,28 @@ lifecycle control.## Computer Use-Computer use is a tool family inside the harness. Accessibility is the primary-source for actionable elements. Screenshots, vision, OCR, and hover evidence-enrich the world model and can provide fallback targets when Accessibility is-insufficient.+Computer use is a tool family inside the harness, and seeing and acting are each+plain tools the planner chooses per step — not a fixed pipeline. The harness+re-plans after every observation, so the model looks, sees the result, then picks+the next tool.++To **see**, it can read the Accessibility tree (fast, structured, best for native+apps) or capture and analyze a screenshot with vision (works for any pixels, e.g.+canvas or Electron content). Either returns elements into the world model.+Accessibility is preferred when it's sufficient; vision is the fallback when it+isn't.++To **act**, it can click an element the AX tree or vision returned, type or press+keys, or generate and run an AppleScript — whichever fits. Clicking an+Accessibility control prefers a native Accessibility press (`AXPress`) and falls+back to a guarded coordinate click on the control's frame; vision elements click+by coordinate. Either way this is not a shortcut around the focus and permission+checks below. The planner can also answer conversationally or ask the user to+clarify instead of acting — responding and clarifying are themselves tools.++A non-LLM monitor watches the frontmost window's screenshot fingerprint and+re-parses on large changes, keeping the vision parse cache warm so a capture is+usually reused instantly rather than paid for inline.Input must be guarded by target focus, permission policy, element eligibility,allowed action type, safety class, and verification criteria. Coordinate inputdiff --git a/plans/master-plan.md b/plans/master-plan.mdindex da1555b7..8bd74d2f 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -21,20 +21,7 @@ even when there are no active tasks.## Current Sequence-- Better Donkey Vision testing UI. Vision (RunPod OmniParser V2) now renders on- the developer debug overlay (`DONKEY_DEBUG_OVERLAY`, fused with AX, gated behind- `remoteAIEngine` in `DebugUIInspectionCoordinator`). That overlay is a debugging- surface, not a real product/testing UI. We need a better way to view and- evaluate raw vision output (boxes, labels, per-window parse latency, hit/skip on- the local image-hash cache) while iterating. Scope/shape TBD.- - Iteration affordance now in place: an env-gated "vision navigation" route- (`DONKEY_VISION_NAV=1`, `VisionNavigationMode` in `UserQueryCommandHandler`)- sends a typed query straight to `VisionActionDriver` against the frontmost- app, so you can type one request after another and watch it navigate. It- console-logs end-to-end grounding latency (time-to-first-action and total)- under the `vision-grounding` logger / `[grounding-e2e]` stdout prefix. The- flag is configurable/revertible; this is a dev-test path, not yet a product- surface.+_No active tasks._## Invariantsdiff --git a/scripts/run-donkey-dev.sh b/scripts/run-donkey-dev.shindex 62629b7a..b365091e 100755--- a/scripts/run-donkey-dev.sh+++ b/scripts/run-donkey-dev.sh@@ -452,5 +452,6 @@ fiecho "Starting Donkey..."print_dev_overlay_statusecho "Hosted inference auth: dev-bypass=${DONKEY_DEV_AUTH_BYPASS:-0} baseURL=$DONKEY_WEB_BASE_URL"+echo "Vision navigation (typed query -> vision click): hardcoded ON in the app"start_loggeropen -W -n "$DEV_APP_DIR"