Skip to content

Open source CapCut alternative.

TypeScript

feat(app): clear the out-of-credits CTA once credits are reloaded

David Lee62bca7d5482
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
index e7771ebf..1bc910c7 100644
--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
@@ -19,6 +19,11 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
/// Mirrors the auth coordinator's session phase into the overlay's `needsLogin`, so the notch
/// flips to/from the login call-to-action as the session is established or expires.
private var authStateCancellable: AnyCancellable?
+ /// Periodically reconciles the out-of-credits reload CTA against the real balance, so it clears once the
+ /// user tops up rather than lingering until relaunch. Paired with an app-reactivation observer for the
+ /// common "topped up in the browser, came back" path. Both are torn down on sign-out.
+ private var creditReloadPollTimer: Timer?
+ private var creditReloadActiveObserver: NSObjectProtocol?
func applicationDidFinishLaunching(_ notification: Notification) {
if ManualCaptureDebugLaunchHandler.shouldHandle(arguments: CommandLine.arguments) {
@@ -181,6 +186,10 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
// the first query's 401. Probe the backend on launch so the notch shows login right away.
validateStoredSession(model: model)
+ // Keep the out-of-credits CTA honest: poll the balance while any task is credit-blocked and clear
+ // the CTA the moment a top-up lands, so it doesn't linger until the next relaunch.
+ startCreditReloadReconciler(model: model)
+
// Warm the on-device speech model in the background so the first voice command
// isn't blocked behind a model download.
AppleSpeechVoiceTranscriptionRuntime.prewarm()
@@ -253,6 +262,67 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
}
}
+ // MARK: - Credit reload reconciliation
+
+ /// Once a task is flagged out-of-credits, nothing in-app retries after the user tops up, so the notch's
+ /// reload CTA would linger until relaunch. Reconcile it against the real balance: a periodic tick while any
+ /// task carries the flag (and only then — the tick is a free no-op otherwise), plus an app-reactivation
+ /// trigger so returning from the billing page in the browser clears the CTA right away.
+ private func startCreditReloadReconciler(model: UserQueryOverlayModel) {
+ creditReloadPollTimer?.invalidate()
+ creditReloadPollTimer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { [weak self, weak model] _ in
+ Task { @MainActor in
+ guard let self, let model else { return }
+ self.reconcileCreditReload(model: model)
+ }
+ }
+ if let creditReloadActiveObserver {
+ NotificationCenter.default.removeObserver(creditReloadActiveObserver)
+ }
+ creditReloadActiveObserver = NotificationCenter.default.addObserver(
+ forName: NSApplication.didBecomeActiveNotification,
+ object: nil,
+ queue: .main
+ ) { [weak self, weak model] _ in
+ Task { @MainActor in
+ guard let self, let model else { return }
+ self.reconcileCreditReload(model: model)
+ }
+ }
+ }
+
+ private func stopCreditReloadReconciler() {
+ creditReloadPollTimer?.invalidate()
+ creditReloadPollTimer = nil
+ if let creditReloadActiveObserver {
+ NotificationCenter.default.removeObserver(creditReloadActiveObserver)
+ self.creditReloadActiveObserver = nil
+ }
+ }
+
+ /// One reconciliation pass: skip entirely unless a task is credit-blocked and the session is usable, then
+ /// fetch the balance and clear the CTA across every flagged task once it goes positive. A 401 routes
+ /// through the same session-expiry handling as every other backend call; any other error is ignored so a
+ /// transient hiccup leaves the CTA in place for the next pass.
+ private func reconcileCreditReload(model: UserQueryOverlayModel) {
+ guard model.hasPendingCreditReload,
+ BackendSessionGate.shared.isAuthenticated,
+ let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment()
+ else { return }
+
+ let backend = DonkeyBackendInferenceClient(
+ configuration: configuration,
+ onAuthenticationRequired: { [weak model] in
+ Task { @MainActor in model?.handleSessionExpired() }
+ }
+ )
+ Task { @MainActor [weak model] in
+ guard let balanceMicros = try? await backend.fetchCreditBalanceMicros(),
+ balanceMicros > 0 else { return }
+ model?.clearPendingCreditReload()
+ }
+ }
+
// MARK: - Sign out
@objc private func signOutMenuAction(_ sender: Any?) {
@@ -283,6 +353,7 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
/// `startAuthenticatedAppSurfaces()` guards on these being nil, so they must be reset here.
private func teardownAuthenticatedSurfaces() {
authStateCancellable = nil
+ stopCreditReloadReconciler()
uiUnderstandingCoordinator?.stop()
uiUnderstandingCoordinator = nil
overlayController?.stop()
diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
index f0d352e8..846de8a6 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
@@ -87,6 +87,9 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
/// `updateConversation`. The same transitions also reset `conversationsStreamingAnswer`.
private static func clearRunMetadata(_ metadata: inout [String: String]) {
metadata[seenMetadataKey] = nil
+ // A fresh run attempt drops the stale out-of-credits CTA; if the new run hits 402 again the harness
+ // re-sets the flag. (The balance poll is the other clear path — see `clearPendingCreditReload`.)
+ metadata[UserQueryConversationMetadataKey.creditReloadRequired] = nil
}
/// Conversation IDs whose final answer is mid-stream. Tracks first-vs-subsequent answer chunk so the
@@ -428,6 +431,30 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
NSWorkspace.shared.open(billingURL)
}
+ /// Whether any task still carries the out-of-credits reload CTA. The app delegate's reconciler reads this
+ /// to decide whether to spend a balance poll at all — with nothing flagged, the periodic tick is a free
+ /// no-op and never touches the network.
+ var hasPendingCreditReload: Bool {
+ notchConversations.contains {
+ $0.metadata[UserQueryConversationMetadataKey.creditReloadRequired] == "true"
+ }
+ }
+
+ /// Drop the out-of-credits reload CTA from every task that carries it, in the notch and in storage. Called
+ /// once the balance poll confirms the account has credits again (see the app delegate's reconciler), so the
+ /// CTA disappears the moment a top-up lands rather than lingering until the next launch. The balance is
+ /// account-wide, so a positive balance clears every credit-blocked task at once.
+ func clearPendingCreditReload() {
+ for index in notchConversations.indices
+ where notchConversations[index].metadata[UserQueryConversationMetadataKey.creditReloadRequired] == "true" {
+ var conversation = notchConversations[index]
+ conversation.metadata[UserQueryConversationMetadataKey.creditReloadRequired] = nil
+ conversation.updatedAt = Date()
+ notchConversations[index] = conversation
+ conversationStore.upsertConversation(conversation)
+ }
+ }
+
/// 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.swift
index ea70fbc2..0657376b 100644
--- a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
@@ -204,6 +204,17 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {
return try JSONDecoder().decode(RemoteInferenceModelList.self, from: data)
}
+ /// The account's current credit balance, in micros. Used to clear a stale "out of credits" CTA once the
+ /// user has topped up: a positive balance means a credit-exhausted task can run again. Reads the typed
+ /// `balanceMicros` field the balance endpoint returns; an absent or unparseable value reads as 0 (still
+ /// empty) rather than throwing, so a malformed body never crashes the poll.
+ public func fetchCreditBalanceMicros() async throws -> Int64 {
+ let request = makeRequest(path: "/api/credits/balance/")
+ let data = try await send(request)
+ let balance = try JSONDecoder().decode(RemoteCreditBalance.self, from: data)
+ return Int64(balance.balanceMicros) ?? 0
+ }
+
/// Mint a short-lived Gemini Live (Vertex AI) connection: an OAuth access
/// token plus the websocket endpoint and fully-qualified model path. The
/// long-lived service-account credential stays on the backend.
@@ -884,3 +895,10 @@ private struct RemoteScreenshotParseStreamError: Decodable {
var message: String
var details: RemoteInferenceJSONValue?
}
+
+/// The slice of `GET /api/credits/balance` the app reads: just the typed balance in micros (a string in the
+/// JSON body). Everything else the endpoint returns (grants, limits, recent usage) is dashboard detail the
+/// app's credit-reload reconciler doesn't need.
+private struct RemoteCreditBalance: Decodable {
+ var balanceMicros: String
+}