Open source CapCut alternative.
TypeScript
Add pointer prompt coaching and log tailing
David Le8714344e7e2c
diff --git a/apps/Donkey/Sources/Donkey/PointerCoachCursorOverlayController.swift b/apps/Donkey/Sources/Donkey/PointerCoachCursorOverlayController.swiftnew file mode 100644index 00000000..d85898f5--- /dev/null+++ b/apps/Donkey/Sources/Donkey/PointerCoachCursorOverlayController.swift@@ -0,0 +1,68 @@+import AppKit+import DonkeyContracts+import DonkeyUI+import SwiftUI++@MainActor+final class PointerCoachCursorOverlayController {+ private var panel: NSPanel?+ private var dismissalWorkItem: DispatchWorkItem?++ func show(request: PointerCoachCursorGuideRequest) {+ close()++ guard let screen = NSScreen.main ?? NSScreen.screens.first else { return }++ let hostingView = NSHostingView(rootView: PointerCoachCursorOverlayView(request: request))+ hostingView.frame = CGRect(origin: .zero, size: screen.frame.size)+ hostingView.autoresizingMask = [.width, .height]+ hostingView.wantsLayer = true+ hostingView.layer?.backgroundColor = NSColor.clear.cgColor++ let panel = NSPanel(+ contentRect: screen.frame,+ styleMask: [.borderless, .nonactivatingPanel],+ backing: .buffered,+ defer: false+ )+ panel.title = "Donkey Guide"+ panel.contentView = hostingView+ panel.backgroundColor = .clear+ panel.isOpaque = false+ panel.hasShadow = false+ panel.hidesOnDeactivate = false+ panel.isReleasedWhenClosed = false+ panel.ignoresMouseEvents = true+ panel.level = .statusBar+ panel.collectionBehavior = [+ .canJoinAllSpaces,+ .fullScreenAuxiliary,+ .ignoresCycle,+ .stationary+ ]+ panel.setFrame(screen.frame, display: true)+ panel.orderFrontRegardless()+ self.panel = panel++ let workItem = DispatchWorkItem { [weak self] in+ Task { @MainActor in+ self?.close()+ }+ }+ dismissalWorkItem = workItem+ DispatchQueue.main.asyncAfter(deadline: .now() + duration(for: request), execute: workItem)+ }++ func close() {+ dismissalWorkItem?.cancel()+ dismissalWorkItem = nil+ panel?.close()+ panel = nil+ }++ private func duration(for request: PointerCoachCursorGuideRequest) -> TimeInterval {+ request.steps.reduce(0.6) { total, step in+ total + step.travelDuration + step.holdDuration+ }+ }+}diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex 3de27892..0a6af4e9 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -2,6 +2,11 @@ import DonkeyAIimport DonkeyContractsimport DonkeyRuntimeimport Foundation+import OSLog++private enum PointerPromptLog {+ static let commands = Logger(subsystem: "com.donkey.app", category: "pointer-prompt")+}struct PointerPromptCommandHandlingResult: Equatable, Sendable {var status: LocalAppTaskLiveRunStatus@@ -12,6 +17,7 @@ struct PointerPromptCommandHandlingResult: Equatable, Sendable {var traceID: Stringvar metadata: [String: String]var documentReviewRequest: DocumentFormFillReviewRequest?+ var cursorGuideRequest: PointerCoachCursorGuideRequest?}struct DocumentFormFillReviewRequest: Equatable, Sendable {@@ -52,6 +58,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {var memoryRetriever: SemanticRunMemoryRetrievervar coordinatorRegistry: PointerPromptRunCoordinatorRegistryvar targetMemoryStore: TargetMemoryJSONLStore?+ var pointerCoachGuideResolver: any PointerCoachCursorGuideResolvinginit(catalog: LocalAppTaskCatalog = .defaultLocal(),@@ -60,7 +67,8 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {redactor: AIHarnessRedactor = AIHarnessRedactor(),memoryRetriever: SemanticRunMemoryRetriever = SemanticRunMemoryRetriever(),coordinatorRegistry: PointerPromptRunCoordinatorRegistry = PointerPromptRunCoordinatorRegistry(),- targetMemoryStore: TargetMemoryJSONLStore? = try? TargetMemoryJSONLStore()+ targetMemoryStore: TargetMemoryJSONLStore? = try? TargetMemoryJSONLStore(),+ pointerCoachGuideResolver: any PointerCoachCursorGuideResolving = ProcessBackedLocalLLMPointerCoachCursorGuideResolver()) {self.catalog = catalogself.appHarnessRouter = AppHarnessTurnRouter(catalog: catalog)@@ -70,6 +78,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {self.redactor = redactorself.memoryRetriever = memoryRetrieverself.targetMemoryStore = targetMemoryStore+ self.pointerCoachGuideResolver = pointerCoachGuideResolver}func handleSubmittedCommand(@@ -78,13 +87,56 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {) async -> PointerPromptCommandHandlingResult {let traceID = "pointer-prompt-\(UUID().uuidString)"let taskID = context?.task.id ?? traceID+ logSubmittedCommand(command, traceID: traceID, taskID: taskID, context: context)+ let cursorGuideResolution = await pointerCoachGuideResolver.resolveGuide(+ PointerCoachCursorGuideResolverRequest(+ command: command,+ runtimeCapabilities: Self.runtimeCapabilities(for: catalog),+ cacheSnippets: LocalItemResolutionCache.shared.contextSnippets(for: command),+ sourceTraceID: traceID+ )+ )+ if let cursorGuideRequest = cursorGuideResolution.guideRequest {+ let result = PointerPromptCommandHandlingResult(+ status: .completed,+ threadStatus: .chatting,+ decision: AppHarnessDecision(+ kind: .respond,+ message: "Showing you.",+ traceID: traceID,+ metadata: [+ "structuredDecision": "true",+ "router": "pointerCoachGuide"+ ]+ ),+ summary: "Showing you.",+ taskLabel: cursorGuideRequest.title,+ traceID: traceID,+ metadata: cursorGuideRequest.metadata.merging([+ "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,+ "appHarness.context.traceID": traceID,+ "cursorGuide.modelCallID": cursorGuideResolution.trace.id,+ "cursorGuide.modelStatus": cursorGuideResolution.trace.status.rawValue,+ "cursorGuide.validationStatus": cursorGuideResolution.trace.validationStatus,+ "cursorGuide.confidence": Self.formatLatency(cursorGuideResolution.confidence),+ "cursorGuide.reason": cursorGuideResolution.reason,+ "cursorGuide.stepCount": String(cursorGuideRequest.steps.count)+ ]) { current, _ in current },+ documentReviewRequest: nil,+ cursorGuideRequest: cursorGuideRequest+ )+ logHandlingResult(result, stage: "cursorGuide", hint: "Showing an instructional cursor guide.")+ return result+ }+let routing = appHarnessRouter.route(request: Self.harnessRequest(command: command, context: context),traceID: traceID)+ logRouting(command: command, traceID: traceID, taskID: taskID, routing: routing)switch routing.outcome.decision.kind {case .respond:- return PointerPromptCommandHandlingResult(+ let result = PointerPromptCommandHandlingResult(status: .completed,threadStatus: .chatting,decision: routing.outcome.decision,@@ -92,10 +144,13 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {taskLabel: nil,traceID: traceID,metadata: Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome),- documentReviewRequest: nil+ documentReviewRequest: nil,+ cursorGuideRequest: nil)+ logHandlingResult(result, stage: "conversation", hint: routingHint(for: routing))+ return resultcase .askClarification:- return PointerPromptCommandHandlingResult(+ let result = PointerPromptCommandHandlingResult(status: .needsConfirmation,threadStatus: .waitingForClarification,decision: routing.outcome.decision,@@ -103,10 +158,13 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {taskLabel: nil,traceID: traceID,metadata: Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome),- documentReviewRequest: nil+ documentReviewRequest: nil,+ cursorGuideRequest: nil)+ logHandlingResult(result, stage: "routing", hint: routingHint(for: routing))+ return resultcase .noOp:- return PointerPromptCommandHandlingResult(+ let result = PointerPromptCommandHandlingResult(status: .completed,threadStatus: .chatting,decision: routing.outcome.decision,@@ -114,8 +172,11 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {taskLabel: nil,traceID: traceID,metadata: Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome),- documentReviewRequest: nil+ documentReviewRequest: nil,+ cursorGuideRequest: nil)+ logHandlingResult(result, stage: "empty", hint: "Empty command; no action was run.")+ return resultcase .openReview, .runLocalTask:break}@@ -140,35 +201,37 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)let resolution = localModelResult.resolutionlet parseLatencyMS = Self.uptimeMilliseconds() - parseStartedAt+ logModelResolution(+ command: modelCommand,+ traceID: traceID,+ resolution: resolution,+ trace: localModelResult.trace,+ latencyMS: parseLatencyMS+ )let semanticMemoryResults = await retrieveSemanticMemory(command: modelCommand,resolution: resolution)let modelObservability = AIModelObservabilityReportBuilder.build(from: [localModelResult.trace])+ let modelMetadata = [+ "appHarness.decision": routing.outcome.decision.kind.rawValue,+ "appHarness.context.promptCharacters": String(routing.contextPacket.promptText.count),+ "appHarness.context.redactionCount": String(routing.contextPacket.redactionCount),+ "intentParser": "localModel",+ "latency.commandParseMS": Self.formatLatency(parseLatencyMS),+ "modelCallID": localModelResult.trace.id,+ "modelCallStatus": localModelResult.trace.status.rawValue,+ "modelValidationStatus": localModelResult.trace.validationStatus,+ "modelObservability.callCount": String(modelObservability.callCount),+ "modelObservability.acceptedCount": String(modelObservability.acceptedCount),+ "modelObservability.recoverySuccessCount": String(modelObservability.recoverySuccessCount),+ "redaction.modelContext.count": String(redaction.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 }- let result = await taskLiveRunner.run(- command: modelCommand,- traceID: traceID,- resolution: resolution,- metadata: [- "appHarness.decision": routing.outcome.decision.kind.rawValue,- "appHarness.context.promptCharacters": String(routing.contextPacket.promptText.count),- "appHarness.context.redactionCount": String(routing.contextPacket.redactionCount),- "intentParser": "localModel",- "latency.commandParseMS": Self.formatLatency(parseLatencyMS),- "modelCallID": localModelResult.trace.id,- "modelCallStatus": localModelResult.trace.status.rawValue,- "modelValidationStatus": localModelResult.trace.validationStatus,- "modelObservability.callCount": String(modelObservability.callCount),- "modelObservability.acceptedCount": String(modelObservability.acceptedCount),- "modelObservability.recoverySuccessCount": String(modelObservability.recoverySuccessCount),- "redaction.modelContext.count": String(redaction.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 }- )await coordinator.recordToolEvent(capability: .model,decision: .allow,@@ -182,6 +245,52 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {])+ if Self.shouldRespondWithoutLocalTask(resolution) {+ let response = "I couldn't find a supported local action for that yet."+ let decision = AppHarnessDecision(+ kind: .respond,+ message: response,+ traceID: traceID,+ metadata: [+ "structuredDecision": "true",+ "router": "modelNoTaskIntent",+ "resolution.status": resolution.status.rawValue+ ]+ )+ let handlingResult = PointerPromptCommandHandlingResult(+ status: .completed,+ threadStatus: .chatting,+ decision: decision,+ summary: response,+ taskLabel: nil,+ traceID: traceID,+ metadata: modelMetadata.merging([+ "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,+ "router": "modelNoTaskIntent",+ "resolution.status": resolution.status.rawValue,+ "resolution.reason": resolution.metadata["reason"] ?? ""+ ]) { _, new in new }.merging(+ Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome)+ ) { current, _ in current },+ documentReviewRequest: nil,+ cursorGuideRequest: nil+ )+ await coordinatorRegistry.finish(taskID: taskID)+ logHandlingResult(+ handlingResult,+ stage: "conversation",+ hint: "No local task intent was produced; responded in the thread."+ )+ return handlingResult+ }++ let result = await taskLiveRunner.run(+ command: modelCommand,+ traceID: traceID,+ resolution: resolution,+ metadata: modelMetadata+ )+let handlingResult = PointerPromptCommandHandlingResult(status: result.status,threadStatus: threadStatus(for: result),@@ -195,9 +304,15 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {documentReviewRequest: documentReviewRequest(traceID: traceID,result: result- )+ ),+ cursorGuideRequest: nil)await coordinatorRegistry.finish(taskID: taskID)+ logHandlingResult(+ handlingResult,+ stage: "localTask",+ hint: runHint(for: result)+ )return handlingResult}@@ -215,6 +330,98 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)}+ private func logRouting(+ command: String,+ traceID: String,+ taskID: String,+ routing: AppHarnessRoutingResult+ ) {+ let decision = routing.outcome.decision.kind.rawValue+ let router = routing.outcome.metadata["router"] ?? "unknown"+ let resolution = routing.outcome.resolution?.status.rawValue ?? "none"+ let missingDetail = routing.outcome.missingDetail ?? ""+ let taskType = routing.outcome.resolution?.definition?.taskType ?? ""+ let hint = routingHint(for: routing)+ PointerPromptLog.commands.notice(+ "command routed traceID=\(traceID, privacy: .public) taskID=\(taskID, privacy: .public) decision=\(decision, privacy: .public) router=\(router, privacy: .public) resolution=\(resolution, privacy: .public) taskType=\(taskType, privacy: .public) missingDetail=\(missingDetail, privacy: .public) hint=\(hint, privacy: .public) command=\(command, privacy: .public)"+ )+ }++ private func logSubmittedCommand(+ _ command: String,+ traceID: String,+ taskID: String,+ context: PointerPromptCommandContext?+ ) {+ let source = context?.turnSource.rawValue ?? AppHarnessTurnSource.typedPrompt.rawValue+ let isFollowUp = context?.isFollowUp ?? false+ PointerPromptLog.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 logModelResolution(+ command: String,+ traceID: String,+ resolution: LocalAppTaskCatalogResolution,+ trace: AIModelCallTrace,+ latencyMS: Double+ ) {+ let taskType = resolution.definition?.taskType ?? resolution.intent?.taskType ?? ""+ let reason = resolution.metadata["reason"] ?? ""+ let latency = Self.formatLatency(latencyMS)+ PointerPromptLog.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) latencyMS=\(latency, privacy: .public) command=\(command, privacy: .public)"+ )+ }++ private func logHandlingResult(+ _ result: PointerPromptCommandHandlingResult,+ stage: String,+ hint: String+ ) {+ let taskLabel = result.taskLabel ?? ""+ PointerPromptLog.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 routingHint(for routing: AppHarnessRoutingResult) -> String {+ let router = routing.outcome.metadata["router"] ?? ""+ switch router {+ case "simpleArithmetic":+ return "Answered a simple arithmetic question locally; no app workflow was run."+ case "followUpActionContext":+ return "Follow-up turn is being treated as an action for the existing task."+ case "modelIntent":+ return "Using local model intent classification with cache-backed local lookup."+ default:+ return "Router path \(router.isEmpty ? "unknown" : router)."+ }+ }++ private func runHint(for result: LocalAppTaskLiveRunResult) -> String {+ if let reason = result.metadata["reason"], !reason.isEmpty {+ 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 static func shouldRespondWithoutLocalTask(_ resolution: LocalAppTaskCatalogResolution) -> Bool {+ resolution.intent == nil+ && resolution.status == .needsConfirmation+ && resolution.metadata["reason"] == "localModelIntentUnavailable"+ }+private func retrieveSemanticMemory(command: String,resolution: LocalAppTaskCatalogResolution@@ -284,7 +491,10 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {}return "Need more detail"case .appUnavailable:- return "App unavailable"+ 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:@@ -313,25 +523,39 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {}let entities = result.resolution.intent?.normalizedEntities ?? [:]- switch definition.taskType {- case "weather_lookup":- if let city = entities["city"], !city.isEmpty {- return "Weather for \(city)"- }- return "Weather lookup"- case "media_playback":- if let query = entities["query"], !query.isEmpty {- return "Play \(query)"- }- return "Play media"- case "document_form_fill":- return "Fill PDF"- default:- return definition.taskType- .split(separator: "_")+ 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 {@@ -368,6 +592,16 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {.joined(separator: "\n\n")}+ 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 func harnessRequest(command: String,context: PointerPromptCommandContext?@@ -381,6 +615,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {),recentEvents: context?.recentEvents ?? [],assets: context?.assets ?? [],+ memory: LocalItemResolutionCache.shared.contextSnippets(for: command),policy: ["localInput": "guarded"])}diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swiftindex bab3fa34..7957ca77 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift@@ -11,6 +11,7 @@ final class PointerPromptOverlayController {private let fixedPlacement: PointerPromptPlacement = .bottomRightprivate let activationShortcut: PointerPromptActivationShortcutprivate let microphoneWaveformMeter = MicrophoneWaveformMeter()+ private let coachCursorController = PointerCoachCursorOverlayController()private var statusPanel: NSPanel?private var statusHostingView: PointerPromptHostingView<PointerPromptNotchStatusView>?@@ -34,6 +35,7 @@ final class PointerPromptOverlayController {private var statusCollapseWorkItem: DispatchWorkItem?private var statusExpansionWorkItem: DispatchWorkItem?private var statusHostShrinkWorkItem: DispatchWorkItem?+ private var hasPrewarmedInputPanel = falseprivate var hasPrewarmedStatusPanelExpansion = falseprivate var lastStatusViewSnapshot: StatusPanelViewSnapshot?@@ -43,6 +45,9 @@ final class PointerPromptOverlayController {) {self.model = modelself.activationShortcut = activationShortcut+ model.coachGuidePresenter = { [weak self] request in+ self?.coachCursorController.show(request: request)+ }microphoneWaveformMeter.onLevelsChanged = { [weak model] levels inmodel?.updateVoiceWaveformLevels(levels)}@@ -56,6 +61,7 @@ final class PointerPromptOverlayController {self.inputPanel = inputPanelself.statusPanel = statusPanel+ prewarmInputPanel()prewarmStatusPanelExpansion()startActivationMonitoring()startAppDeactivationMonitoring()@@ -169,11 +175,13 @@ final class PointerPromptOverlayController {stopActivationMonitoring()stopAppDeactivationMonitoring()microphoneWaveformMeter.stop()+ coachCursorController.close()inputPanel?.close()inputPanel = nilstatusPanel?.close()statusPanel = nilstatusHostingView = nil+ hasPrewarmedInputPanel = falsehasPrewarmedStatusPanelExpansion = falselastStatusViewSnapshot = nil}@@ -697,19 +705,30 @@ final class PointerPromptOverlayController {flushStatusHostLayout()}+ private func prewarmInputPanel() {+ guard !hasPrewarmedInputPanel,+ let inputPanel else { return }+ hasPrewarmedInputPanel = true++ flushPanelLayout(inputPanel)+ }+private func flushStatusHostLayout() {guard let statusPanel else { return }+ flushPanelLayout(statusPanel)+ }++ private func flushPanelLayout(_ panel: NSPanel) {NSAnimationContext.runAnimationGroup { context incontext.duration = 0context.allowsImplicitAnimation = falseCATransaction.begin()CATransaction.setDisableActions(true)- statusPanel.contentView?.layoutSubtreeIfNeeded()- statusHostingView?.layoutSubtreeIfNeeded()- statusHostingView?.displayIfNeeded()- statusPanel.displayIfNeeded()+ panel.contentView?.layoutSubtreeIfNeeded()+ panel.contentView?.displayIfNeeded()+ panel.displayIfNeeded()CATransaction.commit()}}diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swiftindex 5d631a86..48bf0e31 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift@@ -1,5 +1,6 @@import DonkeyAIimport DonkeyContracts+import DonkeyRuntimeimport Foundationimport SwiftUI@@ -17,6 +18,7 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink@Published private(set) var isCurrentTaskPaused = false@Published private(set) var updateState: PointerPromptUpdateState@Published private(set) var notchTasks: [PointerPromptNotchTask]+ var coachGuidePresenter: ((PointerCoachCursorGuideRequest) -> Void)?private let commandHandler: any PointerPromptCommandHandlingprivate let taskStore: any PointerPromptTaskStoring@@ -66,6 +68,7 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkself?.updateState = state}updateChecker.start()+ LocalItemResolutionCache.shared.prewarmDefaultLocalItemsInBackground()checkForUpdates()}@@ -256,6 +259,9 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkif let documentReviewRequest = result.documentReviewRequest {self.documentReviewController.show(request: documentReviewRequest)}+ if let cursorGuideRequest = result.cursorGuideRequest {+ self.coachGuidePresenter?(cursorGuideRequest)+ }}}}diff --git a/apps/Donkey/Sources/DonkeyAI/PointerCoachCursorGuideResolver.swift b/apps/Donkey/Sources/DonkeyAI/PointerCoachCursorGuideResolver.swiftnew file mode 100644index 00000000..31e77cfd--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/PointerCoachCursorGuideResolver.swift@@ -0,0 +1,304 @@+import CoreGraphics+import DonkeyContracts+import DonkeyRuntime+import Foundation++public struct PointerCoachCursorGuideResolverRequest: Equatable, Sendable {+ public var command: String+ public var runtimeCapabilities: [String]+ public var cacheSnippets: [String]+ public var sourceTraceID: String+ public var routeRequest: AIModelRouteRequest++ public init(+ command: String,+ runtimeCapabilities: [String] = [],+ cacheSnippets: [String] = [],+ sourceTraceID: String,+ routeRequest: AIModelRouteRequest = AIModelRouteRequest(+ jobType: .taskIntent,+ privacyMode: .privacySensitive,+ latencyTolerance: .interactive+ )+ ) {+ self.command = command+ self.runtimeCapabilities = runtimeCapabilities+ self.cacheSnippets = cacheSnippets+ self.sourceTraceID = sourceTraceID+ self.routeRequest = routeRequest+ }+}++public struct PointerCoachCursorGuideResolverResult: Equatable, Sendable {+ public var guideRequest: PointerCoachCursorGuideRequest?+ public var confidence: Double+ public var reason: String+ public var trace: AIModelCallTrace++ public init(+ guideRequest: PointerCoachCursorGuideRequest?,+ confidence: Double,+ reason: String,+ trace: AIModelCallTrace+ ) {+ self.guideRequest = guideRequest+ self.confidence = min(max(confidence, 0), 1)+ self.reason = reason+ self.trace = trace+ }+}++public protocol PointerCoachCursorGuideResolving: Sendable {+ func resolveGuide(+ _ request: PointerCoachCursorGuideResolverRequest+ ) async -> PointerCoachCursorGuideResolverResult+}++public struct ProcessBackedLocalLLMPointerCoachCursorGuideResolver: PointerCoachCursorGuideResolving {+ public static let schemaID = "pointer_coach_cursor_guide_v1"++ public var router: AIModelRouter+ public var sidecarRunner: any LocalJSONSidecarRunning+ public var encoder: JSONEncoder+ public var decoder: JSONDecoder+ public var minimumGuideConfidence: Double++ public init(+ router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),+ sidecarRunner: any LocalJSONSidecarRunning = ProcessBackedLocalJSONSidecarRunner(),+ encoder: JSONEncoder = JSONEncoder(),+ decoder: JSONDecoder = JSONDecoder(),+ minimumGuideConfidence: Double = 0.62+ ) {+ self.router = router+ self.sidecarRunner = sidecarRunner+ self.encoder = encoder+ self.decoder = decoder+ self.minimumGuideConfidence = minimumGuideConfidence+ }++ public func resolveGuide(+ _ request: PointerCoachCursorGuideResolverRequest+ ) async -> PointerCoachCursorGuideResolverResult {+ let entry: AIModelRegistryEntry+ do {+ entry = try router.route(request.routeRequest.limitingProviders([.localRuntime]))+ } catch {+ return result(+ entry: nil,+ request: request,+ status: .invalidOutput,+ validationStatus: "routingFailed",+ latencyMS: nil,+ metadata: ["error": String(describing: error)]+ )+ }++ let input = LocalLLMPointerCoachCursorGuideSidecarRequest(+ command: request.command,+ runtimeCapabilities: request.runtimeCapabilities,+ cacheSnippets: request.cacheSnippets,+ sourceTraceID: request.sourceTraceID,+ modelID: entry.modelID,+ metadata: [+ "schemaID": Self.schemaID,+ "promptVersion": entry.promptVersion+ ]+ )+ let sidecarResult = await sidecarRunner.run(+ LocalJSONSidecarRequest(+ environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER",+ inputData: (try? encoder.encode(input)) ?? Data(),+ timeoutMS: entry.timeoutMS,+ metadata: [+ "sidecar.role": "pointerCoachCursorGuide",+ "modelID": entry.modelID+ ]+ )+ )++ guard sidecarResult.status == .completed else {+ return result(+ entry: entry,+ request: request,+ status: sidecarResult.status == .timedOut ? .timeout : .providerOutage,+ validationStatus: "notValidated",+ latencyMS: sidecarResult.latencyMS,+ metadata: sidecarResult.metadata.merging([+ "sidecar.stderr": sidecarResult.stderrText+ ]) { current, _ in current }+ )+ }++ do {+ let response = try decoder.decode(+ LocalLLMPointerCoachCursorGuideSidecarResponse.self,+ from: sidecarResult.outputData+ )+ let decision = try decoder.decode(+ PointerCoachCursorGuideDecision.self,+ from: Data(response.outputText.utf8)+ )+ let confidence = min(max(decision.confidence, 0), 1)+ let guideRequest = Self.guideRequest(+ from: decision,+ confidence: confidence,+ minimumGuideConfidence: minimumGuideConfidence+ )+ return PointerCoachCursorGuideResolverResult(+ guideRequest: guideRequest,+ confidence: confidence,+ reason: decision.reason,+ trace: trace(+ entry: entry,+ request: request,+ status: .completed,+ validationStatus: guideRequest == nil ? "notGuide" : "guideDecoded",+ latencyMS: sidecarResult.latencyMS,+ metadata: sidecarResult.metadata.merging(response.metadata) { current, _ in current }+ )+ )+ } catch {+ return result(+ entry: entry,+ request: request,+ status: .invalidOutput,+ validationStatus: "invalid",+ latencyMS: sidecarResult.latencyMS,+ metadata: sidecarResult.metadata.merging([+ "error": String(describing: error)+ ]) { current, _ in current }+ )+ }+ }++ private static func guideRequest(+ from decision: PointerCoachCursorGuideDecision,+ confidence: Double,+ minimumGuideConfidence: Double+ ) -> PointerCoachCursorGuideRequest? {+ guard decision.shouldShowGuide,+ confidence >= minimumGuideConfidence,+ !decision.steps.isEmpty+ else {+ return nil+ }++ let title = nonEmpty(decision.title)+ ?? nonEmpty(decision.goal).map { "Show \($0)" }+ ?? "Show me"+ let steps = decision.steps.prefix(8).compactMap { step -> PointerCoachCursorGuideStep? in+ guard let label = nonEmpty(step.label) else { return nil }+ return PointerCoachCursorGuideStep(+ label: label,+ target: CGPoint(+ x: min(max(step.x, 0.04), 0.96),+ y: min(max(step.y, 0.06), 0.94)+ ),+ travelDuration: step.travelDuration ?? 0.9,+ holdDuration: step.holdDuration ?? 1.8+ )+ }+ guard !steps.isEmpty else { return nil }++ return PointerCoachCursorGuideRequest(+ title: title,+ steps: steps,+ metadata: (decision.metadata ?? [:]).merging([+ "guide": "pointer-coach-cursor",+ "goal": decision.goal ?? "",+ "targetApp": decision.targetApp ?? "",+ "source": "local-llm-pointer-coach"+ ]) { current, _ in current }+ )+ }++ private func result(+ entry: AIModelRegistryEntry?,+ request: PointerCoachCursorGuideResolverRequest,+ status: AIModelCallStatus,+ validationStatus: String,+ latencyMS: Double?,+ metadata: [String: String] = [:]+ ) -> PointerCoachCursorGuideResolverResult {+ PointerCoachCursorGuideResolverResult(+ guideRequest: nil,+ confidence: 0,+ reason: metadata["error"] ?? metadata["reason"] ?? "",+ trace: trace(+ entry: entry,+ request: request,+ status: status,+ validationStatus: validationStatus,+ latencyMS: latencyMS,+ metadata: metadata+ )+ )+ }++ private func trace(+ entry: AIModelRegistryEntry?,+ request: PointerCoachCursorGuideResolverRequest,+ status: AIModelCallStatus,+ validationStatus: String,+ latencyMS: Double?,+ metadata: [String: String] = [:]+ ) -> AIModelCallTrace {+ AIModelCallTrace(+ id: "model-call-\(request.sourceTraceID)",+ role: entry?.role ?? .taskIntent,+ provider: entry?.provider ?? .localRuntime,+ modelID: entry?.modelID ?? "unrouted",+ promptVersion: entry?.promptVersion ?? "unrouted",+ schemaID: Self.schemaID,+ latencyMS: latencyMS,+ timeoutMS: entry?.timeoutMS ?? 0,+ status: status,+ validationStatus: validationStatus,+ sourceTraceID: request.sourceTraceID,+ metadata: metadata+ )+ }++ private static func nonEmpty(_ value: String?) -> String? {+ guard let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines),+ !trimmed.isEmpty+ else {+ return nil+ }+ return trimmed+ }+}++private struct LocalLLMPointerCoachCursorGuideSidecarRequest: Codable, Equatable, Sendable {+ var command: String+ var runtimeCapabilities: [String]+ var cacheSnippets: [String]+ var sourceTraceID: String+ var modelID: String+ var metadata: [String: String]+}++private struct LocalLLMPointerCoachCursorGuideSidecarResponse: Codable, Equatable, Sendable {+ var outputText: String+ var metadata: [String: String]+}++private struct PointerCoachCursorGuideDecision: Codable, Equatable, Sendable {+ var shouldShowGuide: Bool+ var title: String?+ var goal: String?+ var targetApp: String?+ var confidence: Double+ var reason: String+ var steps: [PointerCoachCursorGuideStepDecision]+ var metadata: [String: String]?+}++private struct PointerCoachCursorGuideStepDecision: Codable, Equatable, Sendable {+ var label: String+ var x: Double+ var y: Double+ var travelDuration: TimeInterval?+ var holdDuration: TimeInterval?+}diff --git a/apps/Donkey/Sources/DonkeyContracts/PointerPromptContracts.swift b/apps/Donkey/Sources/DonkeyContracts/PointerPromptContracts.swiftindex aa2fefbf..072f5203 100644--- a/apps/Donkey/Sources/DonkeyContracts/PointerPromptContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/PointerPromptContracts.swift@@ -235,3 +235,47 @@ public final class NoopPointerPromptIntentSink: PointerPromptIntentSink {public func handle(_ intent: PointerPromptIntent) {}}++public struct PointerCoachCursorGuideRequest: Equatable, Sendable {+ public var id: String+ public var title: String+ public var origin: CGPoint+ public var steps: [PointerCoachCursorGuideStep]+ public var metadata: [String: String]++ public init(+ id: String = UUID().uuidString,+ title: String,+ origin: CGPoint = CGPoint(x: 0.5, y: 0.14),+ steps: [PointerCoachCursorGuideStep],+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.title = title+ self.origin = origin+ self.steps = steps+ self.metadata = metadata+ }+}++public struct PointerCoachCursorGuideStep: Equatable, Sendable, Identifiable {+ public var id: String+ public var label: String+ public var target: CGPoint+ public var travelDuration: TimeInterval+ public var holdDuration: TimeInterval++ public init(+ id: String = UUID().uuidString,+ label: String,+ target: CGPoint,+ travelDuration: TimeInterval = 0.9,+ holdDuration: TimeInterval = 1.8+ ) {+ self.id = id+ self.label = label+ self.target = target+ self.travelDuration = max(0.1, travelDuration)+ self.holdDuration = max(0.4, holdDuration)+ }+}diff --git a/apps/Donkey/Sources/DonkeyUI/PointerCoachCursorOverlayView.swift b/apps/Donkey/Sources/DonkeyUI/PointerCoachCursorOverlayView.swiftnew file mode 100644index 00000000..3599e186--- /dev/null+++ b/apps/Donkey/Sources/DonkeyUI/PointerCoachCursorOverlayView.swift@@ -0,0 +1,245 @@+import DonkeyContracts+import SwiftUI++public struct PointerCoachCursorOverlayView: View {+ private let request: PointerCoachCursorGuideRequest+ @State private var startedAt = Date()+ @State private var now = Date()++ private let timer = Timer.publish(every: 1.0 / 60.0, on: .main, in: .common).autoconnect()++ public init(request: PointerCoachCursorGuideRequest) {+ self.request = request+ }++ public var body: some View {+ GeometryReader { proxy in+ let frame = animationFrame(size: proxy.size)++ ZStack(alignment: .topLeading) {+ Color.black.opacity(0.001)++ if frame.isHolding {+ Circle()+ .stroke(Color.white.opacity(0.55), lineWidth: 1.5)+ .frame(width: 36, height: 36)+ .scaleEffect(frame.haloScale)+ .opacity(frame.haloOpacity)+ .position(frame.position)+ }++ cursor(angle: frame.angle)+ .position(frame.position)++ if !frame.visibleLabel.isEmpty {+ label(text: frame.visibleLabel, accent: frame.accent)+ .position(labelPosition(for: frame.position, in: proxy.size))+ .opacity(frame.labelOpacity)+ }+ }+ .ignoresSafeArea()+ }+ .onAppear {+ startedAt = Date()+ now = startedAt+ }+ .onReceive(timer) { value in+ now = value+ }+ }++ private func cursor(angle: Double) -> some View {+ PointerCoachCursorShape()+ .fill(Color.white)+ .overlay {+ PointerCoachCursorShape()+ .stroke(Color(red: 0.34, green: 0.95, blue: 1.0), lineWidth: 1.4)+ }+ .shadow(color: Color.black.opacity(0.28), radius: 3, x: 0, y: 2)+ .frame(width: 26, height: 26)+ .rotationEffect(.degrees(angle + 50))+ }++ private func label(text: String, accent: Color) -> some View {+ Text(text)+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(.white)+ .lineLimit(2)+ .fixedSize(horizontal: false, vertical: true)+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ .frame(maxWidth: 280, alignment: .leading)+ .background {+ RoundedRectangle(cornerRadius: 7, style: .continuous)+ .fill(accent)+ }+ .overlay {+ RoundedRectangle(cornerRadius: 7, style: .continuous)+ .stroke(Color.white.opacity(0.22), lineWidth: 1)+ }+ .shadow(color: Color.black.opacity(0.32), radius: 8, x: 0, y: 4)+ }++ private func animationFrame(size: CGSize) -> CoachCursorAnimationFrame {+ guard !request.steps.isEmpty else {+ return CoachCursorAnimationFrame(+ position: point(request.origin, in: size),+ angle: 0,+ visibleLabel: "",+ isHolding: false+ )+ }++ var elapsed = now.timeIntervalSince(startedAt)+ var origin = point(request.origin, in: size)+ for step in request.steps {+ let target = point(step.target, in: size)+ if elapsed <= step.travelDuration {+ let progress = eased(elapsed / step.travelDuration)+ let position = curvedPoint(from: origin, to: target, progress: progress)+ return CoachCursorAnimationFrame(+ position: position,+ angle: angle(from: origin, to: target),+ visibleLabel: "",+ isHolding: false+ )+ }++ elapsed -= step.travelDuration+ if elapsed <= step.holdDuration {+ let typeProgress = min(1, elapsed / min(step.holdDuration, max(0.6, Double(step.label.count) * 0.035)))+ let wobble = sin(elapsed * 8) * 1.8+ return CoachCursorAnimationFrame(+ position: CGPoint(x: target.x + wobble, y: target.y),+ angle: angle(from: origin, to: target),+ visibleLabel: typedText(step.label, progress: typeProgress),+ isHolding: true,+ haloScale: 1 + 0.14 * sin(elapsed * 3.2),+ haloOpacity: 0.24 + 0.18 * cos(elapsed * 3.2),+ labelOpacity: min(1, elapsed / 0.18)+ )+ }++ elapsed -= step.holdDuration+ origin = target+ }++ let finalStep = request.steps[request.steps.count - 1]+ return CoachCursorAnimationFrame(+ position: point(finalStep.target, in: size),+ angle: 0,+ visibleLabel: finalStep.label,+ isHolding: true,+ labelOpacity: 1+ )+ }++ private func point(_ normalizedPoint: CGPoint, in size: CGSize) -> CGPoint {+ CGPoint(+ x: min(max(normalizedPoint.x, 0.04), 0.96) * max(1, size.width),+ y: min(max(normalizedPoint.y, 0.06), 0.94) * max(1, size.height)+ )+ }++ private func curvedPoint(+ from origin: CGPoint,+ to target: CGPoint,+ progress: Double+ ) -> CGPoint {+ let dx = target.x - origin.x+ let dy = target.y - origin.y+ let length = max(1, hypot(dx, dy))+ let curve = min(80, length * 0.35)+ let control = CGPoint(+ x: (origin.x + target.x) / 2 + (-dy / length) * curve,+ y: (origin.y + target.y) / 2 + (dx / length) * curve+ )+ let t = CGFloat(progress)+ let inv = 1 - t+ return CGPoint(+ x: inv * inv * origin.x + 2 * inv * t * control.x + t * t * target.x,+ y: inv * inv * origin.y + 2 * inv * t * control.y + t * t * target.y+ )+ }++ private func labelPosition(for cursorPosition: CGPoint, in size: CGSize) -> CGPoint {+ let prefersLeft = cursorPosition.x > size.width - 340+ let prefersAbove = cursorPosition.y > size.height - 120+ return CGPoint(+ x: cursorPosition.x + (prefersLeft ? -156 : 156),+ y: cursorPosition.y + (prefersAbove ? -54 : 54)+ )+ }++ private 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 func angle(from origin: CGPoint, to target: CGPoint) -> Double {+ atan2(target.y - origin.y, target.x - origin.x) * 180 / .pi+ }++ private func eased(_ progress: Double) -> Double {+ let t = min(max(progress, 0), 1)+ return 1 - pow(1 - t, 3)+ }+}++private struct CoachCursorAnimationFrame {+ var position: CGPoint+ var angle: Double+ var visibleLabel: String+ var isHolding: Bool+ var haloScale: Double = 1+ var haloOpacity: Double = 0.35+ var labelOpacity: Double = 0+ var accent: Color = Color(red: 0.34, green: 0.28, blue: 0.95)+}++private struct PointerCoachCursorShape: Shape {+ func path(in rect: CGRect) -> Path {+ var path = Path()+ let w = rect.width+ let h = rect.height++ path.move(to: svgPoint(x: 83.086, y: 5.6406, width: w, height: h))+ path.addLine(to: svgPoint(x: 10.453, y: 34.6836, width: w, height: h))+ path.addCurve(+ to: svgPoint(x: 11.13269, y: 51.0276, width: w, height: h),+ control1: svgPoint(x: 2.8514, y: 37.7227, width: w, height: h),+ control2: svgPoint(x: 3.3085, y: 48.6326, width: w, height: h)+ )+ path.addLine(to: svgPoint(x: 35.69469, y: 58.5471, width: w, height: h))+ path.addCurve(+ to: svgPoint(x: 41.44859, y: 64.301, width: w, height: h),+ control1: svgPoint(x: 38.44859, y: 59.39085, width: w, height: h),+ control2: svgPoint(x: 40.60489, y: 61.5471, width: w, height: h)+ )+ path.addLine(to: svgPoint(x: 48.96809, y: 88.863, width: w, height: h))+ path.addCurve(+ to: svgPoint(x: 65.31209, y: 89.54269, width: w, height: h),+ control1: svgPoint(x: 51.36649, y: 96.6911, width: w, height: h),+ control2: svgPoint(x: 62.27309, y: 97.1442, width: w, height: h)+ )+ path.addLine(to: svgPoint(x: 94.35509, y: 16.90969, width: w, height: h))+ path.addCurve(+ to: svgPoint(x: 83.08209, y: 5.63669, width: w, height: h),+ control1: svgPoint(x: 97.18709, y: 9.83159, width: w, height: h),+ control2: svgPoint(x: 90.15979, y: 2.80769, width: w, height: h)+ )+ path.closeSubpath()++ return path+ }++ private func svgPoint(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) -> CGPoint {+ CGPoint(+ x: (100 - x) / 100 * width,+ y: y / 100 * height+ )+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/PointerCoachCursorGuideResolverTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/PointerCoachCursorGuideResolverTests.swiftnew file mode 100644index 00000000..03c02487--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/PointerCoachCursorGuideResolverTests.swift@@ -0,0 +1,155 @@+import DonkeyAI+import DonkeyContracts+import DonkeyRuntime+import Foundation+import Testing++@Suite+struct PointerCoachCursorGuideResolverTests {+ @Test+ func localLLMResolverBuildsGuideFromStructuredModelOutput() async throws {+ let sidecar = RecordingPointerCoachSidecarRunner(+ result: LocalJSONSidecarResult(+ status: .completed,+ outputData: sidecarResponseData(outputText: """+ {+ "shouldShowGuide": true,+ "title": "Show Export Controls",+ "goal": "export the design",+ "targetApp": "Design App",+ "confidence": 0.91,+ "reason": "The user asked for visual instruction inside an app.",+ "steps": [+ {"label": "Open the export menu", "x": 0.82, "y": 0.18, "travelDuration": 0.4, "holdDuration": 0.8},+ {"label": "Choose the file type", "x": 0.72, "y": 0.36}+ ],+ "metadata": {"modelDecision": "coach"}+ }+ """)+ )+ )+ let resolver = ProcessBackedLocalLLMPointerCoachCursorGuideResolver(+ router: AIModelRouter(registry: registry()),+ sidecarRunner: sidecar+ )++ let result = await resolver.resolveGuide(+ PointerCoachCursorGuideResolverRequest(+ command: "please demonstrate the export flow",+ runtimeCapabilities: ["app_open: open local item"],+ cacheSnippets: ["local_resolution_cache: name=\"Design App\" kind=application"],+ sourceTraceID: "trace-guide"+ )+ )++ let guide = try #require(result.guideRequest)+ #expect(result.confidence == 0.91)+ #expect(result.trace.validationStatus == "guideDecoded")+ #expect(guide.title == "Show Export Controls")+ #expect(guide.metadata["source"] == "local-llm-pointer-coach")+ #expect(guide.metadata["modelDecision"] == "coach")+ #expect(guide.steps.map(\.label) == ["Open the export menu", "Choose the file type"])+ #expect(guide.steps.first?.target.x == 0.82)++ let requests = await sidecar.requests()+ let request = try #require(requests.first)+ #expect(request.environmentVariableName == "DONKEY_LOCAL_LLM_RUNNER")+ #expect(request.metadata["sidecar.role"] == "pointerCoachCursorGuide")+ let input = try JSONDecoder().decode(PointerCoachSidecarInputProbe.self, from: request.inputData)+ #expect(input.command == "please demonstrate the export flow")+ #expect(input.runtimeCapabilities == ["app_open: open local item"])+ #expect(input.cacheSnippets == ["local_resolution_cache: name=\"Design App\" kind=application"])+ #expect(input.metadata["schemaID"] == ProcessBackedLocalLLMPointerCoachCursorGuideResolver.schemaID)+ }++ @Test+ func localLLMResolverDoesNotCreateGuideWhenModelSaysNo() async throws {+ let sidecar = RecordingPointerCoachSidecarRunner(+ result: LocalJSONSidecarResult(+ status: .completed,+ outputData: sidecarResponseData(outputText: """+ {+ "shouldShowGuide": false,+ "title": null,+ "goal": null,+ "targetApp": null,+ "confidence": 0.88,+ "reason": "This is an actionable app command, not a visual coaching request.",+ "steps": []+ }+ """)+ )+ )+ let resolver = ProcessBackedLocalLLMPointerCoachCursorGuideResolver(+ router: AIModelRouter(registry: registry()),+ sidecarRunner: sidecar+ )++ let result = await resolver.resolveGuide(+ PointerCoachCursorGuideResolverRequest(+ command: "show me the weather for SF",+ sourceTraceID: "trace-no-guide"+ )+ )++ #expect(result.guideRequest == nil)+ #expect(result.confidence == 0.88)+ #expect(result.trace.validationStatus == "notGuide")+ }++ private func registry() -> AIModelRegistry {+ AIModelRegistry(+ entries: [+ AIModelRegistryEntry(+ id: "local-guide-test",+ role: .taskIntent,+ provider: .localRuntime,+ modelID: "local-guide-model",+ endpoint: URL(string: "local://guide")!,+ capabilities: [.textInput, .structuredOutputs],+ timeoutMS: 1_000,+ promptVersion: "pointer-coach-test",+ evalStatus: .candidate,+ docsURL: URL(string: "https://example.test/model")!+ )+ ]+ )+ }++ private func sidecarResponseData(outputText: String) -> Data {+ (try? JSONEncoder().encode(PointerCoachSidecarResponseProbe(+ outputText: outputText,+ metadata: ["sidecar": "test"]+ ))) ?? Data()+ }+}++private actor RecordingPointerCoachSidecarRunner: LocalJSONSidecarRunning {+ private let result: LocalJSONSidecarResult+ private var recordedRequests: [LocalJSONSidecarRequest] = []++ init(result: LocalJSONSidecarResult) {+ self.result = result+ }++ func run(_ request: LocalJSONSidecarRequest) async -> LocalJSONSidecarResult {+ recordedRequests.append(request)+ return result+ }++ func requests() -> [LocalJSONSidecarRequest] {+ recordedRequests+ }+}++private struct PointerCoachSidecarInputProbe: Decodable {+ var command: String+ var runtimeCapabilities: [String]+ var cacheSnippets: [String]+ var metadata: [String: String]+}++private struct PointerCoachSidecarResponseProbe: Encodable {+ var outputText: String+ var metadata: [String: String]+}diff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.mdindex f3626368..ad3284bf 100644--- a/docs/guides/pointer-prompt-overlay.md+++ b/docs/guides/pointer-prompt-overlay.md@@ -9,6 +9,10 @@ quick local-app actions:- Double-tap Command and hold the second press to open the prompt in voice mode.- Show a top-center notch status surface for task progress, recent tasks, follow-up input, file drops, updates, and per-task pause/resume.- 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 Spotlight/`mdfind`, bounded filesystem fallback, and a grep-friendly local resolution cache. 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.+- Handle instructional demonstration turns as visual coaching instead of failed app actions when the local LLM classifies the turn as a guide request and returns structured cursor steps. Donkey presents a transparent overlay with an animated agent cursor, moves it along a curved path, and types short guidance in a label next to the cursor while keeping the real mouse and app input untouched.+- Maintain a background local item cache in Application Support. The cache records resolved and missing lookups, prewarms apps plus common user file folders, stores runtime task definitions, keeps metadata such as kind/path/bundle ID/source/task/action, and passes a bounded set of matching hints into the agent harness memory section for classifier and model consideration.- 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. It may request microphone permission for local waveform capture and voice commands, but it must not capture the screen, synthesize input directly, or require Accessibility permission.@@ -21,7 +25,11 @@ quick local-app actions:- `PointerPromptNotchLayout` is the shared source for notch surface frames, content frames, corner radii, and notch-safe offsets. `canRenderTextInTopRow` describes whether text can draw in the top row, not whether that row exists.- 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.- Voice capture and transcription remain separate. The controller records bounded local audio and publishes levels; transcription uses the Parakeet-only adapter before submitting transcript text through the agent-harness turn path.+- Local item cache prewarming must run off the main actor. The cache file is JSONL so it remains inspectable and searchable with tools such as `grep`, but cache hits must still point to an existing path or bundle before they are used as an execution target. Runtime task definitions are loaded from this cache; Weather, Music, and Preview definitions are benchmark fixtures unless a generated/user-reviewed definition for them is present in the cache.+- For scriptable apps, prefer app-native AppleScript task commands before falling back to Accessibility or keyboard input. Bounded screenshots and local UI understanding may supplement observation/verification according to task metadata, but screenshots remain context evidence and do not directly drive input.+- Visual coaching overlays are non-interactive, non-activating panels. They may point and explain, but they do not synthesize mouse movement, keyboard input, or Accessibility actions.- 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.## Verification@@ -30,6 +38,8 @@ Manually verify:- The notch renders at the top center, respects physical notch safe areas, expands only from visible notch hover, and accepts expanded controls/clicks.- Double-Command release opens a centered focused text prompt; double-Command hold opens voice mode; 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.+- 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 instructional prompts complete as chat/coaching turns and show the animated cursor with typed labels without moving the real pointer.- 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/run-donkey-dev.sh b/scripts/run-donkey-dev.shindex 0aa42a9a..ab0d7e6e 100755--- a/scripts/run-donkey-dev.sh+++ b/scripts/run-donkey-dev.sh@@ -34,9 +34,18 @@ start_logger() {if [ -n "${DONKEY_LOG_CONTAINS:-}" ]; thenlog_args+=(--contains "$DONKEY_LOG_CONTAINS")fi+ if [ "${DONKEY_LOG_ALL:-0}" != "1" ]; then+ log_args+=(--subsystem "${DONKEY_LOG_SUBSYSTEM:-com.donkey.app}")+ elif [ -n "${DONKEY_LOG_SUBSYSTEM:-}" ]; then+ log_args+=(--subsystem "$DONKEY_LOG_SUBSYSTEM")+ fiecho "Tailing Donkey logs..."- "$LOG_SCRIPT" "${log_args[@]}" &+ if [ "${#log_args[@]}" -eq 0 ]; then+ "$LOG_SCRIPT" &+ else+ "$LOG_SCRIPT" "${log_args[@]}" &+ fiLOG_PID="$!"}