feat(monitors): 实现 CPU 内存采样诊断与菜单栏实时指标

接入 Mach CPU 差分、内存与负载采样、暂停恢复及按需诊断,合并菜单栏单一原生标题的显示修复。
保留核心检查和本机交互验收记录;长期资源预算仍待验收。
This commit is contained in:
2026-10-30 00:45:34 +08:00
parent 42791b2ee7
commit 631b412d15
19 changed files with 483 additions and 36 deletions
+6 -2
View File
@@ -13,9 +13,13 @@ import SwiftUI
/// 通过 `MenuBarExtra` 场景在系统菜单栏展示状态并承载监控面板。
@main
struct kymoApp: App {
@State private var metrics = MetricsStore()
var body: some Scene {
MenuBarExtra("Kymo", systemImage: "gauge") {
MenuPanelView()
MenuBarExtra {
MenuPanelView(metrics: metrics)
} label: {
MenuBarLabel(snapshot: metrics.snapshot)
}
.menuBarExtraStyle(.window)
}
+27
View File
@@ -0,0 +1,27 @@
import Foundation
nonisolated struct CPUMetrics: Sendable {
let usage: Double
let user: Double
let system: Double
let cores: [Double]
}
nonisolated struct MemoryMetrics: Sendable {
let total: UInt64
let used: UInt64
let wired: UInt64
let compressed: UInt64
let swapUsed: UInt64?
let pressure: Int?
var usage: Double { total == 0 ? 0 : Double(used) / Double(total) }
}
nonisolated struct MetricsSnapshot: Sendable {
var date = Date()
var cpu: CPUMetrics?
var memory: MemoryMetrics?
var load: [Double] = []
// GPU remains unavailable until a reliable IOReport subscription is validated.
var gpuUsage: Double? = nil
}
+43
View File
@@ -0,0 +1,43 @@
import Foundation
import Darwin
nonisolated struct CPUMonitor {
private var previous: [[UInt32]]?
mutating func sample() -> CPUMetrics? {
var count: natural_t = 0
var info: processor_info_array_t?
var infoCount: mach_msg_type_number_t = 0
guard host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO,
&count, &info, &infoCount) == KERN_SUCCESS,
let info else { previous = nil; return nil }
defer {
vm_deallocate(mach_task_self_, vm_address_t(UInt(bitPattern: info)),
vm_size_t(infoCount) * vm_size_t(MemoryLayout<integer_t>.stride))
}
let ticks = (0..<Int(count)).map { core in
(0..<Int(CPU_STATE_MAX)).map { UInt32(bitPattern: info[core * Int(CPU_STATE_MAX) + $0]) }
}
defer { previous = ticks }
guard let previous, previous.count == ticks.count else { return nil }
return Self.calculate(current: ticks, previous: previous)
}
static func calculate(current ticks: [[UInt32]], previous: [[UInt32]]) -> CPUMetrics? {
guard !ticks.isEmpty, ticks.count == previous.count,
ticks.allSatisfy({ $0.count == Int(CPU_STATE_MAX) }),
previous.allSatisfy({ $0.count == Int(CPU_STATE_MAX) }) else { return nil }
let delta = zip(ticks, previous).map { now, old in zip(now, old).map { $0 &- $1 } }
let totals = delta.map { $0.reduce(0.0) { $0 + Double($1) } }
let total = totals.reduce(0, +)
guard total > 0 else { return nil }
let user = delta.reduce(0.0) { $0 + Double($1[Int(CPU_STATE_USER)]) + Double($1[Int(CPU_STATE_NICE)]) }
let system = delta.reduce(0.0) { $0 + Double($1[Int(CPU_STATE_SYSTEM)]) }
let cores = zip(delta, totals).map { values, total in
total > 0 ? 1 - Double(values[Int(CPU_STATE_IDLE)]) / total : 0
}
return CPUMetrics(usage: (user + system) / total, user: user / total,
system: system / total, cores: cores)
}
}
+32
View File
@@ -0,0 +1,32 @@
import Foundation
import Darwin
nonisolated enum MemoryMonitor {
static func sample() -> MemoryMetrics? {
var info = vm_statistics64()
var count = mach_msg_type_number_t(MemoryLayout<vm_statistics64>.size / MemoryLayout<integer_t>.size)
let status = withUnsafeMutablePointer(to: &info) { pointer in
pointer.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
host_statistics64(mach_host_self(), HOST_VM_INFO64, $0, &count)
}
}
guard status == KERN_SUCCESS else { return nil }
let page = UInt64(vm_kernel_page_size)
let total = ProcessInfo.processInfo.physicalMemory
let wired = UInt64(info.wire_count) * page
let compressed = UInt64(info.compressor_page_count) * page
let internalBytes = UInt64(info.internal_page_count) * page
let purgeable = UInt64(info.purgeable_count) * page
let app = internalBytes > purgeable ? internalBytes - purgeable : 0
var swap = xsw_usage()
var size = MemoryLayout<xsw_usage>.size
let swapOK = sysctlbyname("vm.swapusage", &swap, &size, nil, 0) == 0
var pressure: Int32 = 0
size = MemoryLayout<Int32>.size
let pressureOK = sysctlbyname("kern.memorystatus_vm_pressure_level", &pressure, &size, nil, 0) == 0
return MemoryMetrics(total: total, used: min(total, app + wired + compressed),
wired: wired, compressed: compressed,
swapUsed: swapOK ? swap.xsu_used : nil,
pressure: pressureOK ? Int(pressure) : nil)
}
}
+18
View File
@@ -0,0 +1,18 @@
import Foundation
import Darwin
/// Serial ownership keeps CPU baselines coherent and system calls off MainActor.
actor SystemSampler {
private var cpu = CPUMonitor()
func reset() { cpu = CPUMonitor() }
func sample() -> MetricsSnapshot {
var result = MetricsSnapshot()
result.cpu = cpu.sample()
result.memory = MemoryMonitor.sample()
var load = [Double](repeating: 0, count: 3)
if getloadavg(&load, 3) == 3 { result.load = load }
return result
}
}
+40
View File
@@ -0,0 +1,40 @@
import Foundation
import Observation
@MainActor @Observable
final class MetricsStore {
private(set) var snapshot = MetricsSnapshot()
private(set) var isPaused = false
@ObservationIgnored private var task: Task<Void, Never>?
@ObservationIgnored private let sampler = SystemSampler()
init() { start() }
func start() {
guard task == nil else { return }
isPaused = false
task = Task { [weak self, sampler] in
await sampler.reset()
while !Task.isCancelled {
let next = await sampler.sample()
guard !Task.isCancelled else { return }
self?.snapshot = next
SamplingDiagnostics.record(next)
do { try await Task.sleep(for: .seconds(2)) }
catch { return }
}
}
}
func togglePause() {
if isPaused { start() }
else {
task?.cancel()
task = nil
isPaused = true
SamplingDiagnostics.record(snapshot, event: "pause")
}
}
deinit { task?.cancel() }
}
@@ -0,0 +1,35 @@
import Foundation
import Darwin
/// Explicit opt-in for local verification. Normal runs perform no diagnostics IO.
nonisolated enum SamplingDiagnostics {
static let enabled = ProcessInfo.processInfo.environment["KYMO_DIAGNOSTICS"] == "1"
static func record(_ snapshot: MetricsSnapshot, event: String = "sample") {
guard enabled else { return }
var payload: [String: Any] = [
"event": event, "timestamp": snapshot.date.timeIntervalSince1970,
"pid": ProcessInfo.processInfo.processIdentifier,
"load": snapshot.load
]
payload["cpu"] = snapshot.cpu?.usage
payload["cores"] = snapshot.cpu?.cores.count
payload["memoryUsed"] = snapshot.memory?.used
payload["memoryTotal"] = snapshot.memory?.total
payload["swapUsed"] = snapshot.memory?.swapUsed
payload["pressure"] = snapshot.memory?.pressure
var info = task_vm_info_data_t()
var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)
let status = withUnsafeMutablePointer(to: &info) { pointer in
pointer.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
}
}
if status == KERN_SUCCESS {
payload["residentBytes"] = info.resident_size
payload["footprintBytes"] = info.phys_footprint
}
guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]) else { return }
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
}
}
+30
View File
@@ -0,0 +1,30 @@
import SwiftUI
struct MenuBarLabel: View {
let snapshot: MetricsSnapshot
var body: some View {
// Use one native image/title label: the previous multi-view HStack showed
// only its first image and percentage in the user-verified menu bar.
Label {
Text(verbatim: title)
.monospacedDigit()
} icon: {
Image(systemName: "gauge")
}
.labelStyle(.titleAndIcon)
}
private var title: String {
var items = ["CPU \(percent(snapshot.cpu?.usage))"]
if let gpu = snapshot.gpuUsage {
items.append("GPU \(percent(gpu))")
}
items.append("MEM \(percent(snapshot.memory?.usage))")
return items.joined(separator: " · ")
}
private func percent(_ value: Double?) -> String {
value.map { "\(Int(($0 * 100).rounded()))%" } ?? "--"
}
}
+9 -3
View File
@@ -7,14 +7,20 @@
import SwiftUI
/// 菜单栏弹出面板:后续将在这里展示 CPU / 内存 / 磁盘 / 网络等实时监控数据。
/// A 阶段临时面板:展示采样时间与暂停入口,正式面板在 B 阶段实现。
struct MenuPanelView: View {
let metrics: MetricsStore
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Label("Kymo 资源监控", systemImage: "gauge")
.font(.headline)
Text("监控面板开发中,敬请期待…")
Text(metrics.snapshot.date, style: .time)
Button(metrics.isPaused ? "继续监控" : "暂停监控") {
metrics.togglePause()
}
Text("GPU 暂不可用")
.font(.subheadline)
.foregroundStyle(.secondary)
}
@@ -24,5 +30,5 @@ struct MenuPanelView: View {
}
#Preview {
MenuPanelView()
MenuPanelView(metrics: MetricsStore())
}