Skip to content

Open source CapCut alternative.

TypeScript

Add Mac app Google sign-in gate

David Le1e27e229c200
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
index 1649b9fb..e3f7a004 100644
--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
@@ -1,8 +1,12 @@
import AppKit
+import Carbon.HIToolbox
import Darwin
+import Foundation
@MainActor
final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
+ private var authCoordinator: DonkeyAuthCoordinator?
+ private var loginWindowController: DonkeyLoginWindowController?
private var overlayController: PointerPromptOverlayController?
private var runtimeOnboardingController: LocalRuntimeOnboardingWindowController?
@@ -18,6 +22,63 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
return
}
+ let authCoordinator = DonkeyAuthCoordinator()
+ self.authCoordinator = authCoordinator
+ authCoordinator.authenticationCompleted = { [weak self] _ in
+ self?.startAuthenticatedAppSurfaces()
+ }
+ registerAuthCallbackHandler()
+
+ if authCoordinator.isAuthenticated {
+ startAuthenticatedAppSurfaces()
+ } else {
+ showLoginWindow()
+ }
+ }
+
+ func application(_ application: NSApplication, open urls: [URL]) {
+ for url in urls {
+ handleAuthCallbackURL(url)
+ }
+ }
+
+ func applicationShouldHandleReopen(
+ _ sender: NSApplication,
+ hasVisibleWindows flag: Bool
+ ) -> Bool {
+ if authCoordinator?.isAuthenticated != true {
+ showLoginWindow()
+ }
+ return true
+ }
+
+ func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
+ false
+ }
+
+ func applicationWillTerminate(_ notification: Notification) {
+ NSAppleEventManager.shared().removeEventHandler(
+ forEventClass: AEEventClass(kInternetEventClass),
+ andEventID: AEEventID(kAEGetURL)
+ )
+ overlayController?.stop()
+ }
+
+ private func showLoginWindow() {
+ guard let authCoordinator else { return }
+
+ NSApp.setActivationPolicy(.regular)
+ if loginWindowController == nil {
+ loginWindowController = DonkeyLoginWindowController(authCoordinator: authCoordinator)
+ }
+ loginWindowController?.showLogin()
+ }
+
+ private func startAuthenticatedAppSurfaces() {
+ guard overlayController == nil else { return }
+
+ loginWindowController?.close()
+ loginWindowController = nil
NSApp.setActivationPolicy(.accessory)
let model = PointerPromptOverlayModel()
@@ -30,11 +91,33 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
runtimeOnboardingController.showIfSetupNeeded()
}
- func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
- false
+ private func registerAuthCallbackHandler() {
+ NSAppleEventManager.shared().setEventHandler(
+ self,
+ andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)),
+ forEventClass: AEEventClass(kInternetEventClass),
+ andEventID: AEEventID(kAEGetURL)
+ )
}
- func applicationWillTerminate(_ notification: Notification) {
- overlayController?.stop()
+ @objc
+ private func handleGetURLEvent(
+ _ event: NSAppleEventDescriptor,
+ withReplyEvent replyEvent: NSAppleEventDescriptor
+ ) {
+ guard let urlString = event.paramDescriptor(forKeyword: keyDirectObject)?.stringValue,
+ let url = URL(string: urlString) else {
+ return
+ }
+
+ handleAuthCallbackURL(url)
+ }
+
+ private func handleAuthCallbackURL(_ url: URL) {
+ guard authCoordinator?.handleCallbackURL(url) == true else {
+ return
+ }
+
+ NSApp.activate(ignoringOtherApps: true)
}
}
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift b/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift
new file mode 100644
index 00000000..c9e1a8ff
--- /dev/null
+++ b/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift
@@ -0,0 +1,263 @@
+import AppKit
+import Foundation
+
+struct DonkeyAuthSession: Codable, Equatable {
+ var id: String
+ var provider: String
+ var authenticatedAt: Date
+}
+
+enum DonkeyAuthPhase: Equatable {
+ case signedOut
+ case openingBrowser
+ case waitingForCallback
+ case signedIn(DonkeyAuthSession)
+ case failed(String)
+
+ var isSignedIn: Bool {
+ if case .signedIn = self {
+ return true
+ }
+ return false
+ }
+}
+
+struct DonkeyAuthConfiguration: Equatable {
+ var webBaseURL: URL
+ var callbackScheme: String
+
+ static func current(
+ environment: [String: String] = ProcessInfo.processInfo.environment,
+ bundle: Bundle = .main
+ ) -> DonkeyAuthConfiguration {
+ let webBaseURL = Self.configuredURL(
+ environment: environment,
+ bundle: bundle
+ ) ?? URL(string: "http://localhost:3000")!
+ let callbackScheme = Self.configuredValue(
+ environmentKey: "DONKEY_AUTH_CALLBACK_SCHEME",
+ bundleKey: "DonkeyAuthCallbackScheme",
+ environment: environment,
+ bundle: bundle
+ ) ?? "donkey"
+
+ return DonkeyAuthConfiguration(
+ webBaseURL: webBaseURL,
+ callbackScheme: callbackScheme
+ )
+ }
+
+ private static func configuredURL(
+ environment: [String: String],
+ bundle: Bundle
+ ) -> URL? {
+ let configuredValue = configuredValue(
+ environmentKey: "DONKEY_WEB_BASE_URL",
+ bundleKey: "DonkeyWebBaseURL",
+ environment: environment,
+ bundle: bundle
+ ) ?? environment["BETTER_AUTH_URL"]?.trimmingCharacters(in: .whitespacesAndNewlines)
+
+ guard let configuredValue,
+ !configuredValue.isEmpty else {
+ return nil
+ }
+
+ return URL(string: configuredValue)
+ }
+
+ private static func configuredValue(
+ environmentKey: String,
+ bundleKey: String,
+ environment: [String: String],
+ bundle: Bundle
+ ) -> String? {
+ if let environmentValue = environment[environmentKey]?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !environmentValue.isEmpty {
+ return environmentValue
+ }
+
+ let bundleValue = bundle.object(forInfoDictionaryKey: bundleKey) as? String
+ let trimmedBundleValue = bundleValue?.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmedBundleValue?.isEmpty == false ? trimmedBundleValue : nil
+ }
+}
+
+@MainActor
+final class DonkeyAuthCoordinator: ObservableObject {
+ @Published private(set) var phase: DonkeyAuthPhase
+
+ var authenticationCompleted: ((DonkeyAuthSession) -> Void)?
+
+ private let configuration: DonkeyAuthConfiguration
+ private let stateStore: DonkeyAuthStateStoring
+
+ init(
+ configuration: DonkeyAuthConfiguration = .current(),
+ stateStore: DonkeyAuthStateStoring = DonkeyAuthStateStore()
+ ) {
+ self.configuration = configuration
+ self.stateStore = stateStore
+
+ if let session = stateStore.loadSession() {
+ phase = .signedIn(session)
+ } else {
+ phase = .signedOut
+ }
+ }
+
+ var isAuthenticated: Bool {
+ phase.isSignedIn
+ }
+
+ func beginGoogleSignIn() {
+ let state = Self.makeStateToken()
+
+ guard let callbackURL = callbackURL(state: state),
+ let signInURL = signInURL(callbackURL: callbackURL) else {
+ phase = .failed("Sign-in could not be configured.")
+ return
+ }
+
+ stateStore.savePendingState(state)
+ phase = .openingBrowser
+
+ guard NSWorkspace.shared.open(signInURL) else {
+ stateStore.clearPendingState()
+ phase = .failed("The browser could not be opened.")
+ return
+ }
+
+ phase = .waitingForCallback
+ }
+
+ @discardableResult
+ func handleCallbackURL(_ url: URL) -> Bool {
+ guard isAuthCallbackURL(url) else {
+ return false
+ }
+
+ let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
+ guard let returnedState = Self.queryValue(named: "state", in: queryItems),
+ let expectedState = stateStore.loadPendingState(),
+ returnedState == expectedState else {
+ phase = .failed("Sign-in could not be verified. Please try again.")
+ return true
+ }
+
+ stateStore.clearPendingState()
+
+ if let error = Self.queryValue(named: "error", in: queryItems), !error.isEmpty {
+ phase = .failed("Google sign-in did not finish. Please try again.")
+ return true
+ }
+
+ let session = DonkeyAuthSession(
+ id: UUID().uuidString,
+ provider: "google",
+ authenticatedAt: Date()
+ )
+ stateStore.saveSession(session)
+ phase = .signedIn(session)
+ authenticationCompleted?(session)
+ return true
+ }
+
+ func clearFailedState() {
+ guard case .failed = phase else { return }
+ phase = stateStore.loadSession().map(DonkeyAuthPhase.signedIn) ?? .signedOut
+ }
+
+ private func callbackURL(state: String) -> URL? {
+ var components = URLComponents()
+ components.scheme = configuration.callbackScheme
+ components.host = "auth"
+ components.path = "/callback"
+ components.queryItems = [
+ URLQueryItem(name: "state", value: state)
+ ]
+ return components.url
+ }
+
+ private func signInURL(callbackURL: URL) -> URL? {
+ var components = URLComponents(
+ url: configuration.webBaseURL,
+ resolvingAgainstBaseURL: false
+ )
+ let basePath = components?.path.trimmingCharacters(in: CharacterSet(charactersIn: "/")) ?? ""
+ components?.path = "/" + [basePath, "mac-auth"]
+ .filter { !$0.isEmpty }
+ .joined(separator: "/")
+ components?.queryItems = [
+ URLQueryItem(name: "callbackURL", value: callbackURL.absoluteString),
+ URLQueryItem(name: "errorCallbackURL", value: callbackURL.absoluteString)
+ ]
+ return components?.url
+ }
+
+ private func isAuthCallbackURL(_ url: URL) -> Bool {
+ url.scheme == configuration.callbackScheme &&
+ url.host == "auth" &&
+ url.path == "/callback"
+ }
+
+ private static func makeStateToken() -> String {
+ "\(UUID().uuidString)-\(UUID().uuidString)"
+ }
+
+ private static func queryValue(
+ named name: String,
+ in queryItems: [URLQueryItem]
+ ) -> String? {
+ queryItems.first { $0.name == name }?.value
+ }
+}
+
+protocol DonkeyAuthStateStoring {
+ func loadSession() -> DonkeyAuthSession?
+ func saveSession(_ session: DonkeyAuthSession)
+ func loadPendingState() -> String?
+ func savePendingState(_ state: String)
+ func clearPendingState()
+}
+
+struct DonkeyAuthStateStore: DonkeyAuthStateStoring {
+ private let defaults: UserDefaults
+
+ init(defaults: UserDefaults = .standard) {
+ self.defaults = defaults
+ }
+
+ func loadSession() -> DonkeyAuthSession? {
+ guard let data = defaults.data(forKey: Keys.session) else {
+ return nil
+ }
+
+ return try? JSONDecoder().decode(DonkeyAuthSession.self, from: data)
+ }
+
+ func saveSession(_ session: DonkeyAuthSession) {
+ guard let data = try? JSONEncoder().encode(session) else {
+ return
+ }
+
+ defaults.set(data, forKey: Keys.session)
+ }
+
+ func loadPendingState() -> String? {
+ defaults.string(forKey: Keys.pendingState)
+ }
+
+ func savePendingState(_ state: String) {
+ defaults.set(state, forKey: Keys.pendingState)
+ }
+
+ func clearPendingState() {
+ defaults.removeObject(forKey: Keys.pendingState)
+ }
+
+ private enum Keys {
+ static let session = "donkey.auth.session"
+ static let pendingState = "donkey.auth.pendingState"
+ }
+}
diff --git a/apps/Donkey/Sources/Donkey/DonkeyLoginWindowController.swift b/apps/Donkey/Sources/Donkey/DonkeyLoginWindowController.swift
new file mode 100644
index 00000000..64801848
--- /dev/null
+++ b/apps/Donkey/Sources/Donkey/DonkeyLoginWindowController.swift
@@ -0,0 +1,178 @@
+import AppKit
+import SwiftUI
+
+@MainActor
+final class DonkeyLoginWindowController: NSWindowController {
+ private let authCoordinator: DonkeyAuthCoordinator
+
+ init(authCoordinator: DonkeyAuthCoordinator) {
+ self.authCoordinator = authCoordinator
+
+ let contentView = DonkeyLoginView(authCoordinator: authCoordinator)
+ let window = NSWindow(
+ contentRect: CGRect(x: 0, y: 0, width: 820, height: 680),
+ styleMask: [.titled, .closable, .miniaturizable],
+ backing: .buffered,
+ defer: false
+ )
+ window.title = "Donkey"
+ window.titlebarAppearsTransparent = true
+ window.isMovableByWindowBackground = true
+ window.backgroundColor = NSColor(red: 0.13, green: 0.13, blue: 0.12, alpha: 1)
+ window.contentView = NSHostingView(rootView: contentView)
+ window.center()
+
+ super.init(window: window)
+ }
+
+ @available(*, unavailable)
+ required init?(coder: NSCoder) {
+ nil
+ }
+
+ func showLogin() {
+ showWindow(nil)
+ window?.makeKeyAndOrderFront(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ }
+}
+
+private struct DonkeyLoginView: View {
+ @ObservedObject var authCoordinator: DonkeyAuthCoordinator
+
+ var body: some View {
+ ZStack {
+ Color(red: 0.13, green: 0.13, blue: 0.12)
+ .ignoresSafeArea()
+
+ VStack(spacing: 0) {
+ Spacer(minLength: 68)
+
+ DonkeyBurstMark()
+ .frame(width: 86, height: 86)
+ .padding(.bottom, 58)
+
+ Text("Donkey for Mac")
+ .font(.system(size: 48, weight: .bold, design: .serif))
+ .foregroundStyle(.white)
+ .padding(.bottom, 18)
+
+ Text("Sign in to start using Donkey on this Mac.")
+ .font(.system(size: 22, weight: .regular))
+ .foregroundStyle(.white.opacity(0.58))
+
+ Spacer(minLength: 76)
+
+ VStack(spacing: 16) {
+ Button {
+ authCoordinator.beginGoogleSignIn()
+ } label: {
+ HStack(spacing: 14) {
+ GoogleLetterMark()
+ .frame(width: 25, height: 25)
+ Text(buttonTitle)
+ .font(.system(size: 23, weight: .semibold))
+ }
+ .foregroundStyle(.black.opacity(0.82))
+ .frame(maxWidth: .infinity)
+ .frame(height: 60)
+ .background(
+ RoundedRectangle(cornerRadius: 14, style: .continuous)
+ .fill(Color.white.opacity(buttonIsDisabled ? 0.68 : 0.96))
+ )
+ }
+ .buttonStyle(.plain)
+ .disabled(buttonIsDisabled)
+ .accessibilityLabel("Continue with Google")
+
+ statusText
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(statusColor)
+ .frame(height: 20)
+ }
+ .frame(width: 560)
+ .padding(.bottom, 70)
+ }
+ .padding(.horizontal, 52)
+ }
+ }
+
+ private var buttonTitle: String {
+ switch authCoordinator.phase {
+ case .openingBrowser:
+ return "Opening Google..."
+ case .waitingForCallback:
+ return "Waiting for Google..."
+ default:
+ return "Continue with Google"
+ }
+ }
+
+ private var buttonIsDisabled: Bool {
+ switch authCoordinator.phase {
+ case .openingBrowser, .waitingForCallback:
+ return true
+ default:
+ return false
+ }
+ }
+
+ @ViewBuilder
+ private var statusText: some View {
+ switch authCoordinator.phase {
+ case .waitingForCallback:
+ Text("Finish sign-in in your browser to continue.")
+ case .failed(let message):
+ Text(message)
+ default:
+ Text("")
+ }
+ }
+
+ private var statusColor: Color {
+ if case .failed = authCoordinator.phase {
+ return Color(red: 1.0, green: 0.47, blue: 0.36)
+ }
+
+ return .white.opacity(0.54)
+ }
+}
+
+private struct DonkeyBurstMark: View {
+ private let rayCount = 12
+
+ var body: some View {
+ ZStack {
+ RoundedRectangle(cornerRadius: 18, style: .continuous)
+ .fill(Color(red: 0.87, green: 0.43, blue: 0.28))
+
+ ForEach(0..<rayCount, id: \.self) { index in
+ Capsule(style: .continuous)
+ .fill(.white)
+ .frame(width: 6, height: 54)
+ .offset(y: -21)
+ .rotationEffect(.degrees(Double(index) * (360 / Double(rayCount))))
+ }
+ }
+ .shadow(color: .black.opacity(0.24), radius: 20, y: 14)
+ }
+}
+
+private struct GoogleLetterMark: View {
+ var body: some View {
+ Text("G")
+ .font(.system(size: 25, weight: .bold, design: .rounded))
+ .foregroundStyle(
+ LinearGradient(
+ colors: [
+ Color(red: 0.26, green: 0.52, blue: 0.96),
+ Color(red: 0.18, green: 0.66, blue: 0.32),
+ Color(red: 0.98, green: 0.76, blue: 0.18),
+ Color(red: 0.92, green: 0.26, blue: 0.21)
+ ],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ )
+ }
+}
diff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.md
index 56129a74..9d0f08ef 100644
--- a/docs/guides/pointer-prompt-overlay.md
+++ b/docs/guides/pointer-prompt-overlay.md
@@ -5,6 +5,10 @@
Donkey supports a floating macOS overlay for conversational task threads and
quick local-app actions:
+- On first launch, Donkey shows a Google-only Mac sign-in window before starting
+ the overlay. Until the browser returns through the `donkey://auth/callback`
+ handoff, the notch surface is not shown and double-Command activation is not
+ registered.
- Double-tap Command and release to open a centered prompt with keyboard focus.
- Double-tap Command and hold the second press to open the prompt in voice mode.
- Show a top-center notch status surface for task progress, recent tasks, follow-up input, file drops, updates, and per-task pause/resume.
@@ -24,6 +28,9 @@ quick local-app actions:
## Technical Guidelines
- `PointerPromptOverlayController` owns AppKit surfaces, placement, hover tracking, focus, keyboard shortcut recognition, dismissal, file-drop routing, and microphone level capture.
+- `DonkeyAuthCoordinator` and `DonkeyLoginWindowController` own the Mac sign-in
+ gate. App startup should create the overlay controller only after a stored
+ Google session exists or a pending sign-in callback validates its state token.
- SwiftUI rendering lives in `DonkeyUI` and consumes state/contracts from `DonkeyContracts`. It should not perform command parsing, model calls, input execution, screen capture, or microphone capture.
- `PointerPromptOverlayModel` owns product state. Durable task data is persisted through Core Data in Application Support.
- Spawn display state is typed state. The model emits progress, target hints, and current selection; the overlay controller resolves hints against safe visible windows and keeps voice capture on the centered prompt; SwiftUI renders the notch cue, cursors, labels, label-to-editor transition, and selection state.