import AppKit import Combine import Foundation @MainActor final class AppUsageManager { static let shared = AppUsageManager() static let didCompleteFirstSession = Notification.Name("AppUsageManager.didCompleteFirstSession") private static let hasCompletedFirstSessionKey = "AppUsageManager.hasCompletedFirstSession" private let defaults: UserDefaults private var cancellables = Set() private init(defaults: UserDefaults = .standard) { self.defaults = defaults } /// `true` until the user has finished their first app session. var isFirstTimeUser: Bool { !defaults.bool(forKey: Self.hasCompletedFirstSessionKey) } func start() { guard cancellables.isEmpty else { return } NotificationCenter.default.publisher(for: NSApplication.willResignActiveNotification) .sink { [weak self] _ in self?.markFirstSessionCompleted() } .store(in: &cancellables) } func markFirstSessionCompleted() { guard isFirstTimeUser else { return } defaults.set(true, forKey: Self.hasCompletedFirstSessionKey) NotificationCenter.default.post(name: Self.didCompleteFirstSession, object: nil) } }