Open source CapCut alternative.
TypeScript
feat(app): gate always-on backend loops on session auth
David Le979c94bde4e8
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swiftindex 8ebcd6dd..a895e913 100644--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift@@ -1,7 +1,9 @@import AppKitimport Carbon.HIToolbox+import Combineimport Darwinimport DonkeyAI+import DonkeyContractsimport DonkeyRuntimeimport Foundation@@ -14,6 +16,9 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {private var overlayController: UserQueryOverlayController?private var uiUnderstandingCoordinator: UIUnderstandingCoordinator?private var frontmostVisionWarmCache: FrontmostVisionWarmCache?+ /// 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?func applicationDidFinishLaunching(_ notification: Notification) {if ManualCaptureDebugLaunchHandler.shouldHandle(arguments: CommandLine.arguments) {@@ -29,13 +34,20 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {let authCoordinator = DonkeyAuthCoordinator()self.authCoordinator = authCoordinator+ // Seed the process-wide session gate before any surface is built, so the warm cache, Live+ // session, and auto-resume all see the real auth state on their first tick instead of the+ // optimistic default. The phase observer keeps it current from here on.+ BackendSessionGate.shared.update(isAuthenticated: authCoordinator.isAuthenticated)authCoordinator.authenticationCompleted = { [weak self] _ inself?.startAuthenticatedAppSurfaces()}registerAuthCallbackHandler()installMainMenu()- if authCoordinator.isAuthenticated {+ // First install (never signed in) opens the welcome/sign-in window. A returning user whose+ // session has expired skips the window: the notch comes up in login mode (driven by the auth+ // phase observer) and carries them back through sign-in inline.+ if authCoordinator.isAuthenticated || authCoordinator.hasEverSignedIn {startAuthenticatedAppSurfaces()} else {showLoginWindow()@@ -122,6 +134,30 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {)let model = UserQueryOverlayModel(voiceTranscriber: voiceTranscriber)+ // The notch Login button starts the real Google sign-in; the auth phase drives whether the+ // notch shows the login call-to-action, so an expired session surfaces here without a window.+ model.loginActionRequested = { [weak self] in+ self?.authCoordinator?.beginGoogleSignIn()+ }+ // A mid-run 401 expired the session: sign out (clears the dead cookie, flips phase to signedOut)+ // so the $phase observer below sets needsLogin — surfacing the notch login WITHOUT tearing down+ // the overlay or opening the window, so running tasks stay put and re-auth happens inline.+ model.sessionExpired = { [weak self] in+ self?.authCoordinator?.signOut()+ }+ if let authCoordinator {+ model.updateNeedsLogin(!authCoordinator.isAuthenticated)+ authStateCancellable = authCoordinator.$phase+ .sink { [weak self, weak model] phase in+ model?.updateNeedsLogin(!phase.isSignedIn)+ self?.applySessionState(isSignedIn: phase.isSignedIn, model: model)+ }+ }++ // A locally-stored session can already be expired server-side, which otherwise only surfaces on+ // the first query's 401. Probe the backend on launch so the notch shows login right away.+ validateStoredSession(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()@@ -148,14 +184,54 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {)#endifself.uiUnderstandingCoordinator = uiUnderstandingCoordinator- uiUnderstandingCoordinator.start()// Keep ParsedVisionStore warm: watch the frontmost window and re-parse on big changes, so a// typed vision command reuses a fresh parse instead of paying for one inline. No-ops when the// vision backend isn't configured.let frontmostVisionWarmCache = FrontmostVisionWarmCache.fromEnvironment()self.frontmostVisionWarmCache = frontmostVisionWarmCache- frontmostVisionWarmCache?.start()++ // Start the always-on backend loops only while signed in; the phase observer above suspends and+ // resumes them as the session changes (an expired session must not keep them issuing 401s).+ applySessionState(isSignedIn: authCoordinator?.isAuthenticated == true, model: model)+ }++ /// Drive the process-wide session gate and the always-on backend loops from the auth phase. Signed+ /// out: close the gate (every backend call short-circuits to `.authenticationRequired` with no+ /// network round trip) and fully suspend the warm cache, UI-understanding engine, and Live session,+ /// so a logged-out app stops issuing guaranteed-401 requests. Signed in: reopen the gate and restart+ /// them. Idempotent — `start()`/`stop()` on each loop are safe to call repeatedly.+ private func applySessionState(isSignedIn: Bool, model: UserQueryOverlayModel?) {+ BackendSessionGate.shared.update(isAuthenticated: isSignedIn)+ if isSignedIn {+ uiUnderstandingCoordinator?.start()+ frontmostVisionWarmCache?.start()+ model?.resumeLiveSession()+ } else {+ uiUnderstandingCoordinator?.stop()+ frontmostVisionWarmCache?.stop()+ model?.suspendLiveSession()+ }+ }++ /// Confirms a locally-stored session is still valid server-side. Fires one cheap, auth-gated GET+ /// (`/api/inference/models/`); a 401 routes through the model's session-expiry handling (sign out →+ /// notch login) via the inference client's auth-expiry callback. Network or other errors are+ /// ignored so a transient hiccup never signs the user out. Runs off the launch path.+ private func validateStoredSession(model: UserQueryOverlayModel) {+ guard authCoordinator?.isAuthenticated == true,+ let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment()+ else { return }++ let backend = DonkeyBackendInferenceClient(+ configuration: configuration,+ onAuthenticationRequired: { [weak model] in+ Task { @MainActor in model?.handleSessionExpired() }+ }+ )+ Task {+ _ = try? await backend.listModels()+ }}// MARK: - Sign out@@ -187,6 +263,7 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {/// Tears down the live overlay/runtime surfaces so a later sign-in can rebuild them cleanly./// `startAuthenticatedAppSurfaces()` guards on these being nil, so they must be reset here.private func teardownAuthenticatedSurfaces() {+ authStateCancellable = nilfrontmostVisionWarmCache?.stop()frontmostVisionWarmCache = niluiUnderstandingCoordinator?.stop()diff --git a/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift b/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swiftindex 2d5c84f9..1a2554c9 100644--- a/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift@@ -110,6 +110,7 @@ final class DonkeyAuthCoordinator: ObservableObject {self.cookieStorage = cookieStorageif let session = stateStore.loadSession() {+ stateStore.markHasEverSignedIn()phase = .signedIn(session)} else {phase = .signedOut@@ -120,6 +121,13 @@ final class DonkeyAuthCoordinator: ObservableObject {phase.isSignedIn}+ /// Whether this Mac has completed sign-in at least once. Distinguishes a first install (never+ /// signed in → show the welcome window) from an expired session (signed in before → drive the+ /// re-auth through the notch login).+ var hasEverSignedIn: Bool {+ stateStore.loadHasEverSignedIn()+ }+func beginGoogleSignIn() {let state = Self.makeStateToken()@@ -201,6 +209,7 @@ final class DonkeyAuthCoordinator: ObservableObject {userEmail: nativeSession.userEmail,userName: nativeSession.userName)+ stateStore.markHasEverSignedIn()stateStore.saveSession(session)phase = .signedIn(session)authenticationCompleted?(session)@@ -269,6 +278,8 @@ protocol DonkeyAuthStateStoring {func loadPendingState() -> String?func savePendingState(_ state: String)func clearPendingState()+ func loadHasEverSignedIn() -> Bool+ func markHasEverSignedIn()}struct DonkeyAuthStateStore: DonkeyAuthStateStoring {@@ -310,8 +321,17 @@ struct DonkeyAuthStateStore: DonkeyAuthStateStoring {defaults.removeObject(forKey: Keys.pendingState)}+ func loadHasEverSignedIn() -> Bool {+ defaults.bool(forKey: Keys.hasEverSignedIn)+ }++ func markHasEverSignedIn() {+ defaults.set(true, forKey: Keys.hasEverSignedIn)+ }+private enum Keys {static let session = "donkey.auth.session"static let pendingState = "donkey.auth.pendingState"+ static let hasEverSignedIn = "donkey.auth.hasEverSignedIn"}}diff --git a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swift b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swiftindex f52f8e56..e84470f6 100644--- a/apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swift+++ b/apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swift@@ -231,6 +231,9 @@ final class UIUnderstandingCoordinator {private func refresh(force: Bool = false) {reloadConfigAndReschedule()guard currentConfig.enabled else { return }+ // The AI parse pass hits the hosted backend; while signed out it would only 401, so the engine+ // is idle until sign-in restores it (the app delegate also stops this coordinator on sign-out).+ guard BackendSessionGate.shared.isAuthenticated else { return }guard !isAnalyzing else {UIUnderstandingLog.overlay.debug("debug inspection skipped refresh because analysis is already running")returndiff --git a/apps/Donkey/Sources/DonkeyAI/FrontmostVisionWarmCache.swift b/apps/Donkey/Sources/DonkeyAI/FrontmostVisionWarmCache.swiftindex 25ab2c43..4cd88640 100644--- a/apps/Donkey/Sources/DonkeyAI/FrontmostVisionWarmCache.swift+++ b/apps/Donkey/Sources/DonkeyAI/FrontmostVisionWarmCache.swift@@ -134,6 +134,9 @@ public final class FrontmostVisionWarmCache {func tick() async {guard !VisionWarmCacheActivity.shared.isSuspended else { return }+ // Nothing to keep warm while signed out — the parse would only 401. Skip the expensive capture+ // entirely rather than spending it on a doomed backend call.+ guard BackendSessionGate.shared.isAuthenticated else { return }guard permissionChecker.hasScreenRecordingAccess() else { return }guard let target = MacWindowResolver().frontmostUserAppTarget() else { return }let appKey = target.bundleIdentifier.flatMap { $0.isEmpty ? nil : $0 } ?? target.appName ?? ""diff --git a/apps/Donkey/Sources/DonkeyContracts/BackendSessionGate.swift b/apps/Donkey/Sources/DonkeyContracts/BackendSessionGate.swiftnew file mode 100644index 00000000..8cb5da03--- /dev/null+++ b/apps/Donkey/Sources/DonkeyContracts/BackendSessionGate.swift@@ -0,0 +1,33 @@+import Foundation++/// Process-wide authority on whether the hosted backend session is currently usable.+///+/// The auth coordinator is the single writer: it flips this as the session is established, expires, or+/// is signed out. Every backend caller and always-on background loop reads it. When the session is+/// signed out, `DonkeyBackendInferenceClient` short-circuits each request to `.authenticationRequired`+/// without a network round trip, and the warm-cache / UI-understanding loops skip their work — so a+/// logged-out app stops hammering the backend with guaranteed-401 calls instead of retrying forever.+///+/// It defaults to authenticated so first launch, tests, and dev-bypass paths behave exactly as before+/// until the auth coordinator says otherwise.+public final class BackendSessionGate: @unchecked Sendable {+ public static let shared = BackendSessionGate()++ private let lock = NSLock()+ private var isAuthenticatedStorage = true++ public init() {}++ /// Whether backend calls should be attempted. False once the session is signed out.+ public var isAuthenticated: Bool {+ lock.lock()+ defer { lock.unlock() }+ return isAuthenticatedStorage+ }++ public func update(isAuthenticated: Bool) {+ lock.lock()+ isAuthenticatedStorage = isAuthenticated+ lock.unlock()+ }+}