perf(efficiency): 落实首批采样减负与发行包瘦身

This commit is contained in:
2026-11-03 23:19:52 +08:00
parent 935701fca6
commit def3b1e130
40 changed files with 483 additions and 291 deletions
+11 -6
View File
@@ -38,14 +38,19 @@ import AppKit
menuTitle: { [language] key in
AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem")
}, openSettings: { [weak self] in self?.settingsCommand() }) { [self] panel in
AppLanguageScope(preferences: language) {
MenuPanelView(metrics: self.metrics, preferences: self.appearance, keepAwake: self.awake, settingsPresentation: self.presentation,
presentation: panel, onOpenSettings: { [weak self] in
self?.menuBar?.hide()
settings.environment.openSettings()
})
if PanelResourceAudit.omitted == "all" {
Text(verbatim: "Kymo").frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
AppLanguageScope(preferences: language) {
MenuPanelView(metrics: self.metrics, preferences: self.appearance, keepAwake: self.awake, settingsPresentation: self.presentation,
presentation: panel, onOpenSettings: { [weak self] in
self?.menuBar?.hide()
settings.environment.openSettings()
})
}
}
}
if let menuBar { PanelResourceAudit.run(controller: menuBar, metrics: metrics) }
}
private func configureMainMenu() {
+1 -1
View File
@@ -1,4 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<svg xmlns="http://www.w3.org/2000/svg" width="88" height="88" viewBox="0 0 1024 1024">
<defs>
<linearGradient id="ceramic" x1="0" y1="0" x2="0.3" y2="1"><stop stop-color="#ffffff"/><stop offset="1" stop-color="#eeeae4"/></linearGradient>
<linearGradient id="graphite" x1="0" y1="0" x2="0" y2="1"><stop stop-color="#383936"/><stop offset="1" stop-color="#232421"/></linearGradient>

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

+14 -3
View File
@@ -4,6 +4,7 @@ import Darwin
nonisolated struct ProcessMonitor: Sendable {
private var previous: [ProcessIdentity: (UInt64, TimeInterval)] = [:]
private var sampleSerial: UInt64 = 0
private var paths: [ProcessIdentity: (name: String, path: String?, expires: TimeInterval)] = [:]
static func cpu(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? {
guard let previous, current >= previous, elapsed.isFinite, elapsed > 0 else { return nil }
@@ -15,11 +16,13 @@ nonisolated struct ProcessMonitor: Sendable {
let date = Date()
guard let entries = Self.entries() else {
previous = [:]
paths = [:]
return ProcessSnapshot(date: date, enumerated: 0, readable: 0, rows: [], failed: true)
}
let now = ProcessInfo.processInfo.systemUptime
var next: [ProcessIdentity: (UInt64, TimeInterval)] = [:]
var rows: [ProcessMetrics] = []
var pathBuffer = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN))
for entry in entries where entry.kp_proc.p_pid > 0 {
let pid = entry.kp_proc.p_pid
var info = proc_taskallinfo()
@@ -34,8 +37,14 @@ nonisolated struct ProcessMonitor: Sendable {
let name = withUnsafeBytes(of: &copy) { raw in
String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self)
}
var path = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN))
let pathSize = proc_pidpath(pid, &path, UInt32(path.count))
let path: String?
if let cached = paths[id], seconds > 0, cached.name == name, now < cached.expires {
path = cached.path
} else {
let size = proc_pidpath(pid, &pathBuffer, UInt32(pathBuffer.count))
path = size > 0 ? String(cString: pathBuffer) : nil
paths[id] = (name, path, now + 30)
}
var usage: Double?
if valid && seconds > 0 {
let (total, overflow) = info.ptinfo.pti_total_user.addingReportingOverflow(info.ptinfo.pti_total_system)
@@ -44,7 +53,7 @@ nonisolated struct ProcessMonitor: Sendable {
next[id] = (total, now)
}
}
rows.append(ProcessMetrics(id: id, name: name, path: pathSize > 0 ? String(cString: path) : nil,
rows.append(ProcessMetrics(id: id, name: name, path: path,
cpu: usage, residentBytes: valid ? info.ptinfo.pti_resident_size : nil,
threads: valid ? Int(info.ptinfo.pti_threadnum) : nil, restricted: !valid))
}
@@ -56,11 +65,13 @@ nonisolated struct ProcessMonitor: Sendable {
})
rows.removeAll { $0.id.seconds > 0 && !identities.contains($0.id) }
} else {
paths = [:]
rows = rows.map { ProcessMetrics(id: $0.id, name: $0.name, path: nil, cpu: $0.cpu,
residentBytes: $0.residentBytes, threads: $0.threads, restricted: $0.restricted) }
}
let retained = Set(rows.map(\.id))
previous = next.filter { retained.contains($0.key) }
paths = paths.filter { retained.contains($0.key) && $0.key.seconds > 0 }
return ProcessSnapshot(date: date, enumerated: entries.filter { $0.kp_proc.p_pid > 0 }.count,
readable: rows.filter { !$0.restricted }.count, rows: rows, failed: false)
}
+19 -15
View File
@@ -8,7 +8,9 @@ actor SystemSampler {
private var temperatureCache: Double?
private var gpuTemperatureCache: Double?
private var fanCache: [FanMetrics]?
private var nextTemperature: TimeInterval = 0
private var cpuSchedule = SensorSchedule()
private var gpuSchedule = SensorSchedule()
private var fanSchedule = SensorSchedule()
private var didProbe = false
private let diskHealth = DiskHealthMonitor()
private let batteryHealth = SystemBatteryHealthMonitor()
@@ -50,7 +52,8 @@ actor SystemSampler {
// A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied.
}
func sample(includeProcesses: Bool? = nil, processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil) -> MetricsSnapshot {
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true,
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil) -> MetricsSnapshot {
guard !Task.isCancelled else { return MetricsSnapshot() }
if let includeProcesses { setProcessVisible(includeProcesses) }
self.processUpdate = processUpdate
@@ -61,12 +64,13 @@ actor SystemSampler {
let start = ProcessInfo.processInfo.systemUptime
var result = MetricsSnapshot()
result.cpu = cpu.sample()
if temperatureTask == nil && start >= nextTemperature {
let readCPU = cpuSchedule.isDue(at: start)
let readGPU = gpuSchedule.isDue(at: start)
let readFans = fanSchedule.isDue(at: start)
if includeSlowMetrics && temperatureTask == nil && (readCPU || readGPU || readFans) {
temperatureTask = Task { [self] in
async let cpu = CPUTemperatureServiceClient.read()
async let gpu = CPUTemperatureServiceClient.read(gpu: true)
async let fans = CPUTemperatureServiceClient.readFans()
await finishTemperature(cpu, gpu: gpu, fans: fans)
let readings = await CPUTemperatureServiceClient.readSensors(cpu: readCPU, gpu: readGPU, fans: readFans)
finishTemperature(readings, cpu: readCPU, gpu: readGPU, fans: readFans)
}
}
result.cpuTemperature = temperatureCache
@@ -82,16 +86,16 @@ actor SystemSampler {
result.batteryState = result.battery == nil ? BatteryMonitor.availability() : .present
result.gpu = GPUMonitor.sample()
result.gpuUsage = result.gpu?.usage
if volumeTask == nil && start - volumeSampleTime >= 30 {
if includeSlowMetrics && volumeTask == nil && start - volumeSampleTime >= 30 {
volumeTask = Task.detached(priority: .utility) { [self] in
let value = DiskMonitor.volumes()
await finishVolumes(value)
}
}
if diskTask == nil && start >= nextDisk {
if includeSlowMetrics && diskTask == nil && start >= nextDisk {
diskTask = Task { [self, diskHealth] in await finishDisk(diskHealth.sample()) }
}
if result.battery != nil && batteryTask == nil && start >= nextBattery {
if includeSlowMetrics && result.battery != nil && batteryTask == nil && start >= nextBattery {
batteryTask = Task { [self, batteryHealth] in await finishBattery(batteryHealth.sample()) }
}
startProcessesIfNeeded()
@@ -111,11 +115,11 @@ actor SystemSampler {
return result
}
private func finishTemperature(_ value: Double?, gpu: Double?, fans: [FanMetrics]?) {
fanCache = fans
gpuTemperatureCache = gpu
temperatureCache = value
nextTemperature = ProcessInfo.processInfo.systemUptime + (value == nil && gpu == nil && fans == nil ? 60 : 5)
private func finishTemperature(_ readings: SensorReadings?, cpu: Bool, gpu: Bool, fans: Bool) {
let now = ProcessInfo.processInfo.systemUptime
if cpu { temperatureCache = readings?.cpu; cpuSchedule.complete(available: temperatureCache != nil, at: now) }
if gpu { gpuTemperatureCache = readings?.gpu; gpuSchedule.complete(available: gpuTemperatureCache != nil, at: now) }
if fans { fanCache = readings?.fans; fanSchedule.complete(available: fanCache != nil, at: now) }
temperatureTask = nil
}
@@ -1,73 +1,24 @@
import Foundation
nonisolated struct SensorReadings: Sendable {
var cpu: Double?
var gpu: Double?
var fans: [FanMetrics]?
}
nonisolated enum CPUTemperatureServiceClient {
static func read(gpu: Bool = false) async -> Double? {
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc")
guard let requirement = CodeIdentity.requirement(at: url) else { return nil }
return await withCheckedContinuation { continuation in
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
connection.setCodeSigningRequirement(requirement)
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
let reply = Reply(connection: connection, continuation: continuation)
connection.invalidationHandler = { reply.finish(nil) }
connection.interruptionHandler = { reply.finish(nil) }
connection.resume()
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else {
reply.finish(nil)
return
static func readSensors(cpu: Bool, gpu: Bool, fans: Bool) async -> SensorReadings? {
await ServiceRequest.perform(timeout: 2) { proxy, finish in
proxy.readSensors(cpu: cpu, gpu: gpu, fans: fans) { cpu, gpu, fans in
func temperature(_ number: NSNumber?) -> Double? {
number.flatMap { $0.doubleValue.isFinite && $0.doubleValue > 0 && $0.doubleValue < 150 ? $0.doubleValue : nil }
}
let values = fans.flatMap { values -> [FanMetrics]? in
guard values.count <= 10 else { return nil }
return values.enumerated().map { FanMetrics(id: $0.offset, rpm: FanMetrics.validRPM($0.element.doubleValue)) }
}
finish(SensorReadings(cpu: temperature(cpu), gpu: temperature(gpu), fans: values))
}
let receive: (NSNumber?) -> Void = { number in
let value = number?.doubleValue
reply.finish(value.flatMap { $0.isFinite && $0 > 0 && $0 < 150 ? $0 : nil })
}
if gpu { proxy.readGPUTemperature(withReply: receive) }
else { proxy.readCPUTemperature(withReply: receive) }
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { reply.finish(nil) }
}
}
static func readFans() async -> [FanMetrics]? {
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc")
guard let requirement = CodeIdentity.requirement(at: url) else { return nil }
return await withCheckedContinuation { continuation in
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
connection.setCodeSigningRequirement(requirement)
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
let reply = Reply(connection: connection, continuation: continuation)
connection.invalidationHandler = { reply.finish(nil) }
connection.interruptionHandler = { reply.finish(nil) }
connection.resume()
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else {
reply.finish(nil); return
}
proxy.readFanSpeeds { values in
guard let values, values.count <= 10 else { reply.finish(nil); return }
reply.finish(values.enumerated().map { FanMetrics(id: $0.offset, rpm: FanMetrics.validRPM($0.element.doubleValue)) })
}
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { reply.finish(nil) }
}
}
private final class Reply<Value: Sendable>: @unchecked Sendable {
private let lock = NSLock()
private var continuation: CheckedContinuation<Value?, Never>?
private let connection: NSXPCConnection
init(connection: NSXPCConnection, continuation: CheckedContinuation<Value?, Never>) {
self.connection = connection
self.continuation = continuation
}
func finish(_ value: Value?) {
lock.lock()
let callback = continuation
continuation = nil
lock.unlock()
guard let callback else { return }
connection.invalidationHandler = nil
connection.interruptionHandler = nil
connection.invalidate()
callback.resume(returning: value)
}
}
}
+12 -4
View File
@@ -9,6 +9,7 @@ final class MetricsStore {
private(set) var isPanelVisible = false
let sampling: SamplingPreferences
var effectiveMilliseconds: Int { isPanelVisible ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
private var hasSamplingDemand: Bool { isPanelVisible || sampling.backgroundEnabled }
@ObservationIgnored private var generation = 0
@ObservationIgnored private var visibilityGeneration = 0
@ObservationIgnored private var task: Task<Void, Never>?
@@ -21,7 +22,8 @@ final class MetricsStore {
self.sampler = sampler
self.sampling = sampling ?? SamplingPreferences()
self.sampling.onChange = { [weak self] in
guard let self, !self.isPaused, self.effectiveMilliseconds != self.scheduledInterval else { return }
guard let self, !self.isPaused,
self.effectiveMilliseconds != self.scheduledInterval || self.hasSamplingDemand != (self.task != nil) else { return }
self.reschedule(reset: false, sampleImmediately: false)
}
start()
@@ -36,8 +38,10 @@ final class MetricsStore {
private func reschedule(reset: Bool, sampleImmediately: Bool = true) {
generation += 1
task?.cancel()
task = nil
needsHistoryBoundary = needsHistoryBoundary || reset
scheduledInterval = effectiveMilliseconds
guard hasSamplingDemand else { needsHistoryBoundary = true; return }
var delay = Duration.zero
if !sampleImmediately, let lastPublishedAt {
delay = max(.zero, .milliseconds(effectiveMilliseconds) - lastPublishedAt.duration(to: .now))
@@ -51,8 +55,10 @@ final class MetricsStore {
}
if reset { await sampler.reset() }
while !Task.isCancelled {
let sampledAt = ContinuousClock.now
let visibleGeneration = self?.visibilityGeneration
var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true, processUpdate: { [weak self] processes in
var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true,
includeSlowMetrics: self?.isPanelVisible == true, processUpdate: { [weak self] processes in
Task { @MainActor [weak self] in
guard let self, self.visibilityGeneration == visibleGeneration,
self.isPanelVisible, !self.isPaused else { return }
@@ -71,7 +77,9 @@ final class MetricsStore {
self?.needsHistoryBoundary = false
SamplingDiagnostics.record(next)
let interval = self?.effectiveMilliseconds ?? 5_000
do { try await Task.sleep(for: .milliseconds(interval)) }
// Start-to-start cadence; missed deadlines do not trigger catch-up bursts.
let deadline = sampledAt.advanced(by: .milliseconds(interval))
do { try await Task.sleep(until: max(deadline, .now), clock: .continuous) }
catch { return }
}
}
@@ -97,7 +105,7 @@ final class MetricsStore {
if !visible { snapshot.processes = nil }
let active = visible && !isPaused
Task { await sampler.setProcessVisible(active) }
if !isPaused { reschedule(reset: false) }
if !isPaused { reschedule(reset: !sampling.backgroundEnabled) }
}
deinit { task?.cancel() }
+2 -39
View File
@@ -2,50 +2,13 @@ import Foundation
nonisolated enum SMARTServiceClient {
static func read() async -> DiskHealthMetrics? {
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc")
guard let requirement = CodeIdentity.requirement(at: url) else { return nil }
return await withCheckedContinuation { continuation in
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
connection.setCodeSigningRequirement(requirement)
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
let reply = Reply(connection: connection, continuation: continuation)
connection.invalidationHandler = { reply.finish(nil) }
connection.interruptionHandler = { reply.finish(nil) }
connection.resume()
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else {
reply.finish(nil); return
}
await ServiceRequest.perform(timeout: 15) { proxy, finish in
proxy.readSMART { remaining, hours in
let life = remaining?.doubleValue
let validLife = life.flatMap { $0.isFinite && (0...1).contains($0) ? $0 : nil }
let validHours = hours.flatMap { UInt64($0.stringValue) }
reply.finish(validLife != nil || validHours != nil ? DiskHealthMetrics(remainingLife: validLife, powerOnHours: validHours) : nil)
finish(validLife != nil || validHours != nil ? DiskHealthMetrics(remainingLife: validLife, powerOnHours: validHours) : nil)
}
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 15) { reply.finish(nil) }
}
}
/// Error, interruption, timeout and reply may race; resume exactly once.
private final class Reply: @unchecked Sendable {
private let lock = NSLock()
private var continuation: CheckedContinuation<DiskHealthMetrics?, Never>?
private let connection: NSXPCConnection
init(connection: NSXPCConnection, continuation: CheckedContinuation<DiskHealthMetrics?, Never>) {
self.connection = connection
self.continuation = continuation
}
func finish(_ value: DiskHealthMetrics?) {
lock.lock()
let callback = continuation
continuation = nil
lock.unlock()
guard let callback else { return }
connection.invalidationHandler = nil
connection.interruptionHandler = nil
connection.invalidate()
callback.resume(returning: value)
}
}
}
@@ -2,8 +2,7 @@ import Foundation
/// Fixed read-only operation: no caller-supplied paths or commands.
@objc protocol SMARTServiceProtocol {
nonisolated func readFanSpeeds(withReply reply: @escaping ([NSNumber]?) -> Void)
nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void)
nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void)
nonisolated func readGPUTemperature(withReply reply: @escaping (NSNumber?) -> Void)
nonisolated func readCPUTemperature(withReply reply: @escaping (NSNumber?) -> Void)
}
@@ -9,6 +9,8 @@ nonisolated enum SamplingDiagnostics {
guard enabled else { return }
var payload: [String: Any] = [
"event": event, "timestamp": snapshot.date.timeIntervalSince1970,
"recordedAt": Date().timeIntervalSince1970,
"uptime": ProcessInfo.processInfo.systemUptime,
"pid": ProcessInfo.processInfo.processIdentifier,
"load": snapshot.load
]
@@ -44,6 +46,7 @@ nonisolated enum SamplingDiagnostics {
if status == KERN_SUCCESS {
payload["residentBytes"] = info.resident_size
payload["footprintBytes"] = info.phys_footprint
payload["peakFootprintBytes"] = info.ledger_phys_footprint_peak
}
guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]) else { return }
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
+21 -1
View File
@@ -10,6 +10,16 @@ import CoreFoundation
@ObservationIgnored var onChange: (() -> Void)?
private var panelValue: Int
private var backgroundValue: Int
private var backgroundEnabledValue: Bool
var backgroundEnabled: Bool {
get { backgroundEnabledValue }
set {
guard newValue != backgroundEnabledValue else { return }
backgroundEnabledValue = newValue
defaults.set(newValue, forKey: "sampling.backgroundEnabled")
onChange?()
}
}
var panelMilliseconds: Int {
get { panelValue }
set {
@@ -34,7 +44,17 @@ import CoreFoundation
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
panelValue = Self.read(defaults, key: "sampling.panelMilliseconds", fallback: 2_000)
backgroundValue = Self.read(defaults, key: "sampling.backgroundMilliseconds", fallback: 5_000)
backgroundValue = Self.read(defaults, key: "sampling.backgroundMilliseconds", fallback: 30_000)
// Retain an existing explicit background interval; new installs have no hidden consumer.
if let number = defaults.object(forKey: "sampling.backgroundEnabled") as? NSNumber,
CFGetTypeID(number) == CFBooleanGetTypeID() {
backgroundEnabledValue = number.boolValue
} else if let number = defaults.object(forKey: "sampling.backgroundMilliseconds") as? NSNumber,
CFGetTypeID(number) != CFBooleanGetTypeID(), number.doubleValue.isFinite {
backgroundEnabledValue = true
} else {
backgroundEnabledValue = false
}
}
static func normalized(_ value: Int) -> Int {
+14
View File
@@ -0,0 +1,14 @@
import Foundation
/// Missing capabilities back off independently; success in another zone cannot reset this state.
nonisolated struct SensorSchedule {
private(set) var deadline: TimeInterval = 0
private var failures = 0
func isDue(at now: TimeInterval) -> Bool { now >= deadline }
mutating func complete(available: Bool, at now: TimeInterval) {
failures = available ? 0 : min(failures + 1, 5)
deadline = now + (available ? 10 : min(600, 60 * pow(2, Double(failures - 1))))
}
}
+68
View File
@@ -0,0 +1,68 @@
import Foundation
/// One short-lived authenticated connection. Every completion releases the timer and connection.
nonisolated enum ServiceRequest {
private static let requirement = CodeIdentity.requirement(at:
Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc"))
static func perform<Value: Sendable>(timeout: TimeInterval,
invoke: @escaping (SMARTServiceProtocol, @escaping @Sendable (Value?) -> Void) -> Void
) async -> Value? {
guard let requirement else { return nil }
let request = Pending<Value>()
return await withTaskCancellationHandler {
await withCheckedContinuation { continuation in
request.start(requirement: requirement, timeout: timeout, continuation: continuation, invoke: invoke)
}
} onCancel: { request.finish(nil) }
}
private final class Pending<Value: Sendable>: @unchecked Sendable {
private let lock = NSLock()
private var finished = false
private var continuation: CheckedContinuation<Value?, Never>?
private var connection: NSXPCConnection?
private var timer: DispatchSourceTimer?
func start(requirement: String, timeout: TimeInterval, continuation: CheckedContinuation<Value?, Never>,
invoke: (SMARTServiceProtocol, @escaping @Sendable (Value?) -> Void) -> Void) {
lock.lock()
guard !finished else { lock.unlock(); continuation.resume(returning: nil); return }
self.continuation = continuation
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
self.connection = connection
connection.setCodeSigningRequirement(requirement)
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
connection.invalidationHandler = { [weak self] in self?.finish(nil) }
connection.interruptionHandler = { [weak self] in self?.finish(nil) }
let timer = DispatchSource.makeTimerSource(queue: .global(qos: .utility))
self.timer = timer
timer.schedule(deadline: .now() + timeout)
timer.setEventHandler { [weak self] in self?.finish(nil) }
timer.resume()
connection.resume()
lock.unlock()
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ [weak self] _ in self?.finish(nil) }) as? SMARTServiceProtocol else {
finish(nil); return
}
invoke(proxy) { [weak self] in self?.finish($0) }
}
func finish(_ value: Value?) {
lock.lock()
guard !finished else { lock.unlock(); return }
finished = true
let callback = continuation
let timer = timer
let connection = connection
continuation = nil; self.timer = nil; self.connection = nil
lock.unlock()
timer?.setEventHandler {}
timer?.cancel()
connection?.invalidationHandler = nil
connection?.interruptionHandler = nil
connection?.invalidate()
callback?.resume(returning: value)
}
}
}
-2
View File
@@ -5,7 +5,6 @@ struct CPUCoreGrid: View {
let values: [Double]
let kinds: [Int: CPUCoreTopology.Kind]
let interval: TimeInterval
@Environment(\.accessibilityReduceMotion) private var reduceMotion
private func color(_ kind: CPUCoreTopology.Kind?) -> Color {
switch kind {
@@ -93,7 +92,6 @@ struct CPUCoreGrid: View {
Circle().inset(by: 1).trim(from: 0, to: value)
.stroke(color(kind), style: StrokeStyle(lineWidth: 2, lineCap: .round))
.rotationEffect(.degrees(-90))
.animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, interval * 0.8)), value: value)
Text(verbatim: "\(Int((value * 100).rounded()))")
.font(.system(size: 8, weight: .medium)).lineLimit(1).minimumScaleFactor(0.4)
}
@@ -6,7 +6,6 @@ struct GPUStatisticsView: View {
let allocated: UInt64?
let average: Double?
let peak: Double?
@Environment(\.accessibilityReduceMotion) private var reduceMotion
private var reference: Double { max(1, Double(max(inUse ?? 0, allocated ?? 0))) }
@@ -33,8 +32,6 @@ struct GPUStatisticsView: View {
}.font(PanelStyle.label).lineLimit(1)
MetricProgressBar(value: bytes.map { Double($0) / reference } ?? 0, color: color)
.frame(height: 3)
.animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: bytes)
.animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: reference)
.accessibilityHidden(true)
}
}
@@ -52,7 +52,8 @@ extension MenuPanelView {
}.font(PanelStyle.label)
.modifier(CardInset())
}
.task(id: publicIPRoute) {
.task(id: "\(publicIPRoute):\(metrics.isPaused)") {
guard !metrics.isPaused, metrics.isPanelVisible else { return }
publicIPAddress = nil
guard snapshot.networkPath == .available else { return }
await PublicIPAddressService.shared.refreshContinuously(route: publicIPRoute) { address in
@@ -109,7 +109,6 @@ extension MenuPanelView {
HStack(spacing: 8) {
Text(title).font(PanelStyle.label).frame(width: 100, alignment: .leading)
MetricProgressBar(value: value ?? 0, color: color).frame(height: 5)
.animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, chartInterval * 0.8)), value: value)
AnimatedMetricText(value: MetricFormat.percent(value)).font(PanelStyle.value).frame(width: 30, alignment: .trailing)
}.font(PanelStyle.label)
}
@@ -286,7 +285,6 @@ struct EnergyProcessListRow: View {
.clipShape(Capsule())
}
.frame(height: 4)
.animation(.easeInOut(duration: 0.35), value: process.cpu)
AnimatedMetricText(value: process.cpu.map { String(format: "%.1f%%", $0 * 100) } ?? "--")
.foregroundStyle(Color("MetricCPU")).font(PanelStyle.value)
.monospacedDigit().frame(width: 39, alignment: .trailing)
+14 -10
View File
@@ -47,14 +47,14 @@ struct MenuPanelView: View {
var body: some View {
VStack(spacing: PanelStyle.gap) {
header
if PanelResourceAudit.omitted != "header" { header }
if PanelLayout.needsResourceScroll(size: panelSize, rows: rowHeights) {
ScrollView { resourceRows }
.frame(maxHeight: PanelLayout.resourceHeight(rows: rowHeights))
} else {
resourceRows
}
if metrics.isPanelVisible {
if metrics.isPanelVisible && PanelResourceAudit.omitted != "processes" {
ProcessTableView(snapshot: snapshot.processes, wide: panelSize.width >= 900).frame(maxWidth: .infinity, maxHeight: .infinity)
.frame(minHeight: 170)
}
@@ -98,14 +98,18 @@ struct MenuPanelView: View {
}
@ViewBuilder private func resourceCard(at index: Int) -> some View {
switch index {
case 0: cpuCard
case 1: gpuCard
case 2: batteryCard
case 3: memoryCard
case 4: diskCard
case 5: networkCard
default: EmptyView()
if PanelResourceAudit.omitted == "resources" {
Color.clear
} else {
switch index {
case 0: cpuCard
case 1: gpuCard
case 2: batteryCard
case 3: memoryCard
case 4: diskCard
case 5: networkCard
default: EmptyView()
}
}
}
@@ -0,0 +1,39 @@
import AppKit
/// Explicit local measurement only. Never schedules work during normal launches.
@MainActor enum PanelResourceAudit {
static let enabled = ProcessInfo.processInfo.environment["KYMO_RESOURCE_AUDIT"] == "1"
static let omitted = enabled ? ProcessInfo.processInfo.environment["KYMO_AUDIT_OMIT"] ?? "" : ""
static func run(controller: MenuPanelController, metrics: MetricsStore) {
guard enabled else { return }
Task { @MainActor in
@MainActor func mark(_ event: String) { SamplingDiagnostics.record(metrics.snapshot, event: "audit." + event) }
func wait(_ seconds: Int) async { try? await Task.sleep(for: .seconds(seconds)) }
// Pin the test window so unrelated focus changes cannot invalidate a measurement.
controller.presentation.isPinned = true
mark("cold")
await wait(10)
mark("hidden10")
for cycle in 1...3 {
controller.show()
mark("open\(cycle).0")
await wait(1); mark("open\(cycle).1")
await wait(9); mark("open\(cycle).10")
await wait(20); mark("open\(cycle).30")
if cycle == 1 {
metrics.togglePause(); mark("paused.0")
await wait(10); mark("paused.10")
metrics.togglePause(); mark("resumed")
}
controller.hide()
await wait(1); mark("closed\(cycle).1")
await wait(9); mark("closed\(cycle).10")
await wait(20); mark("closed\(cycle).30")
}
controller.shutdown()
mark("complete")
NSApp.terminate(nil)
}
}
}
+1
View File
@@ -17,6 +17,7 @@ struct ProcessIcon: View {
.frame(width: 15, height: 15)
.accessibilityHidden(true)
.task(id: "\(process.id)-\(process.path ?? "")") {
guard PanelResourceAudit.omitted != "icons" else { return }
// Resolve by the sampled executable, avoiding an icon from a reused PID.
guard let path = process.path else { icon = nil; return }
let url = URL(fileURLWithPath: path)
@@ -63,9 +63,10 @@ struct AppearanceSettingsView: View {
}
}
Section {
Toggle("sampling.backgroundEnabled", isOn: $sampling.backgroundEnabled)
LabeledContent("sampling.background") {
IntervalControl(milliseconds: $sampling.backgroundMilliseconds)
}
}.disabled(!sampling.backgroundEnabled)
Text("sampling.backgroundHelp").font(.callout).foregroundStyle(.secondary)
}
}
+27 -4
View File
@@ -3876,19 +3876,19 @@
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Applies while the panel is closed. Default: 5 seconds. Panel interval is adjusted in its toolbar."
"value" : "Off by default to save energy. Reopening starts a new interval; hidden periods remain gaps. Existing custom intervals are retained."
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "仅在面板关闭时生效,默认 5 秒。面板打开时的间隔在顶部工具栏单独调整。"
"value" : "默认关闭以节省能耗。重开后重新采样,隐藏期间保留历史断点;已有自定义间隔会保留。"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "僅在面板關閉時生效,預設 5 秒。面板開啟時的間隔在頂部工具列獨立調整。"
"value" : "預設關閉以節省能耗。重開後重新取樣,隱藏期間保留歷史斷點;既有自訂間隔會保留。"
}
}
}
@@ -4166,7 +4166,30 @@
}
}
}
},
"sampling.backgroundEnabled" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Record trends while hidden"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "隐藏时记录趋势"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "隱藏時記錄趨勢"
}
}
}
}
},
"version" : "1.0"
}
}
+4 -33
View File
@@ -8,7 +8,7 @@ enum TrendValueFormat {
case watts
}
/// Bounded, timestamp-based curves. Gaps remain gaps; animation only runs on append.
/// Bounded, timestamp-based static curves. Gaps remain gaps; no per-sample animation task.
struct PanelTrendChart: View {
let dates: [Date]
let first: [Double?]
@@ -33,18 +33,12 @@ struct PanelTrendChart: View {
var intervals: [TimeInterval] = []
var plotHeight: CGFloat = PanelStyle.plotHeight
var showsLegendValues = true
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var retainedScale: Double = 1
@State private var smallSamples = 0
@State private var retainedSecondScale: Double = 1
@State private var smallSecondSamples = 0
@State private var hoveredDate: Date?
@State private var hoverPoint: CGPoint?
@State private var previousBegin: Date?
@State private var previousEnd: Date?
@State private var progress: CGFloat = 1
@State private var lastFrame: PanelCurveFrame?
@State private var displayedFrame: PanelCurveFrame?
private var inputFrame: PanelCurveFrame {
PanelCurveFrame(dates: dates, series: [first, second, third, fourth],
@@ -129,11 +123,11 @@ struct PanelTrendChart: View {
.lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: plotHeight)
GeometryReader { proxy in
ZStack(alignment: .topLeading) {
PanelCurveCanvas(frame: displayedFrame ?? inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
PanelCurveCanvas(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
scales: [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale],
maximumGap: max(5, expectedInterval * 2),
targetBegin: (lastFrame ?? inputFrame).dates.first, targetEnd: (lastFrame ?? inputFrame).dates.last,
previousBegin: previousBegin, previousEnd: previousEnd, progress: progress)
targetBegin: dates.first, targetEnd: dates.last,
previousBegin: nil, previousEnd: nil, progress: 1)
if hoveredDate != nil, let index, let begin = dates.first, let end = dates.last, end > begin {
let x = proxy.size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin)
Path { path in
@@ -187,8 +181,6 @@ struct PanelTrendChart: View {
.onAppear {
retainedScale = maximum
retainedSecondScale = secondMaximum
lastFrame = inputFrame
displayedFrame = inputFrame
}
.onChange(of: dates) { _, _ in
let target = maximum
@@ -203,28 +195,7 @@ struct PanelTrendChart: View {
smallSecondSamples += 1
if smallSecondSamples >= 10 { retainedSecondScale = secondTarget; smallSecondSamples = 0 }
} else { smallSecondSamples = 0 }
let next = inputFrame
let old = lastFrame
let gap = PanelCurveGeometry.allowedGap(at: next.dates.count - 1, intervals: next.intervals, fallback: max(5, expectedInterval * 2))
let append = old.map { PanelCurveGeometry.isAppend(from: $0.dates, to: next.dates, maximumGap: gap) } == true
&& !(next.dates.last.map { boundaryDates.contains($0) } ?? false)
let animated = append && !reduceMotion
var transaction = Transaction(); transaction.disablesAnimations = true
withTransaction(transaction) {
lastFrame = next
displayedFrame = next
if animated, let old { displayedFrame = PanelCurveFrame.transition(from: old, to: next) }
previousBegin = animated ? old?.dates.first : nil
previousEnd = animated ? old?.dates.last : nil
progress = animated ? 0 : 1
}
}
.task(id: lastFrame?.dates.last) {
guard progress == 0, !reduceMotion else { return }
do { try await Task.sleep(for: .milliseconds(16)) } catch { return }
withAnimation(.easeInOut(duration: 0.35)) { progress = 1 }
}
.onChange(of: reduceMotion) { _, reduced in if reduced { progress = 1; previousBegin = nil; previousEnd = nil; lastFrame = inputFrame; displayedFrame = inputFrame } }
.accessibilityElement(children: .combine)
}
}
+1 -4
View File
@@ -1,15 +1,12 @@
import SwiftUI
/// The same system numeric roll/blur transition as the original metric rows.
/// Static numbers avoid per-sample glyph rasterization and transition caches.
struct AnimatedMetricText: View {
let value: String
@Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
Text(verbatim: value)
.monospacedDigit()
.contentTransition(.numericText())
.animation(reduceMotion ? nil : .spring(duration: 0.35, bounce: 0), value: value)
}
}
+3 -41
View File
@@ -1,57 +1,19 @@
import SwiftUI
/// Approximate visual speed tiers; rotation does not attempt to reproduce physical RPM.
nonisolated struct FanRotation {
private(set) var phase: Double = 0
private(set) var speed: Double = 0
private var reference: TimeInterval = 0
static func speed(rpm: Double?, reducedMotion: Bool) -> Double {
guard !reducedMotion, let rpm, rpm.isFinite, rpm > 0 else { return 0 }
switch rpm {
case ..<2000: return 90
case ..<4000: return 180
case ..<6000: return 300
default: return 450
}
}
func angle(at time: TimeInterval) -> Double {
(phase + max(0, time - reference) * speed).truncatingRemainder(dividingBy: 360)
}
mutating func update(rpm: Double?, reducedMotion: Bool, at time: TimeInterval) {
phase = angle(at: time)
reference = time
speed = Self.speed(rpm: rpm, reducedMotion: reducedMotion)
}
}
struct FanSpeedIndicator: View {
let title: Text
let rpm: Double?
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var rotation = FanRotation()
var body: some View {
HStack(spacing: 5) {
TimelineView(.animation(minimumInterval: 1.0 / 30, paused: rotation.speed == 0)) { context in
Image(systemName: "fanblades.fill")
.rotationEffect(.degrees(rotation.angle(at: context.date.timeIntervalSinceReferenceDate)))
.foregroundStyle(.secondary)
}.frame(width: 14, height: 14).accessibilityHidden(true)
Image(systemName: "fanblades.fill")
.foregroundStyle(.secondary)
.frame(width: 14, height: 14).accessibilityHidden(true)
title.foregroundStyle(.secondary)
Spacer(minLength: 2)
AnimatedMetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM")
.monospacedDigit().fontWeight(.medium)
}
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.7)
.onAppear { update() }
.onChange(of: rpm) { _, _ in update() }
.onChange(of: reduceMotion) { _, _ in update() }
}
private func update() {
rotation.update(rpm: rpm, reducedMotion: reduceMotion, at: Date.timeIntervalSinceReferenceDate)
}
}
-2
View File
@@ -5,7 +5,6 @@ struct MetricRingGauge: View {
let title: LocalizedStringKey
let value: Double?
let color: Color
@Environment(\.accessibilityReduceMotion) private var reduceMotion
private var fraction: Double { value.flatMap { $0.isFinite ? min(1, max(0, $0)) : nil } ?? 0 }
@@ -16,7 +15,6 @@ struct MetricRingGauge: View {
Circle().trim(from: 0, to: fraction)
.stroke(color, style: StrokeStyle(lineWidth: 3, lineCap: .round))
.rotationEffect(.degrees(-90))
.animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: fraction)
AnimatedMetricText(value: MetricFormat.percent(value)).font(.system(size: 8, weight: .semibold))
.lineLimit(1).minimumScaleFactor(0.6).frame(width: 18, height: 12)
}.padding(2).frame(width: 28, height: 28).accessibilityHidden(true)
-2
View File
@@ -54,7 +54,6 @@ struct CapacityBar: View {
let values: [Double]
let colors: [Color]
let total: Double
@Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
GeometryReader { bounds in
@@ -65,7 +64,6 @@ struct CapacityBar: View {
}
}
.clipShape(Capsule())
.animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: values)
}
.frame(height: 8)
.accessibilityHidden(true)