Open source CapCut alternative.
TypeScript
feat(app): show out-of-credits message with a notch Reload CTA
David Le079298728a7c
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 11dcb3c5..7472f52f 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -955,15 +955,21 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {reason: "User query harness run returned without a terminal status")let threadStatus = Self.userQueryStatus(forHarness: finalStatus)+ // A run that failed safe for lack of credits carries a typed flag the notch reads to show the+ // reload CTA banner (instead of inferring the credit state from the narration text).+ var responseMetadata = [+ "appHarness.decision": AppHarnessDecisionKind.respond.rawValue+ ]+ if planner.lastFailureRequiresCreditReload {+ responseMetadata[UserQueryTaskMetadataKey.creditReloadRequired] = "true"+ }let result = UserQueryCommandHandlingResult(status: completed ? .completed : .failedSafe,threadStatus: threadStatus,decision: decision,summary: response,traceID: traceID,- metadata: baseMetadata.merging([- "appHarness.decision": AppHarnessDecisionKind.respond.rawValue- ]) { _, new in new }+ metadata: baseMetadata.merging(responseMetadata) { _, new in new })await coordinatorRegistry.finish(taskID: taskID)logHandlingResult(diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swiftindex c94bce0b..d6d2e4cf 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift@@ -673,6 +673,9 @@ final class UserQueryOverlayController {needsLogin: model.needsLogin,loginRequested: { [weak self] inself?.model.requestLogin()+ },+ reloadCreditsRequested: { [weak self] taskID in+ self?.model.reloadCredits(id: taskID)})}diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swiftindex 13f34f77..bab43d62 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift@@ -1,3 +1,4 @@+import AppKitimport DonkeyAIimport DonkeyContractsimport DonkeyRuntime@@ -284,6 +285,15 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {loginActionRequested?()}+ /// The notch "Reload credits" CTA was tapped on a credit-exhausted task. Open the billing page in+ /// the browser (donkeyuse.com in prod, localhost in dev — the configured web base URL) so the user+ /// can top up; the task stays on the row so it can be re-run once credits land.+ func reloadCredits(id taskID: String) {+ let billingURL = DonkeyAuthConfiguration.current().webBaseURL+ .appendingPathComponent("app/settings")+ NSWorkspace.shared.open(billingURL)+ }+/// A hosted request returned 401 mid-run. Surface login once — ignored if already logged out, so a/// burst of retrying calls doesn't re-fire — and let the app delegate sign out.func handleSessionExpired() {diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swiftindex 3ab5c48f..1005a6ba 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift@@ -11,10 +11,40 @@ public enum DonkeyBackendInferenceClientError: Error, Equatable, Sendable {/// the app can surface re-login instead of a generic failure, keyed on a typed case (never the/// response body text).case authenticationRequired+ /// The backend rejected the request for lack of credits (HTTP 402). Distinct from `httpStatus` so+ /// the app surfaces a "buy credits" message instead of a generic failure. `balance` is the typed+ /// balance from the JSON error body when present (decoded field, never matched from raw text).+ case insufficientCredits(balance: String?)case missingDownloadPayload(String)case invalidBase64(String)}+/// Shared, app-agnostic copy for the "out of credits" state. Centralized so every consumer (the step+/// planner's fail-safe, the image generator, any future caller) surfaces one consistent message and+/// the same billing destination rather than leaking a raw `httpStatus(402, …)` dump to the user.+public enum DonkeyCreditExhaustion {+ /// Where users top up. Shown in the message and used by any UI that opens the billing page.+ public static let billingURLString = "https://donkeyuse.com/app/settings"++ /// Whether a failure is the credit-exhausted state. A 402 reaches us two ways: the typed+ /// `.insufficientCredits` from the normal request path, and a raw `.httpStatus(402, …)` when the+ /// failure surfaces through a streaming error event that skips status-to-error mapping.+ public static func isExhausted(_ error: Error) -> Bool {+ switch error {+ case DonkeyBackendInferenceClientError.insufficientCredits:+ return true+ case DonkeyBackendInferenceClientError.httpStatus(402, _):+ return true+ default:+ return false+ }+ }++ public static func userMessage() -> String {+ "You're out of credits."+ }+}+public struct DonkeyBackendInferenceConfiguration: Equatable, Sendable {public var baseURL: URLpublic var clientID: String@@ -125,7 +155,31 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {onAuthenticationRequired?()return .authenticationRequired}- return .httpStatus(statusCode, message())+ let body = message()+ // Every 402 from this backend is a credits problem (insufficient balance or a configured+ // spend limit). Map it to the typed case so callers surface "buy credits" instead of a raw+ // status dump; the balance is read from the decoded JSON field, never matched from raw text.+ if statusCode == 402 {+ return .insufficientCredits(balance: Self.creditBalance(fromBody: body))+ }+ return .httpStatus(statusCode, body)+ }++ /// Pulls the `balance` from a 402 JSON error body, e.g. {"error":"insufficient_credits","balance":"0"}.+ /// Returns nil for any non-JSON or balance-less body. Decodes the field; does not pattern-match text.+ private static func creditBalance(fromBody body: String) -> String? {+ guard let data = body.data(using: .utf8),+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any]+ else {+ return nil+ }+ if let balance = object["balance"] as? String {+ return balance+ }+ if let balance = object["balance"] as? NSNumber {+ return balance.stringValue+ }+ return nil}public func listModels(diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swiftindex ec9a1500..36793309 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift@@ -56,6 +56,10 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {/// reason a step fell back to run.failSafe). Cleared at the start of each planNextStep; the route/// writes them into the thread transcript so a failed step is diagnosable from the thread alone.public private(set) var lastPlanningErrors: [String] = []+ /// True when the most recent step failed safe because the backend reported the balance is spent+ /// (HTTP 402). The user-query layer reads this typed flag to flag the task for a reload CTA in the+ /// notch, instead of inferring the credit state from the narration text.+ public private(set) var lastFailureRequiresCreditReload = false/// Names of the registered read-only tools (observe/verify/respond/lifecycle), derived from each/// descriptor's safety class. A tool counts as an "action" for first-action timing exactly when it@@ -121,6 +125,7 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {var retryNote: String?var lastFailure: Error?lastPlanningErrors = []+ lastFailureRequiresCreditReload = falselet lastAttempt = Self.maxPlanAttempts - 1for attempt in 0...lastAttempt {let decision: Decision@@ -131,9 +136,10 @@ 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 }+ // An expired session or an exhausted balance never recovers by retrying — every attempt+ // hits the same 401/402 instantly. Stop now and fail safe with a clear, actionable+ // message rather than burning the whole retry budget.+ if Self.isAuthenticationError(error) || DonkeyCreditExhaustion.isExhausted(error) { break }guard attempt < lastAttempt else { break }retryNote = Self.retryNote(after: error)continue@@ -213,6 +219,11 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {+ "and re-run this."return HarnessToolCall(name: "run.failSafe", input: ["reason": "sessionSignedOut"])}+ if let error, DonkeyCreditExhaustion.isExhausted(error) {+ lastNarration = DonkeyCreditExhaustion.userMessage()+ lastFailureRequiresCreditReload = true+ return HarnessToolCall(name: "run.failSafe", input: ["reason": "insufficientCredits"])+ }switch error as? PlanningError {case let .blockedByContentFilter(finishReason, _):lastNarration = "The model provider's content filter blocked every planning reply "diff --git a/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift b/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swiftindex b4d561e5..74801053 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift@@ -71,7 +71,9 @@ public struct HostedImageGenerator: Sendable {let maxPollAttempts = self.maxPollAttempts// One deadline over the whole call (create + poll + write); the request was synchronous in// practice, but polling/writing stay bounded so the harness step can't hang.- let outcome = try? await AIDeadline.enforce(seconds: timeoutSeconds) {+ let outcome: HarnessImageGenerationResult+ do {+ outcome = try await AIDeadline.enforce(seconds: timeoutSeconds) {() -> HarnessImageGenerationResult invar record = try await backend.createAssetGeneration(assetRequest)var attempts = 0@@ -99,12 +101,20 @@ public struct HostedImageGenerator: Sendable {savedPaths: saved,failureReason: saved.isEmpty ? "The image model returned no image." : nil)+ }+ } catch let error where DonkeyCreditExhaustion.isExhausted(error) {+ return HarnessImageGenerationResult(+ savedPaths: [],+ failureReason: DonkeyCreditExhaustion.userMessage()+ )+ } catch {+ return HarnessImageGenerationResult(+ savedPaths: [],+ failureReason: "Image generation timed out or could not reach the model."+ )}- return outcome ?? HarnessImageGenerationResult(- savedPaths: [],- failureReason: "Image generation timed out or could not reach the model."- )+ return outcome}/// Resolves where outputs are written. An absolute `outDir` is used as-is; a relative one resolvesdiff --git a/apps/Donkey/Sources/DonkeyContracts/UserQueryContracts.swift b/apps/Donkey/Sources/DonkeyContracts/UserQueryContracts.swiftindex 44dabcef..b3ec8852 100644--- a/apps/Donkey/Sources/DonkeyContracts/UserQueryContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/UserQueryContracts.swift@@ -232,6 +232,14 @@ public enum SignalLevel: String, Equatable, Sendable {case thinking}+/// Well-known keys on a task's `metadata`. Shared so the harness side that writes them and the notch+/// UI that reads them never drift on a raw string literal.+public enum UserQueryTaskMetadataKey {+ /// Set to "true" on a task that failed because the account is out of credits. The notch shows a+ /// "Reload credits" CTA banner for such a task.+ public static let creditReloadRequired = "credits.reloadRequired"+}+public enum UserQueryIntent: Equatable, Sendable {case addContextRequestedcase voiceInputRequesteddiff --git a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swiftindex 4618692d..736a8138 100644--- a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift+++ b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift@@ -58,6 +58,9 @@ public struct UserQueryNotchStatusView: View {/// Login button fires this to start the real sign-in (handled by the model/controller).private let needsLogin: Boolprivate let loginRequested: @MainActor () -> Void+ /// A task that failed for lack of credits shows a "Reload credits" CTA in its banner; tapping it+ /// fires this so the app can open the billing page (reuses the permission-banner button styling).+ private let reloadCreditsRequested: @MainActor (String) -> Voidpublic init(state: UserQueryState,@@ -91,7 +94,8 @@ public struct UserQueryNotchStatusView: View {denyPermissionRequested: @escaping @MainActor (String) -> Void,updateRequested: @escaping @MainActor () -> Void,needsLogin: Bool = false,- loginRequested: @escaping @MainActor () -> Void = {}+ loginRequested: @escaping @MainActor () -> Void = {},+ reloadCreditsRequested: @escaping @MainActor (String) -> Void = { _ in }) {self.state = stateself.updateState = updateState@@ -125,6 +129,7 @@ public struct UserQueryNotchStatusView: View {self.updateRequested = updateRequestedself.needsLogin = needsLoginself.loginRequested = loginRequested+ self.reloadCreditsRequested = reloadCreditsRequested}public var body: some View {@@ -841,6 +846,9 @@ public struct UserQueryNotchStatusView: View {if isPermission {permissionBanner(for: task).opacity(contentDim)+ } else if showsReloadCreditsBanner(task) {+ reloadCreditsBanner(for: task)+ .opacity(contentDim)}}.padding(.horizontal, 12)@@ -1024,6 +1032,39 @@ public struct UserQueryNotchStatusView: View {.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))}+ /// Whether this task failed for lack of credits and should show the reload CTA. Read from the typed+ /// metadata flag the harness sets — never inferred from the narration text.+ private func showsReloadCreditsBanner(_ task: UserQueryNotchTask) -> Bool {+ task.metadata[UserQueryTaskMetadataKey.creditReloadRequired] == "true"+ }++ /// A reload CTA on a credit-exhausted task. Reuses the permission banner's button styling; tapping+ /// it opens the billing page so the user can top up, then re-run the task (Close is still on the row).+ private func reloadCreditsBanner(for task: UserQueryNotchTask) -> some View {+ HStack(spacing: 8) {+ Image(systemName: "creditcard")+ .font(.system(size: 12, weight: .regular))+ .foregroundStyle(Color.white.opacity(0.7))++ Text("Add credits to continue")+ .font(.system(size: 12, weight: .regular))+ .foregroundStyle(Color.white.opacity(0.7))+ .lineLimit(1)+ .truncationMode(.tail)++ Spacer(minLength: 8)++ permissionButton(label: "Reload", prominent: true) {+ reloadCreditsRequested(task.id)+ }+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 8)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Color.white.opacity(0.05))+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))+ }+/// What the user is actually approving — named by the concrete action, never the word "tools"./// Prefers the shell command being requested, falls back to the gate's own reason, and never/// surfaces the runtime's internal "stopped" placeholder.diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swiftindex 4bb025bd..8c0c5c7e 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift@@ -917,6 +917,24 @@ struct DonkeyBackendInferenceClientTests {#expect(httpClient.requests.isEmpty)}+ @Test+ func http402MapsToInsufficientCreditsWithParsedBalance() async {+ // A 402 means the balance is spent (or a spend limit was hit). The client maps it to the typed+ // `.insufficientCredits` case with the balance decoded from the JSON body, so callers surface a+ // "buy credits" message instead of a raw `httpStatus(402, …)` dump.+ let body = Data(#"{"error":"insufficient_credits","message":"out of credits","balance":"0"}"#.utf8)+ let client = DonkeyBackendInferenceClient(+ configuration: configuration(),+ httpClient: FixtureHTTPClient(data: body, statusCode: 402)+ )++ await #expect(throws: DonkeyBackendInferenceClientError.insufficientCredits(balance: "0")) {+ _ = try await client.createResponse(+ RemoteInferenceResponseCreateRequest(model: "router/large", input: .string("hi"))+ )+ }+ }+@Testfunc devAuthBypassIgnoresTheSignedOutGate() async throws {// The dev-auth bypass is always treated as authenticated, so the gate never blocks it.diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swiftindex 3c67807b..945c6293 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift@@ -184,6 +184,28 @@ struct HostedHarnessStepPlannerTests {#expect(httpClient.requests.count == 1)}+ @Test+ func insufficientCreditsFailsSafeOnceWithABuyCreditsPrompt() async {+ // A 402 is an exhausted balance — retrying just 402s again. The planner must stop on the first+ // attempt and surface a clear "buy credits" message with the billing destination, never a raw+ // `httpStatus(402, …)` dump.+ let outOfCredits = (Data(#"{"error":"insufficient_credits","balance":"0"}"#.utf8), 402)+ let httpClient = SequencedHTTPClient(responses: [outOfCredits, outOfCredits, outOfCredits])+ 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"] == "insufficientCredits")+ #expect(planner.lastNarration?.lowercased().contains("credits") == true)+ // Typed flag the notch reads to show the reload CTA (never inferred from the narration text).+ #expect(planner.lastFailureRequiresCreditReload == true)+ // User-facing: no raw status code or error type leaking into the notch.+ #expect(planner.lastNarration?.lowercased().contains("httpstatus") == false)+ // Terminal on the first attempt — no wasted retries against a balance that can't recover mid-run.+ #expect(httpClient.requests.count == 1)+ }+@Testfunc backendHTTPFailureShowsAFriendlyNarrationAndKeepsTheRawErrorForTheThread() async {// A non-auth backend failure must read as a plain, friendly message to the user — never a raw