diff --git a/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift b/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift index d6c1cd04..9653b47e 100644 --- a/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift +++ b/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift @@ -36,8 +36,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { private var lastContextMenuPresentedAt: Date = .distantPast fileprivate let store = AppStore() let updateChecker = UpdateChecker() - /// Held for the lifetime of the app to opt out of App Nap and Automatic Termination. - private var backgroundActivity: NSObjectProtocol? + /// True while the displays are asleep. Refresh ticks skip spawning + /// entirely then: nobody can see the menubar, and every fetch is a full + /// Node process (#647). + private var displayAsleep = false + /// Bounds status staleness under App Nap: the 30s timer can be coalesced + /// once the app naps (no permanent activity assertion anymore, #647), so + /// this system-scheduled activity guarantees a tick attempt every few + /// minutes. It goes through the same cadence gate as every other tick. + private var napBackstop: NSBackgroundActivityScheduler? private var pendingRefreshWork: DispatchWorkItem? private var refreshTimer: DispatchSourceTimer? private var forceRefreshTask: Task? @@ -81,16 +88,20 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { func applicationDidFinishLaunching(_ notification: Notification) { ProcessInfo.processInfo.automaticTerminationSupportEnabled = false ProcessInfo.processInfo.disableSuddenTermination() - backgroundActivity = ProcessInfo.processInfo.beginActivity( - options: [.automaticTerminationDisabled, .suddenTerminationDisabled], - reason: "CodeBurn menubar background refresh" - ) + // Deliberately NO app-lifetime beginActivity here. A permanent + // assertion opted the app out of App Nap forever, which kept the 30s + // spawn loop running at full tilt on battery and with the display + // off (#647). App Nap coalescing an idle tick is the desired + // behavior; each in-flight refresh holds its own short .background + // activity so a fetch is never napped mid-flight, and any user + // interaction (popover open, wake) refreshes immediately. restorePersistedCurrency() setupStatusItem() setupPopover() observeStore() startRefreshLoop() + startNapBackstop() setupWakeObservers() removeLegacyRefreshAgent() registerLoginItemIfNeeded() @@ -123,6 +134,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { queue: .main ) { [weak self] _ in Task { @MainActor in + self?.displayAsleep = false self?.recoverRefreshPipelineAfterInterruption(resetLoading: true, reason: "wake") } } @@ -133,9 +145,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { queue: .main ) { [weak self] _ in Task { @MainActor in + self?.displayAsleep = false self?.recoverRefreshPipelineAfterInterruption(resetLoading: true, reason: "screen wake") } } + + // Display sleep without system sleep (clamshell displays off, screen + // saver energy settings) previously kept the full spawn cadence + // running for hours. Skip refreshes until the screens wake. + NSWorkspace.shared.notificationCenter.addObserver( + forName: NSWorkspace.screensDidSleepNotification, + object: nil, + queue: .main + ) { [weak self] _ in + Task { @MainActor in + self?.displayAsleep = true + } + } } private func prepareRefreshPipelineForSleep() { @@ -284,11 +310,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { return false } - private func refreshStatusPayloadIfNeeded(reason: String, force: Bool = false) { + private func refreshStatusPayloadIfNeeded(reason: String, force: Bool = false, minAgeSeconds: TimeInterval = 0) { let now = Date() _ = clearStaleStatusPayloadRefreshIfNeeded(now: now) guard statusPayloadRefreshTask == nil else { return } guard force || store.needsStatusPayloadRefresh else { return } + // The 30s cache TTL would otherwise defeat the battery/low-power + // backoff through this fallback path: honor the same spawn interval + // the main loop uses. A missing payload (nil age) always fetches. + if !force, minAgeSeconds > 0, let age = store.menubarPayloadAgeSeconds, + TimeInterval(age) < minAgeSeconds { return } let menubarPeriod = store.menubarPeriod if let age = store.menubarPayloadAgeSeconds, age > 120 { @@ -300,6 +331,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { let generation = statusPayloadRefreshGeneration statusPayloadRefreshTask = Task { [weak self] in guard let self else { return } + let activity = ProcessInfo.processInfo.beginActivity( + options: .background, reason: "CodeBurn status refresh") + defer { ProcessInfo.processInfo.endActivity(activity) } await self.store.refreshQuietly(period: menubarPeriod, force: true) self.refreshStatusButton() guard self.statusPayloadRefreshGeneration == generation, !Task.isCancelled else { return } @@ -324,6 +358,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { let generation = forceRefreshGeneration forceRefreshTask = Task { + let activity = ProcessInfo.processInfo.beginActivity( + options: .background, reason: "CodeBurn refresh") + defer { ProcessInfo.processInfo.endActivity(activity) } async let main: Void = refreshUsagePayloads(force: true, showLoading: true) async let quotas: Bool = refreshLiveQuotaProgressIfDue(force: forceQuota) _ = await main @@ -340,6 +377,21 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { private func refreshUsagePayloads(force: Bool, showLoading: Bool = false) async { let menubarPeriod = store.menubarPeriod + + // With the popover closed, only the payloads the status item actually + // renders are worth a Node spawn: the menubar period, plus today for + // the context-menu summary and day views. The popover's selected key + // is refreshed by refreshPayloadForPopoverOpen the moment it opens, + // so a closed-popover tick never pays for it (#647). + if !(popover?.isShown ?? false) { + async let menubar: Void = store.refreshQuietly(period: menubarPeriod, force: force) + async let today: Void = menubarPeriod != .today + ? store.refreshQuietly(period: .today, force: force) + : () + _ = await (menubar, today) + return + } + let needsMenubarPayload = store.selectedPeriod != menubarPeriod || store.selectedProvider != .all let needsTodayPayload = (store.selectedPeriod != .today || store.selectedProvider != .all) && menubarPeriod != .today @@ -458,9 +510,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { // key's stuck loading / in-flight / generation bookkeeping and force a // fresh fetch — even if the cache looks "not stale yet". This is the // guaranteed one-round-trip recovery path. + // An open popover also proves the screens are on: recover from a + // missed screensDidWake so a latched flag can't suppress refreshes. + displayAsleep = false if refreshTimer == nil { startRefreshLoop(forceQuotaOnStart: false) } + // The status figure may have gone stale under App Nap while the + // popover was closed; catch it up alongside the visible payload. + refreshStatusPayloadIfNeeded(reason: "popover open") if store.shouldResetInteractiveRefreshPipeline, let age = store.staleInteractivePayloadAgeSeconds { NSLog("CodeBurn: popover opened with %ds stale payload cache - hard recovery", age) @@ -478,18 +536,38 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { refreshTimer = nil } + private func startNapBackstop() { + let scheduler = NSBackgroundActivityScheduler( + identifier: "org.agentseal.codeburn-menubar.refresh-backstop") + scheduler.repeats = true + scheduler.interval = 180 + scheduler.tolerance = 60 + scheduler.qualityOfService = .utility + scheduler.schedule { [weak self] completion in + Task { @MainActor [weak self] in + self?.runRefreshLoopTick(reason: "nap backstop") + completion(.finished) + } + } + napBackstop = scheduler + } + private func runRefreshLoopTick(reason: String, forcePayload: Bool = false, forceQuota: Bool = false) { refreshLoopHeartbeatAt = Date() + if displayAsleep && !forcePayload { return } let hadForceRefreshInFlight = forceRefreshTask != nil let clearedStaleForceRefresh = clearStaleForceRefreshIfNeeded() let clearedStaleStatusRefresh = clearStaleStatusPayloadRefreshIfNeeded() let clearedStaleLoading = store.clearStaleLoadingIfNeeded() let statusPayloadStale = store.needsStatusPayloadRefresh let sinceLast = Date().timeIntervalSince(lastRefreshTime) + // The timer stays at 30s; the spawn interval stretches on battery / + // Low Power Mode while the popover is closed (#647). + let interval = currentRefreshInterval() let shouldForceRefresh = forcePayload || clearedStaleForceRefresh || clearedStaleLoading || - sinceLast >= TimeInterval(refreshIntervalSeconds) + sinceLast >= interval if shouldForceRefresh { forceRefresh(bypassRateLimit: true, forceQuota: forceQuota) @@ -497,10 +575,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { let forceRefreshWasBlocked = hadForceRefreshInFlight && forceRefreshTask != nil if statusPayloadStale && (!shouldForceRefresh || forceRefreshWasBlocked || clearedStaleStatusRefresh) { - refreshStatusPayloadIfNeeded(reason: reason, force: forcePayload) + refreshStatusPayloadIfNeeded(reason: reason, force: forcePayload, minAgeSeconds: interval) } } + private func currentRefreshInterval() -> TimeInterval { + RefreshCadence.interval( + popoverOpen: popover?.isShown ?? false, + onBattery: PowerSource.isOnBattery(), + lowPowerMode: ProcessInfo.processInfo.isLowPowerModeEnabled + ) + } + private func startRefreshLoop(forceQuotaOnStart: Bool = false) { stopRefreshTimer() runRefreshLoopTick(reason: "start", forcePayload: true, forceQuota: forceQuotaOnStart) @@ -543,6 +629,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { manualRefreshTask = Task { [weak self] in guard let self else { return } + let activity = ProcessInfo.processInfo.beginActivity( + options: .userInitiated, reason: "CodeBurn manual refresh") + defer { ProcessInfo.processInfo.endActivity(activity) } // "Refresh Now" should refresh the menubar payload AND every // connected provider's live quota. The user's intent is "make // this match reality right now." diff --git a/mac/Sources/CodeBurnMenubar/RefreshCadence.swift b/mac/Sources/CodeBurnMenubar/RefreshCadence.swift new file mode 100644 index 00000000..6c1ab76f --- /dev/null +++ b/mac/Sources/CodeBurnMenubar/RefreshCadence.swift @@ -0,0 +1,32 @@ +import Foundation +import IOKit.ps + +/// Decides how often the background refresh loop may spawn CLI fetches. The +/// 30s timer keeps firing (cheap); this throttles the expensive part - each +/// fetch is a full Node process at 100%+ CPU for seconds (#647). With the +/// popover closed nobody is looking at anything but the status figure, so on +/// battery or in Low Power Mode the spawn cadence backs off. Opening the +/// popover always refreshes immediately via refreshPayloadForPopoverOpen, so +/// the backoff never shows a user stale data they are actually looking at. +enum RefreshCadence { + static let activeSeconds: TimeInterval = 30 + static let batteryIdleSeconds: TimeInterval = 150 + static let lowPowerIdleSeconds: TimeInterval = 300 + + static func interval(popoverOpen: Bool, onBattery: Bool, lowPowerMode: Bool) -> TimeInterval { + if popoverOpen { return activeSeconds } + if lowPowerMode { return lowPowerIdleSeconds } + if onBattery { return batteryIdleSeconds } + return activeSeconds + } +} + +enum PowerSource { + static func isOnBattery() -> Bool { + // Copy function -> retained; Get function -> borrowed (unretained). + guard let snapshot = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(), + let type = IOPSGetProvidingPowerSourceType(snapshot)?.takeUnretainedValue() as String? + else { return false } + return type == kIOPMBatteryPowerKey + } +} diff --git a/mac/Sources/CodeBurnMenubar/Security/CodeburnCLI.swift b/mac/Sources/CodeBurnMenubar/Security/CodeburnCLI.swift index befa3b1b..82d6e265 100644 --- a/mac/Sources/CodeBurnMenubar/Security/CodeburnCLI.swift +++ b/mac/Sources/CodeBurnMenubar/Security/CodeburnCLI.swift @@ -94,7 +94,7 @@ enum CodeburnCLI { // The menubar runs as an accessory app with no foreground window, and macOS // background-throttles accessory apps and their children. Without this lift the // codeburn subprocess parses 5-10x slower than the same command run from a - // user-interactive terminal, which starves the 15s refresh cadence on large corpora. + // user-interactive terminal, which starves the 30s refresh cadence on large corpora. process.qualityOfService = .userInitiated return process } diff --git a/mac/Tests/CodeBurnMenubarTests/RefreshCadenceTests.swift b/mac/Tests/CodeBurnMenubarTests/RefreshCadenceTests.swift new file mode 100644 index 00000000..832c31c1 --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/RefreshCadenceTests.swift @@ -0,0 +1,41 @@ +import XCTest +@testable import CodeBurnMenubar + +final class RefreshCadenceTests: XCTestCase { + func testPopoverOpenAlwaysUsesActiveCadence() { + XCTAssertEqual( + RefreshCadence.interval(popoverOpen: true, onBattery: true, lowPowerMode: true), + RefreshCadence.activeSeconds + ) + } + + func testIdleOnACStaysActive() { + XCTAssertEqual( + RefreshCadence.interval(popoverOpen: false, onBattery: false, lowPowerMode: false), + RefreshCadence.activeSeconds + ) + } + + func testIdleOnBatteryBacksOff() { + XCTAssertEqual( + RefreshCadence.interval(popoverOpen: false, onBattery: true, lowPowerMode: false), + RefreshCadence.batteryIdleSeconds + ) + } + + func testLowPowerModeBacksOffFurthest() { + XCTAssertEqual( + RefreshCadence.interval(popoverOpen: false, onBattery: true, lowPowerMode: true), + RefreshCadence.lowPowerIdleSeconds + ) + XCTAssertEqual( + RefreshCadence.interval(popoverOpen: false, onBattery: false, lowPowerMode: true), + RefreshCadence.lowPowerIdleSeconds + ) + } + + func testBackoffOrdering() { + XCTAssertLessThan(RefreshCadence.activeSeconds, RefreshCadence.batteryIdleSeconds) + XCTAssertLessThan(RefreshCadence.batteryIdleSeconds, RefreshCadence.lowPowerIdleSeconds) + } +}