Skip to content

Open source CapCut alternative.

TypeScript

feat(app): stream the agent's final answer into the notch

David Le50a8ec1ee4a1
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 97b823d8..11dcb3c5 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -147,6 +147,9 @@ protocol UserQueryCommandHandling: Sendable {
taskID: String,
context: UserQueryCommandContext?
) async -> UserQueryCommandHandlingResult?
+ /// Set by the overlay so a mid-run hosted 401 (an expired session) surfaces re-login. The inference
+ /// client fires it off the main actor, so the hook hops back to the main actor itself.
+ var onAuthenticationRequired: (@MainActor @Sendable () -> Void)? { get set }
}
extension UserQueryCommandHandling {
@@ -180,6 +183,9 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
/// Shared across every run (the actor is a reference, so struct copies captured into run Tasks share
/// one gate): only one foreground run drives the GUI at a time. See `ForegroundFocusGate`.
let foregroundFocusGate = ForegroundFocusGate()
+ /// Set by the overlay model; fired when any hosted request in a turn returns 401 so the app can
+ /// surface re-login. Optional, so existing construction sites are unaffected.
+ var onAuthenticationRequired: (@MainActor @Sendable () -> Void)?
init(
permissionPolicy: ToolCallPolicy = ToolCallPolicy(
@@ -194,6 +200,13 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
self.genericHarnessLifecycle = genericHarnessLifecycle
}
+ /// Bridges the struct's main-actor auth-expiry hook to the inference client's off-actor callback,
+ /// hopping back to the main actor. Nil when no hook is set, so the client stays silent.
+ private func backendAuthExpiryHook() -> (@Sendable () -> Void)? {
+ guard let onAuthenticationRequired else { return nil }
+ return { Task { @MainActor in onAuthenticationRequired() } }
+ }
+
func handleSubmittedCommand(
_ command: String,
context: UserQueryCommandContext?
@@ -265,7 +278,8 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
taskID: taskID,
preparedTurnMetadata: Self.genericHarnessMetadata(preparedTurn: genericPreparedTurn),
visualize: context?.agentVisualizationChanged,
- progress: Self.progressLabeler(context?.spawnProgressChanged)
+ progress: Self.progressLabeler(context?.spawnProgressChanged),
+ answerStream: Self.answerDeltaSink(context?.spawnProgressChanged)
)
}
@@ -341,7 +355,8 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
forcedExecutionPreference: forcedExecutionPreference,
forcedDriveTarget: forcedDriveTarget,
visualize: context?.agentVisualizationChanged,
- progress: Self.progressLabeler(context?.spawnProgressChanged)
+ progress: Self.progressLabeler(context?.spawnProgressChanged),
+ answerStream: Self.answerDeltaSink(context?.spawnProgressChanged)
)
}
@@ -373,6 +388,18 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
}
}
+ /// Adapt the spawn-progress callback into a delta sink for the streamed final answer: each chunk is
+ /// forwarded as an `answerDelta` so the model accumulates it onto the task's detail (the chin and the
+ /// open row stream it), rather than replacing the status line the way a `label` update does.
+ private static func answerDeltaSink(
+ _ spawnProgressChanged: (@MainActor @Sendable (UserQuerySpawnProgressUpdate) -> Void)?
+ ) -> (@MainActor @Sendable (String) -> Void)? {
+ guard let spawnProgressChanged else { return nil }
+ return { delta in
+ spawnProgressChanged(UserQuerySpawnProgressUpdate(answerDelta: delta))
+ }
+ }
+
func pauseCommand(taskID: String) async -> Bool {
await genericHarnessLifecycle.pauseTask(
taskID: taskID,
@@ -406,7 +433,8 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
forcedExecutionPreference: ExecutionPreference? = nil,
forcedDriveTarget: (appName: String, bundleIdentifier: String?)? = nil,
visualize: (@MainActor @Sendable (AgentVisualizationPlan) -> Void)? = nil,
- progress: (@MainActor @Sendable (String) -> Void)? = nil
+ progress: (@MainActor @Sendable (String) -> Void)? = nil,
+ answerStream: (@MainActor @Sendable (String) -> Void)? = nil
) async -> UserQueryCommandHandlingResult {
guard permissionPolicy.allowedCapabilities.contains(.input) else {
return await failHarnessRun(
@@ -448,7 +476,13 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
preparedTurnMetadata: preparedTurnMetadata
)
}
- let backend = DonkeyBackendInferenceClient(configuration: configuration)
+ // One client serves the whole turn — understanding, planner, and hosted adapters all share it —
+ // so wiring the auth-expiry hook here catches a 401 on any of those paths, even the ones that
+ // swallow the thrown error.
+ let backend = DonkeyBackendInferenceClient(
+ configuration: configuration,
+ onAuthenticationRequired: backendAuthExpiryHook()
+ )
// The thread is the COMPLETE, human-readable record of the turn (like ChatGPT/Claude), written
// live as markdown. It is opened here — before the very first model call — so the trace manager
@@ -467,7 +501,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
// extract parameters, and decide whether to clarify. Degrades to driving the raw command when
// it returns nil — or when the call outlives its deadline — so a backend hiccup never
// dead-ends or silently stalls the run.
- progress?("Working out what you need")
let understandingBoundary = HostedHarnessRequestUnderstanding(backend: backend, trace: trace)
let understanding = await AIDeadline.race(seconds: Self.understandingTimeoutSeconds) {
await understandingBoundary.understand(command: command, frontmostAppName: frontmostAppName)
@@ -891,9 +924,22 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
let conversationMessage = finalTask?.toolHistory.last { $0.call.name == "conversation.respond" }
.flatMap { $0.call.input["response"] ?? $0.call.input["message"] }
.flatMap { $0.isEmpty ? nil : $0 }
- let response = conversationMessage
+ var response = conversationMessage
?? planner.lastNarration
?? (completed ? "Done." : "I tried operating \(appName) but couldn't confirm the goal was finished.")
+
+ // Stream the assistant's final reply token-by-token into the notch (the chin and the open task
+ // row) when the turn produced a real text answer. It is re-composed from the harness's drafted
+ // answer so it stays grounded; the streamed text becomes the authoritative reply, and a failed
+ // or empty stream falls back to the draft already computed above. Only conversational answers
+ // stream — an action that merely finished ("Done.") has no message worth typing out.
+ if completed, let conversationMessage, let answerStream {
+ let prompt = Self.finalAnswerPrompt(goal: command, draftAnswer: conversationMessage)
+ if let streamed = await textGenerator.generateStreaming(prompt, onDelta: answerStream),
+ !streamed.isEmpty {
+ response = streamed
+ }
+ }
let decision = AppHarnessDecision(
kind: .respond,
message: response,
@@ -1046,6 +1092,20 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
)
}
+ /// Prompt for the streamed final reply: relay the harness's drafted answer to the user, grounded
+ /// strictly in that draft so the streamed message can't drift from what the run actually found.
+ private static func finalAnswerPrompt(goal: String, draftAnswer: String) -> String {
+ """
+ Relay Donkey's reply to the user for this finished request. Base it strictly on the draft \
+ below — do not add facts, steps, or speculation. Reply directly to the user in a concise, \
+ friendly voice; if the draft already reads well, lightly polish it. Output only the reply \
+ text, with no preamble.
+
+ User request: \(goal)
+ Draft reply: \(draftAnswer)
+ """
+ }
+
/// Deadline for the one-shot understanding call; past it the run degrades to
/// driving the raw command instead of stalling silently.
private static let understandingTimeoutSeconds: TimeInterval = 15
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
index 253d23e5..3ab5c48f 100644
--- a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
@@ -7,6 +7,10 @@ public enum DonkeyBackendInferenceClientError: Error, Equatable, Sendable {
case invalidResponse
case invalidURL(String)
case httpStatus(Int, String)
+ /// The backend rejected the request as unauthenticated (HTTP 401). Distinct from `httpStatus` so
+ /// the app can surface re-login instead of a generic failure, keyed on a typed case (never the
+ /// response body text).
+ case authenticationRequired
case missingDownloadPayload(String)
case invalidBase64(String)
}
@@ -91,15 +95,37 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {
public var configuration: DonkeyBackendInferenceConfiguration
public var httpClient: any AIHTTPClient
public var fileManager: FileManager
+ /// Fired the moment the backend returns 401 on any request path, before any caller can swallow the
+ /// thrown error. The app uses it to flip into re-login while keeping the running task in place.
+ public var onAuthenticationRequired: (@Sendable () -> Void)?
+ /// Process-wide authority on whether the session is usable; defaults to the shared instance the auth
+ /// coordinator drives. Injectable so tests exercise the signed-out short-circuit without mutating
+ /// global state (the test suite runs in parallel).
+ public var sessionGate: BackendSessionGate
public init(
configuration: DonkeyBackendInferenceConfiguration,
httpClient: any AIHTTPClient = URLSessionAIHTTPClient(),
- fileManager: FileManager = .default
+ fileManager: FileManager = .default,
+ onAuthenticationRequired: (@Sendable () -> Void)? = nil,
+ sessionGate: BackendSessionGate = .shared
) {
self.configuration = configuration
self.httpClient = httpClient
self.fileManager = fileManager
+ self.onAuthenticationRequired = onAuthenticationRequired
+ self.sessionGate = sessionGate
+ }
+
+ /// Maps a non-2xx status into the right typed error. A 401 fires `onAuthenticationRequired` and
+ /// returns the distinct `.authenticationRequired` case so every request path surfaces an expired
+ /// session the same way; other statuses keep the body message for the planner to read.
+ private func httpError(statusCode: Int, message: @autoclosure () -> String) -> DonkeyBackendInferenceClientError {
+ if statusCode == 401 {
+ onAuthenticationRequired?()
+ return .authenticationRequired
+ }
+ return .httpStatus(statusCode, message())
}
public func listModels(
@@ -228,15 +254,16 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {
)
request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
+ try ensureSessionUsable()
let (lines, response) = try await httpClient.streamLines(request)
var responseBodyLines: [String] = []
guard (200..<300).contains(response.statusCode) else {
for try await line in lines {
responseBodyLines.append(line)
}
- throw DonkeyBackendInferenceClientError.httpStatus(
- response.statusCode,
- responseBodyLines.joined(separator: "\n")
+ throw httpError(
+ statusCode: response.statusCode,
+ message: responseBodyLines.joined(separator: "\n")
)
}
@@ -373,6 +400,56 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {
return request
}
+ /// Stream a chat completion, delivering each text delta to `onDelta` as it arrives and returning
+ /// the full accumulated text. The route emits OpenAI-style SSE chunks — `data:` lines whose
+ /// `choices[0].delta.content` is the next piece — ending with a `[DONE]` sentinel; a terminal
+ /// `event: error` ends the stream with whatever text arrived so far. Mirrors `parseScreenshotStream`'s
+ /// SSE handling (auth pre-flight, status check, line parsing). Used to stream the notch's final reply.
+ public func streamChat(
+ _ completionRequest: RemoteInferenceChatCompletionRequest,
+ onDelta: @escaping @MainActor @Sendable (String) -> Void
+ ) async throws -> String {
+ var request = try makeStreamingChatRequest(completionRequest)
+ request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
+
+ try ensureSessionUsable()
+ let (lines, response) = try await httpClient.streamLines(request)
+ guard (200..<300).contains(response.statusCode) else {
+ var bodyLines: [String] = []
+ for try await line in lines {
+ bodyLines.append(line)
+ }
+ throw httpError(
+ statusCode: response.statusCode,
+ message: bodyLines.joined(separator: "\n")
+ )
+ }
+
+ var accumulated = ""
+ for try await line in lines {
+ guard line.hasPrefix("data:") else { continue }
+ let payload = String(line.dropFirst("data:".count)).trimmingCharacters(in: .whitespaces)
+ guard !payload.isEmpty else { continue }
+ if payload == "[DONE]" { break }
+ guard let piece = Self.chatStreamDeltaText(payload), !piece.isEmpty else { continue }
+ accumulated += piece
+ await onDelta(piece)
+ }
+ return accumulated
+ }
+
+ /// Extracts `choices[0].delta.content` from one OpenAI-style streamed chat chunk. Returns nil for a
+ /// chunk that carries no text delta (role-only opener, finish marker) so the caller skips it.
+ static func chatStreamDeltaText(_ jsonLine: String) -> String? {
+ guard let data = jsonLine.data(using: .utf8),
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let choices = object["choices"] as? [[String: Any]],
+ let delta = choices.first?["delta"] as? [String: Any] else {
+ return nil
+ }
+ return delta["content"] as? String
+ }
+
public func createAssetGeneration(
_ assetRequest: RemoteInferenceAssetGenerationRequest
) async throws -> RemoteInferenceGenerationRecord {
@@ -571,11 +648,23 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {
}
+ /// Refuse a request the moment the session is known to be signed out, before any network round
+ /// trip. This is the single chokepoint that stops every always-on loop (Live token mint, vision
+ /// warm cache, planner steps, catalog refresh) from spraying guaranteed-401 calls at the backend
+ /// while logged out — they get the same typed `.authenticationRequired` they'd get from a real 401,
+ /// just instantly and for free. The dev-auth bypass is always treated as authenticated.
+ private func ensureSessionUsable() throws {
+ guard !configuration.devAuthBypass,
+ !sessionGate.isAuthenticated else { return }
+ throw DonkeyBackendInferenceClientError.authenticationRequired
+ }
+
private func send(_ request: URLRequest) async throws -> Data {
+ try ensureSessionUsable()
let (data, response) = try await httpClient.send(request)
guard (200..<300).contains(response.statusCode) else {
let message = String(data: data, encoding: .utf8) ?? HTTPURLResponse.localizedString(forStatusCode: response.statusCode)
- throw DonkeyBackendInferenceClientError.httpStatus(response.statusCode, message)
+ throw httpError(statusCode: response.statusCode, message: message)
}
return data
}
@@ -600,7 +689,7 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {
request.httpShouldHandleCookies = true
let (data, response) = try await httpClient.send(request)
guard (200..<300).contains(response.statusCode) else {
- throw DonkeyBackendInferenceClientError.httpStatus(response.statusCode, String(data: data, encoding: .utf8) ?? "")
+ throw httpError(statusCode: response.statusCode, message: String(data: data, encoding: .utf8) ?? "")
}
return (data, response.value(forHTTPHeaderField: "Content-Type") ?? output.contentType ?? "application/octet-stream")
}
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
index 1f6112f2..755da1f4 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
@@ -131,6 +131,9 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
lastPlanningErrors.append(
"planning attempt \(attempt + 1)/\(Self.maxPlanAttempts) failed: \(String(describing: error).prefix(300))"
)
+ // An expired session never recovers by retrying — every attempt 401s instantly. Stop now
+ // and fail safe with a clear signed-out message rather than burning the whole retry budget.
+ if Self.isAuthenticationError(error) { break }
guard attempt < lastAttempt else { break }
retryNote = Self.retryNote(after: error)
continue
@@ -203,6 +206,11 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
/// a timeout — so the thread and the user-facing summary name what actually broke instead of a
/// generic plan failure the user has to guess at.
private func failSafeCall(after error: Error?) -> HarnessToolCall {
+ if let error, Self.isAuthenticationError(error) {
+ lastNarration = "Your session is signed out, so I couldn't reach the model. Sign in again "
+ + "and re-run this."
+ return HarnessToolCall(name: "run.failSafe", input: ["reason": "sessionSignedOut"])
+ }
switch error as? PlanningError {
case let .blockedByContentFilter(finishReason, _):
lastNarration = "The model provider's content filter blocked every planning reply "
@@ -223,6 +231,14 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
}
}
+ /// Whether a planning failure is an expired/absent session (a backend 401, or the client's own
+ /// pre-flight refusal while signed out). These are terminal for the step — retrying re-issues the
+ /// same doomed call — so the planner stops instead of spending its retry budget.
+ private static func isAuthenticationError(_ error: Error) -> Bool {
+ if case DonkeyBackendInferenceClientError.authenticationRequired = error { return true }
+ return false
+ }
+
/// Max planning samples per step before failing safe. The first is the normal call; the rest are
/// feedback-driven retries (malformed JSON, empty tool, missing required input, or a reply truncated
/// at the token cap). Mirrors the Hermes agent's "retry up to 3 with feedback" recovery.
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift b/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift
index 3ad2927d..0e025109 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift
@@ -55,6 +55,35 @@ public struct HostedTextGenerator: Sendable {
return (text?.isEmpty == false) ? text : nil
}
+ /// Streams the model's reply to `prompt`, delivering each text delta to `onDelta` as it arrives
+ /// and returning the full text. Used to stream the assistant's final answer into the notch chin and
+ /// the open task row token-by-token. Returns nil on any failure (empty stream, transport, timeout),
+ /// so the caller falls back to the already-drafted answer rather than showing nothing.
+ public func generateStreaming(
+ _ prompt: String,
+ onDelta: @escaping @MainActor @Sendable (String) -> Void
+ ) async -> String? {
+ let request = RemoteInferenceChatCompletionRequest(
+ messages: [
+ RemoteInferenceChatMessage(role: "user", content: .string(prompt))
+ ],
+ stream: true,
+ metadata: ["source": "hosted-text-generator", "prompt_version": "answer-stream-v1"],
+ parameters: [
+ "temperature": .number(0.4),
+ "max_output_tokens": .number(Double(maxOutputTokens))
+ ]
+ )
+ let backend = self.backend
+ guard let text = try? await AIDeadline.enforce(seconds: timeoutSeconds, {
+ try await backend.streamChat(request, onDelta: onDelta)
+ }) else {
+ return nil
+ }
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmed.isEmpty ? nil : trimmed
+ }
+
/// Runs `prompt` against a local media file (audio or video) — the multimodal arm of
/// `llm.generate`. The file is read and sent inline (base64) alongside the prompt, so the prompt
/// decides the output (transcribe to SRT, translate, summarize, answer a question). `mimeType` is
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
index cf585d86..4bb025bd 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
@@ -35,6 +35,36 @@ struct DonkeyBackendInferenceClientTests {
#expect(object["model"] as? String == "router/large")
}
+ @Test
+ func streamChatParsesSSEDeltasAndReturnsAccumulatedText() async throws {
+ // OpenAI-style SSE: a role-only opener (no content) is skipped, content chunks accumulate, and
+ // the [DONE] sentinel ends the stream. The default streamLines splits the buffered body by line.
+ let sse = """
+ data: {"choices":[{"delta":{"role":"assistant"}}]}
+
+ data: {"choices":[{"delta":{"content":"Now "}}]}
+
+ data: {"choices":[{"delta":{"content":"playing."}}]}
+
+ data: [DONE]
+
+ """
+ let client = DonkeyBackendInferenceClient(
+ configuration: configuration(),
+ httpClient: FixtureHTTPClient(data: Data(sse.utf8), statusCode: 200)
+ )
+ let collector = StreamDeltaCollector()
+ let full = try await client.streamChat(
+ RemoteInferenceChatCompletionRequest(
+ messages: [RemoteInferenceChatMessage(role: "user", content: .string("hi"))]
+ ),
+ onDelta: { delta in collector.append(delta) }
+ )
+
+ #expect(full == "Now playing.")
+ #expect(collector.values() == ["Now ", "playing."])
+ }
+
@Test
func createResponseUsesBackendProxyAndStoreFalse() async throws {
let httpClient = FixtureHTTPClient(
@@ -863,6 +893,53 @@ struct DonkeyBackendInferenceClientTests {
#expect(downloads[0].contentType == "image/png")
}
+ @Test
+ func signedOutSessionShortCircuitsRequestsWithoutHittingTheNetwork() async {
+ // While signed out the client must refuse every request locally — no network round trip — so the
+ // always-on loops stop spraying guaranteed-401 calls. It returns the same typed error a real 401
+ // would, instantly. A local gate instance keeps this independent of the parallel test run.
+ let gate = BackendSessionGate()
+ gate.update(isAuthenticated: false)
+
+ let httpClient = FixtureHTTPClient(data: Data("{}".utf8), statusCode: 200)
+ let client = DonkeyBackendInferenceClient(
+ configuration: configuration(),
+ httpClient: httpClient,
+ sessionGate: gate
+ )
+
+ await #expect(throws: DonkeyBackendInferenceClientError.authenticationRequired) {
+ _ = try await client.createResponse(
+ RemoteInferenceResponseCreateRequest(model: "router/large", input: .string("hi"))
+ )
+ }
+ // Never reached the transport.
+ #expect(httpClient.requests.isEmpty)
+ }
+
+ @Test
+ func devAuthBypassIgnoresTheSignedOutGate() async throws {
+ // The dev-auth bypass is always treated as authenticated, so the gate never blocks it.
+ let gate = BackendSessionGate()
+ gate.update(isAuthenticated: false)
+
+ let httpClient = FixtureHTTPClient(data: Data("{}".utf8), statusCode: 200)
+ let client = DonkeyBackendInferenceClient(
+ configuration: DonkeyBackendInferenceConfiguration(
+ baseURL: URL(string: "https://donkey.example")!,
+ clientID: "client-1",
+ devAuthBypass: true
+ ),
+ httpClient: httpClient,
+ sessionGate: gate
+ )
+
+ _ = try await client.createResponse(
+ RemoteInferenceResponseCreateRequest(model: "router/large", input: .string("hi"))
+ )
+ #expect(httpClient.requests.count == 1)
+ }
+
private func configuration() -> DonkeyBackendInferenceConfiguration {
DonkeyBackendInferenceConfiguration(
baseURL: URL(string: "https://donkey.example")!,
@@ -917,6 +994,24 @@ struct DonkeyBackendInferenceClientTests {
}
}
+private final class StreamDeltaCollector: @unchecked Sendable {
+ private let lock = NSLock()
+ private var deltas: [String] = []
+
+ func append(_ delta: String) {
+ lock.lock()
+ deltas.append(delta)
+ lock.unlock()
+ }
+
+ func values() -> [String] {
+ lock.lock()
+ let snapshot = deltas
+ lock.unlock()
+ return snapshot
+ }
+}
+
private final class FixtureHTTPClient: AIHTTPClient, @unchecked Sendable {
var data: Data
var statusCode: Int
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift
index a48c30fb..6fae1511 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift
@@ -167,18 +167,36 @@ struct HostedHarnessStepPlannerTests {
}
@Test
- func backendHTTPFailureSurfacesTheExactErrorInTheNarration() async {
- // An auth failure must not read as a generic plan failure: the narration carries the exact
- // backend error (status code and body) so the user sees what broke without guessing.
+ func unauthorizedFailsSafeOnceWithASignInPrompt() async {
+ // A 401 is an expired session — retrying just 401s again. The planner must stop on the first
+ // attempt (not burn the whole retry budget) and surface a clear "sign in again" message rather
+ // than a generic plan failure the user has to guess at.
let unauthorized = (Data("unauthorized".utf8), 401)
let httpClient = SequencedHTTPClient(responses: [unauthorized, unauthorized, unauthorized])
let planner = makePlanner(httpClient: httpClient, understanding: nil)
let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))
+ #expect(call?.name == "run.failSafe")
+ #expect(call?.input["reason"] == "sessionSignedOut")
+ #expect(planner.lastNarration?.lowercased().contains("sign in") == true)
+ // Terminal on the first attempt — no wasted retries against a session that can't recover.
+ #expect(httpClient.requests.count == 1)
+ }
+
+ @Test
+ func backendHTTPFailureSurfacesTheExactErrorInTheNarration() async {
+ // A non-auth backend failure must not read as a generic plan failure: the narration carries the
+ // exact backend error (status code and body) so the user sees what broke without guessing.
+ let serverError = (Data("server error".utf8), 500)
+ let httpClient = SequencedHTTPClient(responses: [serverError, serverError, serverError])
+ let planner = makePlanner(httpClient: httpClient, understanding: nil)
+
+ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))
+
#expect(call?.name == "run.failSafe")
#expect(call?.input["reason"] == "harnessPlanFailed")
- #expect(planner.lastNarration?.contains("401") == true)
+ #expect(planner.lastNarration?.contains("500") == true)
}
@Test