feat(mac): notify when an update is available

This commit is contained in:
iamtoruk 2026-09-10 12:38:11 -07:00
parent 36dd897913
commit 5e8236f77f
5 changed files with 260 additions and 6 deletions

View file

@ -3,6 +3,7 @@ import SwiftUI
import AppKit
import Observation
import ServiceManagement
import UserNotifications
private let refreshIntervalSeconds: UInt64 = 30
private let forceRefreshWatchdogSeconds: TimeInterval = 90
@ -165,9 +166,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSM
registerLoginItemIfNeeded()
observeSubscriptionDisconnect()
observeCapacityDockProviderSettingsRequests()
setupUpdateNotifications()
Task { await updateChecker.checkIfNeeded() }
}
/// Delegate only: authorization is requested lazily by UpdateChecker the
/// first time a notification would actually be posted.
private func setupUpdateNotifications() {
guard Bundle.main.bundleIdentifier != nil else { return }
UNUserNotificationCenter.current().delegate = self
}
private func observeCapacityDockProviderSettingsRequests() {
providerSettingsObserver = NotificationCenter.default.addObserver(
forName: .capacityDockOpenProviderSettings,
@ -1667,3 +1676,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSM
refreshStatusButton()
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
nonisolated func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification
) async -> UNNotificationPresentationOptions {
[.banner]
}
nonisolated func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse
) async {
await MainActor.run { self.updateChecker.performFullUpdate() }
}
}

View file

@ -6,6 +6,7 @@ private let checkIntervalSeconds: TimeInterval = 2 * 24 * 60 * 60
private let lastCheckKey = "UpdateChecker.lastCheckDate"
private let cachedVersionKey = "UpdateChecker.latestVersion"
private let cachedCliVersionKey = "UpdateChecker.latestCliVersion"
private let lastNotifiedVersionsKey = "UpdateChecker.lastNotifiedVersions"
private let updateTimeoutSeconds: UInt64 = 120
private let maxUpdateStderrBytes = 64 * 1024
// The installer that scans `mac-v*` releases for the menubar zip (instead of
@ -62,6 +63,15 @@ private final class LockedDataBuffer: @unchecked Sendable {
@MainActor
@Observable
final class UpdateChecker {
@ObservationIgnored private let defaults: UserDefaults
@ObservationIgnored private let makeNotifier: () -> any UpdateNotifier
@ObservationIgnored private var notifier: (any UpdateNotifier)?
init(defaults: UserDefaults = .standard, makeNotifier: @escaping () -> any UpdateNotifier = { SystemUpdateNotifier() }) {
self.defaults = defaults
self.makeNotifier = makeNotifier
}
var latestVersion: String?
var latestCliVersion: String?
var installedCliVersion: String?
@ -118,14 +128,19 @@ final class UpdateChecker {
func checkIfNeeded() async {
installedCliVersion = Self.queryInstalledCliVersion()
let lastCheck = UserDefaults.standard.double(forKey: lastCheckKey)
let lastCheck = defaults.double(forKey: lastCheckKey)
let now = Date().timeIntervalSince1970
if now - lastCheck < checkIntervalSeconds {
latestVersion = UserDefaults.standard.string(forKey: cachedVersionKey)
latestCliVersion = UserDefaults.standard.string(forKey: cachedCliVersionKey)
latestVersion = defaults.string(forKey: cachedVersionKey)
latestCliVersion = defaults.string(forKey: cachedCliVersionKey)
return
}
await check()
// Only the background poll notifies; a manual check already shows its result.
await notifyIfUpdateAvailable(
appVersion: updateAvailable ? latestVersion : nil,
cliVersion: cliUpdateAvailable ? latestCliVersion : nil
)
}
func check() async {
@ -157,9 +172,9 @@ final class UpdateChecker {
latestVersion = version
latestCliVersion = cliVersion
UserDefaults.standard.set(Date().timeIntervalSince1970, forKey: lastCheckKey)
UserDefaults.standard.set(version, forKey: cachedVersionKey)
if let cliVersion { UserDefaults.standard.set(cliVersion, forKey: cachedCliVersionKey) }
defaults.set(Date().timeIntervalSince1970, forKey: lastCheckKey)
defaults.set(version, forKey: cachedVersionKey)
if let cliVersion { defaults.set(cliVersion, forKey: cachedCliVersionKey) }
} catch {
updateFailureStage = .check
updateError = error.localizedDescription
@ -167,6 +182,33 @@ final class UpdateChecker {
}
}
/// Posts at most one notification per new version pair; the 2-day repoll
/// finds the same pair stamped and stays quiet.
func notifyIfUpdateAvailable(appVersion: String?, cliVersion: String?) async {
guard UpdateNotificationPreference.isEnabled(defaults: defaults) else { return }
guard let copy = Self.updateNotificationCopy(appVersion: appVersion, cliVersion: cliVersion) else { return }
let stamp = "\(appVersion ?? "-")|\(cliVersion ?? "-")"
guard defaults.string(forKey: lastNotifiedVersionsKey) != stamp else { return }
let notifier = notifier ?? makeNotifier()
self.notifier = notifier
guard await notifier.requestAuthorizationIfNeeded() else { return }
notifier.post(title: copy.title, body: copy.body, identifier: "UpdateChecker.\(stamp)")
defaults.set(stamp, forKey: lastNotifiedVersionsKey)
}
nonisolated static func updateNotificationCopy(appVersion: String?, cliVersion: String?) -> (title: String, body: String)? {
switch (appVersion, cliVersion) {
case let (app?, cli?):
return ("CodeBurn \(AppVersion.display(app)) available", "App and CLI \(AppVersion.display(cli)) updates are ready. Click to install.")
case let (app?, nil):
return ("CodeBurn \(AppVersion.display(app)) available", "Click to install the update.")
case let (nil, cli?):
return ("CodeBurn CLI \(AppVersion.display(cli)) available", "Click to install the update.")
case (nil, nil):
return nil
}
}
nonisolated static func resolveLatestCliVersion(in releases: [GitHubRelease]) -> String? {
for release in releases where release.tag_name.hasPrefix("v") && !release.tag_name.hasPrefix("mac-v") {
return AppVersion.normalize(release.tag_name)

View file

@ -0,0 +1,50 @@
import Foundation
import UserNotifications
/// User preference for proactive update notifications. Absent key is true, so
/// existing installs get the notification without visiting Settings first.
enum UpdateNotificationPreference {
static let defaultsKey = "codeburn.update.notificationsEnabled"
static func isEnabled(defaults: UserDefaults = .standard) -> Bool {
defaults.object(forKey: defaultsKey) as? Bool ?? true
}
}
/// The notification side of the update check, behind a protocol so tests never
/// reach `UNUserNotificationCenter.current()`, which aborts in a process that is
/// not an app bundle (`swift test`, `swift run`).
@MainActor
protocol UpdateNotifier: AnyObject {
func requestAuthorizationIfNeeded() async -> Bool
func post(title: String, body: String, identifier: String)
}
@MainActor
final class SystemUpdateNotifier: UpdateNotifier {
func requestAuthorizationIfNeeded() async -> Bool {
guard Bundle.main.bundleIdentifier != nil else { return false }
let center = UNUserNotificationCenter.current()
switch await center.notificationSettings().authorizationStatus {
case .authorized, .provisional:
return true
case .notDetermined:
do {
return try await center.requestAuthorization(options: [.alert])
} catch {
NSLog("CodeBurn: notification authorization failed: \(error)")
return false
}
default:
return false
}
}
func post(title: String, body: String, identifier: String) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}

View file

@ -388,6 +388,9 @@ private struct GeneralSettingsTab: View {
@AppStorage(PreferredTerminal.defaultsKey)
private var preferredTerminalRaw: String = PreferredTerminal.default.rawValue
@AppStorage(UpdateNotificationPreference.defaultsKey)
private var notifyAboutUpdates: Bool = true
private let costPresets: Set<Double> = [25, 50, 100, 200, 500]
private let tokenPresets: Set<Double> = [1_000_000, 5_000_000, 10_000_000, 25_000_000, 50_000_000, 100_000_000]
@ -481,6 +484,13 @@ private struct GeneralSettingsTab: View {
.foregroundStyle(.secondary)
}
Section("Updates") {
Toggle("Notify me about updates", isOn: $notifyAboutUpdates)
Text("Posts a notification when a new CodeBurn release is available. Click it to install.")
.font(.system(size: 11))
.foregroundStyle(.secondary)
}
Section("Terminal") {
Picker("Open commands in", selection: Binding(
get: { PreferredTerminal(rawValue: preferredTerminalRaw) ?? .default },