// THE PHONE REPORTS ITS OWN HITCHES (fanperf, owner 15 Oct 2026: "the // animations must never make the app heavy; prove it, keep it proven"). iOS // hands the app one MetricKit payload a day; its scroll hitch rate, hangs, CPU // time and peak memory are said to the core (`Diagnostics.sayUsage`), ride the // device's reported state to its row, and This device shows them as the // definition's columns. Nothing of a payload is written anywhere else — no // log line, no file — so the only copy is the four numbers on the row. import CottonKit import Foundation #if os(iOS) import MetricKit #endif @MainActor public final class UsageReporter: NSObject { /// One subscriber per process: MetricKit hands every payload to each one. public static let shared = UsageReporter() private var core: (any CottonCalling)? private var subscribed = false /// Report to `core` from now on; the first call subscribes and says the /// newest payload iOS delivered before this launch. public func start(_ core: (any CottonCalling)?) { self.core = core #if os(iOS) guard !subscribed else { return } subscribed = true MXMetricManager.shared.add(self) let past = UsageReporter.newest(MXMetricManager.shared.pastPayloads) Task { await say(past) } #endif } /// Say one window's figures, when there is a core to say them to. func say(_ usage: DeviceUsage?) async { guard let core, let usage else { return } await Diagnostics.sayUsage(core, usage) } } #if os(iOS) extension UsageReporter: MXMetricManagerSubscriber { public nonisolated func didReceive(_ payloads: [MXMetricPayload]) { let usage = UsageReporter.newest(payloads) Task { @MainActor in await UsageReporter.shared.say(usage) } } /// The window that ended last, read into its four figures. nonisolated static func newest(_ payloads: [MXMetricPayload]) -> DeviceUsage? { payloads.max { $0.timeStampEnd < $1.timeStampEnd }.map(DeviceUsage.init(payload:)) } } extension DeviceUsage { init(payload: MXMetricPayload) { let hangs = payload.applicationResponsivenessMetrics.map { metric in (metric.histogrammedApplicationHangTime.bucketEnumerator.allObjects as? [MXHistogramBucket] ?? []) .reduce(0) { $0 + $1.bucketCount } } self.init( until: payload.timeStampEnd, hitchMsPerS: payload.animationMetrics?.scrollHitchTimeRatio.value, hangs: hangs, cpuSeconds: payload.cpuMetrics?.cumulativeCPUTime.converted(to: .seconds).value, peakMemoryBytes: payload.memoryMetrics?.peakMemoryUsage.converted(to: .bytes).value ) } } #endif