Open source CapCut alternative.
TypeScript
Add app harness turn routing
David Lee05ca6d1cd81
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex 23a2b756..68d3c4a9 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -5,6 +5,8 @@ import Foundationstruct PointerPromptCommandHandlingResult: Equatable, Sendable {var status: LocalAppTaskLiveRunStatus+ var threadStatus: PointerPromptTaskStatus+ var routeKind: AppHarnessTurnRouteKindvar summary: Stringvar taskLabel: String?var traceID: String@@ -42,6 +44,7 @@ extension PointerPromptCommandHandling {struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {var catalog: LocalAppTaskCatalog+ var appHarnessRouter: AppHarnessTurnRoutervar localModelResolver: LocalModelTaskIntentResolvervar liveRunner: LocalAppTaskLiveRunnervar redactor: AIHarnessRedactor@@ -59,6 +62,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {targetMemoryStore: TargetMemoryJSONLStore? = try? TargetMemoryJSONLStore()) {self.catalog = catalog+ self.appHarnessRouter = AppHarnessTurnRouter(catalog: catalog)self.coordinatorRegistry = coordinatorRegistryself.localModelResolver = localModelResolver ?? LocalModelTaskIntentResolver(catalog: catalog)self.liveRunner = liveRunner ?? LocalAppTaskLiveRunner(catalog: catalog)@@ -73,10 +77,56 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {) async -> PointerPromptCommandHandlingResult {let traceID = "pointer-prompt-\(UUID().uuidString)"let taskID = context?.task.id ?? traceID+ let routing = appHarnessRouter.route(+ request: Self.harnessRequest(command: command, context: context),+ traceID: traceID+ )+ switch routing.outcome.kind {+ case .conversation, .assistantResponse:+ return PointerPromptCommandHandlingResult(+ status: .completed,+ threadStatus: .chatting,+ routeKind: routing.outcome.kind,+ summary: routing.outcome.assistantResponse ?? "Tell me what local app task you want to work on.",+ taskLabel: nil,+ traceID: traceID,+ metadata: Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome),+ documentReviewRequest: nil+ )+ case .clarification:+ return PointerPromptCommandHandlingResult(+ status: .needsConfirmation,+ threadStatus: .waitingForClarification,+ routeKind: routing.outcome.kind,+ summary: routing.outcome.assistantResponse ?? "What detail should I use?",+ taskLabel: nil,+ traceID: traceID,+ metadata: Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome),+ documentReviewRequest: nil+ )+ case .noOp:+ return PointerPromptCommandHandlingResult(+ status: .completed,+ threadStatus: .chatting,+ routeKind: routing.outcome.kind,+ summary: "",+ taskLabel: nil,+ traceID: traceID,+ metadata: Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome),+ documentReviewRequest: nil+ )+ case .actionableIntent, .review, .execution, .failure:+ break+ }+let coordinator = await coordinatorRegistry.coordinator(for: taskID)var taskLiveRunner = liveRunnertaskLiveRunner.coordinator = coordinator- let modelCommand = Self.modelCommand(for: command, context: context)+ let modelCommand = Self.modelCommand(+ for: command,+ context: context,+ contextPacket: routing.contextPacket+ )let redaction = redactor.redact(modelCommand, surface: .modelContext)let memoryProposalDecisions = (try? ProviderDecodedMemoryProposalHandler.decisions(from: Data("[]".utf8),@@ -100,6 +150,9 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {traceID: traceID,resolution: resolution,metadata: [+ "appHarness.route": routing.outcome.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,@@ -130,10 +183,14 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {let handlingResult = PointerPromptCommandHandlingResult(status: result.status,+ threadStatus: threadStatus(for: result),+ routeKind: routing.outcome.kind,summary: summary(for: result),taskLabel: taskLabel(for: result),traceID: traceID,- metadata: result.metadata,+ metadata: result.metadata.merging(+ Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome)+ ) { current, _ in current },documentReviewRequest: documentReviewRequest(traceID: traceID,result: result@@ -234,6 +291,19 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {}}+ private func threadStatus(for result: LocalAppTaskLiveRunResult) -> PointerPromptTaskStatus {+ switch result.status {+ case .completed:+ return .completed+ case .needsUserReview:+ return .waitingForReview+ case .needsConfirmation, .unsupportedCommand:+ return .waitingForClarification+ case .appUnavailable, .failedSafe:+ return .failed+ }+ }+private func taskLabel(for result: LocalAppTaskLiveRunResult) -> String? {guard result.status == .completed || result.status == .needsUserReview,let definition = result.resolution.definition@@ -280,30 +350,55 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {private static func modelCommand(for command: String,- context: PointerPromptCommandContext?+ context: PointerPromptCommandContext?,+ contextPacket: AppHarnessContextPacket) -> String {- guard let context, context.isFollowUp else { return command }-- let events = context.recentEvents- .suffix(8)- .map { "\($0.role.rawValue): \($0.text)" }- .joined(separator: "\n")- let assets = context.assets- .suffix(8)- .map { "\($0.displayName) (\($0.contentType))" }- .joined(separator: ", ")+ guard let context, context.isFollowUp else {+ return contextPacket.currentTurn.text+ }+return ["Existing task title: \(context.task.title)","Existing task original request: \(context.task.commandText)","Existing task status: \(context.task.status.rawValue)",- events.isEmpty ? nil : "Recent task thread:\n\(events)",- assets.isEmpty ? nil : "Task assets: \(assets)",- "Latest user follow-up: \(command)"+ contextPacket.promptText].compactMap(\.self).joined(separator: "\n\n")}+ private static func harnessRequest(+ command: String,+ context: PointerPromptCommandContext?+ ) -> AppHarnessTurnRequest {+ AppHarnessTurnRequest(+ turn: AppHarnessTurn(+ text: command,+ source: context?.isFollowUp == true ? .followUp : .typedPrompt,+ taskID: context?.task.id,+ isFollowUp: context?.isFollowUp ?? false+ ),+ recentEvents: context?.recentEvents ?? [],+ assets: context?.assets ?? [],+ policy: ["localInput": "guarded"]+ )+ }++ private static func contextPacketMetadata(+ _ packet: AppHarnessContextPacket,+ outcome: AppHarnessRoutingOutcome+ ) -> [String: String] {+ [+ "appHarness.route": outcome.kind.rawValue,+ "appHarness.missingDetail": outcome.missingDetail ?? "",+ "appHarness.context.traceID": packet.traceID,+ "appHarness.context.eventCount": String(packet.recentEvents.count),+ "appHarness.context.assetCount": String(packet.assets.count),+ "appHarness.context.promptCharacters": String(packet.promptText.count),+ "appHarness.context.redactionCount": String(packet.redactionCount)+ ]+ }+private static func contextMetadata(_ context: PointerPromptCommandContext?) -> [String: String] {guard let context else { return [:] }diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swiftindex b2d5601c..e26ff948 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift@@ -511,14 +511,7 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink}private static func taskStatus(for result: PointerPromptCommandHandlingResult) -> PointerPromptTaskStatus {- switch result.status {- case .completed:- return .completed- case .needsUserReview, .needsConfirmation, .unsupportedCommand:- return .needsAttention- case .appUnavailable, .failedSafe:- return .failed- }+ result.threadStatus}private static func nextAccentIndex(after currentIndex: Int) -> Int {diff --git a/apps/Donkey/Sources/DonkeyContracts/AppHarnessContracts.swift b/apps/Donkey/Sources/DonkeyContracts/AppHarnessContracts.swiftnew file mode 100644index 00000000..9c552d03--- /dev/null+++ b/apps/Donkey/Sources/DonkeyContracts/AppHarnessContracts.swift@@ -0,0 +1,108 @@+import Foundation++public enum AppHarnessTurnSource: String, Codable, Equatable, Sendable {+ case typedPrompt+ case voiceTranscript+ case followUp+ case assetEvent+}++public enum AppHarnessTurnRouteKind: String, Codable, Equatable, Sendable {+ case conversation+ case clarification+ case actionableIntent+ case review+ case execution+ case failure+ case assistantResponse+ case noOp+}++public struct AppHarnessTurn: Codable, Equatable, Sendable {+ public var id: String+ public var text: String+ public var source: AppHarnessTurnSource+ public var taskID: String?+ public var isFollowUp: Bool+ public var createdAt: Date++ public init(+ id: String = UUID().uuidString,+ text: String,+ source: AppHarnessTurnSource,+ taskID: String? = nil,+ isFollowUp: Bool = false,+ createdAt: Date = Date()+ ) {+ self.id = id+ self.text = text+ self.source = source+ self.taskID = taskID+ self.isFollowUp = isFollowUp+ self.createdAt = createdAt+ }+}++public struct AppHarnessContextEvent: Codable, Equatable, Sendable {+ public var role: PointerPromptTaskEventRole+ public var text: String+ public var sequence: Int++ public init(role: PointerPromptTaskEventRole, text: String, sequence: Int) {+ self.role = role+ self.text = text+ self.sequence = sequence+ }+}++public struct AppHarnessContextAsset: Codable, Equatable, Sendable {+ public var displayName: String+ public var contentType: String+ public var byteCount: Int64?++ public init(displayName: String, contentType: String, byteCount: Int64? = nil) {+ self.displayName = displayName+ self.contentType = contentType+ self.byteCount = byteCount+ }+}++public struct AppHarnessContextPacket: Codable, Equatable, Sendable {+ public var traceID: String+ public var currentTurn: AppHarnessTurn+ public var recentEvents: [AppHarnessContextEvent]+ public var assets: [AppHarnessContextAsset]+ public var runtimeCapabilities: [String]+ public var targetState: [String: String]+ public var memory: [String]+ public var policy: [String: String]+ public var promptText: String+ public var redactionCount: Int+ public var metadata: [String: String]++ public init(+ traceID: String,+ currentTurn: AppHarnessTurn,+ recentEvents: [AppHarnessContextEvent] = [],+ assets: [AppHarnessContextAsset] = [],+ runtimeCapabilities: [String] = [],+ targetState: [String: String] = [:],+ memory: [String] = [],+ policy: [String: String] = [:],+ promptText: String,+ redactionCount: Int = 0,+ metadata: [String: String] = [:]+ ) {+ self.traceID = traceID+ self.currentTurn = currentTurn+ self.recentEvents = recentEvents+ self.assets = assets+ self.runtimeCapabilities = runtimeCapabilities+ self.targetState = targetState+ self.memory = memory+ self.policy = policy+ self.promptText = promptText+ self.redactionCount = redactionCount+ self.metadata = metadata+ }+}diff --git a/apps/Donkey/Sources/DonkeyContracts/PointerPromptTaskContracts.swift b/apps/Donkey/Sources/DonkeyContracts/PointerPromptTaskContracts.swiftindex 2fc37a28..c6bc9454 100644--- a/apps/Donkey/Sources/DonkeyContracts/PointerPromptTaskContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/PointerPromptTaskContracts.swift@@ -1,9 +1,12 @@import Foundationpublic enum PointerPromptTaskStatus: String, Codable, Equatable, Sendable {+ case chattingcase runningcase pausedcase completed+ case waitingForClarification+ case waitingForReviewcase needsAttentioncase failed}diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swiftnew file mode 100644index 00000000..70d3d0df--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift@@ -0,0 +1,406 @@+import DonkeyContracts+import Foundation++public struct AppHarnessContextPacketLimits: Equatable, Sendable {+ public var maxRecentEvents: Int+ public var maxAssets: Int+ public var maxEventTextCharacters: Int+ public var maxAssetNameCharacters: Int+ public var maxMemoryItems: Int+ public var maxMemoryTextCharacters: Int+ public var maxPromptCharacters: Int++ public init(+ maxRecentEvents: Int = 8,+ maxAssets: Int = 8,+ maxEventTextCharacters: Int = 360,+ maxAssetNameCharacters: Int = 120,+ maxMemoryItems: Int = 4,+ maxMemoryTextCharacters: Int = 360,+ maxPromptCharacters: Int = 3_200+ ) {+ self.maxRecentEvents = max(0, maxRecentEvents)+ self.maxAssets = max(0, maxAssets)+ self.maxEventTextCharacters = max(40, maxEventTextCharacters)+ self.maxAssetNameCharacters = max(24, maxAssetNameCharacters)+ self.maxMemoryItems = max(0, maxMemoryItems)+ self.maxMemoryTextCharacters = max(40, maxMemoryTextCharacters)+ self.maxPromptCharacters = max(240, maxPromptCharacters)+ }+}++public struct AppHarnessTurnRequest: Equatable, Sendable {+ public var turn: AppHarnessTurn+ public var recentEvents: [PointerPromptTaskEvent]+ public var assets: [PointerPromptTaskAsset]+ public var targetState: [String: String]+ public var memory: [String]+ public var policy: [String: String]++ public init(+ turn: AppHarnessTurn,+ recentEvents: [PointerPromptTaskEvent] = [],+ assets: [PointerPromptTaskAsset] = [],+ targetState: [String: String] = [:],+ memory: [String] = [],+ policy: [String: String] = [:]+ ) {+ self.turn = turn+ self.recentEvents = recentEvents+ self.assets = assets+ self.targetState = targetState+ self.memory = memory+ self.policy = policy+ }+}++public struct AppHarnessRoutingOutcome: Equatable, Sendable {+ public var kind: AppHarnessTurnRouteKind+ public var assistantResponse: String?+ public var missingDetail: String?+ public var resolution: LocalAppTaskCatalogResolution?+ public var metadata: [String: String]++ public init(+ kind: AppHarnessTurnRouteKind,+ assistantResponse: String? = nil,+ missingDetail: String? = nil,+ resolution: LocalAppTaskCatalogResolution? = nil,+ metadata: [String: String] = [:]+ ) {+ self.kind = kind+ self.assistantResponse = assistantResponse+ self.missingDetail = missingDetail+ self.resolution = resolution+ self.metadata = metadata+ }+}++public struct AppHarnessRoutingResult: Equatable, Sendable {+ public var contextPacket: AppHarnessContextPacket+ public var outcome: AppHarnessRoutingOutcome++ public init(contextPacket: AppHarnessContextPacket, outcome: AppHarnessRoutingOutcome) {+ self.contextPacket = contextPacket+ self.outcome = outcome+ }+}++public struct AppHarnessContextPacketBuilder: Sendable {+ public var limits: AppHarnessContextPacketLimits++ public init(limits: AppHarnessContextPacketLimits = AppHarnessContextPacketLimits()) {+ self.limits = limits+ }++ public func build(+ request: AppHarnessTurnRequest,+ catalog: LocalAppTaskCatalog,+ traceID: String+ ) -> AppHarnessContextPacket {+ var redactionCount = 0+ var turn = request.turn+ let redactedTurn = Self.redacted(turn.text)+ redactionCount += redactedTurn.count+ turn.text = Self.truncated(redactedTurn.text, maxLength: limits.maxPromptCharacters)++ let events = request.recentEvents+ .suffix(limits.maxRecentEvents)+ .map { event in+ let redacted = Self.redacted(event.text)+ redactionCount += redacted.count+ return AppHarnessContextEvent(+ role: event.role,+ text: Self.truncated(redacted.text, maxLength: limits.maxEventTextCharacters),+ sequence: event.sequence+ )+ }++ let assets = request.assets+ .suffix(limits.maxAssets)+ .map { asset in+ AppHarnessContextAsset(+ displayName: Self.truncated(asset.displayName, maxLength: limits.maxAssetNameCharacters),+ contentType: asset.contentType,+ byteCount: asset.byteCount+ )+ }++ let memory = request.memory+ .prefix(limits.maxMemoryItems)+ .map { item -> String in+ let redacted = Self.redacted(item)+ redactionCount += redacted.count+ return Self.truncated(redacted.text, maxLength: limits.maxMemoryTextCharacters)+ }++ let runtimeCapabilities = catalog.taskDefinitions+ .map { "\($0.taskType):\($0.targetApp.appName)" }+ .sorted()+ let promptText = Self.truncated(+ Self.promptText(+ turn: turn,+ events: events,+ assets: assets,+ runtimeCapabilities: runtimeCapabilities,+ targetState: request.targetState,+ memory: memory,+ policy: request.policy+ ),+ maxLength: limits.maxPromptCharacters+ )++ return AppHarnessContextPacket(+ traceID: traceID,+ currentTurn: turn,+ recentEvents: events,+ assets: assets,+ runtimeCapabilities: runtimeCapabilities,+ targetState: request.targetState,+ memory: memory,+ policy: request.policy,+ promptText: promptText,+ redactionCount: redactionCount,+ metadata: [+ "bounds.maxRecentEvents": String(limits.maxRecentEvents),+ "bounds.maxAssets": String(limits.maxAssets),+ "bounds.maxPromptCharacters": String(limits.maxPromptCharacters),+ "events.includedCount": String(events.count),+ "assets.includedCount": String(assets.count),+ "memory.includedCount": String(memory.count),+ "prompt.characterCount": String(promptText.count)+ ]+ )+ }++ private static func promptText(+ turn: AppHarnessTurn,+ events: [AppHarnessContextEvent],+ assets: [AppHarnessContextAsset],+ runtimeCapabilities: [String],+ targetState: [String: String],+ memory: [String],+ policy: [String: String]+ ) -> String {+ var sections = [+ "Trace: \(turn.id)",+ "Turn source: \(turn.source.rawValue)",+ "Current turn: \(turn.text)"+ ]+ if !events.isEmpty {+ sections.append("Recent thread:\n" + events.map { "\($0.role.rawValue): \($0.text)" }.joined(separator: "\n"))+ }+ if !assets.isEmpty {+ sections.append("Assets: " + assets.map { "\($0.displayName) (\($0.contentType))" }.joined(separator: ", "))+ }+ if !runtimeCapabilities.isEmpty {+ sections.append("Runtime capabilities: " + runtimeCapabilities.joined(separator: ", "))+ }+ if !targetState.isEmpty {+ sections.append("Target state: " + keyValueText(targetState))+ }+ if !memory.isEmpty {+ sections.append("Memory:\n" + memory.joined(separator: "\n"))+ }+ if !policy.isEmpty {+ sections.append("Policy: " + keyValueText(policy))+ }+ return sections.joined(separator: "\n\n")+ }++ private static func keyValueText(_ values: [String: String]) -> String {+ values+ .sorted { $0.key < $1.key }+ .map { "\($0.key)=\($0.value)" }+ .joined(separator: ", ")+ }++ private static func redacted(_ text: String) -> (text: String, count: Int) {+ var redacted = text+ var count = 0+ let replacements = [+ #"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}"#: "[redacted-email]",+ #"\b(?:\d[ -]*?){13,16}\b"#: "[redacted-number]",+ #"(?i)(password|token|api[_ -]?key)\s*[:=]\s*\S+"#: "$1=[redacted-secret]"+ ]+ for (pattern, replacement) in replacements {+ guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else {+ continue+ }+ let range = NSRange(redacted.startIndex..<redacted.endIndex, in: redacted)+ count += regex.numberOfMatches(in: redacted, range: range)+ redacted = regex.stringByReplacingMatches(+ in: redacted,+ options: [],+ range: range,+ withTemplate: replacement+ )+ }+ return (redacted, count)+ }++ private static func truncated(_ text: String, maxLength: Int) -> String {+ guard text.count > maxLength else { return text }++ let endIndex = text.index(text.startIndex, offsetBy: maxLength)+ return String(text[..<endIndex]).trimmingCharacters(in: .whitespacesAndNewlines) + "..."+ }+}++public struct AppHarnessTurnRouter: Sendable {+ public var catalog: LocalAppTaskCatalog+ public var contextBuilder: AppHarnessContextPacketBuilder++ public init(+ catalog: LocalAppTaskCatalog,+ contextBuilder: AppHarnessContextPacketBuilder = AppHarnessContextPacketBuilder()+ ) {+ self.catalog = catalog+ self.contextBuilder = contextBuilder+ }++ public func route(+ request: AppHarnessTurnRequest,+ traceID: String+ ) -> AppHarnessRoutingResult {+ let packet = contextBuilder.build(+ request: request,+ catalog: catalog,+ traceID: traceID+ )+ let trimmedText = request.turn.text.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmedText.isEmpty else {+ return AppHarnessRoutingResult(+ contextPacket: packet,+ outcome: AppHarnessRoutingOutcome(kind: .noOp)+ )+ }++ let deterministicResolution = catalog.resolve(command: trimmedText)+ switch deterministicResolution.status {+ case .resolved:+ return AppHarnessRoutingResult(+ contextPacket: packet,+ outcome: AppHarnessRoutingOutcome(+ kind: .actionableIntent,+ resolution: deterministicResolution,+ metadata: ["router": "deterministicCatalog"]+ )+ )+ case .needsConfirmation:+ let missingDetail = deterministicResolution.metadata["reason"] ?? "detail"+ return AppHarnessRoutingResult(+ contextPacket: packet,+ outcome: AppHarnessRoutingOutcome(+ kind: .clarification,+ assistantResponse: clarificationPrompt(for: missingDetail, resolution: deterministicResolution),+ missingDetail: missingDetail,+ resolution: deterministicResolution,+ metadata: ["router": "deterministicCatalog"]+ )+ )+ case .appUnavailable:+ return AppHarnessRoutingResult(+ contextPacket: packet,+ outcome: AppHarnessRoutingOutcome(+ kind: .actionableIntent,+ resolution: deterministicResolution,+ metadata: ["router": "deterministicCatalog"]+ )+ )+ case .unsupportedCommand:+ break+ }++ if request.turn.isFollowUp && !Self.isConversational(trimmedText) {+ return AppHarnessRoutingResult(+ contextPacket: packet,+ outcome: AppHarnessRoutingOutcome(+ kind: .actionableIntent,+ resolution: deterministicResolution,+ metadata: ["router": "followUpActionContext"]+ )+ )+ }++ if Self.isConversational(trimmedText) {+ return AppHarnessRoutingResult(+ contextPacket: packet,+ outcome: AppHarnessRoutingOutcome(+ kind: .conversation,+ assistantResponse: conversationResponse(for: trimmedText),+ metadata: ["router": "conversationRules"]+ )+ )+ }++ return AppHarnessRoutingResult(+ contextPacket: packet,+ outcome: AppHarnessRoutingOutcome(+ kind: .clarification,+ assistantResponse: "What would you like Donkey to do?",+ missingDetail: "actionable request",+ resolution: deterministicResolution,+ metadata: ["router": "unsupportedClarification"]+ )+ )+ }++ private func conversationResponse(for text: String) -> String {+ let normalized = LocalAppTaskIntentParser.normalizedPhrase(text)+ if normalized.contains("what can") || normalized.contains("help") || normalized.contains("capabil") {+ let examples = catalog.taskDefinitions+ .map { $0.taskType.split(separator: "_").joined(separator: " ") }+ .sorted()+ .joined(separator: ", ")+ return examples.isEmpty+ ? "I can keep a task thread going and ask for details before taking action."+ : "I can keep a task thread going, ask for missing details, and run supported local tasks such as \(examples)."+ }++ return "Hi. Tell me what local app task you want to work on."+ }++ private func clarificationPrompt(+ for missingDetail: String,+ resolution: LocalAppTaskCatalogResolution+ ) -> String {+ switch missingDetail {+ case "city":+ return "Which city should I use?"+ case "query":+ return "What should I play?"+ case "document":+ return "Which document should I use?"+ default:+ if let taskType = resolution.definition?.taskType.split(separator: "_").joined(separator: " ") {+ return "What \(missingDetail) should I use for \(taskType)?"+ }+ return "What \(missingDetail) should I use?"+ }+ }++ private static func isConversational(_ text: String) -> Bool {+ let normalized = LocalAppTaskIntentParser.normalizedPhrase(text)+ let greetings: Set<String> = [+ "hi",+ "hello",+ "hey",+ "good morning",+ "good afternoon",+ "good evening",+ "thanks",+ "thank you"+ ]+ if greetings.contains(normalized) {+ return true+ }++ return normalized.contains("what can you do")+ || normalized.contains("what can donkey do")+ || normalized.contains("help")+ || normalized.contains("capabilities")+ || normalized.contains("how does donkey work")+ || normalized.contains("who are you")+ }+}diff --git a/apps/Donkey/Sources/DonkeyUI/PointerPromptNotchStatusView.swift b/apps/Donkey/Sources/DonkeyUI/PointerPromptNotchStatusView.swiftindex a3f43931..4134d140 100644--- a/apps/Donkey/Sources/DonkeyUI/PointerPromptNotchStatusView.swift+++ b/apps/Donkey/Sources/DonkeyUI/PointerPromptNotchStatusView.swift@@ -530,6 +530,11 @@ public struct PointerPromptNotchStatusView: View {@ViewBuilderprivate func taskStatusAccessory(_ task: PointerPromptNotchTask) -> some View {switch task.status {+ case .chatting:+ Image(systemName: "text.bubble")+ .font(.system(size: 11, weight: .regular))+ .foregroundStyle(accentColor(for: task.accentIndex))+ .frame(width: 18, height: 18)case .running:activityBars(color: accentColor(for: task.accentIndex))case .paused:@@ -542,6 +547,16 @@ public struct PointerPromptNotchStatusView: View {.font(.system(size: 11, weight: .regular)).foregroundStyle(accentColor(for: task.accentIndex)).frame(width: 18, height: 18)+ case .waitingForClarification:+ Image(systemName: "questionmark")+ .font(.system(size: 12, weight: .regular))+ .foregroundStyle(Color.white.opacity(0.62))+ .frame(width: 18, height: 18)+ case .waitingForReview:+ Image(systemName: "doc.text.magnifyingglass")+ .font(.system(size: 11, weight: .regular))+ .foregroundStyle(Color.white.opacity(0.62))+ .frame(width: 18, height: 18)case .needsAttention:Image(systemName: "exclamationmark").font(.system(size: 12, weight: .regular))@@ -596,12 +611,18 @@ public struct PointerPromptNotchStatusView: View {private var compactTopRowStatusText: String {if let primaryTask {switch primaryTask.status {+ case .chatting:+ return "Chat"case .running:return "Run"case .paused:return "Hld"case .completed:return "Done"+ case .waitingForClarification:+ return "Ask"+ case .waitingForReview:+ return "Rev"case .needsAttention:return "Ask"case .failed:@@ -662,12 +683,18 @@ public struct PointerPromptNotchStatusView: View {private func taskStatusDescription(_ task: PointerPromptNotchTask) -> String {switch task.status {+ case .chatting:+ return task.detail.isEmpty ? "Conversation" : task.detailcase .running:return task.detail.isEmpty ? "Running" : task.detailcase .paused:return "Paused"case .completed:return task.detail.isEmpty ? "Done" : task.detail+ case .waitingForClarification:+ return task.detail.isEmpty ? "Waiting for detail" : task.detail+ case .waitingForReview:+ return task.detail.isEmpty ? "Waiting for review" : task.detailcase .needsAttention:return task.detail.isEmpty ? "Needs attention" : task.detailcase .failed:diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swiftnew file mode 100644index 00000000..9375e37e--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift@@ -0,0 +1,139 @@+import DonkeyContracts+import DonkeyRuntime+import Testing++@Suite+struct AppHarnessTurnRouterTests {+ @Test+ func greetingRoutesToConversationWithoutTaskExecution() {+ let result = router().route(+ request: AppHarnessTurnRequest(+ turn: AppHarnessTurn(text: "hi", source: .typedPrompt)+ ),+ traceID: "trace-chat"+ )++ #expect(result.outcome.kind == .conversation)+ #expect(result.outcome.resolution == nil)+ #expect(result.outcome.assistantResponse?.contains("local app task") == true)+ }++ @Test+ func actionableWeatherRequestRoutesThroughCatalog() {+ let result = router().route(+ request: AppHarnessTurnRequest(+ turn: AppHarnessTurn(text: "show me the weather for SF", source: .typedPrompt)+ ),+ traceID: "trace-action"+ )++ #expect(result.outcome.kind == .actionableIntent)+ #expect(result.outcome.resolution?.status == .resolved)+ #expect(result.outcome.resolution?.intent?.normalizedEntities["city"] == "San Francisco")+ }++ @Test+ func ambiguousWeatherRequestAsksForSpecificMissingDetail() {+ let result = router().route(+ request: AppHarnessTurnRequest(+ turn: AppHarnessTurn(text: "show weather", source: .typedPrompt)+ ),+ traceID: "trace-clarify"+ )++ #expect(result.outcome.kind == .clarification)+ #expect(result.outcome.missingDetail == "city")+ #expect(result.outcome.assistantResponse == "Which city should I use?")+ }++ @Test+ func followUpTurnKeepsRecentThreadContextBoundedAndRedacted() {+ let limits = AppHarnessContextPacketLimits(+ maxRecentEvents: 2,+ maxAssets: 1,+ maxEventTextCharacters: 64,+ maxAssetNameCharacters: 32,+ maxPromptCharacters: 420+ )+ let result = router(limits: limits).route(+ request: AppHarnessTurnRequest(+ turn: AppHarnessTurn(+ text: "use token=secret123 and [email protected]",+ source: .followUp,+ taskID: "task-1",+ isFollowUp: true+ ),+ recentEvents: [+ PointerPromptTaskEvent(+ id: "event-1",+ taskID: "task-1",+ role: .user,+ text: "older event should be excluded",+ sequence: 0+ ),+ PointerPromptTaskEvent(+ id: "event-2",+ taskID: "task-1",+ role: .assistant,+ text: "contact me at [email protected]",+ sequence: 1+ ),+ PointerPromptTaskEvent(+ id: "event-3",+ taskID: "task-1",+ role: .user,+ text: String(repeating: "long ", count: 80),+ sequence: 2+ )+ ],+ assets: [+ PointerPromptTaskAsset(+ id: "asset-1",+ taskID: "task-1",+ source: .userUploaded,+ displayName: "old.pdf",+ contentType: "application/pdf",+ urlString: "file:///tmp/old.pdf"+ ),+ PointerPromptTaskAsset(+ id: "asset-2",+ taskID: "task-1",+ source: .userUploaded,+ displayName: "current-document-with-a-very-long-name.pdf",+ contentType: "application/pdf",+ urlString: "file:///tmp/current.pdf"+ )+ ]+ ),+ traceID: "trace-context"+ )++ #expect(result.contextPacket.recentEvents.count == 2)+ #expect(result.contextPacket.assets.count == 1)+ #expect(result.contextPacket.promptText.count <= 423)+ #expect(!result.contextPacket.promptText.contains("[email protected]"))+ #expect(!result.contextPacket.promptText.contains("[email protected]"))+ #expect(!result.contextPacket.promptText.contains("secret123"))+ #expect(result.contextPacket.promptText.contains("[redacted-email]"))+ #expect(result.contextPacket.promptText.contains("[redacted-secret]"))+ #expect(result.contextPacket.redactionCount == 3)+ }++ private func router(+ limits: AppHarnessContextPacketLimits = AppHarnessContextPacketLimits()+ ) -> AppHarnessTurnRouter {+ AppHarnessTurnRouter(+ catalog: LocalAppTaskCatalog(+ taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,+ availabilityProvider: StaticLocalAppAvailabilityProvider(+ installedBundleIdentifiers: [+ "com.apple.weather",+ "com.apple.Music",+ "com.adobe.Reader"+ ]+ )+ ),+ contextBuilder: AppHarnessContextPacketBuilder(limits: limits)+ )+ }+}diff --git a/plans/master-plan.md b/plans/master-plan.mdindex 86f10117..f2d24b19 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -28,3 +28,5 @@ No active implementation tasks.- Completed behavior belongs in `docs/`, not in active plans.- Plans should stay brief and represent remaining work.- Runtime, input, and latency claims should be tied to verifiable local traces.+- Task threads are conversations first; action execution is a routed outcome of+ the app harness, not the default meaning of every prompt turn.