Open source CapCut alternative.
TypeScript
Ground local app visualization playback
David Le17b9f8b3b02d
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex 6a0e5aa1..aef89991 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -379,6 +379,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {resolution: resolution,metadata: modelMetadata)+ logActionTraces(for: result)let agentVisualizationPlan = LocalAppTaskAgentVisualizationBuilder.plan(for: result,@@ -544,6 +545,30 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)}+ private func logActionTraces(for result: LocalAppTaskLiveRunResult) {+ guard PointerPromptLog.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"] ?? ""++ PointerPromptLog.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=visualOnly appleScriptAction=\(appleScriptAction, privacy: .public) appleScriptOutput=\(appleScriptOutput, privacy: .public) accessibilityResult=\(accessibilityResult, privacy: .public)"+ )+ }+ }+private func routingHint(for routing: AppHarnessRoutingResult) -> String {let router = routing.outcome.metadata["router"] ?? ""switch router {@@ -572,6 +597,51 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {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 .projectedDryRun:+ return "projectedDryRun"+ 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.intent == nil {diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swiftindex 7f9bcd03..7eef0ca8 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift@@ -47,8 +47,11 @@ final class PointerPromptOverlayController {) {self.model = modelself.activationShortcut = activationShortcut- model.agentVisualizationPresenter = { [weak self] request in- self?.agentVisualizationCursorController.show(request: request)+ model.agentVisualizationPresenter = { [weak self] request, preferredSpawnID in+ self?.presentAgentVisualization(+ request: request,+ preferredSpawnID: preferredSpawnID+ )}spawnOverlayController.followUpSubmitted = { [weak self] spawnID, taskID, text inself?.model.submitSpawnFollowUp(spawnID: spawnID, taskID: taskID, text: text)@@ -624,6 +627,22 @@ final class PointerPromptOverlayController {model.showUpdateUI()}+ private func presentAgentVisualization(+ request: PointerCoachCursorGuideRequest,+ preferredSpawnID: String?+ ) {+ if spawnOverlayController.playGuide(+ request: request,+ on: preferredSpawnID,+ screen: activeScreen()+ ) {+ agentVisualizationCursorController.close()+ return+ }++ agentVisualizationCursorController.show(request: request)+ }+private func updateSpawnOverlay() {let screen = activeScreen()let metrics = notchMetrics(for: screen)diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swiftindex a1ca804b..56d3a4d6 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift@@ -20,7 +20,7 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink@Published private(set) var notchTasks: [PointerPromptNotchTask]@Published private(set) var spawnStates: [PointerPromptSpawnState] = []@Published private(set) var selectedSpawnID: String?- var agentVisualizationPresenter: ((PointerCoachCursorGuideRequest) -> Void)?+ var agentVisualizationPresenter: ((PointerCoachCursorGuideRequest, String?) -> Void)?private let commandHandler: any PointerPromptCommandHandlingprivate let taskStore: any PointerPromptTaskStoring@@ -348,10 +348,15 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkif let documentReviewRequest = result.documentReviewRequest {self.documentReviewController.show(request: documentReviewRequest)}- if let cursorOverlayRequest = result.cursorOverlayRequest {- self.agentVisualizationPresenter?(cursorOverlayRequest)+ let cursorOverlayRequest = result.cursorOverlayRequest+ if let cursorOverlayRequest {+ self.agentVisualizationPresenter?(cursorOverlayRequest, spawnID)}- self.finishSpawn(id: spawnID, result: result)+ self.finishSpawn(+ id: spawnID,+ result: result,+ minimumFadeDelay: cursorOverlayRequest.map(Self.visualizationPlaybackDuration)+ )}}}@@ -480,7 +485,8 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkprivate func finishSpawn(id spawnID: String?,- result: PointerPromptCommandHandlingResult+ result: PointerPromptCommandHandlingResult,+ minimumFadeDelay: TimeInterval? = nil) {guard let spawnID,let index = spawnIndex(id: spawnID) else {@@ -496,12 +502,12 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkspawnStates[index] = spawnState} else {spawnStates[index] = spawnState- scheduleSpawnFade(id: spawnID)+ scheduleSpawnFade(id: spawnID, after: minimumFadeDelay ?? 0.5)}}- private func scheduleSpawnFade(id spawnID: String) {- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in+ private func scheduleSpawnFade(id spawnID: String, after delay: TimeInterval = 0.5) {+ DispatchQueue.main.asyncAfter(deadline: .now() + max(0.5, delay)) { [weak self] inguard let self,let index = self.spawnIndex(id: spawnID) else {return@@ -517,6 +523,14 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink}}+ private static func visualizationPlaybackDuration(+ for request: PointerCoachCursorGuideRequest+ ) -> TimeInterval {+ request.steps.reduce(0.5) { total, step in+ total + max(0.82, step.travelDuration) + step.holdDuration+ }+ }+var notchSpawnCue: PointerPromptSpawnState? {spawnStates.last { $0.phase == .notchCue }}@@ -594,6 +608,9 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink) -> PointerPromptNotchTask {if let matchedTaskID,var task = task(withID: matchedTaskID) {+ if let reservedAccentIndex {+ task.accentIndex = PointerPromptAccentPalette.normalizedIndex(reservedAccentIndex)+ }task.detail = "Running"task.status = .runningtask.updatedAt = Date()@@ -672,7 +689,7 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkisFollowUp: isFollowUp,turnSource: source,spawnProgressChanged: spawnProgressHandler(for: spawnID),- agentVisualizationChanged: agentVisualizationHandler()+ agentVisualizationChanged: agentVisualizationHandler(for: spawnID))}@@ -691,10 +708,12 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink}}- private func agentVisualizationHandler() -> (@MainActor @Sendable (AgentVisualizationPlan) -> Void)? {+ private func agentVisualizationHandler(+ for spawnID: String?+ ) -> (@MainActor @Sendable (AgentVisualizationPlan) -> Void)? {{ [weak self] plan inguard let request = plan.cursorOverlayRequest() else { return }- self?.agentVisualizationPresenter?(request)+ self?.agentVisualizationPresenter?(request, spawnID)}}diff --git a/apps/Donkey/Sources/Donkey/PointerPromptSpawnOverlayController.swift b/apps/Donkey/Sources/Donkey/PointerPromptSpawnOverlayController.swiftindex 76b1533b..7442a6c8 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptSpawnOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptSpawnOverlayController.swift@@ -9,6 +9,7 @@ import SwiftUIfinal class PointerPromptSpawnOverlayController {private var surfacesByID: [String: PointerPromptSpawnSurface] = [:]private var viewModelsByID: [String: PointerPromptSpawnOverlayViewModel] = [:]+ private var pendingGuideRequestsBySpawnID: [String: PointerCoachCursorGuideRequest] = [:]private var windowResolver = MacWindowResolver()private var localOutsideClickMonitor: Any?private var globalOutsideClickMonitor: Any?@@ -39,11 +40,16 @@ final class PointerPromptSpawnOverlayController {let visibleSpawnStates = spawnStates.filter { $0.phase != .notchCue }guard !visibleSpawnStates.isEmpty else {+ if spawnStates.isEmpty {+ pendingGuideRequestsBySpawnID = [:]+ }fadeAndCloseAll()return}+ let allSpawnIDs = Set(spawnStates.map(\.id))let visibleIDs = Set(visibleSpawnStates.map(\.id))+ pendingGuideRequestsBySpawnID = pendingGuideRequestsBySpawnID.filter { allSpawnIDs.contains($0.key) }for spawnState in visibleSpawnStates {updateSurface(for: spawnState,@@ -63,11 +69,39 @@ final class PointerPromptSpawnOverlayController {for surface in surfacesByID.values {surface.travelWorkItem?.cancel()surface.removalWorkItem?.cancel()+ cancelGuide(for: surface)surface.viewModel.fadeOut()surface.panel.close()}surfacesByID = [:]viewModelsByID = [:]+ pendingGuideRequestsBySpawnID = [:]+ }++ @discardableResult+ func playGuide(+ request: PointerCoachCursorGuideRequest,+ on spawnID: String?,+ screen: NSScreen?+ ) -> Bool {+ guard let spawnID,+ !request.steps.isEmpty,+ let screen else {+ return false+ }++ guard let surface = surfacesByID[spawnID] else {+ pendingGuideRequestsBySpawnID[spawnID] = request+ return true+ }++ startGuide(+ request: request,+ on: surface,+ screen: screen,+ startDelay: surface.isTraveling ? PointerPromptSpawnOverlayViewModel.travelDuration + 0.04 : 0+ )+ return true}private func updateSurface(@@ -142,6 +176,11 @@ final class PointerPromptSpawnOverlayController {to: destination,on: screen)+ startPendingGuideIfNeeded(+ for: surface,+ screen: screen,+ startDelay: PointerPromptSpawnOverlayViewModel.travelDuration + 0.04+ )}private func updateExistingSurface(@@ -153,6 +192,25 @@ final class PointerPromptSpawnOverlayController {) {surface.screen = screensurface.viewModel.setSelected(spawnState.id == selectedSpawnID)+ if spawnState.phase == .fading {+ fadeAndRemove(id: spawnState.id)+ return+ }++ if surface.isPlayingGuide {+ updateMouseEventPassthrough(for: surface)+ return+ }+ startPendingGuideIfNeeded(+ for: surface,+ screen: screen,+ startDelay: surface.isTraveling ? PointerPromptSpawnOverlayViewModel.travelDuration + 0.04 : 0+ )+ if surface.isPlayingGuide {+ updateMouseEventPassthrough(for: surface)+ return+ }+let shouldRetarget = !surface.viewModel.freezesMovement &&distance(from: surface.destination, to: destination) > 1@@ -162,11 +220,6 @@ final class PointerPromptSpawnOverlayController {screenSize: screen.frame.size)- if spawnState.phase == .fading {- fadeAndRemove(id: spawnState.id)- return- }-if shouldRetarget {animateSurfaceTravel(surface,@@ -355,6 +408,121 @@ final class PointerPromptSpawnOverlayController {updateMouseEventPassthrough(for: surface)}+ private func startGuide(+ request: PointerCoachCursorGuideRequest,+ on surface: PointerPromptSpawnSurface,+ screen: NSScreen,+ startDelay: TimeInterval+ ) {+ cancelGuide(for: surface)+ surface.isPlayingGuide = true++ var delay = startDelay+ for step in request.steps {+ let workItem = DispatchWorkItem { [weak self, weak surface] in+ Task { @MainActor in+ guard let self,+ let surface else {+ return+ }++ self.applyGuideStep(+ step,+ request: request,+ to: surface,+ screen: screen+ )+ }+ }+ surface.guideWorkItems.append(workItem)+ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: workItem)+ delay += PointerPromptSpawnOverlayViewModel.travelDuration + step.holdDuration+ }++ let completionWorkItem = DispatchWorkItem { [weak self, weak surface] in+ guard let self,+ let surface else {+ return+ }++ surface.isPlayingGuide = false+ surface.guideWorkItems = []+ surface.guideCompletionWorkItem = nil+ self.layoutSurface(surface, on: surface.screen, animated: false)+ }+ surface.guideCompletionWorkItem = completionWorkItem+ DispatchQueue.main.asyncAfter(deadline: .now() + delay + 0.05, execute: completionWorkItem)+ }++ private func applyGuideStep(+ _ step: PointerCoachCursorGuideStep,+ request: PointerCoachCursorGuideRequest,+ to surface: PointerPromptSpawnSurface,+ screen: NSScreen+ ) {+ guard var state = surface.viewModel.state else { return }++ state.label = step.label+ state.phase = .traveling+ state.updatedAt = Date()+ state.targetHint = PointerPromptSpawnTargetHint(+ metadata: [+ "agentVisualization.planID": request.id,+ "agentVisualization.stepID": step.id,+ "agentVisualization.reusedSpawn": "true"+ ]+ )+ let destination = guideDestination(+ for: step,+ on: screen+ )+ surface.screen = screen+ surface.viewModel.update(+ state: state,+ destination: destination,+ screenSize: screen.frame.size+ )+ animateSurfaceTravel(surface, to: destination, on: screen)+ }++ private func guideDestination(+ for step: PointerCoachCursorGuideStep,+ on screen: NSScreen+ ) -> CGPoint {+ AgentVisualizationCursorPathSampler.point(+ step.target,+ metadata: step.metadata,+ screenFrame: screen.frame+ )+ }++ private func cancelGuide(for surface: PointerPromptSpawnSurface) {+ for workItem in surface.guideWorkItems {+ workItem.cancel()+ }+ surface.guideWorkItems = []+ surface.guideCompletionWorkItem?.cancel()+ surface.guideCompletionWorkItem = nil+ surface.isPlayingGuide = false+ }++ private func startPendingGuideIfNeeded(+ for surface: PointerPromptSpawnSurface,+ screen: NSScreen,+ startDelay: TimeInterval+ ) {+ guard let request = pendingGuideRequestsBySpawnID.removeValue(forKey: surface.id) else {+ return+ }++ startGuide(+ request: request,+ on: surface,+ screen: screen,+ startDelay: startDelay+ )+ }+private func layoutSurface(_ surface: PointerPromptSpawnSurface,on screen: NSScreen,@@ -445,6 +613,8 @@ final class PointerPromptSpawnOverlayController {surface.travelWorkItem?.cancel()surface.removalWorkItem?.cancel()+ pendingGuideRequestsBySpawnID[spawnID] = nil+ cancelGuide(for: surface)surface.viewModel.fadeOut()let workItem = DispatchWorkItem { [weak self, weak surface] inguard let self,@@ -653,6 +823,9 @@ private final class PointerPromptSpawnSurface {var isTraveling = falsevar travelWorkItem: DispatchWorkItem?var removalWorkItem: DispatchWorkItem?+ var isPlayingGuide = false+ var guideWorkItems: [DispatchWorkItem] = []+ var guideCompletionWorkItem: DispatchWorkItem?init(id: String,diff --git a/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swiftindex 2d65487b..ab07c7f8 100644--- a/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift@@ -870,18 +870,31 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {let definitions = (try? JSONEncoder().encode(request.taskDefinitions)).flatMap { String(data: $0, encoding: .utf8) } ?? "[]"return [- "command: \(request.command)",- "context: \(request.contextSnippets.joined(separator: " | "))",- "taskDefinitions: \(definitions)"+ "Command: \(request.command)",+ "Relevant local cache:",+ request.contextSnippets.joined(separator: "\n"),+ "Supported task definitions JSON:",+ definitions].joined(separator: "\n")}private static let instructions = ["Decide whether the user is asking Donkey to run one of the provided local app task definitions.","Return strict JSON only.",- "If the command is conversation, a question, or does not match a supported task definition, return taskType \"none\", targetAppName \"none\", empty entities, confidence 0, needsConfirmation false, an empty actionPlan, and metadata.responseMode \"conversation\".",- "For supported actions, choose only a provided taskType and target app. Fill normalizedEntities with the concrete values needed by required entity rules.",- "Model-planned actions may use only the enum tools allowed by the schema. Do not invent app scripts or direct input outside the schema."+ "First decide whether Command is an executable local-app task or a conversation turn.",+ "Executable local-app task means all three are clear: action, destination or target app/item, and enough payload to execute safely.",+ "If Command is conversation, a question, malformed, or lacks a real executable payload, return taskType \"none\", targetAppName \"none\", empty entities, confidence 0, needsConfirmation false, an empty actionPlan, and metadata.responseMode \"conversation\".",+ "For supported actions, choose only a provided taskType and target app. Fill entities and normalizedEntities with the concrete values needed by required entity rules.",+ "Use the generic local_app_interaction task type for executable local app requests that need a model-planned app workflow and do not have a more specific provided task type.",+ "For local_app_interaction, select the most likely local app, set targetAppName and entities.appName to the human app name, set entities.goal, and when text must be entered set entities.query plus normalizedEntities.query.",+ "For local_app_interaction, fill actionPlan.tools with allowed tools only: app.openOrFocus, app.observe, ui.newDocument, ui.focusSearch, ui.focusAddressBar, ui.focusTextEntry, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",+ "When ui.setText is present, entities.query and normalizedEntities.query must be non-empty, actionPlan.inputEntity should usually be query, and actionPlan.controlID/focusKey should describe the guarded UI strategy.",+ "For media playback, targetAppName=Music, entities.appName=Music, entities.goal=play media, entities.query=<artist/song/album to play>, and actionPlan.tools=[app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyCommand] with inputEntity=query, controlID=search, focusKey=Command+F.",+ "For website navigation, choose Safari or the user's browser, set query to the URL, and use ui.focusAddressBar, ui.setText, ui.pressReturn, app.verifyCommand.",+ "For writing in Notes, choose Notes, make query the complete text to type, and use ui.newDocument, ui.setText, app.verifyCommand.",+ "For spreadsheet or table creation, choose Numbers, put compact tab-separated table content in query, and use ui.newDocument, ui.setText, app.verifyCommand.",+ "For every other task type, actionPlan.tools must be empty.",+ "Do not invent task types, unsupported entities, unsupported tools, app scripts, or direct input outside the schema."].joined(separator: " ")private static func outputDiagnostics(for outputText: String) -> [String: String] {diff --git a/apps/Donkey/Sources/DonkeyContracts/AgentVisualizationContracts.swift b/apps/Donkey/Sources/DonkeyContracts/AgentVisualizationContracts.swiftindex ed888b05..2f138c9f 100644--- a/apps/Donkey/Sources/DonkeyContracts/AgentVisualizationContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/AgentVisualizationContracts.swift@@ -148,13 +148,16 @@ public struct AgentVisualizationPlan: Codable, Equatable, Sendable, Identifiable}public func cursorOverlayRequest() -> PointerCoachCursorGuideRequest? {+ guard metadata["cursorGuideEligible"] != "false" else { return nil }+let cursorSteps = steps.prefix(8).enumerated().map { index, step inPointerCoachCursorGuideStep(id: step.id,label: step.label,target: cursorPoint(for: step, index: index),travelDuration: step.travelDuration,- holdDuration: step.holdDuration+ holdDuration: step.holdDuration,+ metadata: cursorStepMetadata(for: step))}guard !cursorSteps.isEmpty else { return nil }@@ -194,6 +197,23 @@ public struct AgentVisualizationPlan: Codable, Equatable, Sendable, Identifiablereturn Self.fallbackPoint(index: index)}+ private func cursorStepMetadata(for step: AgentVisualizationStep) -> [String: String] {+ var metadata = step.metadata+ if let targetMetadata = step.target?.metadata {+ metadata.merge(targetMetadata) { current, _ in current }+ }+ if metadata["control.bounds.space"] == HotLoopCoordinateSpace.normalizedTarget.rawValue,+ metadata["target.bounds.x"] != nil,+ metadata["target.bounds.y"] != nil,+ metadata["target.bounds.width"] != nil,+ metadata["target.bounds.height"] != nil {+ metadata["cursor.targetSpace"] = "targetWindowNormalized"+ } else {+ metadata["cursor.targetSpace"] = "screenNormalized"+ }+ return metadata+ }+private static func fallbackPoint(index: Int) -> CGPoint {let lane = Double(index % 4)let row = Double(index / 4)diff --git a/apps/Donkey/Sources/DonkeyContracts/AgentVisualizationCursorPathSampler.swift b/apps/Donkey/Sources/DonkeyContracts/AgentVisualizationCursorPathSampler.swiftindex cbbcf652..89f78461 100644--- a/apps/Donkey/Sources/DonkeyContracts/AgentVisualizationCursorPathSampler.swift+++ b/apps/Donkey/Sources/DonkeyContracts/AgentVisualizationCursorPathSampler.swift@@ -60,6 +60,7 @@ public enum AgentVisualizationCursorPathSampler {elapsed: TimeInterval,screenSize: CGSize) -> AgentVisualizationCursorPathSample {+ let screenFrame = CGRect(origin: .zero, size: screenSize)guard !request.steps.isEmpty else {return AgentVisualizationCursorPathSample(position: point(request.origin, in: screenSize),@@ -73,7 +74,7 @@ public enum AgentVisualizationCursorPathSampler {var remaining = elapsedvar origin = point(request.origin, in: screenSize)for (index, step) in request.steps.enumerated() {- let target = point(step.target, in: screenSize)+ let target = point(step.target, metadata: step.metadata, screenFrame: screenFrame)if remaining <= step.travelDuration {let linearProgress = min(max(remaining / step.travelDuration, 0), 1)let easedProgress = eased(linearProgress)@@ -93,19 +94,18 @@ public enum AgentVisualizationCursorPathSampler {remaining -= step.travelDurationif remaining <= step.holdDuration {- let typeProgress = min(1, remaining / min(step.holdDuration, max(0.6, Double(step.label.count) * 0.035)))let wobble = sin(remaining * 8) * 1.8return AgentVisualizationCursorPathSample(position: CGPoint(x: target.x + wobble, y: target.y),angle: angle(from: origin, to: target),- visibleLabel: typedText(step.label, progress: typeProgress),+ visibleLabel: step.label,isHolding: true,phase: .hold,stepIndex: index,stepID: step.id,elapsedInPhase: max(0, remaining),- linearProgress: typeProgress,- easedProgress: typeProgress,+ linearProgress: min(1, remaining / step.holdDuration),+ easedProgress: min(1, remaining / step.holdDuration),haloScale: 1 + 0.14 * sin(remaining * 3.2),haloOpacity: 0.24 + 0.18 * cos(remaining * 3.2),labelOpacity: min(1, remaining / 0.18)@@ -118,7 +118,7 @@ public enum AgentVisualizationCursorPathSampler {let finalStep = request.steps[request.steps.count - 1]return AgentVisualizationCursorPathSample(- position: point(finalStep.target, in: screenSize),+ position: point(finalStep.target, metadata: finalStep.metadata, screenFrame: screenFrame),angle: 0,visibleLabel: finalStep.label,isHolding: true,@@ -139,6 +139,27 @@ public enum AgentVisualizationCursorPathSampler {)}+ public static func point(+ _ normalizedPoint: CGPoint,+ metadata: [String: String],+ screenFrame: CGRect+ ) -> CGPoint {+ guard metadata["cursor.targetSpace"] == "targetWindowNormalized",+ let bounds = targetBounds(from: metadata)+ else {+ return point(normalizedPoint, in: screenFrame.size)+ }++ let localPoint = CGPoint(+ x: CGFloat(bounds.x + Double(normalizedPoint.x) * bounds.width) - screenFrame.minX,+ y: CGFloat(bounds.y + Double(normalizedPoint.y) * bounds.height)+ )+ return CGPoint(+ x: min(max(localPoint.x, 0), max(1, screenFrame.size.width)),+ y: min(max(localPoint.y, 0), max(1, screenFrame.size.height))+ )+ }+public static func curvedPoint(from origin: CGPoint,to target: CGPoint,@@ -169,11 +190,20 @@ public enum AgentVisualizationCursorPathSampler {return 1 - pow(1 - t, 3)}- private static func typedText(_ text: String, progress: Double) -> String {- guard progress < 1 else { return text }-- let count = max(1, Int(Double(text.count) * progress))- let endIndex = text.index(text.startIndex, offsetBy: min(count, text.count))- return String(text[..<endIndex])+ private static func targetBounds(from metadata: [String: String]) -> WindowTargetBounds? {+ guard let x = Double(metadata["target.bounds.x"] ?? ""),+ let y = Double(metadata["target.bounds.y"] ?? ""),+ let width = Double(metadata["target.bounds.width"] ?? ""),+ let height = Double(metadata["target.bounds.height"] ?? "")+ else {+ return nil+ }+ let bounds = WindowTargetBounds(+ x: x,+ y: y,+ width: width,+ height: height+ )+ return bounds.hasPositiveArea ? bounds : nil}}diff --git a/apps/Donkey/Sources/DonkeyContracts/PointerPromptContracts.swift b/apps/Donkey/Sources/DonkeyContracts/PointerPromptContracts.swiftindex 40f0dd9e..b61a07b1 100644--- a/apps/Donkey/Sources/DonkeyContracts/PointerPromptContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/PointerPromptContracts.swift@@ -282,18 +282,21 @@ public struct PointerCoachCursorGuideStep: Equatable, Sendable, Identifiable {public var target: CGPointpublic var travelDuration: TimeIntervalpublic var holdDuration: TimeInterval+ public var metadata: [String: String]public init(id: String = UUID().uuidString,label: String,target: CGPoint,travelDuration: TimeInterval = 0.9,- holdDuration: TimeInterval = 1.8+ holdDuration: TimeInterval = 1.8,+ metadata: [String: String] = [:]) {self.id = idself.label = labelself.target = targetself.travelDuration = max(0.1, travelDuration)self.holdDuration = max(0.4, holdDuration)+ self.metadata = metadata}}diff --git a/apps/Donkey/Sources/DonkeyRuntime/AgentVisualizationRuntime.swift b/apps/Donkey/Sources/DonkeyRuntime/AgentVisualizationRuntime.swiftindex d8581368..3b455a97 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AgentVisualizationRuntime.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AgentVisualizationRuntime.swift@@ -31,6 +31,7 @@ public enum LocalAppTaskAgentVisualizationBuilder {"taskType": definition.taskType,"resolution.status": resolution.status.rawValue,"realPointerMoved": "false",+ "cursorGuideEligible": "false","grounding.source": AgentVisualizationGroundingSource.dryRun.rawValue,"workflowStage": "preExecution"].merging(resolution.metadata) { current, _ in current }@@ -68,11 +69,15 @@ public enum LocalAppTaskAgentVisualizationBuilder {guard let definition = result.resolution.definition else { return nil }let evidencePlan = result.finalPlan ?? result.initialPlan+ let initialStepsByID = Dictionary(+ uniqueKeysWithValues: (result.initialPlan?.steps ?? []).map { ($0.id, $0) }+ )var steps = (evidencePlan?.steps ?? []).enumerated().map { index, dryRunStep invisualizationStep(from: dryRunStep,index: index,definition: definition,+ fallbackStep: initialStepsByID[dryRunStep.id],actionTrace: matchingTrace(for: dryRunStep, in: result.actionTraces))}@@ -96,6 +101,12 @@ public enum LocalAppTaskAgentVisualizationBuilder {guard !steps.isEmpty else { return nil }let verification = verificationReport(for: result)+ let controllerAutomationOnly = !result.actionTraces.isEmpty &&+ result.actionTraces.allSatisfy { $0.command.kind == .controller }+ let hasGroundedElementTargets = steps.contains { step in+ step.target?.metadata["control.bounds.space"] == HotLoopCoordinateSpace.normalizedTarget.rawValue+ }+ let cursorGuideEligible = controllerAutomationOnly == false || hasGroundedElementTargetsreturn AgentVisualizationPlan(id: "agent-visualization-\(result.traceID)",title: title(for: result, definition: definition),@@ -108,6 +119,8 @@ public enum LocalAppTaskAgentVisualizationBuilder {"targetApp": definition.targetApp.appName,"taskType": definition.taskType,"realPointerMoved": "false",+ "cursorGuideEligible": String(cursorGuideEligible),+ "cursorGuide.reason": cursorGuideEligible ? "" : "controllerAutomationNoElementTargets","actionTraceCount": String(result.actionTraces.count),"workflowStageCount": String(result.workflowProgress.stages.count)].merging(result.metadata.filter { key, _ in@@ -150,6 +163,7 @@ public enum LocalAppTaskAgentVisualizationBuilder {from step: LocalAppTaskDryRunStep,index: Int,definition: LocalAppTaskDefinition,+ fallbackStep: LocalAppTaskDryRunStep?,actionTrace: ActionEngineCommandTrace?) -> AgentVisualizationStep {var metadata = step.metadata.merging([@@ -162,17 +176,31 @@ public enum LocalAppTaskAgentVisualizationBuilder {if let actionTrace {metadata.merge(actionTraceMetadata(actionTrace)) { current, _ in current }}+ if LocalAppObservationGeometry.normalizedStepBounds(metadata: metadata) == nil,+ let fallbackStep {+ metadata.merge(fallbackStep.metadata.filter { key, _ in+ key.hasPrefix("control.")+ }) { current, _ in current }+ }+ let groundedBounds = LocalAppObservationGeometry.normalizedStepBounds(metadata: metadata)+ let groundedPoint = centerPoint(for: groundedBounds)+ let actionTracePoint = centerPoint(for: actionTrace?.command.targetBounds)+ let targetSource = groundingSource(+ metadata["control.source"],+ fallback: actionTrace == nil ? .dryRun : .actionTrace+ )return AgentVisualizationStep(id: step.id,kind: kind(for: step.role),label: label(for: step),target: AgentVisualizationStepTarget(- point: targetPoint(for: step.role, index: index),+ point: groundedPoint ?? actionTracePoint ?? targetPoint(for: step.role, index: index),+ bounds: groundedBounds ?? normalizedBounds(actionTrace?.command.targetBounds),description: step.summary,controlID: step.metadata["controlID"],- source: actionTrace == nil ? .dryRun : .actionTrace,- confidence: confidence(for: step.status, actionTrace: actionTrace),+ source: groundedBounds == nil ? (actionTrace == nil ? .dryRun : .actionTrace) : targetSource,+ confidence: groundedBounds == nil ? confidence(for: step.status, actionTrace: actionTrace) : 0.9,metadata: metadata),travelDuration: duration(for: step.role).travel,@@ -391,6 +419,27 @@ public enum LocalAppTaskAgentVisualizationBuilder {)}+ private static func normalizedBounds(_ rect: HotLoopRect?) -> HotLoopRect? {+ guard let rect,+ rect.space == .normalizedTarget,+ rect.hasPositiveArea else {+ return nil+ }+ return rect+ }++ private static func groundingSource(+ _ value: String?,+ fallback: AgentVisualizationGroundingSource+ ) -> AgentVisualizationGroundingSource {+ guard let value,+ let source = AgentVisualizationGroundingSource(rawValue: value)+ else {+ return fallback+ }+ return source+ }+private static func point(_ x: Double, _ y: Double) -> HotLoopPoint {HotLoopPoint(x: min(max(x, 0.04), 0.96), y: min(max(y, 0.06), 0.94), space: .normalizedTarget)}@@ -461,6 +510,11 @@ public struct AgentVisualizationGrounder: Sendable {"target.windowID": String(target.windowID),"target.appName": target.appName ?? "","target.bundleIdentifier": target.bundleIdentifier ?? "",+ "target.bounds.x": String(target.bounds.x),+ "target.bounds.y": String(target.bounds.y),+ "target.bounds.width": String(target.bounds.width),+ "target.bounds.height": String(target.bounds.height),+ "target.bounds.space": HotLoopCoordinateSpace.screen.rawValue,"grounding.source": AgentVisualizationGroundingSource.windowMetadata.rawValue]if var stepTarget = copy.target {@@ -480,6 +534,11 @@ public struct AgentVisualizationGrounder: Sendable {}grounded.metadata["grounding.source"] = AgentVisualizationGroundingSource.windowMetadata.rawValuegrounded.metadata["grounding.targetWindowID"] = String(target.windowID)+ grounded.metadata["target.bounds.x"] = String(target.bounds.x)+ grounded.metadata["target.bounds.y"] = String(target.bounds.y)+ grounded.metadata["target.bounds.width"] = String(target.bounds.width)+ grounded.metadata["target.bounds.height"] = String(target.bounds.height)+ grounded.metadata["target.bounds.space"] = HotLoopCoordinateSpace.screen.rawValuereturn grounded}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swiftindex 849a020d..a49b9ec6 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift@@ -96,9 +96,13 @@ public struct LocalAppAccessibilityControlDiscovery: Sendable {"observer": "local-app-accessibility-control-discovery","target.windowID": String(snapshot.target.windowID),"target.processID": String(snapshot.target.processID),+ "target.appName": snapshot.target.appName ?? "",+ "target.bundleIdentifier": snapshot.target.bundleIdentifier ?? "","controlCount": String(controls.count),"treeTruncated": String(snapshot.isTreeTruncated)- ]+ ].merging(+ LocalAppObservationGeometry.targetBoundsMetadata(snapshot.target.bounds)+ ) { current, _ in current })}@@ -249,7 +253,31 @@ public struct LocalAppAccessibilityActionPlanner: Sendable {])case .submit:- return nil+ guard let controlID = step.metadata["controlID"],+ let control = index.firstControl(+ matching: controlID,+ acceptedKinds: [.button, .menuItem, .checkbox]+ )+ else {+ return nil+ }+ return command(+ id: "\(intent.intentID)-ax-\(step.id)",+ traceID: intent.metadata["traceID"] ?? intent.intentID,+ targetID: adapter.targetID,+ issuedAt: issuedAt,+ kind: .tap,+ control: control,+ definition: definition,+ step: step,+ metadata: [+ "accessibility.action": "AXPress",+ "accessibility.nodeID": control.id,+ "controlID": controlID,+ "inputStrategy": "accessibility",+ "inputIntent": "submit"+ ]+ )case .parseIntent, .launchOrFocusApp, .observeApp, .verifyResult, .custom:return nil}@@ -448,6 +476,9 @@ public struct MacAccessibilityActionEngineInputBackend: ActionEngineInputBackendcompletedAt: command.issuedAt,metadata: ["liveInputBackend": "mac-accessibility",+ "inputMode": "accessibilityElement",+ "elementClick": String(command.kind == .tap),+ "controlID": command.metadata["controlID"] ?? "","accessibility.result": reason])diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppObservationGeometry.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppObservationGeometry.swiftnew file mode 100644index 00000000..235ed588--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppObservationGeometry.swift@@ -0,0 +1,213 @@+import DonkeyContracts+import Foundation++enum LocalAppObservationGeometry {+ static func targetBoundsMetadata(_ bounds: WindowTargetBounds) -> [String: String] {+ [+ "target.bounds.x": String(bounds.x),+ "target.bounds.y": String(bounds.y),+ "target.bounds.width": String(bounds.width),+ "target.bounds.height": String(bounds.height),+ "target.bounds.space": HotLoopCoordinateSpace.screen.rawValue+ ]+ }++ static func cropBoundsMetadata(_ bounds: HotLoopRect) -> [String: String] {+ [+ "crop.bounds.x": String(bounds.origin.x),+ "crop.bounds.y": String(bounds.origin.y),+ "crop.bounds.width": String(bounds.size.width),+ "crop.bounds.height": String(bounds.size.height),+ "crop.bounds.space": bounds.space.rawValue+ ]+ }++ static func pixelSizeMetadata(_ size: HotLoopSize) -> [String: String] {+ [+ "pixelSize.width": String(size.width),+ "pixelSize.height": String(size.height),+ "pixelSize.space": size.space.rawValue+ ]+ }++ static func controlMetadata(+ controlID: String,+ frame: HotLoopRect?,+ source: AgentVisualizationGroundingSource,+ label: String? = nil,+ kind: LocalAppControlKind? = nil,+ confidence: Double? = nil,+ extra: [String: String] = [:]+ ) -> [String: String] {+ let prefix = controlPrefix(controlID)+ var metadata: [String: String] = [:]+ for (key, value) in extra {+ metadata["\(prefix)metadata.\(key)"] = value+ }+ metadata["\(prefix)source"] = source.rawValue+ if let label {+ metadata["\(prefix)label"] = label+ }+ if let kind {+ metadata["\(prefix)kind"] = kind.rawValue+ }+ if let confidence {+ metadata["\(prefix)confidence"] = String(confidence)+ }+ if let frame {+ metadata["\(prefix)bounds.x"] = String(frame.origin.x)+ metadata["\(prefix)bounds.y"] = String(frame.origin.y)+ metadata["\(prefix)bounds.width"] = String(frame.size.width)+ metadata["\(prefix)bounds.height"] = String(frame.size.height)+ metadata["\(prefix)bounds.space"] = frame.space.rawValue+ }+ return metadata+ }++ static func groundedMetadata(+ controlID: String?,+ observation: LocalAppTaskObservation?+ ) -> [String: String] {+ guard let controlID,+ let observation+ else {+ return [:]+ }++ let prefix = controlPrefix(controlID)+ var metadata: [String: String] = [:]+ if let normalizedBounds = normalizedControlBounds(controlID: controlID, metadata: observation.metadata) {+ metadata["control.bounds.x"] = String(normalizedBounds.origin.x)+ metadata["control.bounds.y"] = String(normalizedBounds.origin.y)+ metadata["control.bounds.width"] = String(normalizedBounds.size.width)+ metadata["control.bounds.height"] = String(normalizedBounds.size.height)+ metadata["control.bounds.space"] = normalizedBounds.space.rawValue+ }++ for suffix in ["source", "label", "kind", "confidence"] {+ if let value = observation.metadata["\(prefix)\(suffix)"] {+ metadata["control.\(suffix)"] = value+ }+ }+ for prefix in ["target.bounds.", "crop.bounds."] {+ for suffix in ["x", "y", "width", "height", "space"] {+ if let value = observation.metadata["\(prefix)\(suffix)"] {+ metadata["\(prefix)\(suffix)"] = value+ }+ }+ }+ return metadata+ }++ static func hasNormalizedControlBounds(+ controlID: String,+ metadata: [String: String]+ ) -> Bool {+ normalizedControlBounds(controlID: controlID, metadata: metadata) != nil+ }++ static func normalizedStepBounds(metadata: [String: String]) -> HotLoopRect? {+ metadataRect(prefix: "control.bounds.", metadata: metadata).flatMap { rect in+ normalizedBounds(rect, metadata: metadata)+ }+ }++ private static func normalizedControlBounds(+ controlID: String,+ metadata: [String: String]+ ) -> HotLoopRect? {+ metadataRect(prefix: "\(controlPrefix(controlID))bounds.", metadata: metadata).flatMap { rect in+ normalizedBounds(rect, metadata: metadata)+ }+ }++ private static func normalizedBounds(+ _ rect: HotLoopRect,+ metadata: [String: String]+ ) -> HotLoopRect? {+ guard rect.hasPositiveArea else { return nil }+ if rect.space == .normalizedTarget {+ return clamped(rect)+ }++ if rect.space == .screen,+ let targetBounds = metadataRect(prefix: "target.bounds.", metadata: metadata) {+ let mapper = HotLoopCoordinateMapper(+ windowBoundsInScreen: targetBounds,+ cropBoundsInWindow: HotLoopRect(+ x: 0,+ y: 0,+ width: targetBounds.size.width,+ height: targetBounds.size.height,+ space: .window+ )+ )+ return mapper.convert(rect, to: HotLoopCoordinateSpace.normalizedTarget).map { clamped($0) }+ }++ guard let mapper = coordinateMapper(metadata: metadata),+ let normalized = mapper.convert(rect, to: .normalizedTarget)+ else {+ return nil+ }+ return clamped(normalized)+ }++ private static func coordinateMapper(metadata: [String: String]) -> HotLoopCoordinateMapper? {+ let targetBounds = metadataRect(prefix: "target.bounds.", metadata: metadata)+ let cropBounds = metadataRect(prefix: "crop.bounds.", metadata: metadata)++ if let targetBounds {+ return HotLoopCoordinateMapper(+ windowBoundsInScreen: targetBounds,+ cropBoundsInWindow: cropBounds ?? HotLoopRect(+ x: 0,+ y: 0,+ width: targetBounds.size.width,+ height: targetBounds.size.height,+ space: .window+ )+ )+ }++ guard let cropBounds else { return nil }+ return HotLoopCoordinateMapper(+ windowBoundsInScreen: HotLoopRect(+ x: 0,+ y: 0,+ width: cropBounds.size.width,+ height: cropBounds.size.height,+ space: .screen+ ),+ cropBoundsInWindow: cropBounds+ )+ }++ private static func metadataRect(prefix: String, metadata: [String: String]) -> HotLoopRect? {+ guard let x = Double(metadata["\(prefix)x"] ?? ""),+ let y = Double(metadata["\(prefix)y"] ?? ""),+ let width = Double(metadata["\(prefix)width"] ?? ""),+ let height = Double(metadata["\(prefix)height"] ?? ""),+ let spaceValue = metadata["\(prefix)space"],+ let space = HotLoopCoordinateSpace(rawValue: spaceValue)+ else {+ return nil+ }+ let rect = HotLoopRect(x: x, y: y, width: width, height: height, space: space)+ return rect.hasPositiveArea ? rect : nil+ }++ private static func clamped(_ rect: HotLoopRect) -> HotLoopRect {+ HotLoopRect(+ x: min(max(rect.origin.x, 0), 1),+ y: min(max(rect.origin.y, 0), 1),+ width: min(max(rect.size.width, 0.01), 1),+ height: min(max(rect.size.height, 0.01), 1),+ space: .normalizedTarget+ )+ }++ private static func controlPrefix(_ controlID: String) -> String {+ "control.\(controlID)."+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swiftindex 93e17ce8..b0168a31 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift@@ -224,13 +224,24 @@ public struct LocalAppTaskAdapter: Sendable {]}+ var activeControlID: String?return definition.workflowSteps.map { step in- LocalAppTaskDryRunStep(+ let controlID = step.metadata["controlID"] ?? activeControlID+ if let stepControlID = step.metadata["controlID"] {+ activeControlID = stepControlID+ }+ return LocalAppTaskDryRunStep(id: step.id,role: step.role,status: status(for: step, observation: observation, verificationStatus: verification.status),summary: summary(for: step, observation: observation, verificationSummary: verification.summary),- metadata: metadata(for: step, intent: intent, verificationMetadata: verification.metadata)+ metadata: metadata(+ for: step,+ intent: intent,+ verificationMetadata: verification.metadata,+ observation: observation,+ inheritedControlID: controlID+ ))}}@@ -279,12 +290,26 @@ public struct LocalAppTaskAdapter: Sendable {private func metadata(for step: LocalAppTaskWorkflowStepDefinition,intent: TaskIntent,- verificationMetadata: [String: String]+ verificationMetadata: [String: String],+ observation: LocalAppTaskObservation?,+ inheritedControlID: String?) -> [String: String] {var metadata = step.metadata.merging(["taskIntentID": intent.intentID,"taskType": intent.taskType]) { current, _ in current }+ let controlID = step.metadata["controlID"] ?? inheritedControlID+ if let controlID,+ metadata["controlID"] == nil,+ [.enterText, .submit].contains(step.role) {+ metadata["controlID"] = controlID+ }+ metadata.merge(+ LocalAppObservationGeometry.groundedMetadata(+ controlID: controlID,+ observation: observation+ )+ ) { current, _ in current }for (name, value) in intent.normalizedEntities {metadata["normalizedEntity.\(name)"] = valuediff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swiftindex 2dbe5ff1..40bed0b5 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift@@ -529,6 +529,9 @@ public struct LocalAppTaskLiveRunner: Sendable {"latency.keyboardActionMS": Self.formatLatency(keyboardActionMS),"latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)], uniquingKeysWith: { current, _ in current }).merging(+ Self.actionTraceMetadata(actionTraces),+ uniquingKeysWith: { current, _ in current }+ ).merging(Self.workflowProgressMetadata(progress),uniquingKeysWith: { current, _ in current })@@ -536,6 +539,7 @@ public struct LocalAppTaskLiveRunner: Sendable {}}runMetadata["latency.keyboardActionMS"] = Self.formatLatency(keyboardActionMS)+ runMetadata.merge(Self.actionTraceMetadata(actionTraces)) { current, _ in current }if usesAutomationBackend {runMetadata["automation.backend"] = automationCommands.first?.metadata["automationBackend"] ?? ""runMetadata["automation.action"] = automationCommands.first?.metadata["appleScript.action"] ?? ""@@ -809,6 +813,69 @@ public struct LocalAppTaskLiveRunner: Sendable {})}++ private static func actionTraceMetadata(_ traces: [ActionEngineCommandTrace]) -> [String: String] {+ guard !traces.isEmpty else { return [:] }++ let lastTrace = traces[traces.count - 1]+ let backends = Set(traces.compactMap { trace in+ trace.metadata["liveInputBackend"]+ }).sorted()+ let elementClickCount = traces.filter { trace in+ isElementClick(trace.command)+ }.count+ let targetedElementCount = traces.filter { trace in+ trace.command.targetBounds != nil || trace.command.metadata["controlID"]?.isEmpty == false+ }.count++ return [+ "action.traceCount": String(traces.count),+ "action.executedCount": String(traces.filter(\.executed).count),+ "action.backends": backends.joined(separator: ","),+ "action.elementClickCount": String(elementClickCount),+ "action.targetedElementCount": String(targetedElementCount),+ "action.lastCommandID": lastTrace.command.id,+ "action.lastCommandKind": lastTrace.command.kind.rawValue,+ "action.lastDecision": decisionDescription(lastTrace.decision),+ "action.lastBackend": lastTrace.metadata["liveInputBackend"] ?? "",+ "action.lastTarget": actionTargetDescription(lastTrace.command),+ "action.lastAppleScriptOutput": lastTrace.metadata["appleScript.output"] ?? "",+ "action.lastAccessibilityResult": lastTrace.metadata["accessibility.result"] ?? "",+ "action.overlayPointer": "visualOnly"+ ]+ }++ private static func isElementClick(_ command: ActionEngineCommand) -> Bool {+ (command.kind == .tap || command.kind == .mouse) &&+ (command.targetBounds != nil || command.metadata["controlID"]?.isEmpty == false)+ }++ private static func actionTargetDescription(_ 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 static func decisionDescription(_ decision: ActionEngineCommandDecision) -> String {+ switch decision {+ case .projectedDryRun:+ return "projectedDryRun"+ case .executedLive:+ return "executedLive"+ case .denied(let reason):+ return "denied:\(reason)"+ }+ }}public struct MacLocalAppFocusGuard: ActionEngineFocusGuard {@@ -915,18 +982,47 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {textValues[verificationKey] = visibleText}+ var accessibilityMetadata = [+ "observer": "mac-local-app-controller",+ "accessibilityTrusted": String(AXIsProcessTrusted()),+ "accessibilityControlDiscovery": String(accessibilityIndex != nil),+ "accessibilityControlCount": accessibilityIndex?.metadata["controlCount"] ?? "0"+ ].merging(accessibilityIndex?.metadata ?? [:]) { current, _ in current }+ for step in definition.workflowSteps {+ guard let controlID = step.metadata["controlID"],+ let control = accessibilityIndex?.firstControl(matching: controlID)+ else {+ continue+ }+ let frame = control.frame.map {+ HotLoopRect(+ x: $0.x,+ y: $0.y,+ width: $0.width,+ height: $0.height,+ space: .screen+ )+ }+ accessibilityMetadata.merge(+ LocalAppObservationGeometry.controlMetadata(+ controlID: controlID,+ frame: frame,+ source: .accessibility,+ label: control.label,+ kind: control.kind,+ confidence: 0.86,+ extra: control.metadata+ )+ ) { current, _ in current }+ }+let accessibilityObservation = LocalAppTaskObservation(appIsRunning: runningApplication != nil,appIsFocused: isFocused,availableControls: controls,visibleText: textValues,confidence: accessibilityIndex == nil ? (visibleText == nil ? 0.4 : 0.75) : 0.86,- metadata: [- "observer": "mac-local-app-controller",- "accessibilityTrusted": String(AXIsProcessTrusted()),- "accessibilityControlDiscovery": String(accessibilityIndex != nil),- "accessibilityControlCount": accessibilityIndex?.metadata["controlCount"] ?? "0"- ]+ metadata: accessibilityMetadata)guard shouldIncludeScreenshotUnderstanding(@@ -1039,7 +1135,7 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {"verificationTextKey": verificationKey,"target.windowID": String(target.windowID),"capture.method": screenshot.captureMethod.rawValue- ]+ ].merging(LocalAppObservationGeometry.targetBoundsMetadata(target.bounds)) { current, _ in current })do {diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskObservationFallbackPolicy.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskObservationFallbackPolicy.swiftindex 1fe9bb3f..e19e57a2 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskObservationFallbackPolicy.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskObservationFallbackPolicy.swift@@ -19,7 +19,7 @@ public enum LocalAppTaskObservationFallbackPolicy {case .missingVerificationText:return accessibilityObservation.visibleText[verificationKey]?.isEmpty != falsecase .missingControls:- return missingRequiredControls(+ return missingRequiredControlsOrBounds(definition: definition,accessibilityObservation: accessibilityObservation)@@ -27,14 +27,16 @@ public enum LocalAppTaskObservationFallbackPolicy {break}- if accessibilityObservation.visibleText[verificationKey]?.isEmpty == false {+ let missingControlsOrBounds = missingRequiredControlsOrBounds(+ definition: definition,+ accessibilityObservation: accessibilityObservation+ )+ if accessibilityObservation.visibleText[verificationKey]?.isEmpty == false,+ missingControlsOrBounds == false {return false}- return missingRequiredControls(- definition: definition,- accessibilityObservation: accessibilityObservation- ) || accessibilityObservation.visibleText.isEmpty+ return missingControlsOrBounds || accessibilityObservation.visibleText.isEmpty}static func screenshotFallbackMode(@@ -54,7 +56,7 @@ public enum LocalAppTaskObservationFallbackPolicy {}}- private static func missingRequiredControls(+ private static func missingRequiredControlsOrBounds(definition: LocalAppTaskDefinition,accessibilityObservation: LocalAppTaskObservation) -> Bool {@@ -65,7 +67,13 @@ public enum LocalAppTaskObservationFallbackPolicy {return false}- return accessibilityObservation.availableControls[controlID] != true+ if accessibilityObservation.availableControls[controlID] != true {+ return true+ }+ return LocalAppObservationGeometry.hasNormalizedControlBounds(+ controlID: controlID,+ metadata: accessibilityObservation.metadata+ ) == false}}}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swiftindex 159d76ba..824963e7 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift@@ -87,22 +87,55 @@ public struct LocalUIUnderstandingResult: Codable, Equatable, Sendable {}public func observation(for request: LocalUIUnderstandingRequest) -> LocalAppTaskObservation {- LocalAppTaskObservation(+ var observationMetadata = request.metadata.merging(metadata) { _, new in new }+ observationMetadata.merge([+ "observer": "local-ui-understanding",+ "traceID": request.traceID,+ "targetID": request.targetID,+ "controlCount": String(controls.count),+ "formFieldCount": String(formFields.count),+ "directInputActionsAllowed": "false"+ ]) { current, _ in current }+ if let cropBounds = request.cropBounds {+ observationMetadata.merge(+ LocalAppObservationGeometry.cropBoundsMetadata(cropBounds)+ ) { current, _ in current }+ }+ if let pixelSize = request.pixelSize {+ observationMetadata.merge(+ LocalAppObservationGeometry.pixelSizeMetadata(pixelSize)+ ) { current, _ in current }+ }+ for control in controls {+ let controlID = control.metadata["controlID"] ?? control.id+ observationMetadata.merge(+ LocalAppObservationGeometry.controlMetadata(+ controlID: controlID,+ frame: control.frame,+ source: .localUIUnderstanding,+ label: control.label,+ kind: control.kind,+ confidence: control.confidence,+ extra: control.metadata+ )+ ) { current, _ in current }+ }++ let availableControls = controls.reduce(into: [String: Bool]()) { result, control in+ result[control.id] = true+ if let controlID = control.metadata["controlID"],+ !controlID.isEmpty {+ result[controlID] = true+ }+ }++ return LocalAppTaskObservation(appIsRunning: request.appIsRunning,appIsFocused: request.appIsFocused,- availableControls: Dictionary(uniqueKeysWithValues: controls.map { control in- (control.metadata["controlID"] ?? control.id, true)- }),+ availableControls: availableControls,visibleText: visibleText,confidence: confidence,- metadata: metadata.merging([- "observer": "local-ui-understanding",- "traceID": request.traceID,- "targetID": request.targetID,- "controlCount": String(controls.count),- "formFieldCount": String(formFields.count),- "directInputActionsAllowed": "false"- ]) { current, _ in current }+ metadata: observationMetadata)}}diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swift b/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swiftindex 4762a226..57ca11f3 100644--- a/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swift@@ -64,6 +64,8 @@ public struct MacAppleScriptActionEngineInputBackend: ActionEngineInputBackend {executed: false,metadata: ["liveInputBackend": "mac-apple-script",+ "inputMode": "appAutomation",+ "elementClick": "false","reason": "unsupportedCommandKind"])@@ -75,6 +77,8 @@ public struct MacAppleScriptActionEngineInputBackend: ActionEngineInputBackend {executed: false,metadata: ["liveInputBackend": "mac-apple-script",+ "inputMode": "appAutomation",+ "elementClick": "false","reason": "missingAppleScriptBackendMarker"])@@ -86,6 +90,8 @@ public struct MacAppleScriptActionEngineInputBackend: ActionEngineInputBackend {executed: false,metadata: ["liveInputBackend": "mac-apple-script",+ "inputMode": "appAutomation",+ "elementClick": "false","reason": "unsupportedAppleScriptAction","appleScript.action": command.metadata["appleScript.action"] ?? ""]@@ -104,6 +110,8 @@ public struct MacAppleScriptActionEngineInputBackend: ActionEngineInputBackend {executed: executed,metadata: ["liveInputBackend": "mac-apple-script",+ "inputMode": "appAutomation",+ "elementClick": "false","appleScript.action": generatedScript.action,"appleScript.scriptKind": generatedScript.kind,"appleScript.output": output,diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacKeyboardActionEngineInputBackend.swift b/apps/Donkey/Sources/DonkeyRuntime/MacKeyboardActionEngineInputBackend.swiftindex 540d7c51..c074000d 100644--- a/apps/Donkey/Sources/DonkeyRuntime/MacKeyboardActionEngineInputBackend.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/MacKeyboardActionEngineInputBackend.swift@@ -11,7 +11,12 @@ public struct MacKeyboardActionEngineInputBackend: ActionEngineInputBackend {return result(command: command,executed: false,- metadata: ["liveInputBackend": "mac-keyboard", "reason": "unsupportedCommandKind"]+ metadata: [+ "liveInputBackend": "mac-keyboard",+ "inputMode": "keyboard",+ "elementClick": "false",+ "reason": "unsupportedCommandKind"+ ])}@@ -35,6 +40,7 @@ public struct MacKeyboardActionEngineInputBackend: ActionEngineInputBackend {metadata: ["liveInputBackend": "mac-keyboard","inputMode": inputMode,+ "elementClick": "false","key": key])diff --git a/apps/Donkey/Sources/DonkeyUI/PointerCoachCursorOverlayView.swift b/apps/Donkey/Sources/DonkeyUI/PointerCoachCursorOverlayView.swiftindex 1d7b361d..336d4ec0 100644--- a/apps/Donkey/Sources/DonkeyUI/PointerCoachCursorOverlayView.swift+++ b/apps/Donkey/Sources/DonkeyUI/PointerCoachCursorOverlayView.swift@@ -68,16 +68,25 @@ public final class PointerCoachCursorOverlayViewModel: ObservableObject {)if !frame.visibleLabel.isEmpty {let labelCenter = labelPosition(for: frame.position)+ let labelSize = Self.labelSize(for: frame.visibleLabel)bounds = bounds.union(CGRect(- x: labelCenter.x - 160,- y: labelCenter.y - 42,- width: 320,- height: 84+ x: labelCenter.x - labelSize.width / 2,+ y: labelCenter.y - labelSize.height / 2,+ width: labelSize.width,+ height: labelSize.height))}return bounds.insetBy(dx: -8, dy: -8)}+ private static func labelSize(for text: String) -> CGSize {+ let lineCount = max(1, Int(ceil(Double(text.count) / 34.0)))+ return CGSize(+ width: 300,+ height: max(40, CGFloat(lineCount) * 16 + 16)+ )+ }+private func animationFrame(size: CGSize) -> CoachCursorAnimationFrame {let sample = AgentVisualizationCursorPathSampler.sample(request: request,@@ -143,11 +152,11 @@ public struct PointerCoachCursorOverlayView: View {Text(text).font(.system(size: 12, weight: .medium)).foregroundStyle(.white)- .lineLimit(2)+ .lineLimit(nil).fixedSize(horizontal: false, vertical: true).padding(.horizontal, 10).padding(.vertical, 6)- .frame(maxWidth: 280, alignment: .leading)+ .frame(width: 280, alignment: .leading).background {RoundedRectangle(cornerRadius: 7, style: .continuous).fill(accent)diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swiftindex 9061251f..f6e45a7d 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift@@ -528,6 +528,10 @@ struct AIHarnessAdapterTests {#expect(body["model"] == nil)#expect(body["store"] as? Bool == false)#expect(body["donkeyProvider"] == nil)+ let parameters = try #require(body["parameters"] as? [String: Any])+ let instructions = try #require(parameters["instructions"] as? String)+ #expect(instructions.contains("local_app_interaction"))+ #expect(instructions.contains("media playback"))}@Testdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AgentVisualizationCursorPathFeedbackTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AgentVisualizationCursorPathFeedbackTests.swiftindex 9df761a0..968c6b8c 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AgentVisualizationCursorPathFeedbackTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AgentVisualizationCursorPathFeedbackTests.swift@@ -175,6 +175,37 @@ struct AgentVisualizationCursorPathFeedbackTests {}}+ @Test+ func targetWindowNormalizedCursorPointsMapToScreenLocalPixels() {+ let step = PointerCoachCursorGuideStep(+ id: "search",+ label: "Search",+ target: CGPoint(x: 0.25, y: 0.225),+ metadata: [+ "cursor.targetSpace": "targetWindowNormalized",+ "target.bounds.x": "100",+ "target.bounds.y": "200",+ "target.bounds.width": "800",+ "target.bounds.height": "600"+ ]+ )++ let mapped = AgentVisualizationCursorPathSampler.point(+ step.target,+ metadata: step.metadata,+ screenFrame: CGRect(x: 0, y: 0, width: 1200, height: 900)+ )++ expectPoint(mapped, x: 300, y: 335)++ let secondaryScreenMapped = AgentVisualizationCursorPathSampler.point(+ step.target,+ metadata: step.metadata.merging(["target.bounds.x": "1100"]) { _, new in new },+ screenFrame: CGRect(x: 1000, y: 0, width: 1200, height: 900)+ )+ expectPoint(secondaryScreenMapped, x: 300, y: 335)+ }+private func cursorRequest() -> PointerCoachCursorGuideRequest {PointerCoachCursorGuideRequest(id: "exact-cursor-path",diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AgentVisualizationRuntimeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AgentVisualizationRuntimeTests.swiftindex 173a408c..48823fdd 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AgentVisualizationRuntimeTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AgentVisualizationRuntimeTests.swift@@ -26,6 +26,8 @@ struct AgentVisualizationRuntimeTests {#expect(plan.usesRealPointer == false)#expect(plan.metadata["source"] == "local-app-projected-workflow")#expect(plan.metadata["workflowStage"] == "preExecution")+ #expect(plan.metadata["cursorGuideEligible"] == "false")+ #expect(plan.cursorOverlayRequest() == nil)#expect(plan.steps.map(\.kind).contains(.observe))#expect(plan.steps.map(\.kind).contains(.enterText))#expect(plan.steps.first?.target?.source == .dryRun)@@ -81,6 +83,73 @@ struct AgentVisualizationRuntimeTests {#expect(cursorRequest.metadata["agentVisualization.executionMode"] == "live")}+ @Test+ func localAppVisualizationUsesObservedControlBounds() throws {+ let definition = localAppDefinition()+ let intent = taskIntent(definition: definition)+ let adapter = LocalAppTaskAdapter(definition: definition)+ var observationMetadata = LocalAppObservationGeometry.targetBoundsMetadata(+ WindowTargetBounds(x: 100, y: 200, width: 800, height: 600)+ )+ observationMetadata.merge(+ LocalAppObservationGeometry.controlMetadata(+ controlID: "editor",+ frame: HotLoopRect(x: 180, y: 320, width: 240, height: 30, space: .screen),+ source: .accessibility,+ label: "Editor",+ kind: .textField,+ confidence: 0.88+ )+ ) { current, _ in current }+ let observation = LocalAppTaskObservation(+ appIsRunning: true,+ appIsFocused: true,+ availableControls: ["editor": true],+ visibleText: ["query": "Item"],+ confidence: 0.9,+ metadata: observationMetadata+ )+ let dryRunPlan = adapter.dryRunPlan(for: intent, observation: observation)+ let result = LocalAppTaskLiveRunResult(+ command: "create a table in Numbers",+ traceID: "trace-grounded-control",+ status: .completed,+ resolution: LocalAppTaskCatalogResolution(+ status: .resolved,+ intent: intent,+ definition: definition,+ availability: LocalAppAvailability(target: definition.targetApp, isInstalled: true)+ ),+ initialPlan: dryRunPlan,+ finalPlan: dryRunPlan,+ observation: observation+ )++ let plan = try #require(LocalAppTaskAgentVisualizationBuilder.plan(for: result))+ let focusStep = try #require(plan.steps.first(where: { $0.id == "focus-input" }))+ let enterStep = try #require(plan.steps.first(where: { $0.id == "set-text" }))+ let cursorRequest = try #require(plan.cursorOverlayRequest())+ let cursorFocusStep = try #require(cursorRequest.steps.first(where: { $0.id == "focus-input" }))+ let cursorEnterStep = try #require(cursorRequest.steps.first(where: { $0.id == "set-text" }))++ #expect(focusStep.target?.source == .accessibility)+ #expect(focusStep.target?.bounds?.space == .normalizedTarget)+ #expect(enterStep.target?.controlID == "editor")+ #expect(cursorFocusStep.metadata["cursor.targetSpace"] == "targetWindowNormalized")+ #expect(cursorFocusStep.metadata["target.bounds.x"] == "100.0")+ #expect(abs(cursorFocusStep.target.x - 0.25) < 0.001)+ #expect(abs(cursorFocusStep.target.y - 0.225) < 0.001)+ #expect(abs(cursorEnterStep.target.x - cursorFocusStep.target.x) < 0.001)+ #expect(abs(cursorEnterStep.target.y - cursorFocusStep.target.y) < 0.001)+ let screenPoint = AgentVisualizationCursorPathSampler.point(+ cursorFocusStep.target,+ metadata: cursorFocusStep.metadata,+ screenFrame: CGRect(x: 0, y: 0, width: 1200, height: 900)+ )+ #expect(abs(screenPoint.x - 300) < 0.001)+ #expect(abs(screenPoint.y - 335) < 0.001)+ }+@Testfunc visualOnlyPlanConvertsToOverlayCursorWithoutRealPointerMovement() throws {let plan = AgentVisualizationPlan(diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swiftindex 04758571..076518d6 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift@@ -689,6 +689,66 @@ struct LocalAppTaskTests {#expect(fields.first(where: { $0.id == "ax-1.2" })?.label == "Name")}+ @Test+ func accessibilityActionPlannerPressesExplicitSubmitControls() throws {+ let definition = LocalAppTaskDefinition(+ taskType: "button_submit",+ targetApp: LocalAppTarget(appName: "Music", bundleIdentifier: "com.apple.Music"),+ triggerTerms: [],+ workflowSteps: [+ LocalAppTaskWorkflowStepDefinition(+ id: "play-result",+ role: .submit,+ summary: "Play the selected result",+ metadata: ["controlID": "play-result"]+ )+ ]+ )+ let intent = TaskIntent(+ intentID: "button-submit-play-result",+ taskType: definition.taskType,+ targetApp: definition.targetApp,+ entities: [:],+ normalizedEntities: [:],+ confidence: 0.9,+ parserSource: .localModel+ )+ let index = LocalAppAccessibilityControlIndex(+ controls: [+ LocalAppDiscoveredControl(+ id: "ax-1.4",+ kind: .button,+ role: "AXButton",+ label: "Play Result",+ frame: WindowTargetBounds(x: 320, y: 240, width: 42, height: 28),+ actions: ["AXPress"],+ metadata: ["controlID": "play-result"]+ )+ ],+ visibleText: "Play Result"+ )++ let commands = LocalAppAccessibilityActionPlanner().commands(+ for: intent,+ definition: definition,+ index: index,+ issuedAt: timestamp(200)+ )+ let command = try #require(commands.first)++ #expect(commands.count == 1)+ #expect(command.kind == .tap)+ #expect(command.metadata["workflowStepID"] == "play-result")+ #expect(command.metadata["inputIntent"] == "submit")+ #expect(command.metadata["accessibility.action"] == "AXPress")+ #expect(command.metadata["controlID"] == "play-result")+ #expect(command.targetBounds?.origin.x == 320)+ #expect(command.targetBounds?.origin.y == 240)+ #expect(command.targetBounds?.size.width == 42)+ #expect(command.targetBounds?.size.height == 28)+ #expect(command.targetBounds?.space == .screen)+ }+@Test @MainActorfunc liveRunnerReturnsReviewPlanForDocumentFormFillWithoutExecutingInput() async throws {let catalog = LocalAppTaskCatalog(@@ -831,6 +891,9 @@ struct LocalAppTaskTests {#expect(await backend.executedKeys() == ["justin bieber"])#expect(result.metadata["automation.backend"] == "appleScript")#expect(result.metadata["automation.action"] == "music.playMediaQuery")+ #expect(result.metadata["action.elementClickCount"] == "0")+ #expect(result.metadata["action.lastTarget"] == "none")+ #expect(result.metadata["action.overlayPointer"] == "visualOnly")#expect(result.workflowProgress.state(for: .execute)?.status == .completed)#expect(result.workflowProgress.state(for: .verify)?.status == .completed)}@@ -890,6 +953,19 @@ struct LocalAppTaskTests {@Testfunc screenshotUnderstandingIsOnlyUsedWhenAccessibilityIsInsufficient() {let definition = BuiltInLocalAppTaskDefinitions.weatherLookup+ var boundedSearchMetadata = LocalAppObservationGeometry.targetBoundsMetadata(+ WindowTargetBounds(x: 100, y: 120, width: 900, height: 700)+ )+ boundedSearchMetadata.merge(+ LocalAppObservationGeometry.controlMetadata(+ controlID: "search",+ frame: HotLoopRect(x: 140, y: 180, width: 320, height: 44, space: .screen),+ source: .accessibility,+ label: "Search",+ kind: .searchField,+ confidence: 0.86+ )+ ) { current, _ in current }#expect(LocalAppTaskObservationFallbackPolicy.shouldUseScreenshotUnderstanding(definition: definition,@@ -898,11 +974,24 @@ struct LocalAppTaskTests {appIsFocused: true,availableControls: ["search": true],visibleText: ["city": "San Francisco"],- confidence: 0.9+ confidence: 0.9,+ metadata: boundedSearchMetadata),verificationKey: "city") == false)+ #expect(LocalAppTaskObservationFallbackPolicy.shouldUseScreenshotUnderstanding(+ definition: definition,+ accessibilityObservation: LocalAppTaskObservation(+ appIsRunning: true,+ appIsFocused: true,+ availableControls: ["search": true],+ visibleText: ["city": "San Francisco"],+ confidence: 0.9+ ),+ verificationKey: "city"+ ) == true)+#expect(LocalAppTaskObservationFallbackPolicy.shouldUseScreenshotUnderstanding(definition: definition,accessibilityObservation: LocalAppTaskObservation(@@ -944,6 +1033,50 @@ struct LocalAppTaskTests {) == true)}+ @Test+ func localUIUnderstandingObservationDeduplicatesModelControlIDs() {+ let request = LocalUIUnderstandingRequest(+ traceID: "trace-duplicate-controls",+ targetID: "weather",+ metadata: LocalAppObservationGeometry.targetBoundsMetadata(+ WindowTargetBounds(x: 100, y: 120, width: 900, height: 700)+ )+ )+ let result = LocalUIUnderstandingResult(+ controls: [+ LocalUIUnderstandingControl(+ id: "search-field",+ label: "Search",+ kind: .searchField,+ frame: HotLoopRect(x: 140, y: 180, width: 320, height: 44, space: .screen),+ confidence: 0.86,+ metadata: ["controlID": "search"]+ ),+ LocalUIUnderstandingControl(+ id: "search-button",+ label: "Search",+ kind: .button,+ frame: HotLoopRect(x: 480, y: 180, width: 80, height: 44, space: .screen),+ confidence: 0.72,+ metadata: ["controlID": "search"]+ )+ ],+ confidence: 0.84+ )++ let observation = result.observation(for: request)++ #expect(observation.availableControls["search"] == true)+ #expect(observation.availableControls["search-field"] == true)+ #expect(observation.availableControls["search-button"] == true)+ #expect(observation.metadata["control.search.bounds.space"] == HotLoopCoordinateSpace.screen.rawValue)+ let groundedMetadata = LocalAppObservationGeometry.groundedMetadata(+ controlID: "search",+ observation: observation+ )+ #expect(groundedMetadata["control.bounds.space"] == HotLoopCoordinateSpace.normalizedTarget.rawValue)+ }+@Test @MainActorfunc documentApprovalRunnerExecutesOnlyApprovedFields() async throws {let backend = RecordingLocalAppTaskInputBackend()diff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.mdindex e66e5d91..d17efc6e 100644--- a/docs/guides/pointer-prompt-overlay.md+++ b/docs/guides/pointer-prompt-overlay.md@@ -18,12 +18,12 @@ quick local-app actions:- When a typed prompt or notch follow-up is submitted, show a task spawn cue: the notch arrow rotates toward the exit direction, moves out of the notch, and a Donkey cursor overlay travels onto the desktop.- Spawned cursors travel to a known safe visible target window when one is available. Otherwise they hold about 250 px below the notch near screen center as a loading/thinking state, then retarget if the destination becomes visible.- Multiple spawned cursors can be present at the same time. The newest spawned cursor is selected by default, and clicking a cursor or its label selects it as the current agent.-- A stationary spawned cursor types the submitted turn first, then compact progress or response text in its label. Conversational responses, clarifications, review waits, failures, and other attention states stay visible so the user can read them and follow up; completed action-only cursors may fade out. Spawn labels clamp to two lines by default, reveal the full label on hover only when the collapsed label would truncate, and select the cursor on click. Clicking a tasked label turns the same agent-colored surface into an inline editor with the agent message above and a lighter color-matched user input area below; Return submits the typed follow-up to that spawn's task, Shift-Return inserts a newline, Escape returns to the label, and clicking outside the editor closes it.+- A stationary spawned cursor shows the submitted turn first, then compact progress or response text in its label. Labels render complete words and wrap to their measured size instead of revealing partial typewriter text or clipping at the panel edge. Conversational responses, clarifications, review waits, failures, and other attention states stay visible so the user can read them and follow up; completed action-only cursors may fade out. Spawn labels expand wider on hover when that reduces wrapping, and select the cursor on click. Clicking a tasked label turns the same agent-colored surface into an inline editor with the agent message above and a lighter color-matched user input area below; Return submits the typed follow-up to that spawn's task, Shift-Return inserts a newline, Escape returns to the label, and clicking outside the editor closes it.- Double-Command always opens the centered prompt, even when spawned cursors are visible. If a spawned cursor is selected, centered typed or voice input attaches to that task behind the scenes; otherwise Donkey uses the latest interactable spawned cursor before falling back to follow-up resolution.- Keep prompt submissions, voice transcripts, and follow-ups on the same agent-harness path: task-thread routing, context assembly, conversational response, clarification, review, catalog-backed action parsing, task validation, and guarded local-app execution when a turn is actionable.- Resolve model-classified local-item requests against local apps, files, and folders by querying the current Mac with the SQLite-backed agent memory store, Spotlight/`mdfind`, and bounded filesystem fallback. If the requested local item cannot be found, keep the task safe and report that it was not found instead of falling back to a vague clarification.- Handle scriptable app tasks as guarded AppleScript automation when possible. Commands may use task metadata, generated source, or compact templates; completion is verified through generic task verification policy instead of requiring visible result text for every app.-- Visualize agent work with a transparent overlay cursor. Normal local-app tasks emit a projected `AgentVisualizationPlan` once the workflow is resolved, then a verified plan from runtime evidence such as dry-run steps, observations, and action traces; visual-only demonstration turns use the same plan shape without live input. Donkey moves the overlay cursor along curved paths and types compact labels next to it while keeping the real mouse untouched.+- Visualize agent work with the spawned task cursor when a submitted turn already has one. Normal local-app tasks may create a projected `AgentVisualizationPlan` once the workflow is resolved, but cursor playback waits for runtime evidence such as dry-run steps, observations, and action traces so it does not animate to invented coordinates. Visual-only demonstration turns use the same plan shape without live input. Local-app visualizations use observed Accessibility or screenshot-understanding control bounds when available, convert target-window-normalized element centers into the active overlay screen's pixel coordinates, and only then move the overlay cursor. Donkey moves the overlay cursor along curved paths and shows compact labels next to it while keeping the real mouse untouched. A separate visualization-only cursor is only a fallback when no spawned cursor is available to attach to.- Maintain a background agent memory store in Application Support. The store records resolved and missing local-item lookups, prewarms apps, stores runtime task definitions, keeps metadata such as kind/path/bundle ID/source/task/action, indexes records with SQLite FTS5 plus local vectors, and passes a bounded set of matching hints into the agent harness memory section for classifier and model consideration. Protected file folders such as Desktop, Documents, and Downloads stay lazy and are searched only when a user-requested local-item lookup needs them. See `docs/guides/decision-system.md` for how those hints feed typed model decisions and guarded local-app plans.- Persist task threads as searchable Core Data conversations with event history, task assets, and per-run runtime coordination for any action work attached to the thread.- Keep the overlay non-invasive. Permission setup requests Accessibility, screenshot, and microphone access with user-visible reasons, but the overlay itself does not capture the screen or synthesize input directly. Bounded screenshots and Accessibility reads are used only by guarded local-app workflows.@@ -45,25 +45,26 @@ quick local-app actions:- The prompt is a compact black composer: single-line text is pill-shaped, multiline text becomes a bounded rounded rectangle, Return submits, Shift-Return inserts a newline, Escape and outside clicks dismiss, and non-input capsule areas can drag the modal.- The centered composer keeps text and voice modes on the same input surface. Double-Command release opens focused text input, double-Command hold opens the same input with voice active, and typed text promotes the send button while the microphone affordance becomes secondary.- Voice capture and transcription remain separate. The controller records bounded local audio and publishes levels; transcription is model-backed through the hosted agent-harness boundary before transcript text enters the turn path.-- Local item prewarming must run off the main actor. Agent memory is stored in SQLite under Application Support and uses FTS5 plus deterministic local embeddings for retrieval; JSONL is only an explicit export/debug format. Cached local-item hits must still point to an existing path or bundle before they are used as an execution target. Runtime task definitions are loaded from agent memory; Weather, Music, and Preview definitions are benchmark fixtures unless a generated/user-reviewed definition for them is present in memory.-- For scriptable apps, prefer app-native AppleScript task commands before falling back to Accessibility or keyboard input. Bounded screenshots may supplement observation/verification according to task metadata, but screenshots remain context evidence and do not directly drive input.-- Agent visualization overlays are non-interactive, non-activating panels. They may point, explain, and replay what the agent is doing or would do, but they do not synthesize mouse movement. Live keyboard or Accessibility actions remain separate guarded runtime actions.+- Local item prewarming must run off the main actor and must not eagerly scan protected user folders. Agent memory is stored in SQLite under Application Support and uses FTS5 plus deterministic local embeddings for retrieval; JSONL is only an explicit export/debug format. Cached local-item hits must still point to an existing path or bundle before they are used as an execution target. Runtime task definitions are loaded from agent memory; Weather, Music, and Preview definitions are benchmark fixtures unless a generated/user-reviewed definition for them is present in memory.+- For scriptable apps, prefer app-native AppleScript task commands before falling back to Accessibility or keyboard input. Submit steps with an explicit structured `controlID` may execute as an Accessibility `AXPress` against button-like controls, with the control bounds carried into action traces. Bounded screenshots may supplement observation/verification according to task metadata, but screenshots remain context evidence and do not directly drive input.+- Agent visualization overlays are non-interactive, non-activating panels. They may point, explain, and replay what the agent is doing or would do, but they do not synthesize mouse movement. Live keyboard or Accessibility actions remain separate guarded runtime actions. When a local-app dry run is based on an observation, preserve target-window geometry and control bounds on the dry-run steps so cursor replay can use pixel-grounded element positions instead of invented coordinates.- Task actions in the notch, including follow-up submission and pause/resume, must cross the model/controller command boundary with the selected task ID.-- Pointer prompt command handling should emit actionable `com.donkey.app` route/result logs for submitted commands, routing decisions, intent resolution, unsupported requests, unavailable apps, and final task status.+- Pointer prompt command handling should emit actionable `com.donkey.app` route/result logs for submitted commands, routing decisions, intent resolution, local action traces, unsupported requests, unavailable apps, and final task status. Action trace logs should state the backend, input mode, whether an element click happened, the control or bounds target, and that the overlay pointer is visual-only.## VerificationManually verify:- The notch renders at the top center, respects physical notch safe areas, expands only from visible notch hover, and accepts expanded controls/clicks.+- First launch shows the permission setup after sign-in, explains Accessibility, Screenshots, and Microphone before requesting them, enables Continue only when all three are ready, and does not trigger Desktop/Documents/Downloads prompts during startup.- Double-Command release opens a centered focused text prompt; double-Command hold opens the same prompt with voice active; typed text shows a primary send button and a secondary microphone affordance; unrelated Command use does not activate the overlay.- Typed, voice, and follow-up submissions create or update durable task threads, answer non-actionable conversation without showing action failure, show action status in the notch when work runs, and preserve per-task pause/resume behavior.- Typed prompt and notch follow-up submissions show the spawn sequence: notch cue, desktop cursor emergence, direct travel to a known target or fallback holding point, typed submitted-turn label, typed progress/response label, retargeting when the target becomes visible, persistent labels for conversational or attention states, and fade-out only for completed action-only turns.-- Stationary spawn labels clamp to two lines, reveal the full label on hover only when truncated, select the cursor on click, and transition in place into a same-styled inline editor for tasked follow-ups.+- Stationary spawn labels render complete text without typewriter clipping, wrap to fit available width, select the cursor on click, and transition in place into a same-styled inline editor for tasked follow-ups without clipping the carried-over label.- With multiple spawned cursors visible, clicking a cursor selects it; double-Command still opens the centered prompt, and the submitted typed or voice turn routes to the selected/latest cursor's task without opening the inline label editor.- Open requests for installed apps, files, and folders launch or open the local item; missing local items show a not-found result and log the lookup provider/reason.- LLM-classified visual-only prompts complete as visualization turns and show the animated cursor with typed labels without moving the real pointer.-- Normal local-app tasks can produce visualization steps for planning, observing, navigating, acting, and verifying. The visualization must not claim completion unless the runtime verification state supports it.+- Normal local-app tasks can produce visualization steps for planning, observing, navigating, acting, and verifying. The visualization should target observed control centers from Accessibility or screenshot understanding when those bounds exist, and must not claim completion unless the runtime verification state supports it.- The prompt supports wrapping, Shift-Return newline insertion, Return submission, Escape dismissal, outside-click dismissal, and dragging from non-input areas.- File drops on the notch attach to the active or most recent task.diff --git a/scripts/local-runtime-runners/donkey_runtime_runner.py b/scripts/local-runtime-runners/donkey_runtime_runner.pyindex 73fc4db9..687b22a4 100644--- a/scripts/local-runtime-runners/donkey_runtime_runner.py+++ b/scripts/local-runtime-runners/donkey_runtime_runner.py@@ -1223,6 +1223,7 @@ def agent_visualization_plan_prompt(["Classify whether the user's request should be answered by visual-only agent action visualization.","Use semantic intent, not command wording. Visual-only visualization is for teaching or demonstrating where the agent would observe, point, focus, type, submit, or verify inside an app.",+ "If the user wants Donkey to perform an app action now, such as playing media, opening a site, writing text, searching, submitting, or editing, set shouldVisualize=false even if cursor steps could be imagined.","If the request is an executable local task, app/file open request, arithmetic/chat answer, or missing-detail clarification, set shouldVisualize=false. Normal executable tasks emit their own visualization from runtime traces.","If shouldVisualize=true, generate two to five cursor steps with short labels. Coordinates are normalized screen positions from 0 to 1.","The visualization must explain and point only. It must not claim to move the real mouse, click, type, submit, or perform the user's task.",diff --git a/site/src/lib/inference/adapters/gemini-computer-use.ts b/site/src/lib/inference/adapters/gemini-computer-use.tsindex 5d6f0818..28faa93d 100644--- a/site/src/lib/inference/adapters/gemini-computer-use.ts+++ b/site/src/lib/inference/adapters/gemini-computer-use.ts@@ -3,7 +3,7 @@ import {Environment,GoogleGenAI,} from "@google/genai";-import type { JWTInput } from "google-auth-library";+import { JWT, type JWTInput } from "google-auth-library";import type {Content,GenerateContentConfig,@@ -40,6 +40,7 @@ const geminiProviderID = "gemini";const defaultVertexResponsesModel = "gemini-3.5-flash";const defaultComputerUseModel = "gemini-3-flash-preview";const vertexLocation = "global";+const vertexAIScope = "https://www.googleapis.com/auth/cloud-platform";export const geminiBrowserInteractionToolType = "donkey_gemini_browser_interaction";@@ -582,7 +583,7 @@ function geminiClientConfig(environment: AdapterEnvironment): {}if (googleCredentials) {options.googleAuthOptions = {- credentials: googleCredentials,+ authClient: googleAuthClient(googleCredentials),};}@@ -604,6 +605,15 @@ function googleCredentialsFromEnvironment(return serviceAccountCredentials(rawCredentials);}+function googleAuthClient(credentials: JWTInput) {+ return new JWT({+ email: credentials.client_email,+ key: credentials.private_key,+ keyId: credentials.private_key_id,+ scopes: [vertexAIScope],+ });+}+function serviceAccountCredentials(rawCredentials: string): JWTInput {let parsed: unknown;try {