diff --git a/PRODUCT.md b/PRODUCT.md index 4afa6e8..8f3f82e 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -28,7 +28,9 @@ Avoid SaaS dashboard gradients, decorative glassmorphism, vague neon palettes, o - Prefer native macOS and WidgetKit behavior over custom machinery. - The default Summer theme uses ocean teal, sky blue, warm sand, and sunlit amber over deep coastal surfaces. - Use teal for selection and primary actions, amber for warmth and attention, and semantic system colors for status. -- First run uses one aligned setup sheet with explicit Codex access, background refresh, and widget-registration requirements. Setup remains replayable from Help. +- First run uses one aligned setup sheet with explicit Codex access and widget-registration requirements. Setup remains replayable from Help. +- Refresh from local source events while Runway and ChatGPT or Codex are running, plus explicit launch, foreground, and manual actions. Keep cached usage readable after either app quits without scheduled background work. +- Widgets keep their last observation between changed snapshots. Optional reset alerts require a confirming refresh; automatic alerts require Runway and ChatGPT or Codex to be running. - The app icon and decorative symbols may use restrained beach, sun, wave, and palm motifs without competing with the data. - Widget surfaces stay restrained and instrument-like while respecting WidgetKit monochrome and tinted rendering. - Label graph scaling explicitly: each chart is normalized to the largest visible day, shown as its peak value rather than an unexplained percentage. diff --git a/README.md b/README.md index 8049d0c..747877a 100644 --- a/README.md +++ b/README.md @@ -34,11 +34,11 @@ These previews use an anonymous ad-hoc signature and are not Apple-notarized. Ho ## See the app -![Runway appearance and background monitoring settings in Runway Glass](docs/screenshots/runway-settings.png) +![Runway appearance and monitoring settings in Runway Glass](docs/screenshots/runway-settings.png) ![Runway appearance and monitoring settings in the Graphite theme](docs/screenshots/runway-dark-settings.png) -Screenshots show local preview builds. Empty queues and standby states are shown where applicable. +Screenshots show local preview builds and may include retired controls. Empty queues and standby states are shown where applicable. ## Forks and attribution @@ -90,10 +90,19 @@ are available in the release downloads. The native macOS app retains the full wi - Top model today, seven days, this month, and lifetime - Headroom tokens saved, savings rate, and estimated cost avoided - Live account five-hour and weekly Codex limits, reset times, pace, and local seven-day history -- A native menu bar meter with percentage, meter, and reset-countdown modes -- Background widget snapshots every minute while the app is closed +- A native menu bar meter with percentage, meter, and reset-time modes +- Event-driven usage updates while Runway and ChatGPT or Codex are running; cached widgets remain readable after either app quits - Independent settings for small, medium, and large widgets +Runway has no periodic background refresh service. Open Runway to resume automatic +updates, or refresh manually at any time. Widgets retain their last observation +until Runway publishes a changed snapshot. Optional desktop and iPhone reset alerts +depend on a refresh confirming the reset; automatic alerts require Runway and +ChatGPT or Codex to be running. + +App updates are checked manually with **Runway → Check for Updates…**; there are +no scheduled update checks. + ## Privacy Runway reads local Codex logs and the local Headroom database. When diff --git a/Runway/AppUpdater.swift b/Runway/AppUpdater.swift index 4d1d4a7..0564371 100644 --- a/Runway/AppUpdater.swift +++ b/Runway/AppUpdater.swift @@ -11,11 +11,12 @@ final class AppUpdater: ObservableObject { private init() { controller = SPUStandardUpdaterController( - startingUpdater: true, + startingUpdater: false, updaterDelegate: nil, userDriverDelegate: nil ) - controller.updater.checkForUpdatesInBackground() + controller.updater.automaticallyChecksForUpdates = false + controller.startUpdater() controller.updater.publisher(for: \.canCheckForUpdates) .assign(to: &$canCheckForUpdates) } diff --git a/Runway/BackgroundRefreshAgent.swift b/Runway/BackgroundRefreshAgent.swift index 9d734b0..1a72be9 100644 --- a/Runway/BackgroundRefreshAgent.swift +++ b/Runway/BackgroundRefreshAgent.swift @@ -21,27 +21,9 @@ struct BackgroundRefreshRecord: Codable, Equatable { } } -struct BackgroundRefreshAgentStatus: Sendable { - var enabled: Bool - var installed: Bool - var loaded: Bool - var lastSuccess: Date? - - var detail: String { - if !enabled { return "Off" } - if !BackgroundRefreshAgent.isStableInstall { - return installed ? "Managed by the installed app" : "Move the app to Applications first" - } - if !installed || !loaded { return "Needs repair" } - guard let lastSuccess else { return "Scheduled every minute" } - return "Last refreshed \(lastSuccess.formatted(date: .omitted, time: .shortened))" - } -} - enum BackgroundRefreshAgent { static let identifier = "com.codexusage.Runway.refresh" static let legacyIdentifier = "com.codexusage.CodexUsageMonitor.refresh" - static let interval: TimeInterval = 60 static var isStableInstall: Bool { let path = Bundle.main.bundleURL.standardizedFileURL.path @@ -50,61 +32,20 @@ enum BackgroundRefreshAgent { return path.hasPrefix("/Applications/") || path.hasPrefix(homeApplications + "/") } - static func installIfEnabled() { - if CodexUsageSettingsStore.load().settings.backgroundRefreshEnabled { - _ = install() - } else { - _ = uninstall() - } - } - - @discardableResult - static func setEnabled(_ enabled: Bool) -> Bool { - return enabled ? install() : uninstall() - } - - @discardableResult - static func install() -> Bool { - guard canManageInstalledAgents, - removeAgent(identifier: legacyIdentifier), - OnboardingStateStore.hasCurrentCodexDataAccess(), - let executable = Bundle.main.executableURL - else { - return false - } - let fileManager = FileManager.default - let directory = plistURL.deletingLastPathComponent() - let plist: [String: Any] = [ - "Label": identifier, - "ProgramArguments": [executable.path, "--background-refresh"], - "RunAtLoad": true, - "StartInterval": Int(interval), - "ThrottleInterval": 60, - "ProcessType": "Background", - "LowPriorityIO": true, - "Nice": 10, - "AbandonProcessGroup": true - ] - - do { - try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) - let data = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0) - if (try? Data(contentsOf: plistURL)) == data, isLoaded { return true } - if isLoaded { _ = launchctl(["bootout", domain, plistURL.path]) } - try data.write(to: plistURL, options: .atomic) - guard launchctl(["bootstrap", domain, plistURL.path]) == 0 else { return false } - return isLoaded - } catch { - return false - } - } - @discardableResult static func uninstall() -> Bool { guard canManageInstalledAgents else { return false } - let legacyRemoved = removeAgent(identifier: legacyIdentifier) - let currentRemoved = removeAgent(identifier: identifier) - return legacyRemoved && currentRemoved + let ownService = ProcessInfo.processInfo.environment["XPC_SERVICE_NAME"] + // A launchd-invoked migration must boot out its own job last: that terminates this process. + let labels: [String] = ownService == legacyIdentifier + ? [identifier, legacyIdentifier] : [legacyIdentifier, identifier] + var removed = true + for label in labels { + let result = removeAgent(identifier: label, directory: plistURL.deletingLastPathComponent(), + domain: domain, allowed: true, isOwnService: label == ownService, run: launchctl) + removed = result && removed + } + return removed } static func canManageAgents(bundleIdentifier: String?, isStableInstall: Bool) -> Bool { @@ -115,27 +56,32 @@ enum BackgroundRefreshAgent { canManageAgents(bundleIdentifier: Bundle.main.bundleIdentifier, isStableInstall: isStableInstall) } - private static func removeAgent(identifier: String) -> Bool { - removeAgent(identifier: identifier, directory: plistURL.deletingLastPathComponent(), - domain: domain, allowed: canManageInstalledAgents, run: launchctl) - } - /// Use the service label so upgrades can stop a loaded job whose plist was moved or removed. /// Keep its registration file intact if launchctl cannot confirm the job was stopped. static func removeAgent(identifier: String, directory: URL, domain: String, - allowed: Bool, run: ([String]) -> Int32) -> Bool { + allowed: Bool, isOwnService: Bool = false, run: ([String]) -> Int32) -> Bool { guard allowed else { return false } let service = "\(domain)/\(identifier)" let status = run(["print", service]) // `launchctl print` uses 113 for a missing service; other failures do not prove it is gone. let serviceNotFound: Int32 = 113 guard status == 0 || status == serviceNotFound else { return false } + let registrationURL = directory.appendingPathComponent("\(identifier).plist") + let registration = isOwnService ? try? Data(contentsOf: registrationURL) : nil + if isOwnService && FileManager.default.fileExists(atPath: registrationURL.path) { + // Self-bootout may never return, so remove the recurring registration first. + guard registration != nil else { return false } + do { try FileManager.default.removeItem(at: registrationURL) } catch { return false } + } if status == 0 { guard run(["bootout", service]) == 0, - run(["print", service]) == serviceNotFound else { return false } + run(["print", service]) == serviceNotFound else { + if isOwnService, let registration { try? registration.write(to: registrationURL, options: .atomic) } + return false + } } do { - try FileManager.default.removeItem(at: directory.appendingPathComponent("\(identifier).plist")) + try FileManager.default.removeItem(at: registrationURL) return true } catch let error as CocoaError where error.code == .fileNoSuchFile { return true @@ -144,17 +90,6 @@ enum BackgroundRefreshAgent { } } - static func status() -> BackgroundRefreshAgentStatus { - BackgroundRefreshAgentStatus( - enabled: CodexUsageSettingsStore.load().settings.backgroundRefreshEnabled, - installed: isStableInstall - ? targetsCurrentExecutable - : FileManager.default.fileExists(atPath: plistURL.path), - loaded: isLoaded, - lastSuccess: loadRecord()?.lastSuccess - ) - } - static func saveRecord(_ record: BackgroundRefreshRecord) { do { try FileManager.default.createDirectory( @@ -162,6 +97,9 @@ enum BackgroundRefreshAgent { withIntermediateDirectories: true ) try JSONEncoder().encode(record).write(to: CodexUsageSnapshotStore.backgroundStatusURL, options: .atomic) + DispatchQueue.main.async { + NotificationCenter.default.post(name: .codexUsageSnapshotDidChange, object: nil) + } } catch { // Status is diagnostic only; a failed status write must not fail refresh. } @@ -177,20 +115,7 @@ enum BackgroundRefreshAgent { .appendingPathComponent("Library/LaunchAgents/\(identifier).plist") } - private static var targetsCurrentExecutable: Bool { - guard let executable = Bundle.main.executableURL?.standardizedFileURL.path, - let data = try? Data(contentsOf: plistURL), - let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any], - let arguments = plist["ProgramArguments"] as? [String] - else { - return false - } - return arguments.first.map { URL(fileURLWithPath: $0).standardizedFileURL.path } == executable - } - private static var domain: String { "gui/\(getuid())" } - private static var service: String { "\(domain)/\(identifier)" } - private static var isLoaded: Bool { launchctl(["print", service]) == 0 } private static func launchctl(_ arguments: [String]) -> Int32 { let process = Process() diff --git a/Runway/ContentView.swift b/Runway/ContentView.swift index 96deade..4add21b 100644 --- a/Runway/ContentView.swift +++ b/Runway/ContentView.swift @@ -24,7 +24,6 @@ struct DetailedContentView: View { @State private var refreshRecord = BackgroundRefreshAgent.loadRecord() @State private var isRefreshing = false @State private var presentsDataHealth = false - private let snapshotTimer = Timer.publish(every: 5, on: .main, in: .common).autoconnect() private var health: SnapshotHealth { SnapshotHealth(snapshot: snapshot, record: refreshRecord, isRefreshing: isRefreshing) @@ -86,10 +85,6 @@ struct DetailedContentView: View { snapshot = SnapshotDisplay.load() ?? snapshot refreshRecord = BackgroundRefreshAgent.loadRecord() } - .onReceive(snapshotTimer) { _ in - snapshot = SnapshotDisplay.load() ?? snapshot - refreshRecord = BackgroundRefreshAgent.loadRecord() - } } } @@ -114,7 +109,6 @@ struct ContentView: View { @State private var refreshRecord = BackgroundRefreshAgent.loadRecord() @State private var showsRefreshFailure = false @State private var refreshFailureMessage = "" - private let timer = Timer.publish(every: 5, on: .main, in: .common).autoconnect() private var activity: CodexSessionActivity? { snapshot.sessionActivity.first { $0.id == selectedSessionID } @@ -147,7 +141,6 @@ struct ContentView: View { .hidden().accessibilityHidden(true) } } - .onReceive(timer) { _ in reload() } .onReceive(NotificationCenter.default.publisher(for: .codexUsageSnapshotDidChange)) { _ in reload() } .onExitCommand(perform: dismissRail) .alert("Refresh failed", isPresented: $showsRefreshFailure) { diff --git a/Runway/Info.plist b/Runway/Info.plist index 76798d9..b55c1ed 100644 --- a/Runway/Info.plist +++ b/Runway/Info.plist @@ -27,7 +27,7 @@ NSAppDataUsageDescription Reads local Codex and Headroom usage files to update your statistics and widgets. Nothing is uploaded. SUEnableAutomaticChecks - + SUScheduledCheckInterval 86400 SUAutomaticallyUpdate diff --git a/Runway/LimitViews.swift b/Runway/LimitViews.swift index bb83373..da06350 100644 --- a/Runway/LimitViews.swift +++ b/Runway/LimitViews.swift @@ -101,33 +101,16 @@ struct LimitPreferencesView: View { var showsMonitoring = true var showsNotifications = true @EnvironmentObject private var settingsModel: CodexUsageSettingsModel - @State private var agentStatus = BackgroundRefreshAgentStatus( - enabled: CodexUsageSettingsStore.load().settings.backgroundRefreshEnabled, - installed: false, - loaded: false, - lastSuccess: nil - ) @State private var phoneTopicURL: String? @State private var phoneTestStatus: String? var body: some View { VStack(alignment: .leading, spacing: 10) { if showsMonitoring { - Toggle("Continue monitoring after you quit", isOn: $settingsModel.settings.backgroundRefreshEnabled) - .onChange(of: settingsModel.settings.backgroundRefreshEnabled) { _, enabled in - updateAgentStatus { _ = BackgroundRefreshAgent.setEnabled(enabled) } - } - Text(agentStatus.detail) + Text("Updates follow local changes while Runway and ChatGPT or Codex are running. Widgets keep their last snapshot after either app quits. You can refresh manually at any time.") .font(.system(size: 10)) .foregroundStyle(.secondary) - if settingsModel.settings.backgroundRefreshEnabled && (!agentStatus.installed || !agentStatus.loaded) { - Button("Repair background refresh") { - updateAgentStatus { _ = BackgroundRefreshAgent.install() } - } - .buttonStyle(.link) - } - LabeledContent("Menu bar") { Picker("Menu bar", selection: $settingsModel.settings.menuBarDisplayMode) { ForEach(MenuBarDisplayMode.allCases) { mode in @@ -196,15 +179,13 @@ struct LimitPreferencesView: View { .onChange(of: settingsModel.settings.phoneNotificationsEnabled) { _, enabled in if enabled { phoneTopicURL = PhoneResetNotificationManager.ensureTopic().map { "https://ntfy.sh/\($0)" } - settingsModel.settings.backgroundRefreshEnabled = true - updateAgentStatus { _ = BackgroundRefreshAgent.install() } } else { Task { await PhoneResetNotificationManager.cancelScheduled() } } } if settingsModel.settings.phoneNotificationsEnabled { - Text("Install ntfy on your iPhone, then subscribe to this private topic. The topic is stored in Keychain.") + Text("Automatic reset alerts require Runway and ChatGPT or Codex to be running. Install ntfy on your iPhone, then subscribe to this private topic. The topic is stored in Keychain.") .font(.system(size: 10)) .foregroundStyle(.secondary) if let phoneTopicURL { @@ -247,19 +228,9 @@ struct LimitPreferencesView: View { } } .onAppear { - updateAgentStatus() if settingsModel.settings.phoneNotificationsEnabled { phoneTopicURL = PhoneResetNotificationManager.topicURL } } } - - private func updateAgentStatus(action: @escaping @Sendable () -> Void = {}) { - Task { - agentStatus = await Task.detached(priority: .utility) { - action() - return BackgroundRefreshAgent.status() - }.value - } - } } diff --git a/Runway/MenuBarView.swift b/Runway/MenuBarView.swift index d557b51..aef8cb8 100644 --- a/Runway/MenuBarView.swift +++ b/Runway/MenuBarView.swift @@ -1,5 +1,6 @@ import AppKit import Combine +import Combine import SwiftUI extension AppPresenceMode { @@ -22,7 +23,7 @@ extension MenuBarDisplayMode { switch self { case .percentage: "Remaining percentage" case .meter: "Meter" - case .reset: "Reset countdown" + case .reset: "Reset time" case .hidden: "Hidden" } } @@ -33,20 +34,16 @@ final class MenuBarSnapshotModel: ObservableObject { @Published private(set) var snapshot = CodexUsageSnapshotStore.load() ?? .empty @Published private(set) var isRefreshing = false @Published private(set) var refreshRecord = BackgroundRefreshAgent.loadRecord() - private var timer: Timer? - - var health: SnapshotHealth { - SnapshotHealth(snapshot: snapshot, record: refreshRecord, isRefreshing: isRefreshing) - } + private var observation: AnyCancellable? init() { - timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in - Task { @MainActor in self?.reload() } - } + observation = NotificationCenter.default.publisher(for: .codexUsageSnapshotDidChange) + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in self?.reload() } } - deinit { - timer?.invalidate() + var health: SnapshotHealth { + SnapshotHealth(snapshot: snapshot, record: refreshRecord, isRefreshing: isRefreshing) } func reload() { @@ -119,7 +116,7 @@ struct CodexMenuBarLabel: View { let filled = min(5, max(0, Int(ceil(window.remainingPercent / 20)))) return "\(prefix) " + String(repeating: "●", count: filled) + String(repeating: "○", count: 5 - filled) case .reset: - return "\(prefix) \(window.resetText())" + return "\(prefix) \(window.resetsAt.formatted(date: .omitted, time: .shortened))" case .hidden: return "" } @@ -194,6 +191,6 @@ struct CodexMenuBarView: View { .preferredColorScheme(settingsModel.settings.appTheme.colorScheme) .environment(\.colorScheme, settingsModel.settings.appTheme.colorScheme) .tint(accent) - .onReceive(NotificationCenter.default.publisher(for: .codexUsageSnapshotDidChange)) { _ in model.reload() } + .onAppear { model.reload() } } } diff --git a/Runway/OnboardingStateStore.swift b/Runway/OnboardingStateStore.swift index 2d7951c..20dc6f5 100644 --- a/Runway/OnboardingStateStore.swift +++ b/Runway/OnboardingStateStore.swift @@ -12,6 +12,8 @@ enum SetupRequirement: String, Codable, CaseIterable { case codexDataAccess case backgroundRefresh case widgetRegistration + + static let currentRequirements: [Self] = [.codexDataAccess, .widgetRegistration] } struct OnboardingState: Codable, Equatable { @@ -101,7 +103,7 @@ enum OnboardingStateStore { static func shouldPresent(appVersion: String, state: OnboardingState?) -> Bool { guard let state else { return true } - var unmet = Set(SetupRequirement.allCases).subtracting(state.completedRequirements) + var unmet = Set(SetupRequirement.currentRequirements).subtracting(state.completedRequirements) if !hasCurrentCodexDataAccess(appVersion: appVersion, state: state) { unmet.insert(.codexDataAccess) } @@ -117,7 +119,7 @@ enum OnboardingStateStore { from url: URL = stateURL ) -> Bool { guard let state = load(from: url) else { return false } - return state.completedRequirements == Set(SetupRequirement.allCases) + return Set(SetupRequirement.currentRequirements).isSubset(of: state.completedRequirements) } static func hasCurrentCodexDataAccess( diff --git a/Runway/OnboardingView.swift b/Runway/OnboardingView.swift index 58cb2f5..8e0f8b9 100644 --- a/Runway/OnboardingView.swift +++ b/Runway/OnboardingView.swift @@ -48,7 +48,7 @@ final class OnboardingModel: ObservableObject { } var unmetRequirements: [SetupRequirement] { - SetupRequirement.allCases.filter { !state.completedRequirements.contains($0) } + SetupRequirement.currentRequirements.filter { !state.completedRequirements.contains($0) } } func present() { @@ -81,10 +81,6 @@ final class OnboardingModel: ObservableObject { } } - func recordBackgroundRefresh(installed: Bool) { - update(.backgroundRefresh, satisfied: installed) - } - func recordWidgetRegistration(registered: Bool) { update(.widgetRegistration, satisfied: registered) } @@ -149,7 +145,6 @@ struct CodexUsageRootView: View { private struct SetupSheet: View { @ObservedObject var model: OnboardingModel - @EnvironmentObject private var settingsModel: CodexUsageSettingsModel @State private var showsSkipWarning = false var body: some View { @@ -223,8 +218,7 @@ private struct SetupSheet: View { detail: "Runway reads local session totals and optional Headroom savings. Your prompts and logs are never uploaded." ) setupRow(.codexDataAccess, symbol: "folder.fill", detail: "Read local Codex session totals") - setupRow(.backgroundRefresh, symbol: "arrow.clockwise", detail: "Keep the shared snapshot current") - setupRow(.widgetRegistration, symbol: "rectangle.3.group.fill", detail: "Show live data in macOS widgets") + setupRow(.widgetRegistration, symbol: "rectangle.3.group.fill", detail: "Show cached usage in macOS widgets") Spacer() } } @@ -261,30 +255,10 @@ private struct SetupSheet: View { symbol: model.unmetRequirements.isEmpty ? "checkmark.seal.fill" : "slider.horizontal.3", title: model.unmetRequirements.isEmpty ? "You’re ready to go" : "Keep widgets up to date", detail: model.unmetRequirements.isEmpty - ? "The local reader, background refresh, and widget extension are ready." - : "Finish the two services that keep your desktop widgets current." + ? "The local reader and widget extension are ready. Updates run while Runway and ChatGPT or Codex are open; widgets keep their last snapshot after either app quits." + : "Check the widget extension. Runway updates it while Runway and ChatGPT or Codex are open, or when you refresh manually." ) - serviceRow( - title: "Background refresh", - detail: BackgroundRefreshAgent.status().detail, - symbol: "arrow.clockwise", - complete: model.state.completedRequirements.contains(.backgroundRefresh) - ) { - Toggle("", isOn: $settingsModel.settings.backgroundRefreshEnabled) - .labelsHidden() - .onChange(of: settingsModel.settings.backgroundRefreshEnabled) { _, enabled in - model.recordBackgroundRefresh(installed: BackgroundRefreshAgent.setEnabled(enabled)) - } - if settingsModel.settings.backgroundRefreshEnabled, - !model.state.completedRequirements.contains(.backgroundRefresh) { - Button("Repair") { - model.recordBackgroundRefresh(installed: BackgroundRefreshAgent.setEnabled(true)) - } - .controlSize(.small) - } - } - serviceRow( title: "Widget extension", detail: widgetRegistered ? "Available to macOS" : "Extension not found", @@ -308,15 +282,6 @@ private struct SetupSheet: View { } .onAppear { model.recordWidgetRegistration(registered: widgetRegistered) - guard settingsModel.settings.backgroundRefreshEnabled, - BackgroundRefreshAgent.isStableInstall - else { return } - Task { - let installed = await Task.detached(priority: .utility) { - BackgroundRefreshAgent.setEnabled(true) - }.value - model.recordBackgroundRefresh(installed: installed) - } } } diff --git a/Runway/RefreshCoordinator.swift b/Runway/RefreshCoordinator.swift index c7bc0e7..7551a55 100644 --- a/Runway/RefreshCoordinator.swift +++ b/Runway/RefreshCoordinator.swift @@ -26,7 +26,9 @@ struct RefreshResult: @unchecked Sendable { actor RefreshCoordinator { typealias Engine = @Sendable (RefreshTrigger, Bool) async -> RefreshResult - static let shared = RefreshCoordinator() + static let shared = RefreshCoordinator(isSourceAppRunning: { + await MainActor.run { SourceChangeMonitor.isSourceAppRunning } + }) private struct Flight { var id: UUID @@ -37,12 +39,25 @@ actor RefreshCoordinator { private let engine: Engine private var inFlight: Flight? - init(engine: @escaping Engine = { trigger, force in - await Task.detached(priority: .utility) { + init(isSourceAppRunning: @escaping @Sendable () async -> Bool = { true }, + engine: @escaping Engine = { trigger, force in + let result = await Task.detached(priority: .utility) { SnapshotRefresh.run(trigger: trigger, force: force) }.value + if result.outcome == .updated || result.outcome == .unchanged { + await PhoneResetNotificationManager.scheduleIfNeeded(result.snapshot) + } + return result }) { - self.engine = engine + self.engine = { trigger, force in + if trigger != .manual { + guard await isSourceAppRunning() else { + return RefreshResult(outcome: .unchanged, snapshot: nil, + message: "Automatic refresh is paused while ChatGPT and Codex are closed.") + } + } + return await engine(trigger, force) + } } func refresh(trigger: RefreshTrigger, force: Bool = false) async -> RefreshResult { @@ -73,6 +88,12 @@ actor RefreshCoordinator { Flight(id: UUID(), force: force, task: Task(operation: operation)) } + func refreshAfterSourceChange() async -> RefreshResult { + // A source event can arrive after the current pass already read its fingerprint. + if let current = inFlight { _ = await finish(current) } + return await refresh(trigger: .sourceChange) + } + private func finish(_ flight: Flight) async -> RefreshResult { let result = await flight.task.value if inFlight?.id == flight.id { diff --git a/Runway/RunwayApp.swift b/Runway/RunwayApp.swift index 728016d..bafd2bb 100644 --- a/Runway/RunwayApp.swift +++ b/Runway/RunwayApp.swift @@ -11,7 +11,7 @@ final class GlassWorkspaceWindow: NSWindow { final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { private var window: NSWindow? private var compactObserver: NSObjectProtocol? - private var refreshTimer: Timer? + private var sourceAppObservers: [NSObjectProtocol] = [] private var wakeObserver: NSObjectProtocol? private var dataAccessObserver: NSObjectProtocol? private let sourceChangeMonitor = SourceChangeMonitor() @@ -39,25 +39,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { if BackgroundRefreshAgent.isStableInstall { AppRegistration.refresh() } - let hasCurrentAccess = OnboardingStateStore.hasCurrentCodexDataAccess() - if OnboardingStateStore.completedCurrentVersion() { - DispatchQueue.global(qos: .utility).async { - BackgroundRefreshAgent.installIfEnabled() - } - } else { - DispatchQueue.global(qos: .utility).async { - _ = BackgroundRefreshAgent.uninstall() - } + DispatchQueue.global(qos: .utility).async { + _ = BackgroundRefreshAgent.uninstall() } - if hasCurrentAccess { - sourceChangeMonitor.start() + updateSourceMonitoring() + sourceAppObservers = [NSWorkspace.didLaunchApplicationNotification, NSWorkspace.didTerminateApplicationNotification].map { name in + NSWorkspace.shared.notificationCenter.addObserver(forName: name, object: nil, queue: .main) { [weak self] notification in + guard let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication, + SourceChangeMonitor.isSourceApplication(bundleIdentifier: app.bundleIdentifier) else { return } + self?.updateSourceMonitoring() + } } dataAccessObserver = NotificationCenter.default.addObserver( forName: .codexDataAccessApproved, object: nil, queue: .main ) { [weak self] _ in - self?.sourceChangeMonitor.start() + self?.updateSourceMonitoring() } wakeObserver = NSWorkspace.shared.notificationCenter.addObserver( forName: NSWorkspace.didWakeNotification, @@ -66,13 +64,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { ) { _ in Task { _ = await RefreshCoordinator.shared.refresh(trigger: .wake) } } - scheduleWidgetRefresh() - requestRefresh(.launch) showMainWindowSoon() } func applicationDidBecomeActive(_ notification: Notification) { guard !ProcessInfo.processInfo.arguments.contains("--background-refresh") else { return } + NotificationCenter.default.post(name: .codexUsageSnapshotDidChange, object: nil) requestRefresh(.foreground) } @@ -82,6 +79,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { if let wakeObserver { NSWorkspace.shared.notificationCenter.removeObserver(wakeObserver) } + sourceAppObservers.forEach { NSWorkspace.shared.notificationCenter.removeObserver($0) } if let dataAccessObserver { NotificationCenter.default.removeObserver(dataAccessObserver) } @@ -110,9 +108,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { } } - private func scheduleWidgetRefresh() { - refreshTimer = Timer.scheduledTimer(withTimeInterval: 15, repeats: true) { _ in - Task { _ = await RefreshCoordinator.shared.refresh(trigger: .fallbackTimer) } + private func updateSourceMonitoring() { + if OnboardingStateStore.hasCurrentCodexDataAccess() && SourceChangeMonitor.isSourceAppRunning { + sourceChangeMonitor.start() + requestRefresh(.launch) + } else { + sourceChangeMonitor.stop() } } @@ -234,12 +235,7 @@ enum RunwayEntry { return } if arguments.contains("--safe-verification") { exit(EXIT_SUCCESS) } - Task.detached(priority: .utility) { - let result = await RefreshCoordinator.shared.refresh(trigger: .backgroundAgent) - await PhoneResetNotificationManager.scheduleIfNeeded(result.snapshot) - exit(result.outcome == .failed ? EXIT_FAILURE : EXIT_SUCCESS) - } - dispatchMain() + exit(BackgroundRefreshAgent.uninstall() ? EXIT_SUCCESS : EXIT_FAILURE) } } diff --git a/Runway/SnapshotRefresh.swift b/Runway/SnapshotRefresh.swift index 59f0e0a..7548fdd 100644 --- a/Runway/SnapshotRefresh.swift +++ b/Runway/SnapshotRefresh.swift @@ -80,7 +80,6 @@ enum SnapshotRefresh { let account = shouldReadAccount ? CodexAccountReader.read() : nil let headroom = headroomCollector.collect() ?? previous?.cachedHeadroomActivity var candidate: CodexUsageSnapshot - var outcome: RefreshOutcome var retainedPreviousLocal = false var sourceReadPending = false @@ -93,9 +92,7 @@ enum SnapshotRefresh { cached.rateLimits = limits } candidate = cached - outcome = .unchanged candidate.headroom = headroom?.savings - if candidate.headroom != previous?.headroom { outcome = .updated } } else { let read = reader.snapshotResult(headroomActivity: headroom) sourceReadPending = read.sourceReadPending @@ -105,7 +102,6 @@ enum SnapshotRefresh { .mergingLegacyHistory(CodexUsageSnapshotStore.loadLegacyHistory()) if snapshot.hasUsage { candidate = snapshot - outcome = .updated } else if let previous, previous.lifetime.hasUsage || previous.headroom?.isAvailable == true { guard accountAvailableWhenLocalMissing( fetched: account?.lifetimeTokens, @@ -119,11 +115,9 @@ enum SnapshotRefresh { return RefreshResult(outcome: .failed, snapshot: previous, message: message) } candidate = previous - outcome = .unchanged retainedPreviousLocal = true } else { candidate = previous ?? snapshot - outcome = .unchanged } } @@ -133,15 +127,6 @@ enum SnapshotRefresh { candidate.accountLifetimeTokens = account.lifetimeTokens ?? previous?.accountLifetimeTokens candidate.accountUsageDays = account.lifetimeTokens != nil ? account.usageDays : previous?.accountUsageDays candidate.accountUsageObservedAt = account.lifetimeTokens != nil ? Date() : previous?.accountUsageObservedAt - if candidate.accountLifetimeTokens != previous?.accountLifetimeTokens - || candidate.accountUsageDays != previous?.accountUsageDays - || candidate.accountUsageObservedAt != previous?.accountUsageObservedAt - || candidate.rateLimits?.fiveHour?.usedPercent != previous?.rateLimits?.fiveHour?.usedPercent - || candidate.rateLimits?.weekly?.usedPercent != previous?.rateLimits?.weekly?.usedPercent - || candidate.rateLimits?.fiveHour?.resetsAt != previous?.rateLimits?.fiveHour?.resetsAt - || candidate.rateLimits?.weekly?.resetsAt != previous?.rateLimits?.weekly?.resetsAt { - outcome = .updated - } } else { candidate.accountLifetimeTokens = previous?.accountLifetimeTokens candidate.accountUsageDays = previous?.accountUsageDays @@ -157,18 +142,17 @@ enum SnapshotRefresh { if account?.lifetimeTokens != nil && !candidate.lifetime.hasUsage { candidate.generatedAt = Date() } - if candidate.rateLimits != previous?.rateLimits { outcome = .updated } // Refresh names even when token logs are unchanged: chat renames live in a separate index. let namesURL = FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent(".codex/session_index.jsonl") - let namedCandidate = CodexSessionNames.applying(to: candidate, from: namesURL) - if namedCandidate.sessionActivity != candidate.sessionActivity - || namedCandidate.recentSessions != candidate.recentSessions { outcome = .updated } - candidate = namedCandidate + candidate = CodexSessionNames.applying(to: candidate, from: namesURL) candidate.appearanceTheme = CodexUsageSettingsStore.load().settings.appTheme.rawValue - if candidate.appearanceTheme != previous?.appearanceTheme { outcome = .updated } - guard CodexUsageSnapshotStore.save(candidate) else { + let changed = hasSemanticChanges(candidate, from: previous) + let outcome: RefreshOutcome = changed ? .updated : .unchanged + if changed { candidate.generatedAt = Date() } + else if let previous { candidate = previous } + guard !changed || CodexUsageSnapshotStore.save(candidate) else { let message = "Could not save the refreshed snapshot." saveRecord( startedAt: startedAt, @@ -189,13 +173,12 @@ enum SnapshotRefresh { reloadPending: previousRecord?.widgetReloadPending == true, lastRequested: previousRecord?.widgetReloadRequestedAt ) - // Keep the heartbeat current even when WidgetKit does not need a redraw. - let widgetSynced = shouldReloadWidget - ? CodexWidgetReloader.reloadAll() - : WidgetDataBridge.syncToWidgetExtension() + let widgetSynced = !shouldReloadWidget || CodexWidgetReloader.reloadAll() let widgetReloaded = shouldReloadWidget && widgetSynced let widgetReloadRequestedAt = widgetReloaded ? Date() : nil - LimitNotificationManager.evaluate(candidate) + if changed || trigger == .manual || trigger == .launch { + LimitNotificationManager.evaluate(candidate) + } saveRecord( startedAt: startedAt, outcome: outcome, @@ -207,9 +190,6 @@ enum SnapshotRefresh { lastAccountAttempt: lastAccountAttempt, lastAccountSuccess: account?.lifetimeTokens != nil ? Date() : previousRecord?.lastAccountSuccess ) - DispatchQueue.main.async { - NotificationCenter.default.post(name: .codexUsageSnapshotDidChange, object: nil) - } let message = outcome == .updated ? "Snapshot refreshed with the latest Codex data." : "Sources are unchanged; the cached snapshot remains current." @@ -226,8 +206,24 @@ enum SnapshotRefresh { !force && hasSnapshot && previousFingerprint == currentFingerprint } + static func hasSemanticChanges(_ candidate: CodexUsageSnapshot, from previous: CodexUsageSnapshot?) -> Bool { + guard let previous else { return true } + var comparable = candidate + // Observation clocks alone do not change displayed usage; keep real history and rate samples. + comparable.generatedAt = previous.generatedAt + comparable.accountUsageObservedAt = previous.accountUsageObservedAt + comparable.rateLimits?.accountObservedAt = previous.rateLimits?.accountObservedAt + if let observedAt = previous.rateLimits?.fiveHour?.observedAt { + comparable.rateLimits?.fiveHour?.observedAt = observedAt + } + if let observedAt = previous.rateLimits?.weekly?.observedAt { + comparable.rateLimits?.weekly?.observedAt = observedAt + } + return comparable != previous + } + static func shouldReadAccount(lastAttempt: Date?, trigger: RefreshTrigger, now: Date) -> Bool { - trigger == .manual || trigger == .wake || trigger == .launch + trigger == .manual || lastAttempt.map { $0 > now || now.timeIntervalSince($0) >= 60 } != false } @@ -306,8 +302,7 @@ enum SnapshotRefresh { lastRequested: Date? = nil, now: Date = .now ) -> Bool { - if syncPending || trigger == .launch || trigger == .wake || trigger == .manual { return true } - return (outcome == .updated || reloadPending) && lastRequested.map { $0 > now || now.timeIntervalSince($0) >= 60 } != false + syncPending || reloadPending || outcome == .updated } static func saveRecord( diff --git a/Runway/SourceChangeMonitor.swift b/Runway/SourceChangeMonitor.swift index 69d1c1f..5a8f291 100644 --- a/Runway/SourceChangeMonitor.swift +++ b/Runway/SourceChangeMonitor.swift @@ -1,17 +1,40 @@ +import AppKit import CoreServices +import Darwin import Foundation final class SourceChangeMonitor { + static func isSourceApplication(bundleIdentifier: String?) -> Bool { + bundleIdentifier == "com.openai.codex" || bundleIdentifier == "com.openai.chat" + } + + static var isSourceAppRunning: Bool { + NSWorkspace.shared.runningApplications.contains { + !$0.isTerminated && isSourceApplication(bundleIdentifier: $0.bundleIdentifier) + } + } + private var stream: FSEventStreamRef? private var debounceWorkItem: DispatchWorkItem? + private var isRefreshing = false + private var refreshPending = false + private let codexDirectory: URL + private let headroomDirectory: URL + private let refresh: @MainActor () async -> Void + + init(home: URL = FileManager.default.homeDirectoryForCurrentUser, + headroomDirectory: URL = HeadroomSavingsCollector().ledgerURL.deletingLastPathComponent(), + refresh: @escaping @MainActor () async -> Void = { _ = await RefreshCoordinator.shared.refreshAfterSourceChange() }) { + self.codexDirectory = Self.canonicalDirectory(home.appendingPathComponent(".codex")) + self.headroomDirectory = Self.canonicalDirectory(headroomDirectory) + self.refresh = refresh + } func start() { guard stream == nil else { return } - let home = FileManager.default.homeDirectoryForCurrentUser let paths = [ - home.appendingPathComponent(".codex/sessions").path, - home.appendingPathComponent(".codex/archived_sessions").path, - HeadroomSavingsCollector().ledgerURL.deletingLastPathComponent().path, + codexDirectory.path, + headroomDirectory.path, ].filter { FileManager.default.fileExists(atPath: $0) } guard !paths.isEmpty else { return } @@ -24,12 +47,12 @@ final class SourceChangeMonitor { ) guard let stream = FSEventStreamCreate( kCFAllocatorDefault, - { _, info, _, _, _, _ in + { _, info, count, paths, _, _ in guard let info else { return } Unmanaged .fromOpaque(info) .takeUnretainedValue() - .scheduleRefresh() + .handleEvents(count: count, paths: paths) }, &context, paths as CFArray, @@ -50,6 +73,7 @@ final class SourceChangeMonitor { func stop() { debounceWorkItem?.cancel() debounceWorkItem = nil + refreshPending = false guard let stream else { return } FSEventStreamStop(stream) FSEventStreamInvalidate(stream) @@ -58,18 +82,50 @@ final class SourceChangeMonitor { } private func scheduleRefresh() { + if isRefreshing { + refreshPending = true + return + } // Coalesce without postponing forever while Codex continuously writes. guard debounceWorkItem == nil else { return } let workItem = DispatchWorkItem { [weak self] in - self?.debounceWorkItem = nil - Task { - _ = await RefreshCoordinator.shared.refresh(trigger: .sourceChange) + guard let self, self.stream != nil else { return } + self.debounceWorkItem = nil + self.isRefreshing = true + Task { @MainActor in + await self.refresh() + self.isRefreshing = false + if self.refreshPending { + self.refreshPending = false + if self.stream != nil { self.scheduleRefresh() } + } } } debounceWorkItem = workItem DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: workItem) } + private func handleEvents(count: Int, paths: UnsafeMutableRawPointer) { + let paths = paths.assumingMemoryBound(to: UnsafePointer.self) + let codex = codexDirectory.path + let roots = [codex + "/sessions", codex + "/archived_sessions", headroomDirectory.path] + for index in 0.. URL { + // FSEvents uses real paths, including /private prefixes even after a file is deleted. + guard let path = realpath(url.path, nil) else { return url.standardizedFileURL } + defer { free(path) } + return URL(fileURLWithPath: String(cString: path), isDirectory: true) + } + deinit { stop() } diff --git a/RunwayTests/OnboardingStateTests.swift b/RunwayTests/OnboardingStateTests.swift index 1dce71a..ff21e91 100644 --- a/RunwayTests/OnboardingStateTests.swift +++ b/RunwayTests/OnboardingStateTests.swift @@ -63,24 +63,34 @@ struct OnboardingStateTests { } @MainActor - @Test("Installing background refresh cannot grant Codex access") - func backgroundRefreshDoesNotGrantAccess() { + @Test("Current setup completes without the retired background service") + func currentSetupDoesNotRequireBackgroundRefresh() { + let state = OnboardingState( + lastPresentedVersion: "2.0", + completedRequirements: [.codexDataAccess, .widgetRegistration], + dismissedUpdateChecklistVersion: nil, + updatedAt: .now + ) let model = OnboardingModel( appVersion: "2.0", - state: .empty, + state: state, save: { _ in }, probe: { .approved } ) + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("onboarding.json") + OnboardingStateStore.save(state, to: url) - model.recordBackgroundRefresh(installed: true) - - #expect(model.state.completedRequirements == [.backgroundRefresh]) - #expect(model.dataAccessState == .notRequested) + #expect(model.unmetRequirements.isEmpty) + #expect(!model.isPresented) + #expect(!OnboardingStateStore.shouldPresent(appVersion: "2.0", state: state)) + #expect(OnboardingStateStore.completedCurrentVersion(appVersion: "2.0", from: url)) } @MainActor - @Test("A failed service recheck revokes stale completion") - func failedServiceRecheckRevokesCompletion() { + @Test("A failed widget recheck revokes stale completion") + func failedWidgetRecheckRevokesCompletion() { let model = OnboardingModel( appVersion: "2.0", state: OnboardingState( @@ -93,10 +103,9 @@ struct OnboardingStateTests { probe: { .approved } ) - model.recordBackgroundRefresh(installed: false) model.recordWidgetRegistration(registered: false) - #expect(model.unmetRequirements == [.backgroundRefresh, .widgetRegistration]) + #expect(model.unmetRequirements == [.widgetRegistration]) } @MainActor diff --git a/RunwayTests/RefreshCoordinatorTests.swift b/RunwayTests/RefreshCoordinatorTests.swift index 5762df7..c9a5181 100644 --- a/RunwayTests/RefreshCoordinatorTests.swift +++ b/RunwayTests/RefreshCoordinatorTests.swift @@ -4,6 +4,114 @@ import Testing @Suite struct RefreshCoordinatorTests { + @MainActor + @Test("An index created after monitoring starts refreshes without a polling fallback") + func newlyCreatedSessionIndexTriggersRefresh() async throws { + let home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let codex = home.appendingPathComponent(".codex") + try FileManager.default.createDirectory(at: codex.appendingPathComponent("sessions"), withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + var refreshes = 0 + let monitor = SourceChangeMonitor(home: home, headroomDirectory: home.appendingPathComponent("headroom")) { + refreshes += 1 + } + monitor.start() + defer { monitor.stop() } + try await Task.sleep(for: .seconds(2)) + let before = refreshes + try Data("{}\n".utf8).write(to: codex.appendingPathComponent("session_index.jsonl"), options: .atomic) + for _ in 0..<80 where refreshes == before { try await Task.sleep(for: .milliseconds(50)) } + #expect(refreshes > before) + try await Task.sleep(for: .seconds(2)) + let beforeDeletion = refreshes + try FileManager.default.removeItem(at: codex.appendingPathComponent("session_index.jsonl")) + for _ in 0..<80 where refreshes == beforeDeletion { try await Task.sleep(for: .milliseconds(50)) } + #expect(refreshes > beforeDeletion) + try await Task.sleep(for: .seconds(2)) + let afterIndex = refreshes + try Data("ignored".utf8).write(to: codex.appendingPathComponent("unrelated-cache.json")) + try await Task.sleep(for: .seconds(2)) + #expect(refreshes == afterIndex) + } + + @Test("A final source event arriving during another pass gets a follow-up without a timer") + func lateSourceEventIsNotLost() async { + let calls = CallRecorder() + let coordinator = RefreshCoordinator(engine: { trigger, force in + await calls.record(trigger: trigger, force: force) + try? await Task.sleep(for: .milliseconds(50)) + return RefreshResult(outcome: .updated, snapshot: nil, message: "updated") + }) + async let foreground = coordinator.refresh(trigger: .foreground) + while await calls.count == 0 { await Task.yield() } + _ = await coordinator.refreshAfterSourceChange() + _ = await foreground + #expect(await calls.count == 2) + #expect(await calls.values.last?.trigger == .sourceChange) + } + + @Test("Observation-only changes do not rewrite snapshots; limits, retries and consumption samples do") + func semanticSnapshotChanges() { + let now = Date(timeIntervalSince1970: 1_800_000_000) + var previous = CodexUsageSnapshot.empty + previous.generatedAt = now + previous.accountUsageObservedAt = now + let window = RateLimitWindow(usedPercent: 20, windowMinutes: 300, + resetsAt: now.addingTimeInterval(3_600), observedAt: now) + previous.rateLimits = CodexRateLimits(fiveHour: window, weekly: nil, history: [], accountObservedAt: now) + var candidate = previous + candidate.generatedAt = now.addingTimeInterval(10) + candidate.accountUsageObservedAt = candidate.generatedAt + candidate.rateLimits?.accountObservedAt = candidate.generatedAt + candidate.rateLimits?.fiveHour?.observedAt = now.addingTimeInterval(10) + #expect(!SnapshotRefresh.hasSemanticChanges(candidate, from: previous)) + candidate.rateLimits?.fiveHour?.usedPercent = 21 + #expect(SnapshotRefresh.hasSemanticChanges(candidate, from: previous)) + candidate = previous + candidate.rateLimits?.fiveHour = nil + #expect(SnapshotRefresh.hasSemanticChanges(candidate, from: previous)) + candidate = previous + candidate.sourceReadPending = true + #expect(SnapshotRefresh.hasSemanticChanges(candidate, from: previous)) + candidate = previous + candidate.rateLimits?.consumptionSamples = [window] + #expect(SnapshotRefresh.hasSemanticChanges(candidate, from: previous)) + } + + @Test("Closed desktop apps prevent every automatic refresh while manual refresh stays available") + func closedDesktopAppsAreIdle() async { + let calls = CallRecorder() + let coordinator = RefreshCoordinator(isSourceAppRunning: { false }) { trigger, force in + await calls.record(trigger: trigger, force: force) + return RefreshResult(outcome: .updated, snapshot: nil, message: "updated") + } + for trigger: RefreshTrigger in [.launch, .foreground, .sourceChange, .fallbackTimer, .backgroundAgent, .wake] { + let result = await coordinator.refresh(trigger: trigger) + #expect(result.outcome == .unchanged) + } + #expect(await calls.count == 0) + _ = await coordinator.refresh(trigger: .manual) + #expect(await calls.values == [RecordedCall(trigger: .manual, force: true)]) + } + + @Test("Queued source events recheck desktop presence before collecting data") + func queuedRefreshRechecksPresence() async { + let calls = CallRecorder() + let coordinator = RefreshCoordinator(isSourceAppRunning: { await calls.count == 0 }) { trigger, force in + await calls.record(trigger: trigger, force: force) + try? await Task.sleep(for: .milliseconds(50)) + return RefreshResult(outcome: .updated, snapshot: nil, message: "updated") + } + async let foreground = coordinator.refresh(trigger: .foreground) + while await calls.count == 0 { await Task.yield() } + let result = await coordinator.refreshAfterSourceChange() + _ = await foreground + #expect(result.outcome == .unchanged) + #expect(await calls.count == 1) + _ = await coordinator.refresh(trigger: .manual) + #expect(await calls.count == 2) + } + @Test("ISO account dates stay Gregorian in the user's time zone", arguments: [Calendar.Identifier.buddhist, .japanese]) func accountUsageDatesUseGregorianCalendar(identifier: Calendar.Identifier) throws { var calendar = Calendar(identifier: identifier) @@ -99,7 +207,8 @@ struct RefreshCoordinatorTests { #expect(!SnapshotRefresh.shouldReadAccount(lastAttempt: now.addingTimeInterval(-15), trigger: .sourceChange, now: now)) #expect(SnapshotRefresh.shouldReadAccount(lastAttempt: now.addingTimeInterval(-60), trigger: .fallbackTimer, now: now)) #expect(SnapshotRefresh.shouldReadAccount(lastAttempt: now, trigger: .manual, now: now)) - #expect(SnapshotRefresh.shouldReadAccount(lastAttempt: now, trigger: .wake, now: now)) + #expect(!SnapshotRefresh.shouldReadAccount(lastAttempt: now, trigger: .wake, now: now)) + #expect(!SnapshotRefresh.shouldReadAccount(lastAttempt: now, trigger: .launch, now: now)) #expect(SnapshotRefresh.shouldReadAccount(lastAttempt: now.addingTimeInterval(3600), trigger: .backgroundAgent, now: now)) } @@ -114,11 +223,11 @@ struct RefreshCoordinatorTests { @Test("Simultaneous refresh requests share one engine pass") func coalescesSimultaneousRequests() async { let calls = CallRecorder() - let coordinator = RefreshCoordinator { trigger, force in + let coordinator = RefreshCoordinator(engine: { trigger, force in await calls.record(trigger: trigger, force: force) try? await Task.sleep(for: .milliseconds(50)) return RefreshResult(outcome: .updated, snapshot: nil, message: "updated") - } + }) await withTaskGroup(of: RefreshResult.self) { group in for _ in 0..<10 { @@ -137,10 +246,10 @@ struct RefreshCoordinatorTests { @Test("Manual refresh always reaches the engine as forced") func manualRefreshIsForced() async { let calls = CallRecorder() - let coordinator = RefreshCoordinator { trigger, force in + let coordinator = RefreshCoordinator(engine: { trigger, force in await calls.record(trigger: trigger, force: force) return RefreshResult(outcome: .updated, snapshot: nil, message: "updated") - } + }) _ = await coordinator.refresh(trigger: .manual) @@ -150,11 +259,11 @@ struct RefreshCoordinatorTests { @Test("A forced request behind an unforced pass queues one follow-up") func queuesOneForcedFollowUp() async { let calls = CallRecorder() - let coordinator = RefreshCoordinator { trigger, force in + let coordinator = RefreshCoordinator(engine: { trigger, force in await calls.record(trigger: trigger, force: force) try? await Task.sleep(for: .milliseconds(40)) return RefreshResult(outcome: .updated, snapshot: nil, message: "updated") - } + }) async let background = coordinator.refresh(trigger: .backgroundAgent) while await calls.count == 0 { @@ -170,7 +279,7 @@ struct RefreshCoordinatorTests { @Test("Matching fingerprints make an unforced background pass unchanged") func matchingFingerprintIsUnchanged() async { - let coordinator = RefreshCoordinator { trigger, force in + let coordinator = RefreshCoordinator(engine: { trigger, force in let unchanged = SnapshotRefresh.canReuseSnapshot( previousFingerprint: "same", currentFingerprint: "same", @@ -182,24 +291,24 @@ struct RefreshCoordinatorTests { snapshot: nil, message: "complete" ) - } + }) let result = await coordinator.refresh(trigger: .backgroundAgent) #expect(result.outcome == .unchanged) } - @Test("Widget sync retries after failure and refreshes on launch") + @Test("Widgets reload for changed data and pending retries, never an unchanged launch") func widgetSyncRetry() { #expect(SnapshotRefresh.shouldReloadWidget(outcome: .unchanged, trigger: .backgroundAgent, syncPending: true)) - #expect(SnapshotRefresh.shouldReloadWidget(outcome: .unchanged, trigger: .launch, syncPending: false)) - #expect(SnapshotRefresh.shouldReloadWidget(outcome: .unchanged, trigger: .manual, syncPending: false)) + #expect(!SnapshotRefresh.shouldReloadWidget(outcome: .unchanged, trigger: .launch, syncPending: false)) + #expect(!SnapshotRefresh.shouldReloadWidget(outcome: .unchanged, trigger: .manual, syncPending: false)) #expect(!SnapshotRefresh.shouldReloadWidget(outcome: .unchanged, trigger: .backgroundAgent, syncPending: false)) let now = Date() - #expect(!SnapshotRefresh.shouldReloadWidget(outcome: .updated, trigger: .sourceChange, syncPending: false, lastRequested: now, now: now)) + #expect(SnapshotRefresh.shouldReloadWidget(outcome: .updated, trigger: .sourceChange, syncPending: false, lastRequested: now, now: now)) #expect(SnapshotRefresh.shouldReloadWidget(outcome: .updated, trigger: .sourceChange, syncPending: false, lastRequested: now.addingTimeInterval(-60), now: now)) #expect(SnapshotRefresh.shouldReloadWidget(outcome: .updated, trigger: .backgroundAgent, syncPending: false, lastRequested: now.addingTimeInterval(3600), now: now)) - #expect(!SnapshotRefresh.shouldReloadWidget(outcome: .unchanged, trigger: .backgroundAgent, syncPending: false, + #expect(SnapshotRefresh.shouldReloadWidget(outcome: .unchanged, trigger: .backgroundAgent, syncPending: false, reloadPending: true, lastRequested: now, now: now)) #expect(SnapshotRefresh.shouldReloadWidget(outcome: .unchanged, trigger: .backgroundAgent, syncPending: false, reloadPending: true, lastRequested: now, now: now.addingTimeInterval(60))) diff --git a/RunwayTests/RunwayTests.swift b/RunwayTests/RunwayTests.swift index 46c4421..9ad0532 100644 --- a/RunwayTests/RunwayTests.swift +++ b/RunwayTests/RunwayTests.swift @@ -224,9 +224,12 @@ func emptySnapshotStartsAtZero() { #expect(CodexUsageSnapshot.empty.lifetime.total == 0) } -@Test("Background refresh runs once per minute") -func backgroundRefreshRunsOncePerMinute() { - #expect(BackgroundRefreshAgent.interval == 60) +@Test("Only the ChatGPT and Codex desktop apps enable automatic monitoring") +func desktopActivityGate() { + #expect(SourceChangeMonitor.isSourceApplication(bundleIdentifier: "com.openai.codex")) + #expect(SourceChangeMonitor.isSourceApplication(bundleIdentifier: "com.openai.chat")) + #expect(!SourceChangeMonitor.isSourceApplication(bundleIdentifier: nil)) + #expect(!SourceChangeMonitor.isSourceApplication(bundleIdentifier: "com.codexusage.CodexUsageMonitor")) } @Test("Menu bar label formats both limit rows") diff --git a/RunwayTests/SettingsMigrationTests.swift b/RunwayTests/SettingsMigrationTests.swift index b41754c..a5938ed 100644 --- a/RunwayTests/SettingsMigrationTests.swift +++ b/RunwayTests/SettingsMigrationTests.swift @@ -27,7 +27,7 @@ struct SettingsMigrationTests { ) #expect(result.settings.appTheme == .graphite) - #expect(result.settings.backgroundRefreshEnabled) + #expect(!result.settings.backgroundRefreshEnabled) #expect(result.settings.appPresence == .dock) #expect(result.settings.menuBarDisplayMode == .reset) #expect(result.settings.notificationsEnabled) @@ -48,7 +48,7 @@ struct SettingsMigrationTests { #expect(result.settings.schemaVersion == CodexUsageSettings.currentSchemaVersion) #expect(result.settings.appTheme == .rain) - #expect(result.settings.backgroundRefreshEnabled) + #expect(!result.settings.backgroundRefreshEnabled) #expect(!result.settings.phoneNotificationsEnabled) #expect(result.settings.warningThreshold == 70) #expect(result.repairedFields.isEmpty) @@ -69,6 +69,26 @@ struct SettingsMigrationTests { #expect(result.repairedFields == ["warningThreshold"]) } + @Test("Retiring background refresh preserves every other saved preference") + func retiresBackgroundRefreshWithoutResettingPreferences() throws { + var settings = CodexUsageSettings.default + settings.appTheme = .graphite + settings.defaultWidgetTheme = .monochrome + settings.backgroundRefreshEnabled = true + settings.appPresence = .dock + settings.menuBarDisplayMode = .reset + settings.notificationsEnabled = true + settings.phoneNotificationsEnabled = true + settings.warningThreshold = 80 + settings.criticalThreshold = 95 + + let result = CodexUsageSettingsStore.load(data: try JSONEncoder().encode(settings), legacy: .empty) + settings.backgroundRefreshEnabled = false + + #expect(result.settings == settings) + #expect(result.repairedFields.isEmpty) + } + @Test("Unknown future fields are ignored and thresholds are clamped") func ignoresUnknownFieldsAndClampsThresholds() throws { let data = try jsonData([ diff --git a/RunwayTests/SnapshotRefreshRepairTests.swift b/RunwayTests/SnapshotRefreshRepairTests.swift index aed9858..138b4b5 100644 --- a/RunwayTests/SnapshotRefreshRepairTests.swift +++ b/RunwayTests/SnapshotRefreshRepairTests.swift @@ -5,6 +5,34 @@ import Testing @Suite struct SnapshotRefreshRepairTests { + @Test("Self-migration removes its registration before launchd can terminate it") + func selfMigrationRemovesRegistrationBeforeBootout() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let url = directory.appendingPathComponent("\(BackgroundRefreshAgent.identifier).plist") + let registration = Data("registration".utf8) + try registration.write(to: url) + var loaded = true + let removed = BackgroundRefreshAgent.removeAgent(identifier: BackgroundRefreshAgent.identifier, + directory: directory, domain: "gui/123", allowed: true, isOwnService: true) { arguments in + if arguments.first == "bootout" { + #expect(!FileManager.default.fileExists(atPath: url.path)) + loaded = false + return 0 + } + return loaded ? 0 : 113 + } + #expect(removed) + #expect(!FileManager.default.fileExists(atPath: url.path)) + try registration.write(to: url) + #expect(!BackgroundRefreshAgent.removeAgent(identifier: BackgroundRefreshAgent.identifier, + directory: directory, domain: "gui/123", allowed: true, isOwnService: true) { arguments in + arguments.first == "bootout" ? 5 : 0 + }) + #expect(try Data(contentsOf: url) == registration) + } + @Test("An account child closing stdin after initialization cannot kill Runway") func accountChildClosesStdin() throws { let process = Process() diff --git a/RunwayWidget/RunwayWidget.swift b/RunwayWidget/RunwayWidget.swift index abba7f8..2a1a689 100644 --- a/RunwayWidget/RunwayWidget.swift +++ b/RunwayWidget/RunwayWidget.swift @@ -18,16 +18,7 @@ struct CodexUsageProvider: TimelineProvider { } func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { - let now = Date() - let next = Calendar.current.date(byAdding: .minute, value: 1, to: now) - ?? now.addingTimeInterval(60) - let current = entry(at: now, family: context.family) - // Age cached readings even when the system delays the requested reload. - let entries = (0...15).map { minute in - CodexUsageEntry(date: now.addingTimeInterval(Double(minute) * 60), - snapshot: current.snapshot, configuration: current.configuration) - } - completion(Timeline(entries: entries, policy: .after(next))) + completion(Timeline(entries: [entry(at: .now, family: context.family)], policy: .never)) } private func entry(at date: Date, family: WidgetFamily) -> CodexUsageEntry { @@ -58,6 +49,14 @@ struct CodexUsageWidgetView: View { monochrome: entry.configuration.theme == .monochrome, now: entry.date ) + .overlay(alignment: .bottomTrailing) { + if let observedAt = entry.snapshot.generatedAt { + Text("Snapshot \(observedAt.formatted(date: .abbreviated, time: .shortened))") + .font(.system(size: 8)) + .foregroundStyle(.secondary) + .padding(3) + } + } .containerBackground(for: .widget) { if let customBackground { CodexWidgetCustomImageBackground(image: customBackground, light: entry.configuration.theme == .runway) diff --git a/Shared/CodexUsageSettings.swift b/Shared/CodexUsageSettings.swift index af1fcea..1c044bb 100644 --- a/Shared/CodexUsageSettings.swift +++ b/Shared/CodexUsageSettings.swift @@ -47,6 +47,7 @@ struct CodexUsageSettings: Codable, Equatable, Sendable { var schemaVersion: Int var appTheme: AppTheme var defaultWidgetTheme: WidgetTheme + // Retained for older settings; scheduled background refresh is retired. var backgroundRefreshEnabled: Bool var appPresence: AppPresenceMode var menuBarDisplayMode: MenuBarDisplayMode @@ -110,6 +111,7 @@ enum CodexUsageSettingsStore { static func save(_ settings: CodexUsageSettings) throws { var settings = settings settings.schemaVersion = CodexUsageSettings.currentSchemaVersion + settings.backgroundRefreshEnabled = false try FileManager.default.createDirectory( at: CodexUsageSnapshotStore.settingsV2URL.deletingLastPathComponent(), withIntermediateDirectories: true @@ -131,6 +133,7 @@ enum CodexUsageSettingsStore { importValue("CodexUsageMonitor.limitNotificationsEnabled", from: legacy, into: &settings.notificationsEnabled, imported: &imported) importValue("CodexUsageMonitor.limitWarningThreshold", from: legacy, into: &settings.warningThreshold, imported: &imported) importValue("CodexUsageMonitor.limitCriticalThreshold", from: legacy, into: &settings.criticalThreshold, imported: &imported) + settings.backgroundRefreshEnabled = false settings.warningThreshold = settings.warningThreshold.clamped(to: 1...100) settings.criticalThreshold = settings.criticalThreshold.clamped(to: 1...100) @@ -193,6 +196,7 @@ private struct SettingsPayload: Decodable { settings.appTheme = decode(.appTheme, from: container, default: settings.appTheme, repairedFields: &repairedFields) settings.defaultWidgetTheme = decode(.defaultWidgetTheme, from: container, default: settings.defaultWidgetTheme, repairedFields: &repairedFields) settings.backgroundRefreshEnabled = decode(.backgroundRefreshEnabled, from: container, default: settings.backgroundRefreshEnabled, repairedFields: &repairedFields) + settings.backgroundRefreshEnabled = false settings.appPresence = decode(.appPresence, from: container, default: settings.appPresence, repairedFields: &repairedFields) settings.menuBarDisplayMode = decode(.menuBarDisplayMode, from: container, default: settings.menuBarDisplayMode, repairedFields: &repairedFields) settings.notificationsEnabled = decode(.notificationsEnabled, from: container, default: settings.notificationsEnabled, repairedFields: &repairedFields) diff --git a/Shared/WidgetComponents.swift b/Shared/WidgetComponents.swift index 55f1801..96fb018 100644 --- a/Shared/WidgetComponents.swift +++ b/Shared/WidgetComponents.swift @@ -232,7 +232,7 @@ struct WidgetLimitDial: View { .frame(width: diameter, height: diameter) VStack(alignment: .leading, spacing: 3) { Text(title).font(.system(size: 12, weight: .semibold)).foregroundStyle(palette.primary) - Text(current.map { "Resets \($0.resetText(at: now))" } ?? "Awaiting data") + Text(current.map { "Resets \($0.resetsAt.formatted(date: .abbreviated, time: .shortened))" } ?? "Awaiting data") .font(.system(size: 10)).foregroundStyle(palette.secondary) .lineLimit(2).fixedSize(horizontal: false, vertical: true) .multilineTextAlignment(.leading) @@ -242,7 +242,7 @@ struct WidgetLimitDial: View { } .accessibilityElement(children: .ignore) .accessibilityLabel("\(title) allowance") - .accessibilityValue(current.map { "\($0.remainingPercent.compactPercentString) remaining, resets \($0.resetText(at: now))" } ?? "Awaiting current data") + .accessibilityValue(current.map { "\($0.remainingPercent.compactPercentString) remaining, resets \($0.resetsAt.formatted(date: .abbreviated, time: .shortened))" } ?? "Awaiting current data") } } @@ -281,8 +281,8 @@ struct WidgetAllowanceMeter: View { }.frame(height: 4) if !compact { Text(current.map { now.timeIntervalSince($0.observedAt) > 180 - ? "Last read \(Int(now.timeIntervalSince($0.observedAt) / 60))m ago" - : "Resets \($0.resetText(at: now))" } ?? "Not reported") + ? "Read \($0.observedAt.formatted(date: .abbreviated, time: .shortened))" + : "Resets \($0.resetsAt.formatted(date: .abbreviated, time: .shortened))" } ?? "Not reported") .font(.system(size: 10)) .foregroundStyle(palette.secondary) .lineLimit(2) @@ -299,7 +299,7 @@ struct WidgetAllowanceMeter: View { .frame(maxWidth: .infinity, alignment: .leading) .accessibilityElement(children: .ignore) .accessibilityLabel("\(title) allowance") - .accessibilityValue((current.map { "\($0.remainingPercent.compactPercentString) remaining, resets \($0.resetText(at: now))" } ?? "Awaiting current data") + .accessibilityValue((current.map { "\($0.remainingPercent.compactPercentString) remaining, resets \($0.resetsAt.formatted(date: .abbreviated, time: .shortened))" } ?? "Awaiting current data") + (showsConsumption ? consumptionRate.map { ", approximately \($0.formatted(.number.precision(.fractionLength(1)))) percentage points consumed per 15 minutes" } ?? ", rate awaiting samples" : "")) } } diff --git a/Shared/WidgetFamilyViews.swift b/Shared/WidgetFamilyViews.swift index 403b51d..a633681 100644 --- a/Shared/WidgetFamilyViews.swift +++ b/Shared/WidgetFamilyViews.swift @@ -97,7 +97,7 @@ enum WidgetFamilySemanticBuilder { secondaryValues: [ .init(label: "Weekly", value: weekly.map { "\(Int($0.remainingPercent.rounded()))%" } ?? "—"), .init(label: "Pace", value: preferred?.pace(at: now).label ?? "Unavailable"), - .init(label: "Reset", value: [fiveHour, weekly].compactMap { $0 }.min { $0.resetsAt < $1.resetsAt }?.resetText(at: now) ?? "—") + .init(label: "Reset", value: [fiveHour, weekly].compactMap { $0 }.min { $0.resetsAt < $1.resetsAt }?.resetsAt.formatted(date: .abbreviated, time: .shortened) ?? "—") ], chart: WidgetChartContent( points: history.suffix(14).map { @@ -137,7 +137,7 @@ enum WidgetFamilySemanticBuilder { private static func session(snapshot: CodexUsageSnapshot, now: Date) -> WidgetSemanticContent { let activity = snapshot.sessionActivity.first { $0.status(at: now) == "Working" } ?? snapshot.sessionActivity.first - let age = (activity?.observedAt ?? snapshot.generatedAt).map { compactDuration(max(0, now.timeIntervalSince($0))) + " ago" } ?? "—" + let age = (activity?.observedAt ?? snapshot.generatedAt)?.formatted(date: .abbreviated, time: .shortened) ?? "—" return WidgetSemanticContent( eyebrow: "Session Live", heroValue: (activity?.usage ?? snapshot.currentSession).total.compactTokenString, diff --git a/docs/snapshot-schema-v2.md b/docs/snapshot-schema-v2.md index 0192014..6e6ff34 100644 --- a/docs/snapshot-schema-v2.md +++ b/docs/snapshot-schema-v2.md @@ -1,6 +1,6 @@ # Runway Usage Snapshot V2 -Runway writes one local JSON snapshot for the macOS app, menu bar, refresh helper, and WidgetKit extension. This document defines the platform-neutral data contract for a possible future Windows reader. It does not define a cross-platform runtime. +Runway writes one local JSON snapshot for the macOS app, menu bar, and WidgetKit extension. This document defines the platform-neutral data contract for a possible future Windows reader. It does not define a cross-platform runtime. ## Contract @@ -21,9 +21,15 @@ Runway writes one local JSON snapshot for the macOS app, menu bar, refresh helpe - Stale: a valid snapshot exists but is older than 10 minutes. - Partial: valid usage exists, but a source read is pending, account coverage is incomplete, or an optional model, limit, or Headroom source is missing. - Unavailable: no valid usage source was found. -- Permission blocked and refresh errors are stored in the separate background refresh status record, not inferred from zero usage. - -Widget timelines request a new shared snapshot every minute. WidgetKit may delay the visible redraw after a reload request. +- Permission blocked and refresh errors are stored in the separate refresh status record, not inferred from zero usage. + +Widget timelines contain one cached observation and request no periodic reload. +Runway requests a widget reload after publishing a changed snapshot; WidgetKit may +delay the visible redraw. Automatic local updates require Runway and ChatGPT or +Codex to be running. Launch, foreground, and manual refreshes remain available; +widgets keep the last snapshot after either app quits. The retired interval +LaunchAgent is removed on upgrade, and saved `backgroundRefreshEnabled` values are +treated as false without resetting other preferences or usage history. ## Root fields