Open source CapCut alternative.
TypeScript
feat(app): answer conversational turns in one round trip
David Le9f749f535151
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex bb4b5fef..68c6d978 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -502,8 +502,24 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// dead-ends or silently stalls the run.let understandingBoundary = HostedHarnessRequestUnderstanding(backend: backend, trace: trace)let skillSelectionCatalog = BuiltInLocalAppSkillPacks.skillSelectionCatalog()++ // A fresh turn — no assistant reply yet in this conversation — lets a `.converse` reply stream+ // straight out of the understanding boundary in ONE round trip: the same call that types the turn+ // also generates the reply, and the field extractor streams it to the chin live. A follow-up may+ // lean on earlier context the understanding boundary never sees, so it uses the non-streaming+ // understanding and routes any converse reply through the context-aware responder below.+ let priorEvents = await genericHarnessLifecycle.conversationStore.events(conversationID: conversationID)+ let isFreshTurn = !priorEvents.contains { $0.role == .assistant }let understanding = await AIDeadline.race(seconds: Self.understandingTimeoutSeconds) {- await understandingBoundary.understand(+ if isFreshTurn {+ return await understandingBoundary.understandStreaming(+ command: command,+ frontmostAppName: frontmostAppName,+ skillCatalog: skillSelectionCatalog,+ onReplyDelta: answerStream ?? { _ in }+ )+ }+ return await understandingBoundary.understand(command: command,frontmostAppName: frontmostAppName,skillCatalog: skillSelectionCatalog@@ -527,6 +543,8 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {conversationID: conversationID,agentID: agentID,preparedTurnMetadata: preparedTurnMetadata,+ inlineReply: understanding?.conversationReply,+ inlineReplyAlreadyStreamed: isFreshTurn,answerStream: answerStream)}@@ -1161,30 +1179,40 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {conversationID: String,agentID: String,preparedTurnMetadata: [String: String],+ inlineReply: String?,+ inlineReplyAlreadyStreamed: Bool,answerStream: (@MainActor @Sendable (String) -> Void)?) async -> UserQueryCommandHandlingResult {transcript.systemEvent("Conversational turn — responding without driving the Mac.")VisionGroundingLog.emit("conversation traceID=\(traceID) kind=converse")- // Carry the same bounded rolling conversation context the planner would get, so multi-turn chat- // keeps continuity ("what did I just ask?") without ever entering the action loop.- let textGenerator = HostedTextGenerator(backend: backend)- let compactionDriver = ConversationCompactionDriver(- conversationStore: genericHarnessLifecycle.conversationStore,- coordinator: genericHarnessLifecycle.coordinator,- compactor: genericHarnessLifecycle.compactor,- generate: { await textGenerator.generate($0) }- )- let conversationContext = await compactionDriver.rollingContext(agentID: agentID)+ // On a fresh turn the understanding boundary already generated AND streamed this reply live (one+ // round trip), so adopt it as-is — re-emitting would double it on screen. A follow-up turn falls to+ // the context-aware responder, which streams a reply that can see the earlier conversation.+ let reply: String+ if let inlineReply, !inlineReply.isEmpty, inlineReplyAlreadyStreamed {+ reply = inlineReply+ } else {+ // Carry the same bounded rolling conversation context the planner would get, so multi-turn chat+ // keeps continuity ("what did I just ask?") without ever entering the action loop.+ let textGenerator = HostedTextGenerator(backend: backend)+ let compactionDriver = ConversationCompactionDriver(+ conversationStore: genericHarnessLifecycle.conversationStore,+ coordinator: genericHarnessLifecycle.coordinator,+ compactor: genericHarnessLifecycle.compactor,+ generate: { await textGenerator.generate($0) }+ )+ let conversationContext = await compactionDriver.rollingContext(agentID: agentID)- let responder = HostedHarnessConversationalResponder(backend: backend, trace: trace)- let streamed = await responder.respond(- command: command,- frontmostAppName: frontmostAppName,- conversationContext: conversationContext,- onDelta: answerStream ?? { _ in }- )- let reply = (streamed?.isEmpty == false) ? streamed! : "Hey! What can I help you with?"+ let responder = HostedHarnessConversationalResponder(backend: backend, trace: trace)+ let streamed = await responder.respond(+ command: command,+ frontmostAppName: frontmostAppName,+ conversationContext: conversationContext,+ onDelta: answerStream ?? { _ in }+ )+ reply = (streamed?.isEmpty == false) ? streamed! : "Hey! What can I help you with?"+ }transcript.response(reply)transcript.writeSummary(Self.deterministicThreadSummary(command: command, app: frontmostAppName, outcome: "ok", steps: [], finalDetail: replydiff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swiftindex a5fc6e31..1a0c980a 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift@@ -13,6 +13,9 @@ final class UserQueryOverlayController {private let microphoneWaveformMeter = MicrophoneWaveformMeter()private let agentVisualizationCursorController = PointerCoachCursorOverlayController()private let spawnOverlayController = UserQuerySpawnOverlayController()+ /// The conversation whose playback the standalone pointer is currently showing, so dismissing that row+ /// can close it. Nil when the pointer is idle or its playback is riding a spawn cursor instead.+ private var agentVisualizationConversationID: String?private var statusPanel: NSPanel?private var statusHostingView: UserQueryHostingView<UserQueryNotchStatusView>?@@ -54,12 +57,16 @@ final class UserQueryOverlayController {) {self.model = modelself.activationShortcut = activationShortcut- model.agentVisualizationPresenter = { [weak self] request, preferredSpawnID in+ model.agentVisualizationPresenter = { [weak self] request, conversationID, preferredSpawnID inself?.presentAgentVisualization(request: request,+ conversationID: conversationID,preferredSpawnID: preferredSpawnID)}+ model.agentVisualizationDismisser = { [weak self] conversationID in+ self?.dismissAgentVisualization(conversationID: conversationID)+ }spawnOverlayController.followUpSubmitted = { [weak self] spawnID, conversationID, text inself?.model.submitSpawnFollowUp(spawnID: spawnID, conversationID: conversationID, text: text)}@@ -761,6 +768,7 @@ final class UserQueryOverlayController {private func presentAgentVisualization(request: PointerCoachCursorGuideRequest,+ conversationID: String,preferredSpawnID: String?) {if spawnOverlayController.playGuide(@@ -768,11 +776,23 @@ final class UserQueryOverlayController {on: preferredSpawnID,screen: activeScreen()) {+ // Playback rode a spawn cursor (removed with its row), so the standalone pointer is idle.agentVisualizationCursorController.close()+ agentVisualizationConversationID = nilreturn}agentVisualizationCursorController.show(request: request)+ agentVisualizationConversationID = conversationID+ }++ /// Close the standalone pointer if it is still showing the dismissed row's playback. A newer row's+ /// playback reuses the same panel and re-keys `agentVisualizationConversationID`, so this only clears the+ /// pointer when it actually belongs to the row being deleted.+ private func dismissAgentVisualization(conversationID: String) {+ guard agentVisualizationConversationID == conversationID else { return }+ agentVisualizationCursorController.close()+ agentVisualizationConversationID = nil}private func updateSpawnOverlay() {diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swiftindex 63690a7c..e3c41a9e 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift@@ -37,7 +37,13 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {/// delegate pushes this from the auth coordinator's session state (true while signed out after a/// prior sign-in, i.e. an expired session) and clears it once sign-in completes.@Published private(set) var needsLogin = false- var agentVisualizationPresenter: ((PointerCoachCursorGuideRequest, String?) -> Void)?+ /// Presents the agent's pointer playback for a conversation. The conversation ID binds the pointer's+ /// lifetime to its row: the controller remembers which conversation a standalone pointer belongs to so+ /// `agentVisualizationDismisser` can tear it down when that row is deleted.+ var agentVisualizationPresenter: ((PointerCoachCursorGuideRequest, _ conversationID: String, _ preferredSpawnID: String?) -> Void)?+ /// Clears any pointer playback still on screen for a conversation. Fired when a row is dismissed so a+ /// standalone pointer never outlives the row it was narrating.+ var agentVisualizationDismisser: ((_ conversationID: String) -> Void)?/// Fired when the notch Login button is tapped, so the app delegate can start the real sign-in/// (the Google browser flow). The model never opens browsers or windows itself.var loginActionRequested: (() -> Void)?@@ -859,7 +865,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {refreshPromptStateAfterRunResult(conversationID: conversationID, result: result)let cursorOverlayRequest = result.cursorOverlayRequestif let cursorOverlayRequest {- agentVisualizationPresenter?(cursorOverlayRequest, spawnID)+ agentVisualizationPresenter?(cursorOverlayRequest, conversationID, spawnID)}finishSpawn(id: spawnID,@@ -1061,6 +1067,10 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {if let spawnID = spawnStates.first(where: { $0.conversationID == conversationID })?.id {removeSpawn(id: spawnID)}+ // Tear down any pointer playback still narrating this row. Spawn cursors are removed above; this+ // covers the standalone pointer overlay, which is keyed by conversation rather than spawn and would+ // otherwise linger after the row is gone.+ agentVisualizationDismisser?(conversationID)// Drop the persisted row (and its events/assets) too, so the conversation does not// reappear when the notch reloads recent conversations on the next launch.conversationStore.deleteConversation(id: conversationID)@@ -1521,7 +1531,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {isFollowUp: isFollowUp,turnSource: source,spawnProgressChanged: runProgressHandler(conversationID: conversationID, spawnID: spawnID),- agentVisualizationChanged: agentVisualizationHandler(for: spawnID)+ agentVisualizationChanged: agentVisualizationHandler(conversationID: conversationID, spawnID: spawnID))}@@ -1576,11 +1586,12 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}private func agentVisualizationHandler(- for spawnID: String?+ conversationID: String,+ spawnID: String?) -> (@MainActor @Sendable (AgentVisualizationPlan) -> Void)? {{ [weak self] plan inguard let request = plan.cursorOverlayRequest() else { return }- self?.agentVisualizationPresenter?(request, spawnID)+ self?.agentVisualizationPresenter?(request, conversationID, spawnID)}}diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swiftindex d31adbb4..d2149bb5 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift@@ -165,6 +165,11 @@ public enum DonkeyPrompts {under (0, 1, or a few — match on each skill's description and keywords). Its full guide is loadedfor the planner, so the right pick makes the work reliable and a wrong one wastes attention. Emptyfor conversation, a task no skill covers, or when no SKILLS list is shown.+ - conversationReply: ONLY when turnKind is "converse", write the actual reply to send the user here —+ the friendly, helpful thing you would say (a greeting back, the answer to their question, etc.),+ in a sentence or three. This is what they will read, so make it complete on its own. When the turn+ is "converse", output this field FIRST in the JSON so it can stream to the user immediately. Leave+ it empty for "act" and "clarify" — those are handled elsewhere.Return JSON only."""diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swiftindex 5312e65a..b567e6db 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift@@ -41,6 +41,12 @@ public struct HarnessRequestUnderstanding: Sendable, Equatable {/// skill's instructions from step one. Empty when no skill applies. Selected by the model against a/// typed catalog, never matched from raw text.public var relevantSkillIDs: [String]+ /// For a `.converse` turn, the actual reply to show the user — produced in this same boundary so a+ /// greeting or simple question is answered in one round trip instead of a second responder call. It is+ /// context-free (this boundary sees only the current turn), so the caller uses it directly only on a+ /// fresh turn and still routes a multi-turn follow-up through the context-aware responder. Empty/nil for+ /// `.act` and `.clarify`.+ public var conversationReply: String?public init(turnKind: HarnessTurnKind = .act,@@ -51,7 +57,8 @@ public struct HarnessRequestUnderstanding: Sendable, Equatable {needsClarification: Bool = false,clarifyingQuestion: String? = nil,executionPreference: ExecutionPreference = .background,- relevantSkillIDs: [String] = []+ relevantSkillIDs: [String] = [],+ conversationReply: String? = nil) {self.turnKind = turnKindself.restatedGoal = restatedGoal@@ -62,6 +69,7 @@ public struct HarnessRequestUnderstanding: Sendable, Equatable {self.clarifyingQuestion = clarifyingQuestionself.executionPreference = executionPreferenceself.relevantSkillIDs = relevantSkillIDs+ self.conversationReply = conversationReply}}@@ -108,24 +116,7 @@ public final class HostedHarnessRequestUnderstanding {recordCall(prompt: prompt, response: text,finishReason: RemoteInferenceResponseHelpers.providerFinishReason(from: response),status: .ok, startedAt: startedAt, endedAt: endedAt)- let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)- let wire = try JSONDecoder().decode(UnderstandingWire.self, from: Data(json.utf8))- let restated = wire.restatedGoal?.trimmingCharacters(in: .whitespacesAndNewlines)- guard let restated, !restated.isEmpty else { return nil }- return HarnessRequestUnderstanding(- turnKind: wire.turnKind.flatMap { HarnessTurnKind(rawValue: $0) } ?? .act,- restatedGoal: restated,- targetAppName: wire.targetAppName.flatMap { $0.isEmpty ? nil : $0 },- parameters: wire.parameters ?? [:],- successCriteria: wire.successCriteria.flatMap { $0.isEmpty ? nil : $0 },- needsClarification: wire.needsClarification ?? false,- clarifyingQuestion: wire.clarifyingQuestion.flatMap { $0.isEmpty ? nil : $0 },- executionPreference: wire.executionPreference- .flatMap { ExecutionPreference(rawValue: $0) } ?? .background,- relevantSkillIDs: (wire.relevantSkillIDs ?? [])- .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }- .filter { !$0.isEmpty }- )+ return Self.decodeUnderstanding(from: text)} catch {recordCall(prompt: prompt, response: String(String(describing: error).prefix(500)),finishReason: nil, status: .failed, startedAt: startedAt, endedAt: .now())@@ -133,6 +124,87 @@ public final class HostedHarnessRequestUnderstanding {}}+ /// Streaming counterpart of `understand`: the SAME typed understanding, but produced by a streaming call+ /// so a `.converse` turn's `conversationReply` types into the UI live — and in ONE round trip. Each delta+ /// is fed to a field extractor that forwards only the decoded `conversationReply` characters to+ /// `onReplyDelta`; the rest of the JSON (the typed decision) streams past untouched and is parsed once the+ /// stream completes. For an `.act`/`.clarify` turn nothing is forwarded (the field stays empty), so this+ /// is safe to use for any fresh turn. Returns nil on any failure, exactly like `understand`.+ public func understandStreaming(+ command: String,+ frontmostAppName: String,+ skillCatalog: String? = nil,+ onReplyDelta: @escaping @MainActor @Sendable (String) -> Void+ ) async -> HarnessRequestUnderstanding? {+ let prompt = DonkeyPrompts.requestUnderstanding(+ command: command,+ frontmostAppName: frontmostAppName,+ skillCatalog: skillCatalog+ )+ let startedAt = RunTraceTimestamp.now()+ let streamer = ReplyFieldStreamer()+ let request = RemoteInferenceChatCompletionRequest(+ messages: [RemoteInferenceChatMessage(role: "user", content: .string(prompt))],+ stream: true,+ metadata: ["source": "hosted-harness-request-understanding", "prompt_version": "harness-request-understanding-v1-stream"],+ parameters: [+ "temperature": .number(0),+ "max_output_tokens": .number(2_500),+ "thinking_level": .string("medium"),+ "response_format": .object(["type": .string("json_object")])+ ]+ )+ let backend = self.backend+ do {+ let text = try await backend.streamChat(request) { delta in+ let reply = streamer.ingest(delta)+ if !reply.isEmpty { onReplyDelta(reply) }+ }+ let endedAt = RunTraceTimestamp.now()+ guard !text.isEmpty else {+ recordCall(prompt: prompt, response: "<no output text>", finishReason: nil,+ status: .empty, startedAt: startedAt, endedAt: endedAt)+ return nil+ }+ recordCall(prompt: prompt, response: text, finishReason: nil,+ status: .ok, startedAt: startedAt, endedAt: endedAt)+ return Self.decodeUnderstanding(from: text)+ } catch {+ recordCall(prompt: prompt, response: String(String(describing: error).prefix(500)),+ finishReason: nil, status: .failed, startedAt: startedAt, endedAt: .now())+ return nil+ }+ }++ /// Decode the model's text (tolerant of surrounding prose via `jsonObjectSubstring`) into the typed+ /// understanding. Shared by the structured and streaming paths so both yield the same shape. Returns nil+ /// when the JSON is unparseable or carries no restated goal.+ private static func decodeUnderstanding(from text: String) -> HarnessRequestUnderstanding? {+ let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)+ guard let wire = try? JSONDecoder().decode(UnderstandingWire.self, from: Data(json.utf8)) else {+ return nil+ }+ let restated = wire.restatedGoal?.trimmingCharacters(in: .whitespacesAndNewlines)+ guard let restated, !restated.isEmpty else { return nil }+ return HarnessRequestUnderstanding(+ turnKind: wire.turnKind.flatMap { HarnessTurnKind(rawValue: $0) } ?? .act,+ restatedGoal: restated,+ targetAppName: wire.targetAppName.flatMap { $0.isEmpty ? nil : $0 },+ parameters: wire.parameters ?? [:],+ successCriteria: wire.successCriteria.flatMap { $0.isEmpty ? nil : $0 },+ needsClarification: wire.needsClarification ?? false,+ clarifyingQuestion: wire.clarifyingQuestion.flatMap { $0.isEmpty ? nil : $0 },+ executionPreference: wire.executionPreference+ .flatMap { ExecutionPreference(rawValue: $0) } ?? .background,+ relevantSkillIDs: (wire.relevantSkillIDs ?? [])+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }+ .filter { !$0.isEmpty },+ conversationReply: wire.conversationReply+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }+ .flatMap { $0.isEmpty ? nil : $0 }+ )+ }+private func recordCall(prompt: String,response: String,@@ -164,10 +236,11 @@ public final class HostedHarnessRequestUnderstanding {var clarifyingQuestion: String?var executionPreference: String?var relevantSkillIDs: [String]?+ var conversationReply: String?private enum CodingKeys: String, CodingKey {case turnKind, restatedGoal, targetAppName, parameters, successCriteria, needsClarification, clarifyingQuestion- case executionPreference, relevantSkillIDs+ case executionPreference, relevantSkillIDs, conversationReply}init(from decoder: Decoder) throws {@@ -180,6 +253,7 @@ public final class HostedHarnessRequestUnderstanding {needsClarification = try container.decodeIfPresent(Bool.self, forKey: .needsClarification)executionPreference = try container.decodeIfPresent(String.self, forKey: .executionPreference)relevantSkillIDs = try container.decodeIfPresent([String].self, forKey: .relevantSkillIDs)+ conversationReply = try container.decodeIfPresent(String.self, forKey: .conversationReply)// The schema is non-strict, so a parameter value may arrive as a number or boolean. Coerce// scalars to strings instead of failing the whole decode.parameters = try container.decodeIfPresent([String: ScalarString].self, forKey: .parameters)?@@ -264,7 +338,8 @@ public final class HostedHarnessRequestUnderstanding {"relevantSkillIDs": .object(["type": .string("array"),"items": .object(["type": .string("string")])- ])+ ]),+ "conversationReply": .object(["type": .string("string")])])])])@@ -281,3 +356,17 @@ public final class HostedHarnessRequestUnderstanding {}}++/// Accumulates streamed deltas and extracts the `conversationReply` field live. A reference type so the+/// `@MainActor @Sendable` stream callback can mutate it; only ever touched on the main actor, hence+/// `@unchecked Sendable`.+private final class ReplyFieldStreamer: @unchecked Sendable {+ private var buffer = ""+ private var field = StreamingJSONStringField(key: "conversationReply")++ /// Append a delta and return the newly-decoded reply characters (empty until the field appears).+ func ingest(_ delta: String) -> String {+ buffer += delta+ return field.consume(buffer)+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/StreamingJSONStringField.swift b/apps/Donkey/Sources/DonkeyAI/StreamingJSONStringField.swiftnew file mode 100644index 00000000..4c750f61--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/StreamingJSONStringField.swift@@ -0,0 +1,97 @@+import Foundation++/// Pulls one string field's value out of a JSON object *as it streams in*. Feed it the growing buffer on+/// each delta; it returns only the newly-available, fully-decoded characters of that field's value. This is+/// what lets a reply embedded in a streamed JSON understanding type into the UI live without ever forwarding+/// raw JSON — or a half-finished `\u` escape — to the screen: the consumer only ever sees decoded reply text.+///+/// It locks onto the field the first time the `"key":"` opener appears, decodes standard JSON string escapes,+/// and stops at the closing quote. Bytes for other fields (and the model's structured decision) stream past+/// untouched.+struct StreamingJSONStringField {+ let key: String+ /// Index (in the char array) of the first content character after the value's opening quote, once found.+ private var valueStart: Int?+ /// How many decoded characters have already been returned, so each call yields only the new suffix.+ private var emittedCount = 0+ private var finished = false++ init(key: String) { self.key = key }++ /// Feed the full accumulated buffer; returns the newly-decoded characters of the field's value (empty+ /// when nothing new is available yet, the field hasn't appeared, or the value has ended).+ mutating func consume(_ buffer: String) -> String {+ guard !finished else { return "" }+ let chars = Array(buffer)+ guard let start = valueStart ?? Self.locateValueStart(of: key, in: chars) else { return "" }+ valueStart = start++ var decoded: [Character] = []+ var index = start+ decodeLoop: while index < chars.count {+ let character = chars[index]+ if character == "\\" {+ guard index + 1 < chars.count else { break decodeLoop } // incomplete escape — wait for more+ switch chars[index + 1] {+ case "\"": decoded.append("\""); index += 2+ case "\\": decoded.append("\\"); index += 2+ case "/": decoded.append("/"); index += 2+ case "n": decoded.append("\n"); index += 2+ case "t": decoded.append("\t"); index += 2+ case "r": decoded.append("\r"); index += 2+ case "b": decoded.append("\u{08}"); index += 2+ case "f": decoded.append("\u{0C}"); index += 2+ case "u":+ guard index + 5 < chars.count else { break decodeLoop } // incomplete \uXXXX — wait+ if let code = UInt32(String(chars[(index + 2)...(index + 5)]), radix: 16),+ let scalar = Unicode.Scalar(code) {+ decoded.append(Character(scalar))+ }+ index += 6+ default: decoded.append(chars[index + 1]); index += 2+ }+ } else if character == "\"" {+ finished = true+ break decodeLoop+ } else {+ decoded.append(character)+ index += 1+ }+ }++ guard decoded.count > emittedCount else { return "" }+ let newPart = String(decoded[emittedCount...])+ emittedCount = decoded.count+ return newPart+ }++ /// Find `"key"`, the following `:`, and the opening `"` of its value; return the index just past that+ /// quote, or nil if the value hasn't started streaming yet.+ private static func locateValueStart(of key: String, in chars: [Character]) -> Int? {+ let needle = Array("\"\(key)\"")+ guard let keyStart = firstIndex(of: needle, in: chars) else { return nil }+ var index = keyStart + needle.count+ while index < chars.count, chars[index] != ":" { index += 1 }+ guard index < chars.count else { return nil }+ index += 1 // past the colon+ while index < chars.count, chars[index] != "\"" {+ guard chars[index].isWhitespace else { return nil } // value isn't a string (or not yet here)+ index += 1+ }+ guard index < chars.count, chars[index] == "\"" else { return nil }+ return index + 1+ }++ private static func firstIndex(of needle: [Character], in haystack: [Character]) -> Int? {+ guard !needle.isEmpty, haystack.count >= needle.count else { return nil }+ for start in 0...(haystack.count - needle.count) {+ var matched = true+ for offset in 0..<needle.count where haystack[start + offset] != needle[offset] {+ matched = false+ break+ }+ if matched { return start }+ }+ return nil+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/GreetingRoundTripEvalTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/GreetingRoundTripEvalTests.swiftnew file mode 100644index 00000000..81d456f4--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/GreetingRoundTripEvalTests.swift@@ -0,0 +1,120 @@+import DonkeyAI+import DonkeyContracts+import DonkeyHarness+import DonkeyRuntime+import Foundation+import Testing++/// Prompt eval — GREETING LATENCY / round-trip budget. A bare greeting like "Hi" must be cheap: the+/// understanding boundary types it `.converse` AND returns the reply inline (`conversationReply`), so a fresh+/// greeting is answered in ONE model round trip — no second responder call, and crucially zero planner+/// steps. This test drives the real understanding boundary and counts model calls through a trace sink, so a+/// regression that makes a greeting slow is localized:+/// - `plannerStep > 0` → the greeting was misrouted into the action loop (the expensive failure).+/// - `understanding > 1` → the understanding boundary started doing multiple calls.+/// - empty `conversationReply` → the inline reply regressed, forcing the second responder round trip.+/// - total > 1 → an extra round trip crept into the fresh-greeting path.+///+/// Opt-in like the other prompt evals (see `HarnessEvalRunner.configFromEnvironment`); a plain `swift test`+/// returns early. Per-call latency is printed (not asserted — it is network-dependent) so a "slow today"+/// report can be read as "too many round trips" vs "each call is slow".+@Suite+@MainActor+struct GreetingRoundTripEvalTests {+ @Test+ func greetingIsConverseAnsweredInOneRoundTrip() async {+ guard let config = HarnessEvalRunner.configFromEnvironment() else { return }++ var configuration = DonkeyBackendInferenceConfiguration(+ baseURL: config.baseURL,+ clientID: config.clientID,+ devAuthBypass: config.devAuthBypass+ )+ configuration.conversationID = "greeting-eval-\(UUID().uuidString)"+ let backend = DonkeyBackendInferenceClient(configuration: configuration)+ let trace = CountingTurnTrace()+ let streamed = StreamedReplyBox()++ // The one round trip: stream the understanding. A greeting must classify as converse — only then does+ // it skip the action planner — and the reply must arrive as live deltas from this same call, so a+ // fresh greeting is one round trip with real streaming (the path `UserQueryCommandHandler` takes).+ let understanding = await HostedHarnessRequestUnderstanding(backend: backend, trace: trace)+ .understandStreaming(+ command: "Hi",+ frontmostAppName: "Finder",+ skillCatalog: BuiltInLocalAppSkillPacks.skillSelectionCatalog(),+ onReplyDelta: { delta in streamed.append(delta) }+ )++ let calls = trace.snapshot()+ print(+ "\n=== greeting round trips (\(calls.count) total) ===\n"+ + calls.map { " \($0.kind.rawValue) — \(Int($0.milliseconds))ms" }.joined(separator: "\n")+ + "\nstreamed reply: \(streamed.text.isEmpty ? "<none>" : "\"\(streamed.text.prefix(80))\"") in \(streamed.deltaCount) deltas\n"+ )++ #expect(+ understanding?.turnKind == .converse,+ "a bare greeting must classify as converse (never .act, which enters the planner loop); got \(String(describing: understanding?.turnKind))"+ )+ #expect(+ understanding?.conversationReply?.isEmpty == false,+ "understanding must carry an inline conversationReply for a converse turn so a fresh greeting is one round trip"+ )+ #expect(+ !streamed.text.isEmpty,+ "the reply must arrive as live stream deltas (real streaming), not all at once after the call"+ )+ #expect(+ streamed.text == (understanding?.conversationReply ?? ""),+ "the streamed deltas should reconstruct the final reply exactly; streamed=\"\(streamed.text.prefix(60))\" final=\"\(understanding?.conversationReply?.prefix(60) ?? "")\""+ )+ #expect(trace.count(of: .understanding) == 1, "expected exactly 1 understanding call; got \(trace.count(of: .understanding))")+ #expect(trace.count(of: .conversationalReply) == 0, "a fresh greeting should NOT need the separate responder; conversational replies: \(trace.count(of: .conversationalReply))")+ #expect(trace.count(of: .plannerStep) == 0, "a greeting must NOT reach the planner; planner steps: \(trace.count(of: .plannerStep))")+ #expect(+ calls.count == 1,+ "a fresh greeting should be exactly 1 model round trip (understanding streams the reply); got \(calls.count): \(calls.map { $0.kind.rawValue })"+ )+ }+}++/// Collects streamed reply deltas from the `@MainActor @Sendable` callback so the test can assert real+/// streaming happened (non-empty, multiple deltas) and that the pieces reconstruct the final reply.+@MainActor+final class StreamedReplyBox {+ private(set) var text = ""+ private(set) var deltaCount = 0+ func append(_ delta: String) {+ text += delta+ deltaCount += 1+ }+}++/// A trace sink that just tallies model calls and their spans, so a test can assert how many round trips a+/// turn took and how long each was. Thread-safe because the harness may record from off the main actor.+final class CountingTurnTrace: HarnessTurnTracing, @unchecked Sendable {+ struct Entry {+ var kind: TraceModelCallKind+ var milliseconds: Double+ }++ private let lock = NSLock()+ private var entries: [Entry] = []++ func recordModelCall(_ call: TraceModelCall) {+ lock.lock()+ entries.append(Entry(kind: call.kind, milliseconds: call.durationMS ?? 0))+ lock.unlock()+ }++ func snapshot() -> [Entry] {+ lock.lock(); defer { lock.unlock() }+ return entries+ }++ func count(of kind: TraceModelCallKind) -> Int {+ lock.lock(); defer { lock.unlock() }+ return entries.filter { $0.kind == kind }.count+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/StreamingJSONStringFieldTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/StreamingJSONStringFieldTests.swiftnew file mode 100644index 00000000..f061528a--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/StreamingJSONStringFieldTests.swift@@ -0,0 +1,70 @@+@testable import DonkeyAI+import Foundation+import Testing++/// Offline unit tests for the streaming JSON field extractor — the fragile part of one-round-trip streaming.+/// Pure logic, no model, so these run in a plain `swift test`. They feed the field in arbitrary chunk+/// boundaries (the real stream splits tokens unpredictably) and check the decoded value is delivered exactly+/// once, in order, with escapes handled and no partial-escape leakage.+@Suite+struct StreamingJSONStringFieldTests {+ /// Feed `full` to a fresh extractor one Unicode scalar at a time (the meanest possible chunking) and+ /// return everything it emitted, concatenated.+ private func emitCharByChar(_ full: String, key: String = "conversationReply") -> String {+ var field = StreamingJSONStringField(key: key)+ var emitted = ""+ var buffer = ""+ for character in full {+ buffer.append(character)+ emitted += field.consume(buffer)+ }+ return emitted+ }++ @Test+ func extractsValueDeliveredCharByChar() {+ let json = #"{"conversationReply":"Hey there!","turnKind":"converse"}"#+ #expect(emitCharByChar(json) == "Hey there!")+ }++ @Test+ func decodesEscapesAcrossChunkBoundaries() {+ let json = #"{"conversationReply":"line1\nline2 \"quoted\" end","turnKind":"converse"}"#+ #expect(emitCharByChar(json) == "line1\nline2 \"quoted\" end")+ }++ @Test+ func decodesUnicodeEscape() {+ let json = #"{"conversationReply":"café","turnKind":"converse"}"#+ #expect(emitCharByChar(json) == "café")+ }++ @Test+ func emitsNothingWhenFieldAbsent() {+ let json = #"{"turnKind":"act","restatedGoal":"open Safari"}"#+ #expect(emitCharByChar(json) == "")+ }++ @Test+ func emptyValueEmitsNothingAndDoesNotLeakIntoNextField() {+ let json = #"{"conversationReply":"","turnKind":"act"}"#+ #expect(emitCharByChar(json) == "")+ }++ @Test+ func handlesFieldNotFirst() {+ let json = #"{"turnKind":"converse","restatedGoal":"hi","conversationReply":"Hello!"}"#+ #expect(emitCharByChar(json) == "Hello!")+ }++ @Test+ func deliversEachCharacterExactlyOnce() {+ // Whole-buffer-at-once should match char-by-char: no duplication, no drops.+ let json = #"{"conversationReply":"abcdef","turnKind":"converse"}"#+ var field = StreamingJSONStringField(key: "conversationReply")+ let once = field.consume(json)+ #expect(once == "abcdef")+ // A second consume of the same (now-complete) buffer yields nothing more.+ #expect(field.consume(json) == "")+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swiftindex 7f8b0d78..ad3ea3e9 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift@@ -300,7 +300,7 @@ struct HostedHarnessStepPlannerTests {)_ = await planner.planNextStep(for: task(goal: "create a subtitled clip", toolHistory: []))- let narration = UserQueryCommandHandler.stepNarration(for: step, planner: planner)+ let narration = LocalAppUserQueryCommandHandler.stepNarration(for: step, planner: planner)#expect(narration == longNarration)}