refactor(project): 清理闲置展示链路与重复采样状态

This commit is contained in:
2026-11-09 00:41:09 +08:00
parent 7b3abe37c5
commit b73d51c953
57 changed files with 210 additions and 2822 deletions
View File
-2
View File
@@ -30,6 +30,4 @@ nonisolated enum MetricFormat {
guard let value, value.isFinite, value >= 0 else { return "--" }
return String(format: "%.1f W", value)
}
static func decimal(_ value: Double) -> String { String(format: "%.1f", value) }
}
View File
+1 -29
View File
@@ -6,7 +6,6 @@ nonisolated struct TrendSample: Sendable {
let gpu: Double?
let memory: Double?
var download: Double?
var disk: Double?
var battery: Double?
var batteryPower: Double?
var upload: Double?
@@ -45,7 +44,7 @@ nonisolated struct MetricHistory: Sendable {
mutating func append(_ snapshot: MetricsSnapshot, breakBefore: Bool = false, expectedInterval: TimeInterval = 2) {
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
download: snapshot.downloadRate, disk: snapshot.disk?.usage,
download: snapshot.downloadRate,
battery: snapshot.battery?.charge, batteryPower: snapshot.battery?.power,
upload: snapshot.uploadRate,
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
@@ -71,30 +70,3 @@ nonisolated struct InterfaceTrendSample: Sendable {
/// Scheduled cadence from this point to the next interface sample.
var expectedInterval: TimeInterval = 2
}
/// Time-weighted observed utilization; never bridge failures or sleep boundaries.
nonisolated struct GPUUtilizationSummary {
let average: Double?
let peak: Double?
let coverage: TimeInterval
init(samples: [TrendSample], window: TimeInterval = 60) {
guard let end = samples.last?.date else { average = nil; peak = nil; coverage = 0; return }
let start = end.addingTimeInterval(-window)
peak = samples.filter { $0.date >= start }.compactMap(\.gpu).max()
var area = 0.0
var duration = 0.0
for (a, b) in zip(samples, samples.dropFirst()) {
let dt = b.date.timeIntervalSince(a.date)
guard !b.breakBefore, dt > 0, dt <= a.expectedInterval * 2.5,
let av = a.gpu, let bv = b.gpu else { continue }
let overlap = b.date.timeIntervalSince(max(a.date, start))
guard overlap > 0 else { continue }
let left = av + (bv - av) * (1 - overlap / dt)
area += (left + bv) * 0.5 * overlap
duration += overlap
}
coverage = duration
average = duration > 0 ? area / duration : nil
}
}
+1 -4
View File
@@ -35,15 +35,12 @@ nonisolated struct MetricsSnapshot: Sendable {
var diskIO: DiskIOMetrics?
var volumes: [VolumeMetrics]?
var battery: BatteryMetrics?
var load: [Double] = []
var uptime: TimeInterval = 0
var gpu: GPUMetrics?
var processes: ProcessSnapshot?
var diskHealthDate: Date?
var batteryHealthDate: Date?
var batteryState: BatteryAvailability = .unknown
// GPU total is backed by validated IOAccelerator device statistics.
var gpuUsage: Double? = nil
var gpuUsage: Double? { gpu?.usage }
}
nonisolated extension MetricsSnapshot {
+2 -4
View File
@@ -23,19 +23,17 @@ nonisolated struct ProcessEnergyReply: Codable, Sendable {
let readings: [ProcessEnergyReading]
}
nonisolated struct ProcessEnergyUsage: Identifiable, Sendable {
let process: ProcessMetrics
let id: ProcessIdentity
let watts: Double
let seconds: TimeInterval
var id: ProcessIdentity { process.id }
var formattedPower: String { watts >= 1 ? String(format: "%.2f W", watts) : String(format: "%.1f mW", watts * 1000) }
}
nonisolated struct ProcessEnergySnapshot: Sendable {
enum State: Sendable { case waiting, available, partial, unavailable, unsupported }
let date: Date
let candidates: Int
let readable: Int
let measured: Int
let rows: [ProcessEnergyUsage] // All valid measurements; no CPU prefilter.
var measured: Int { rows.count }
let state: State
}
View File
+1 -13
View File
@@ -6,9 +6,6 @@ nonisolated struct GPUMetrics: Sendable {
let coreCount: Int?
var renderer: Double? = nil
var tiler: Double? = nil
// Driver accounting, not dedicated VRAM or a capacity denominator.
var inUseMemory: UInt64? = nil
var allocatedMemory: UInt64? = nil
// Independent per-core counters have not been obtained. Never split total usage.
}
@@ -27,21 +24,12 @@ nonisolated enum GPUMonitor {
let cores = (IORegistryEntryCreateCFProperty(service, "gpu-core-count" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? NSNumber)?.intValue
devices.append(GPUMetrics(usage: normalized(raw), coreCount: cores.flatMap { $0 > 0 ? $0 : nil },
renderer: normalized((stats?["Renderer Utilization %"] as? NSNumber)?.doubleValue),
tiler: normalized((stats?["Tiler Utilization %"] as? NSNumber)?.doubleValue),
inUseMemory: memoryBytes(stats?["In use system memory"]),
allocatedMemory: memoryBytes(stats?["Alloc system memory"])))
tiler: normalized((stats?["Tiler Utilization %"] as? NSNumber)?.doubleValue)))
}
// Do not average incompatible utilization counters on multi-GPU machines.
return devices.count == 1 ? devices[0] : nil
}
static func memoryBytes(_ raw: Any?) -> UInt64? {
guard let number = raw as? NSNumber else { return nil }
let value = number.doubleValue
guard value.isFinite, value >= 0, value < Double(UInt64.max) else { return nil }
return UInt64(value)
}
static func normalized(_ value: Double?) -> Double? {
value.flatMap { $0.isFinite && (0...100).contains($0) ? $0 / 100 : nil }
}
+6 -10
View File
@@ -17,30 +17,26 @@ nonisolated struct ProcessEnergyMonitor: Sendable {
}
mutating func update(processes: ProcessSnapshot, readings: [ProcessEnergyReading], capability: EnergyCapability, maximumInterval: TimeInterval = 30) -> ProcessEnergySnapshot {
let processesByID = Dictionary(processes.rows.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
let identities = Set(processes.rows.map(\.id))
var next: [ProcessIdentity: ProcessEnergyReading] = [:]
var usages: [ProcessEnergyUsage] = []
var measured = 0
if capability == .verifiedCPU && !processes.failed {
for reading in readings where next[reading.id] == nil {
guard let process = processesByID[reading.id], reading.status == .available,
guard identities.contains(reading.id), reading.status == .available,
reading.nanojoules != nil, reading.birth > 0, reading.uptime.isFinite else { continue }
next[reading.id] = reading
if let (power, seconds) = Self.watts(current: reading, previous: previous[reading.id], maximumInterval: maximumInterval) {
measured += 1
let usage = ProcessEnergyUsage(process: process, watts: power, seconds: seconds)
usages.append(usage)
usages.append(ProcessEnergyUsage(id: reading.id, watts: power, seconds: seconds))
}
}
}
previous = next // Failed / missing readings invalidate the old baseline.
usages.sort { $0.watts == $1.watts ? $0.id.pid < $1.id.pid : $0.watts > $1.watts }
let state: ProcessEnergySnapshot.State
if capability == .unsupported { state = .unsupported }
else if capability == .unavailable || processes.failed || (capability == .verifiedCPU && next.isEmpty) { state = .unavailable }
else if measured == 0 { state = .waiting }
else { state = measured < processes.enumerated ? .partial : .available }
else if usages.isEmpty { state = .waiting }
else { state = usages.count < processes.enumerated ? .partial : .available }
return ProcessEnergySnapshot(date: Date(), candidates: processes.enumerated, readable: next.count,
measured: measured, rows: usages, state: state)
rows: usages, state: state)
}
}
+4 -11
View File
@@ -24,8 +24,6 @@ actor SystemSampler {
private var batteryTask: Task<Void, Never>?
private var diskCache: DiskHealthMetrics?
private var batteryCache: Double?
private var diskDate: Date?
private var batteryDate: Date?
private var nextDisk: TimeInterval = 0
private var nextBattery: TimeInterval = 0
private let processRead: @Sendable (inout ProcessMonitor) -> ProcessSnapshot
@@ -67,7 +65,7 @@ actor SystemSampler {
// A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied.
}
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, includeEnergy: Bool = true, demandRevision: Int? = nil,
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, demandRevision: Int? = nil,
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil,
energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)? = nil) -> MetricsSnapshot {
guard !Task.isCancelled else { return MetricsSnapshot() }
@@ -75,7 +73,7 @@ actor SystemSampler {
setProcessVisible(includeProcesses ?? processVisible, revision: demandRevision)
self.maximumEnergyInterval = min(3600, max(30, maximumEnergyInterval))
self.processUpdate = processUpdate
self.energyUpdate = includeEnergy ? energyUpdate : nil
self.energyUpdate = energyUpdate
if !didProbe {
didProbe = true
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { PanelCapabilityProbe.run() }
@@ -104,7 +102,6 @@ actor SystemSampler {
result.battery = BatteryMonitor.sample()
result.batteryState = result.battery == nil ? BatteryMonitor.availability() : .present
result.gpu = GPUMonitor.sample()
result.gpuUsage = result.gpu?.usage
if includeSlowMetrics && volumeTask == nil && start - volumeSampleTime >= 30 {
volumeTask = Task.detached(priority: .utility) { [self] in
let value = DiskMonitor.volumes()
@@ -120,13 +117,9 @@ actor SystemSampler {
startProcessesIfNeeded()
result.processes = processVisible ? processCache : nil
result.diskHealth = diskCache
result.diskHealthDate = diskDate
result.battery?.health = batteryCache
result.batteryHealthDate = batteryDate
result.volumes = volumes
result.uptime = ProcessInfo.processInfo.systemUptime
var load = [Double](repeating: 0, count: 3)
if getloadavg(&load, 3) == 3 { result.load = load }
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" {
let line = "{\"event\":\"sampleDuration\",\"milliseconds\":\((ProcessInfo.processInfo.systemUptime - start) * 1000)}\n"
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
@@ -146,11 +139,11 @@ actor SystemSampler {
volumes = value; volumeSampleTime = ProcessInfo.processInfo.systemUptime; volumeTask = nil
}
private func finishDisk(_ value: DiskHealthMetrics?) {
diskCache = value; diskDate = value == nil ? nil : Date()
diskCache = value
nextDisk = ProcessInfo.processInfo.systemUptime + (value == nil ? 600 : 3600); diskTask = nil
}
private func finishBattery(_ value: Double?) {
batteryCache = value; batteryDate = value == nil ? nil : Date()
batteryCache = value
nextBattery = ProcessInfo.processInfo.systemUptime + (value == nil ? 600 : 3600); batteryTask = nil
}
private func startProcessesIfNeeded() {
-3
View File
@@ -1,3 +0,0 @@
# 核心层
模块职责统一见[架构](../../docs/architecture.md)。
+2 -4
View File
@@ -14,7 +14,6 @@ final class MetricsStore {
private(set) var processUpdatesRequested = false
private(set) var slowMetricsRequested = true
let sampling: SamplingPreferences
private let energyEnabled: Bool
private var panelDemand: Bool { isPanelVisible && !isDisplaySleeping }
private var processDemand: Bool { panelDemand && processUpdatesRequested }
var effectiveMilliseconds: Int { panelDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
@@ -31,9 +30,8 @@ final class MetricsStore {
@ObservationIgnored private var needsHistoryBoundary = true
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler(), energyEnabled: Bool = true) {
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler()) {
self.sampler = sampler
self.energyEnabled = energyEnabled
self.sampling = sampling ?? SamplingPreferences()
self.sampling.onChange = { [weak self] in
guard let self, !self.isPaused,
@@ -78,7 +76,7 @@ final class MetricsStore {
var next = await sampler.sample(includeProcesses: self?.processDemand == true,
includeSlowMetrics: self?.panelDemand == true && self?.slowMetricsRequested == true,
maximumEnergyInterval: max(30, Double(self?.effectiveMilliseconds ?? 2000) / 500),
includeEnergy: self?.energyEnabled == true, demandRevision: visibleGeneration, processUpdate: { [weak self] processes in
demandRevision: visibleGeneration, processUpdate: { [weak self] processes in
Task { @MainActor [weak self] in
guard let self, self.visibilityGeneration == visibleGeneration,
self.processDemand, !self.isPaused, !self.isSystemSleeping else { return }
+2 -10
View File
@@ -5,12 +5,6 @@ import Darwin
nonisolated enum SamplingDiagnostics {
static let enabled = ProcessInfo.processInfo.environment["KYMO_DIAGNOSTICS"] == "1"
static func recordTextPresentation(processes: Int, cells: Int) {
guard enabled else { return }
let line = "{\"event\":\"textPresentation\",\"processes\":\(processes),\"createdCells\":\(cells)}\n"
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
}
static func recordEnergy(_ snapshot: ProcessEnergySnapshot) {
guard enabled else { return }
let payload: [String: Any] = ["event": "energy", "recordedAt": Date().timeIntervalSince1970,
@@ -21,14 +15,13 @@ nonisolated enum SamplingDiagnostics {
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
}
static func record(_ snapshot: MetricsSnapshot, event: String = "sample", hiddenHostAlive: Bool? = nil, windowNumber: Int? = nil, hoveredPlots: Int? = nil, nativePlots: Int? = nil, pointerInsidePanel: Bool? = nil, plotBounds: [[Double]]? = nil, animatedPlots: Int? = nil) {
static func record(_ snapshot: MetricsSnapshot, event: String = "sample", hiddenHostAlive: Bool? = nil, windowNumber: Int? = nil, hoveredPlots: Int? = nil, nativePlots: Int? = nil, pointerInsidePanel: Bool? = nil, plotBounds: [[Double]]? = nil) {
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
"pid": ProcessInfo.processInfo.processIdentifier
]
payload["hiddenHostAlive"] = hiddenHostAlive
payload["windowNumber"] = windowNumber
@@ -36,7 +29,6 @@ nonisolated enum SamplingDiagnostics {
payload["nativePlots"] = nativePlots
payload["pointerInsidePanel"] = pointerInsidePanel
payload["plotBounds"] = plotBounds
payload["animatedPlots"] = animatedPlots
payload["cpu"] = snapshot.cpu?.usage
payload["cores"] = snapshot.cpu?.cores.count
payload["cpuTemperature"] = snapshot.cpuTemperature