From 5e8236f77fbd8dac4dcc281fcefb8dffefc77993 Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Thu, 10 Sep 2026 12:38:11 -0700 Subject: [PATCH] feat(mac): notify when an update is available --- mac/Sources/CodeBurnMenubar/CodeBurnApp.swift | 25 ++++ .../CodeBurnMenubar/Data/UpdateChecker.swift | 54 +++++++- .../CodeBurnMenubar/Data/UpdateNotifier.swift | 50 +++++++ .../CodeBurnMenubar/Views/SettingsView.swift | 10 ++ .../UpdateNotificationTests.swift | 127 ++++++++++++++++++ 5 files changed, 260 insertions(+), 6 deletions(-) create mode 100644 mac/Sources/CodeBurnMenubar/Data/UpdateNotifier.swift create mode 100644 mac/Tests/CodeBurnMenubarTests/UpdateNotificationTests.swift diff --git a/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift b/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift index a3a592fa..bfdddba9 100644 --- a/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift +++ b/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift @@ -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() } + } +} diff --git a/mac/Sources/CodeBurnMenubar/Data/UpdateChecker.swift b/mac/Sources/CodeBurnMenubar/Data/UpdateChecker.swift index c7d24598..0b6a8d3c 100644 --- a/mac/Sources/CodeBurnMenubar/Data/UpdateChecker.swift +++ b/mac/Sources/CodeBurnMenubar/Data/UpdateChecker.swift @@ -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) diff --git a/mac/Sources/CodeBurnMenubar/Data/UpdateNotifier.swift b/mac/Sources/CodeBurnMenubar/Data/UpdateNotifier.swift new file mode 100644 index 00000000..83cc9f22 --- /dev/null +++ b/mac/Sources/CodeBurnMenubar/Data/UpdateNotifier.swift @@ -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) + } +} diff --git a/mac/Sources/CodeBurnMenubar/Views/SettingsView.swift b/mac/Sources/CodeBurnMenubar/Views/SettingsView.swift index e008584f..91211281 100644 --- a/mac/Sources/CodeBurnMenubar/Views/SettingsView.swift +++ b/mac/Sources/CodeBurnMenubar/Views/SettingsView.swift @@ -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 = [25, 50, 100, 200, 500] private let tokenPresets: Set = [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 }, diff --git a/mac/Tests/CodeBurnMenubarTests/UpdateNotificationTests.swift b/mac/Tests/CodeBurnMenubarTests/UpdateNotificationTests.swift new file mode 100644 index 00000000..ca0487e8 --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/UpdateNotificationTests.swift @@ -0,0 +1,127 @@ +import Foundation +import Testing +@testable import CodeBurnMenubar + +@Suite("Update notifications") +@MainActor +struct UpdateNotificationTests { + @Test("same version pair notifies once, a newer one notifies again") + func dedupesUntilVersionChanges() async throws { + try await withIsolatedChecker { checker, notifier, _ in + await checker.notifyIfUpdateAvailable(appVersion: "0.9.25", cliVersion: nil) + await checker.notifyIfUpdateAvailable(appVersion: "0.9.25", cliVersion: nil) + + #expect(notifier.posts.count == 1) + + await checker.notifyIfUpdateAvailable(appVersion: "0.9.26", cliVersion: nil) + + #expect(notifier.posts.count == 2) + } + } + + @Test("dedupe survives a fresh checker over the same defaults") + func dedupePersists() async throws { + try await withIsolatedChecker { checker, notifier, defaults in + await checker.notifyIfUpdateAvailable(appVersion: "0.9.25", cliVersion: "0.9.25") + + let relaunched = UpdateChecker(defaults: defaults, makeNotifier: { notifier }) + await relaunched.notifyIfUpdateAvailable(appVersion: "0.9.25", cliVersion: "0.9.25") + + #expect(notifier.posts.count == 1) + } + } + + @Test("toggle off posts nothing and never asks for authorization") + func toggleOffStaysSilent() async throws { + try await withIsolatedChecker { checker, notifier, defaults in + defaults.set(false, forKey: UpdateNotificationPreference.defaultsKey) + + await checker.notifyIfUpdateAvailable(appVersion: "0.9.25", cliVersion: "0.9.25") + + #expect(notifier.posts.isEmpty) + #expect(notifier.authorizationRequests == 0) + } + } + + @Test("denied authorization posts nothing") + func deniedAuthorizationPostsNothing() async throws { + try await withIsolatedChecker { checker, notifier, _ in + notifier.authorized = false + + await checker.notifyIfUpdateAvailable(appVersion: "0.9.25", cliVersion: nil) + + #expect(notifier.posts.isEmpty) + #expect(notifier.authorizationRequests == 1) + } + } + + @Test("no update available posts nothing") + func nothingAvailablePostsNothing() async throws { + try await withIsolatedChecker { checker, notifier, _ in + await checker.notifyIfUpdateAvailable(appVersion: nil, cliVersion: nil) + + #expect(notifier.posts.isEmpty) + #expect(notifier.authorizationRequests == 0) + } + } + + @Test("app-only copy names the app version") + func appOnlyCopy() async throws { + try await withIsolatedChecker { checker, notifier, _ in + await checker.notifyIfUpdateAvailable(appVersion: "0.9.25", cliVersion: nil) + + #expect(notifier.posts.first?.title == "CodeBurn v0.9.25 available") + #expect(notifier.posts.first?.body == "Click to install the update.") + } + } + + @Test("cli-only copy names the CLI") + func cliOnlyCopy() async throws { + try await withIsolatedChecker { checker, notifier, _ in + await checker.notifyIfUpdateAvailable(appVersion: nil, cliVersion: "0.9.25") + + #expect(notifier.posts.first?.title == "CodeBurn CLI v0.9.25 available") + #expect(notifier.posts.first?.body == "Click to install the update.") + } + } + + @Test("both-available copy mentions app and CLI") + func bothCopy() async throws { + try await withIsolatedChecker { checker, notifier, _ in + await checker.notifyIfUpdateAvailable(appVersion: "0.9.25", cliVersion: "0.9.24") + + #expect(notifier.posts.first?.title == "CodeBurn v0.9.25 available") + #expect(notifier.posts.first?.body == "App and CLI v0.9.24 updates are ready. Click to install.") + } + } +} + +@MainActor +private func withIsolatedChecker( + _ body: @MainActor (UpdateChecker, RecordingUpdateNotifier, UserDefaults) async throws -> Void +) async throws { + let suiteName = "codeburn.update.notifications.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defaults.removePersistentDomain(forName: suiteName) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let notifier = RecordingUpdateNotifier() + let checker = UpdateChecker(defaults: defaults, makeNotifier: { notifier }) + try await body(checker, notifier, defaults) +} + +@MainActor +private final class RecordingUpdateNotifier: UpdateNotifier { + var authorized = true + var authorizationRequests = 0 + var posts: [(title: String, body: String, identifier: String)] = [] + + func requestAuthorizationIfNeeded() async -> Bool { + authorizationRequests += 1 + return authorized + } + + func post(title: String, body: String, identifier: String) { + posts.append((title, body, identifier)) + } +}