perf(efficiency): 接入真实CPU能量并隔离展示与采样需求
This commit is contained in:
+18
-2
@@ -13,7 +13,7 @@ import AppKit
|
||||
}
|
||||
|
||||
@MainActor private final class ApplicationLifecycle: NSObject, NSApplicationDelegate {
|
||||
private let metrics = MetricsStore()
|
||||
private let metrics = MetricsStore(energyEnabled: PanelResourceAudit.omitted != "energy")
|
||||
private let awake = KeepAwakeService()
|
||||
private let presentation = SettingsPresentation()
|
||||
private let appearance = AppearancePreferences()
|
||||
@@ -21,8 +21,20 @@ import AppKit
|
||||
private var openSettingsAction: (() -> Void)?
|
||||
private var scenes: AnyObject?
|
||||
private var menuBar: MenuPanelController?
|
||||
private var workspaceTokens: [NSObjectProtocol] = []
|
||||
|
||||
func applicationWillFinishLaunching(_ notification: Notification) {
|
||||
let center = NSWorkspace.shared.notificationCenter
|
||||
for (name, sleeping) in [(NSWorkspace.willSleepNotification, true), (NSWorkspace.didWakeNotification, false)] {
|
||||
workspaceTokens.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.metrics.setSystemSleeping(sleeping) }
|
||||
})
|
||||
}
|
||||
for (name, sleeping) in [(NSWorkspace.screensDidSleepNotification, true), (NSWorkspace.screensDidWakeNotification, false)] {
|
||||
workspaceTokens.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.metrics.setDisplaySleeping(sleeping) }
|
||||
})
|
||||
}
|
||||
let settings = NSHostingSceneRepresentation {
|
||||
Settings {
|
||||
AppLanguageScope(preferences: language, onChange: { self.configureMainMenu() }) { [self] in
|
||||
@@ -38,7 +50,9 @@ import AppKit
|
||||
menuTitle: { [language] key in
|
||||
AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem")
|
||||
}, openSettings: { [weak self] in self?.settingsCommand() }) { [self] panel in
|
||||
if PanelResourceAudit.omitted == "all" {
|
||||
if PanelResourceAudit.omitted == "text" {
|
||||
TextMonitoringAuditView(metrics: self.metrics, appearance: self.appearance)
|
||||
} else if PanelResourceAudit.omitted == "all" {
|
||||
Text(verbatim: "Kymo").frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
} else {
|
||||
AppLanguageScope(preferences: language) {
|
||||
@@ -84,6 +98,8 @@ import AppKit
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
workspaceTokens.forEach(NSWorkspace.shared.notificationCenter.removeObserver)
|
||||
workspaceTokens.removeAll()
|
||||
menuBar?.shutdown()
|
||||
awake.disable()
|
||||
menuBar = nil
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated enum EnergyReadStatus: String, Codable, Sendable {
|
||||
case available, denied, gone, failed, identityChanged, deadline, unsupported, unverified
|
||||
}
|
||||
nonisolated enum EnergyCapability: String, Codable, Sendable { case verifiedCPU, unverified, unsupported, unavailable }
|
||||
nonisolated struct ProcessEnergyRequest: Codable, Sendable {
|
||||
let token: UUID
|
||||
let identities: [ProcessIdentity]
|
||||
static let limit = 256
|
||||
static let byteLimit = 65_536
|
||||
}
|
||||
nonisolated struct ProcessEnergyReading: Codable, Sendable {
|
||||
let id: ProcessIdentity
|
||||
let birth: UInt64
|
||||
let uptime: TimeInterval
|
||||
let nanojoules: UInt64?
|
||||
let status: EnergyReadStatus
|
||||
}
|
||||
nonisolated struct ProcessEnergyReply: Codable, Sendable {
|
||||
let token: UUID
|
||||
let capability: EnergyCapability
|
||||
let readings: [ProcessEnergyReading]
|
||||
}
|
||||
nonisolated struct ProcessEnergyUsage: Identifiable, Sendable {
|
||||
let process: ProcessMetrics
|
||||
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] // Only the top three; no CPU prefilter.
|
||||
let state: State
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated struct ProcessIdentity: Hashable, Sendable {
|
||||
nonisolated struct ProcessIdentity: Hashable, Codable, Sendable {
|
||||
let pid: Int32
|
||||
let seconds: UInt64
|
||||
let microseconds: UInt64
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import Foundation
|
||||
|
||||
/// Uses system CPU energy attribution; never derives energy from CPU time or percentage.
|
||||
nonisolated struct ProcessEnergyMonitor: Sendable {
|
||||
private var previous: [ProcessIdentity: ProcessEnergyReading] = [:]
|
||||
|
||||
static func watts(current: ProcessEnergyReading, previous: ProcessEnergyReading?, maximumInterval: TimeInterval = 30) -> (Double, Double)? {
|
||||
guard current.status == .available, let currentEnergy = current.nanojoules,
|
||||
let previous, previous.status == .available, let previousEnergy = previous.nanojoules,
|
||||
current.id == previous.id, current.birth != 0, current.birth == previous.birth,
|
||||
currentEnergy >= previousEnergy else { return nil }
|
||||
let elapsed = current.uptime - previous.uptime
|
||||
guard elapsed.isFinite, elapsed > 0, maximumInterval.isFinite, elapsed <= maximumInterval else { return nil }
|
||||
// Integer subtraction preserves low bits of large cumulative counters.
|
||||
let power = Double(currentEnergy - previousEnergy) / 1_000_000_000 / elapsed
|
||||
return power.isFinite && power >= 0 ? (power, elapsed) : nil
|
||||
}
|
||||
|
||||
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 })
|
||||
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,
|
||||
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)
|
||||
let index = usages.firstIndex {
|
||||
$0.watts < power || ($0.watts == power && $0.id.pid > process.id.pid)
|
||||
} ?? usages.endIndex
|
||||
usages.insert(usage, at: index)
|
||||
if usages.count > 3 { usages.removeLast() }
|
||||
}
|
||||
}
|
||||
}
|
||||
previous = next // Failed / missing readings invalidate the old baseline.
|
||||
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 }
|
||||
return ProcessEnergySnapshot(date: Date(), candidates: processes.enumerated, readable: next.count,
|
||||
measured: measured, rows: usages, state: state)
|
||||
}
|
||||
}
|
||||
@@ -30,11 +30,17 @@ actor SystemSampler {
|
||||
private var nextBattery: TimeInterval = 0
|
||||
private let processRead: @Sendable (inout ProcessMonitor) -> ProcessSnapshot
|
||||
private var processMonitor = ProcessMonitor()
|
||||
private var energyMonitor = ProcessEnergyMonitor()
|
||||
private var energyTask: Task<Void, Never>?
|
||||
private var energySchedule = SensorSchedule(successInterval: 5, failureInterval: 30)
|
||||
private var maximumEnergyInterval: TimeInterval = 30
|
||||
private var energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)?
|
||||
private var processTask: Task<Void, Never>?
|
||||
private var processCache: ProcessSnapshot?
|
||||
private var processUpdate: (@Sendable (ProcessSnapshot) -> Void)?
|
||||
private var processVisible = false
|
||||
private var processGeneration = 0
|
||||
private var demandRevision = Int.min
|
||||
|
||||
init(processRead: @escaping @Sendable (inout ProcessMonitor) -> ProcessSnapshot = { $0.sample() }) {
|
||||
self.processRead = processRead
|
||||
@@ -42,21 +48,34 @@ actor SystemSampler {
|
||||
|
||||
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
|
||||
|
||||
func setProcessVisible(_ visible: Bool) {
|
||||
guard visible != processVisible else { return }
|
||||
func setProcessVisible(_ visible: Bool, revision: Int? = nil) {
|
||||
var changedRevision = false
|
||||
if let revision {
|
||||
guard revision >= demandRevision else { return }
|
||||
changedRevision = revision != demandRevision
|
||||
demandRevision = revision
|
||||
}
|
||||
guard visible != processVisible || changedRevision else { return }
|
||||
processVisible = visible
|
||||
processGeneration += 1
|
||||
processCache = nil
|
||||
if !visible { processUpdate = nil }
|
||||
if !visible { processUpdate = nil; energyUpdate = nil }
|
||||
energyTask?.cancel()
|
||||
energyMonitor = ProcessEnergyMonitor()
|
||||
energySchedule = SensorSchedule(successInterval: 5, failureInterval: 30)
|
||||
processMonitor = ProcessMonitor()
|
||||
// A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied.
|
||||
}
|
||||
|
||||
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true,
|
||||
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil) -> MetricsSnapshot {
|
||||
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, includeEnergy: Bool = true, demandRevision: Int? = nil,
|
||||
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil,
|
||||
energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)? = nil) -> MetricsSnapshot {
|
||||
guard !Task.isCancelled else { return MetricsSnapshot() }
|
||||
if let includeProcesses { setProcessVisible(includeProcesses) }
|
||||
if let demandRevision, demandRevision < self.demandRevision { return MetricsSnapshot() }
|
||||
setProcessVisible(includeProcesses ?? processVisible, revision: demandRevision)
|
||||
self.maximumEnergyInterval = min(3600, max(30, maximumEnergyInterval))
|
||||
self.processUpdate = processUpdate
|
||||
self.energyUpdate = includeEnergy ? energyUpdate : nil
|
||||
if !didProbe {
|
||||
didProbe = true
|
||||
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { PanelCapabilityProbe.run() }
|
||||
@@ -157,5 +176,25 @@ actor SystemSampler {
|
||||
}
|
||||
processMonitor = monitor; processCache = value
|
||||
processUpdate?(value)
|
||||
startEnergyIfNeeded(value)
|
||||
}
|
||||
private func startEnergyIfNeeded(_ processes: ProcessSnapshot) {
|
||||
guard processVisible, energyUpdate != nil, energyTask == nil,
|
||||
energySchedule.isDue(at: ProcessInfo.processInfo.systemUptime) else { return }
|
||||
let generation = processGeneration
|
||||
energyTask = Task { [self] in
|
||||
let (readings, capability) = await ProcessEnergyServiceClient.read(processes.rows.map(\.id))
|
||||
finishEnergy(processes, readings: readings, capability: capability, generation: generation)
|
||||
}
|
||||
}
|
||||
|
||||
private func finishEnergy(_ processes: ProcessSnapshot, readings: [ProcessEnergyReading],
|
||||
capability: EnergyCapability, generation: Int) {
|
||||
energyTask = nil
|
||||
guard processVisible, processGeneration == generation else { return }
|
||||
energySchedule.complete(available: capability == .verifiedCPU, at: ProcessInfo.processInfo.systemUptime,
|
||||
retryInterval: capability == .unsupported ? 600 : nil)
|
||||
energyUpdate?(energyMonitor.update(processes: processes, readings: readings, capability: capability, maximumInterval: maximumEnergyInterval))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -4,12 +4,18 @@ import Observation
|
||||
@MainActor @Observable
|
||||
final class MetricsStore {
|
||||
private(set) var snapshot = MetricsSnapshot()
|
||||
private(set) var processSnapshot: ProcessSnapshot?
|
||||
private(set) var history = MetricHistory()
|
||||
private(set) var energy: ProcessEnergySnapshot?
|
||||
private(set) var isPaused = false
|
||||
private(set) var isSystemSleeping = false
|
||||
private(set) var isDisplaySleeping = false
|
||||
private(set) var isPanelVisible = false
|
||||
let sampling: SamplingPreferences
|
||||
var effectiveMilliseconds: Int { isPanelVisible ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
|
||||
private var hasSamplingDemand: Bool { isPanelVisible || sampling.backgroundEnabled }
|
||||
private let energyEnabled: Bool
|
||||
private var panelDemand: Bool { isPanelVisible && !isDisplaySleeping }
|
||||
var effectiveMilliseconds: Int { panelDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
|
||||
private var hasSamplingDemand: Bool { !isSystemSleeping && (panelDemand || sampling.backgroundEnabled) }
|
||||
@ObservationIgnored private var generation = 0
|
||||
@ObservationIgnored private var visibilityGeneration = 0
|
||||
@ObservationIgnored private var task: Task<Void, Never>?
|
||||
@@ -18,8 +24,9 @@ final class MetricsStore {
|
||||
@ObservationIgnored private var needsHistoryBoundary = true
|
||||
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
|
||||
|
||||
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler()) {
|
||||
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler(), energyEnabled: Bool = true) {
|
||||
self.sampler = sampler
|
||||
self.energyEnabled = energyEnabled
|
||||
self.sampling = sampling ?? SamplingPreferences()
|
||||
self.sampling.onChange = { [weak self] in
|
||||
guard let self, !self.isPaused,
|
||||
@@ -31,6 +38,7 @@ final class MetricsStore {
|
||||
|
||||
func start() {
|
||||
guard task == nil else { return }
|
||||
if isPaused { energy = nil; visibilityGeneration += 1 }
|
||||
isPaused = false
|
||||
reschedule(reset: true)
|
||||
}
|
||||
@@ -57,21 +65,32 @@ final class MetricsStore {
|
||||
while !Task.isCancelled {
|
||||
let sampledAt = ContinuousClock.now
|
||||
let visibleGeneration = self?.visibilityGeneration
|
||||
var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true,
|
||||
includeSlowMetrics: self?.isPanelVisible == true, processUpdate: { [weak self] processes in
|
||||
var next = await sampler.sample(includeProcesses: self?.panelDemand == true,
|
||||
includeSlowMetrics: self?.panelDemand == true,
|
||||
maximumEnergyInterval: max(30, Double(self?.effectiveMilliseconds ?? 2000) / 500),
|
||||
includeEnergy: self?.energyEnabled == true, demandRevision: visibleGeneration, processUpdate: { [weak self] processes in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.visibilityGeneration == visibleGeneration,
|
||||
self.isPanelVisible, !self.isPaused else { return }
|
||||
if self.snapshot.processes.map({ $0.date > processes.date }) != true { self.snapshot.processes = processes }
|
||||
self.panelDemand, !self.isPaused, !self.isSystemSleeping else { return }
|
||||
if self.processSnapshot.map({ $0.date > processes.date }) != true { self.processSnapshot = processes }
|
||||
}
|
||||
}, energyUpdate: { [weak self] energy in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.visibilityGeneration == visibleGeneration,
|
||||
self.panelDemand, !self.isPaused, !self.isSystemSleeping else { return }
|
||||
self.energy = energy
|
||||
SamplingDiagnostics.recordEnergy(energy)
|
||||
}
|
||||
})
|
||||
guard !Task.isCancelled, self?.generation == currentGeneration else { return }
|
||||
if self?.isPanelVisible != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil }
|
||||
else if let completed = self?.snapshot.processes, completed.date >= next.date {
|
||||
if self?.panelDemand != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil }
|
||||
else if let completed = self?.processSnapshot, completed.date >= next.date {
|
||||
// A fast detached process result may reach MainActor before this quick snapshot.
|
||||
next.processes = completed
|
||||
}
|
||||
self?.snapshot = next
|
||||
var resources = next
|
||||
resources.processes = nil
|
||||
self?.snapshot = resources
|
||||
self?.history.append(next, breakBefore: self?.needsHistoryBoundary == true, expectedInterval: Double(self?.effectiveMilliseconds ?? 5_000) / 1000)
|
||||
self?.lastPublishedAt = .now
|
||||
self?.needsHistoryBoundary = false
|
||||
@@ -92,20 +111,39 @@ final class MetricsStore {
|
||||
visibilityGeneration += 1
|
||||
task?.cancel()
|
||||
task = nil
|
||||
Task { await sampler.setProcessVisible(false) }
|
||||
let revision = visibilityGeneration
|
||||
Task { await sampler.setProcessVisible(false, revision: revision) }
|
||||
isPaused = true
|
||||
SamplingDiagnostics.record(snapshot, event: "pause")
|
||||
}
|
||||
}
|
||||
|
||||
func setSystemSleeping(_ sleeping: Bool) {
|
||||
guard sleeping != isSystemSleeping else { return }
|
||||
isSystemSleeping = sleeping
|
||||
updateDemand(reset: true)
|
||||
}
|
||||
|
||||
func setDisplaySleeping(_ sleeping: Bool) {
|
||||
guard sleeping != isDisplaySleeping else { return }
|
||||
isDisplaySleeping = sleeping
|
||||
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
|
||||
}
|
||||
|
||||
func setPanelVisible(_ visible: Bool) {
|
||||
guard isPanelVisible != visible else { return }
|
||||
visibilityGeneration += 1
|
||||
isPanelVisible = visible
|
||||
if !visible { snapshot.processes = nil }
|
||||
let active = visible && !isPaused
|
||||
Task { await sampler.setProcessVisible(active) }
|
||||
if !isPaused { reschedule(reset: !sampling.backgroundEnabled) }
|
||||
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
|
||||
}
|
||||
|
||||
private func updateDemand(reset: Bool, sampleImmediately: Bool = true) {
|
||||
visibilityGeneration += 1
|
||||
let revision = visibilityGeneration
|
||||
let active = panelDemand && !isPaused && !isSystemSleeping
|
||||
if !active { processSnapshot = nil }
|
||||
energy = nil
|
||||
Task { await sampler.setProcessVisible(active, revision: revision) }
|
||||
if !isPaused { reschedule(reset: reset, sampleImmediately: sampleImmediately) }
|
||||
}
|
||||
|
||||
deinit { task?.cancel() }
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated enum ProcessEnergyServiceClient {
|
||||
static func read(_ identities: [ProcessIdentity]) async -> ([ProcessEnergyReading], EnergyCapability) {
|
||||
var readings: [ProcessEnergyReading] = []
|
||||
var capability: EnergyCapability = .unavailable
|
||||
let deadline = ProcessInfo.processInfo.systemUptime + 3
|
||||
for start in stride(from: 0, to: identities.count, by: ProcessEnergyRequest.limit) {
|
||||
guard !Task.isCancelled, ProcessInfo.processInfo.systemUptime < deadline else { break }
|
||||
let chunk = Array(identities[start..<min(start + ProcessEnergyRequest.limit, identities.count)])
|
||||
let request = ProcessEnergyRequest(token: UUID(), identities: chunk)
|
||||
guard let data = try? JSONEncoder().encode(request), data.count <= ProcessEnergyRequest.byteLimit else { continue }
|
||||
let reply: ProcessEnergyReply? = await ServiceRequest.perform(timeout: min(1.5, deadline - ProcessInfo.processInfo.systemUptime)) { proxy, finish in
|
||||
proxy.readProcessEnergy(data) { data in
|
||||
guard let data, data.count <= 262_144,
|
||||
let value = try? JSONDecoder().decode(ProcessEnergyReply.self, from: data), value.token == request.token,
|
||||
value.readings.count == chunk.count,
|
||||
Set(value.readings.map(\.id)) == Set(chunk) else { finish(nil); return }
|
||||
finish(value)
|
||||
}
|
||||
}
|
||||
if let reply {
|
||||
if capability == .unavailable { capability = .unverified }
|
||||
if reply.capability == .unsupported { return ([], .unsupported) }
|
||||
if reply.capability == .verifiedCPU {
|
||||
capability = .verifiedCPU
|
||||
readings.append(contentsOf: reply.readings)
|
||||
}
|
||||
}
|
||||
}
|
||||
return (readings, capability)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import Foundation
|
||||
|
||||
/// Fixed read-only operation: no caller-supplied paths or commands.
|
||||
@objc protocol SMARTServiceProtocol {
|
||||
nonisolated func readProcessEnergy(_ request: Data, withReply reply: @escaping (Data?) -> 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)
|
||||
|
||||
@@ -5,7 +5,23 @@ import Darwin
|
||||
nonisolated enum SamplingDiagnostics {
|
||||
static let enabled = ProcessInfo.processInfo.environment["KYMO_DIAGNOSTICS"] == "1"
|
||||
|
||||
static func record(_ snapshot: MetricsSnapshot, event: String = "sample") {
|
||||
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,
|
||||
"state": String(describing: snapshot.state), "candidates": snapshot.candidates,
|
||||
"readable": snapshot.readable, "measured": snapshot.measured,
|
||||
"watts": snapshot.rows.map(\.watts), "intervals": snapshot.rows.map(\.seconds)]
|
||||
guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]) else { return }
|
||||
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
|
||||
}
|
||||
|
||||
static func record(_ snapshot: MetricsSnapshot, event: String = "sample", hiddenHostAlive: Bool? = nil) {
|
||||
guard enabled else { return }
|
||||
var payload: [String: Any] = [
|
||||
"event": event, "timestamp": snapshot.date.timeIntervalSince1970,
|
||||
@@ -14,6 +30,7 @@ nonisolated enum SamplingDiagnostics {
|
||||
"pid": ProcessInfo.processInfo.processIdentifier,
|
||||
"load": snapshot.load
|
||||
]
|
||||
payload["hiddenHostAlive"] = hiddenHostAlive
|
||||
payload["cpu"] = snapshot.cpu?.usage
|
||||
payload["cores"] = snapshot.cpu?.cores.count
|
||||
payload["cpuTemperature"] = snapshot.cpuTemperature
|
||||
|
||||
@@ -4,11 +4,17 @@ import Foundation
|
||||
nonisolated struct SensorSchedule {
|
||||
private(set) var deadline: TimeInterval = 0
|
||||
private var failures = 0
|
||||
private let successInterval: TimeInterval
|
||||
private let failureInterval: TimeInterval
|
||||
init(successInterval: TimeInterval = 10, failureInterval: TimeInterval = 60) {
|
||||
self.successInterval = successInterval
|
||||
self.failureInterval = failureInterval
|
||||
}
|
||||
|
||||
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))))
|
||||
mutating func complete(available: Bool, at now: TimeInterval, retryInterval: TimeInterval? = nil) {
|
||||
failures = available ? 0 : min(failures + 1, 8)
|
||||
deadline = now + (retryInterval ?? (available ? successInterval : min(600, failureInterval * pow(2, Double(failures - 1)))))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import SwiftUI
|
||||
|
||||
/// A separate observation scope: energy completion does not replace the resource snapshot.
|
||||
struct EnergyProcessSection: View {
|
||||
let metrics: MetricsStore
|
||||
private var snapshot: ProcessEnergySnapshot? { metrics.energy }
|
||||
private var rows: [ProcessEnergyUsage] { snapshot?.rows ?? [] }
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack {
|
||||
Text("energy.cpuProcesses").font(PanelStyle.section)
|
||||
if snapshot?.state == .partial {
|
||||
Text("energy.partial").font(.system(size: 8)).foregroundStyle(.secondary)
|
||||
.help(Text("energy.coverage \(snapshot?.measured ?? 0) \(snapshot?.candidates ?? 0)"))
|
||||
}
|
||||
Spacer()
|
||||
Text("energy.averagePower").foregroundStyle(.secondary)
|
||||
}.font(PanelStyle.label)
|
||||
if rows.isEmpty {
|
||||
Text(statusKey).foregroundStyle(.secondary).font(PanelStyle.label)
|
||||
} else {
|
||||
ForEach(rows) { usage in
|
||||
EnergyProcessListRow(usage: usage, maximum: rows.first?.watts ?? 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
.help(Text("energy.scopeHelp"))
|
||||
}
|
||||
private var statusKey: LocalizedStringKey {
|
||||
switch snapshot?.state {
|
||||
case .unsupported: "energy.unsupported"
|
||||
case .unavailable: "energy.unavailable"
|
||||
default: "energy.waiting"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct EnergyProcessListRow: View {
|
||||
let usage: ProcessEnergyUsage
|
||||
let maximum: Double
|
||||
private var progress: Double { maximum > 0 ? min(1, max(0, usage.watts / maximum)) : 0 }
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 5) {
|
||||
ProcessIcon(process: usage.process)
|
||||
Text(verbatim: usage.process.name).lineLimit(1).truncationMode(.middle)
|
||||
.frame(width: 66, alignment: .leading)
|
||||
GeometryReader { proxy in
|
||||
Capsule().fill(.primary.opacity(0.07))
|
||||
.overlay(alignment: .leading) {
|
||||
Capsule().fill(Color("MetricCPU"))
|
||||
.frame(width: proxy.size.width * progress, height: 4).clipped()
|
||||
}.clipShape(Capsule())
|
||||
}.frame(height: 4)
|
||||
Text(verbatim: usage.formattedPower)
|
||||
.foregroundStyle(Color("MetricCPU")).font(PanelStyle.value)
|
||||
.monospacedDigit().frame(width: 57, alignment: .trailing)
|
||||
}
|
||||
.font(PanelStyle.label).frame(height: 16)
|
||||
.help(Text("energy.window \(usage.seconds.formatted(.number.precision(.fractionLength(1))))"))
|
||||
.accessibilityElement(children: .combine)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import SwiftUI
|
||||
import Observation
|
||||
|
||||
@MainActor @Observable final class PanelPresentation {
|
||||
fileprivate(set) var isOpen = false
|
||||
var isPinned = false { didSet { onPinChange?(isPinned) } }
|
||||
@ObservationIgnored var onPinChange: ((Bool) -> Void)?
|
||||
}
|
||||
@@ -11,10 +12,14 @@ import Observation
|
||||
@MainActor final class MenuPanelController: NSObject {
|
||||
let presentation = PanelPresentation()
|
||||
let panel = MonitoringPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
|
||||
#if DEBUG || KYMO_AUDIT
|
||||
private(set) weak var lastHiddenContent: NSView?
|
||||
#endif
|
||||
private var statusItem: NSStatusItem?
|
||||
private var localMouse: Any?
|
||||
private var globalMouse: Any?
|
||||
private var tokens: [NSObjectProtocol] = []
|
||||
private var visibilityObservation: NSKeyValueObservation?
|
||||
private let content: (PanelPresentation) -> NSView
|
||||
private let visibility: (Bool) -> Void
|
||||
private let menuTitle: (String) -> String
|
||||
@@ -52,6 +57,12 @@ import Observation
|
||||
tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.place() }
|
||||
})
|
||||
visibilityObservation = panel.observe(\.isVisible, options: [.new]) { [weak self] _, _ in
|
||||
Task { @MainActor [weak self] in self?.publishVisibility() }
|
||||
}
|
||||
tokens.append(NotificationCenter.default.addObserver(forName: NSWindow.didChangeOcclusionStateNotification, object: panel, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.publishVisibility() }
|
||||
})
|
||||
tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didResignActiveNotification, object: NSApp, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated {
|
||||
guard let self, !self.showingStatusMenu, !self.isOverStatusItem(NSEvent.mouseLocation) else { return }
|
||||
@@ -98,6 +109,7 @@ import Observation
|
||||
func show() {
|
||||
guard !panel.isVisible else { panel.makeKeyAndOrderFront(nil); return }
|
||||
place()
|
||||
presentation.isOpen = true
|
||||
panel.contentView = content(presentation)
|
||||
panel.level = presentation.isPinned ? .floating : .normal
|
||||
panel.makeKeyAndOrderFront(nil)
|
||||
@@ -105,12 +117,20 @@ import Observation
|
||||
// Opening the panel must not start editing the first text field.
|
||||
// Explicit clicks and keyboard navigation can still focus its controls.
|
||||
panel.makeFirstResponder(panel)
|
||||
visibility(true)
|
||||
publishVisibility()
|
||||
installMonitors()
|
||||
}
|
||||
|
||||
private func publishVisibility() {
|
||||
visibility(panel.isVisible && panel.occlusionState.contains(.visible))
|
||||
}
|
||||
|
||||
func hide() {
|
||||
presentation.isOpen = false
|
||||
panel.orderOut(nil)
|
||||
#if DEBUG || KYMO_AUDIT
|
||||
if let content = panel.contentView { lastHiddenContent = content }
|
||||
#endif
|
||||
panel.contentView = nil
|
||||
visibility(false)
|
||||
removeMonitors()
|
||||
@@ -127,6 +147,7 @@ import Observation
|
||||
statusItem = nil
|
||||
tokens.forEach(NotificationCenter.default.removeObserver)
|
||||
tokens.removeAll()
|
||||
visibilityObservation = nil
|
||||
}
|
||||
|
||||
private func place() {
|
||||
|
||||
@@ -52,20 +52,7 @@ extension MenuPanelView {
|
||||
}.font(PanelStyle.label)
|
||||
.modifier(CardInset())
|
||||
}
|
||||
.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
|
||||
await MainActor.run {
|
||||
guard !Task.isCancelled else { return }
|
||||
publicIPAddress = address
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var publicIPRoute: String {
|
||||
"\(snapshot.defaultNetworkInterface ?? ""):\(String(describing: snapshot.networkPath)):\(snapshot.network?.filter { $0.active }.map { $0.addresses.joined(separator: ",") }.joined(separator: ";") ?? "")"
|
||||
.modifier(PanelPublicIPRefresh(metrics: metrics, address: $publicIPAddress))
|
||||
}
|
||||
func networkAddress(_ title: LocalizedStringKey, address: String?) -> some View {
|
||||
HStack(spacing: 4) {
|
||||
|
||||
@@ -237,22 +237,7 @@ extension MenuPanelView {
|
||||
.frame(height: 32)
|
||||
Spacer(minLength: 0)
|
||||
CardSeparator()
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack {
|
||||
Text("battery.highestEnergyProcess").font(PanelStyle.section)
|
||||
Spacer()
|
||||
Text("battery.cpuUsage").foregroundStyle(.secondary)
|
||||
}
|
||||
.font(PanelStyle.label)
|
||||
let energyProcesses = snapshot.processes?.highestCPUProcesses(limit: 3) ?? []
|
||||
if energyProcesses.isEmpty {
|
||||
Text("metric.waiting").foregroundStyle(.secondary)
|
||||
} else {
|
||||
ForEach(energyProcesses) { process in
|
||||
EnergyProcessListRow(process: process)
|
||||
}
|
||||
}
|
||||
}
|
||||
EnergyProcessSection(metrics: metrics)
|
||||
// Reserve the header and all three rows before process sampling completes.
|
||||
.frame(height: 74, alignment: .top)
|
||||
.lineLimit(1)
|
||||
@@ -261,36 +246,3 @@ extension MenuPanelView {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
struct EnergyProcessListRow: View {
|
||||
let process: ProcessMetrics
|
||||
|
||||
private var progress: Double {
|
||||
guard let value = process.cpu, value.isFinite else { return 0 }
|
||||
return min(max(value, 0), 1)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 5) {
|
||||
ProcessIcon(process: process)
|
||||
Text(verbatim: process.name).lineLimit(1).truncationMode(.middle)
|
||||
.frame(width: 66, alignment: .leading)
|
||||
GeometryReader { proxy in
|
||||
Capsule().fill(.primary.opacity(0.07))
|
||||
.overlay(alignment: .leading) {
|
||||
Capsule().fill(Color("MetricCPU"))
|
||||
.frame(width: proxy.size.width * progress, height: 4)
|
||||
.clipped()
|
||||
}
|
||||
.clipShape(Capsule())
|
||||
}
|
||||
.frame(height: 4)
|
||||
AnimatedMetricText(value: process.cpu.map { String(format: "%.1f%%", $0 * 100) } ?? "--")
|
||||
.foregroundStyle(Color("MetricCPU")).font(PanelStyle.value)
|
||||
.monospacedDigit().frame(width: 39, alignment: .trailing)
|
||||
}
|
||||
.font(PanelStyle.label)
|
||||
.frame(height: 16)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,8 +54,8 @@ struct MenuPanelView: View {
|
||||
} else {
|
||||
resourceRows
|
||||
}
|
||||
if metrics.isPanelVisible && PanelResourceAudit.omitted != "processes" {
|
||||
ProcessTableView(snapshot: snapshot.processes, wide: panelSize.width >= 900).frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
if presentation.isOpen && PanelResourceAudit.omitted != "processes" {
|
||||
PanelProcessSection(metrics: metrics, wide: panelSize.width >= 900).frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.frame(minHeight: 170)
|
||||
}
|
||||
}
|
||||
@@ -65,13 +65,11 @@ struct MenuPanelView: View {
|
||||
if panelSize != size { panelSize = size }
|
||||
}.frame(width: 0, height: 0))
|
||||
.onAppear {
|
||||
metrics.setPanelVisible(true)
|
||||
reservedFanCount = snapshot.fans?.count ?? 0
|
||||
}
|
||||
.onChange(of: snapshot.fans?.count) { _, count in
|
||||
reservedFanCount = max(reservedFanCount, count ?? 0)
|
||||
}
|
||||
.onDisappear { metrics.setPanelVisible(false) }
|
||||
.onChange(of: snapshot.network?.map(\.identity)) { _, keys in
|
||||
if !selectedInterface.isEmpty && !(keys ?? []).contains(selectedInterface) { selectedInterface = "" }
|
||||
}
|
||||
@@ -215,3 +213,10 @@ private struct PanelControlButtonBody<Content: View>: View {
|
||||
.onHover { isHovered = $0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep process publications out of the resource-card observation scope.
|
||||
private struct PanelProcessSection: View {
|
||||
let metrics: MetricsStore
|
||||
let wide: Bool
|
||||
var body: some View { ProcessTableView(snapshot: metrics.processSnapshot, wide: wide) }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import SwiftUI
|
||||
|
||||
/// Shared by the dashboard and the text-only audit so network work is comparable.
|
||||
struct PanelPublicIPRefresh: ViewModifier {
|
||||
let metrics: MetricsStore
|
||||
@Binding var address: String?
|
||||
private var route: String {
|
||||
let snapshot = metrics.snapshot
|
||||
return "\(snapshot.defaultNetworkInterface ?? ""):\(String(describing: snapshot.networkPath)):\(snapshot.network?.filter { $0.active }.map { $0.addresses.joined(separator: ",") }.joined(separator: ";") ?? "")"
|
||||
}
|
||||
func body(content: Content) -> some View {
|
||||
content.task(id: "\(route):\(metrics.isPaused):\(metrics.isSystemSleeping):\(metrics.isDisplaySleeping):\(metrics.isPanelVisible)") {
|
||||
guard !metrics.isPaused, !metrics.isSystemSleeping, !metrics.isDisplaySleeping, metrics.isPanelVisible else { return }
|
||||
address = nil
|
||||
guard metrics.snapshot.networkPath == .available else { return }
|
||||
await PublicIPAddressService.shared.refreshContinuously(route: route) { value in
|
||||
await MainActor.run {
|
||||
guard !Task.isCancelled else { return }
|
||||
address = value
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,26 @@ import AppKit
|
||||
|
||||
/// Explicit local measurement only. Never schedules work during normal launches.
|
||||
@MainActor enum PanelResourceAudit {
|
||||
#if DEBUG || KYMO_AUDIT
|
||||
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) }
|
||||
controller.panel.animationBehavior = .none
|
||||
if ProcessInfo.processInfo.environment["KYMO_XPC_AUDIT"] == "1" {
|
||||
await checkRequestCompletion()
|
||||
SamplingDiagnostics.record(metrics.snapshot, event: "audit.xpcChecksPassed")
|
||||
controller.shutdown()
|
||||
NSApp.terminate(nil)
|
||||
return
|
||||
}
|
||||
@MainActor func mark(_ event: String) {
|
||||
var report = metrics.snapshot
|
||||
report.processes = metrics.processSnapshot
|
||||
SamplingDiagnostics.record(report, event: "audit." + event, hiddenHostAlive: controller.lastHiddenContent != nil)
|
||||
}
|
||||
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
|
||||
@@ -36,4 +49,43 @@ import AppKit
|
||||
NSApp.terminate(nil)
|
||||
}
|
||||
}
|
||||
/// Uses real connection lifecycle but injects local callbacks; peer auth is tested separately by RPCs.
|
||||
private static func checkRequestCompletion() async {
|
||||
for _ in 0..<20 {
|
||||
let result: Int? = await ServiceRequest.perform(timeout: 0.2) { _, finish in
|
||||
finish(1); finish(2)
|
||||
}
|
||||
precondition(result == 1, "A reply must finish exactly once")
|
||||
}
|
||||
for _ in 0..<20 {
|
||||
let result: Int? = await ServiceRequest.perform(timeout: 0.2) { _, finish in
|
||||
DispatchQueue.concurrentPerform(iterations: 2) { finish($0) }
|
||||
}
|
||||
precondition(result == 0 || result == 1)
|
||||
}
|
||||
let timeoutStart = ContinuousClock.now
|
||||
let timedOut: Int? = await ServiceRequest.perform(timeout: 0.1) { _, _ in }
|
||||
let timeoutElapsed = timeoutStart.duration(to: .now)
|
||||
precondition(timedOut == nil && timeoutElapsed >= .milliseconds(80) && timeoutElapsed < .seconds(2))
|
||||
let cancellationStart = ContinuousClock.now
|
||||
let (started, signal) = AsyncStream<Void>.makeStream()
|
||||
let cancelled = Task<Int?, Never> {
|
||||
await ServiceRequest.perform(timeout: 10) { _, _ in signal.yield(()); signal.finish() }
|
||||
}
|
||||
for await _ in started { break }
|
||||
cancelled.cancel()
|
||||
let cancelledResult = await cancelled.value
|
||||
precondition(cancelledResult == nil && cancellationStart.duration(to: .now) < .seconds(2))
|
||||
let early = Task<Int?, Never> { await ServiceRequest.perform(timeout: 10) { _, _ in } }
|
||||
early.cancel()
|
||||
let earlyResult = await early.value
|
||||
precondition(earlyResult == nil)
|
||||
}
|
||||
|
||||
#else
|
||||
static let enabled = false
|
||||
static let omitted = ""
|
||||
static func run(controller: MenuPanelController, metrics: MetricsStore) {}
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
#if DEBUG || KYMO_AUDIT
|
||||
/// An opt-in comparison frontend. Sampling, history, IPC and public-IP policy remain enabled.
|
||||
struct TextMonitoringAuditView: View {
|
||||
let metrics: MetricsStore
|
||||
let appearance: AppearancePreferences
|
||||
@State private var publicAddress: String?
|
||||
var body: some View {
|
||||
TextReportHost(snapshot: metrics.snapshot, processes: metrics.processSnapshot, energy: metrics.energy,
|
||||
historyPoints: metrics.history.samples.count, publicAddress: publicAddress, appearance: appearance.appearance)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.modifier(PanelPublicIPRefresh(metrics: metrics, address: $publicAddress))
|
||||
}
|
||||
}
|
||||
|
||||
private struct TextReportHost: NSViewRepresentable {
|
||||
let snapshot: MetricsSnapshot
|
||||
let processes: ProcessSnapshot?
|
||||
let energy: ProcessEnergySnapshot?
|
||||
let historyPoints: Int
|
||||
let publicAddress: String?
|
||||
let appearance: AppAppearance
|
||||
func makeCoordinator() -> Coordinator { Coordinator() }
|
||||
func makeNSView(context: Context) -> ReportScrollView {
|
||||
let scroll = ReportScrollView()
|
||||
scroll.hasVerticalScroller = true
|
||||
scroll.hasHorizontalScroller = true
|
||||
scroll.autohidesScrollers = false
|
||||
scroll.scrollerStyle = .legacy
|
||||
let table = NSTableView(frame: NSRect(x: 0, y: 0, width: 3200, height: 800))
|
||||
table.headerView = nil
|
||||
table.style = .plain
|
||||
table.rowHeight = 15
|
||||
table.intercellSpacing = .zero
|
||||
table.selectionHighlightStyle = .none
|
||||
table.backgroundColor = .windowBackgroundColor
|
||||
table.columnAutoresizingStyle = .noColumnAutoresizing
|
||||
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("text"))
|
||||
column.width = 3200
|
||||
table.addTableColumn(column)
|
||||
table.delegate = context.coordinator
|
||||
table.dataSource = context.coordinator
|
||||
scroll.documentView = table
|
||||
return scroll
|
||||
}
|
||||
func updateNSView(_ scroll: ReportScrollView, context: Context) {
|
||||
scroll.choice = appearance
|
||||
guard let table = scroll.documentView as? NSTableView else { return }
|
||||
let c = context.coordinator
|
||||
if c.processDate != processes?.date {
|
||||
c.processDate = processes?.date
|
||||
c.rows = ProcessTableProjection.rows(processes?.rows ?? [], query: "", sorting: [ProcessSort(key: .cpu)], order: [])
|
||||
}
|
||||
let heading = Self.resourceText(snapshot) + "\nHistory points retained: \(historyPoints)\nPublic IP: \(publicAddress ?? "--")\n\n" + Self.energyText(energy)
|
||||
+ "\nProcesses: \(processes?.readable ?? 0)/\(processes?.enumerated ?? 0), failed=\(processes?.failed ?? false)\nPID\tCPU %\tRSS bytes\tThreads\tRestricted\tName\tPath"
|
||||
c.lines = heading.components(separatedBy: "\n")
|
||||
let origin = scroll.contentView.bounds.origin
|
||||
let oldCount = table.numberOfRows
|
||||
let newCount = c.lines.count + c.rows.count
|
||||
if newCount != oldCount {
|
||||
table.beginUpdates()
|
||||
if newCount > oldCount { table.insertRows(at: IndexSet(integersIn: oldCount..<newCount), withAnimation: []) }
|
||||
else { table.removeRows(at: IndexSet(integersIn: newCount..<oldCount), withAnimation: []) }
|
||||
table.endUpdates()
|
||||
}
|
||||
let visible = table.rows(in: table.visibleRect)
|
||||
if visible.location != NSNotFound, visible.length > 0 {
|
||||
for row in visible.location..<min(newCount, visible.location + visible.length) {
|
||||
if let cell = table.view(atColumn: 0, row: row, makeIfNecessary: false) as? NSTableCellView {
|
||||
c.update(cell, row: row)
|
||||
}
|
||||
}
|
||||
}
|
||||
scroll.contentView.scroll(to: origin)
|
||||
scroll.reflectScrolledClipView(scroll.contentView)
|
||||
SamplingDiagnostics.recordTextPresentation(processes: c.rows.count, cells: c.createdCells)
|
||||
}
|
||||
/// Fixed-height native text rows format only visible records. All sampled rows remain scrollable.
|
||||
final class Coordinator: NSObject, NSTableViewDataSource, NSTableViewDelegate {
|
||||
var processDate: Date?
|
||||
var rows: [ProcessMetrics] = []
|
||||
var lines: [String] = []
|
||||
var createdCells = 0
|
||||
func numberOfRows(in tableView: NSTableView) -> Int { lines.count + rows.count }
|
||||
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
|
||||
guard row >= 0, row < lines.count + rows.count else { return nil }
|
||||
let key = NSUserInterfaceItemIdentifier("text.cell")
|
||||
let cell: NSTableCellView
|
||||
if let reused = tableView.makeView(withIdentifier: key, owner: nil) as? NSTableCellView { cell = reused }
|
||||
else {
|
||||
cell = NSTableCellView()
|
||||
cell.identifier = key
|
||||
let field = NSTextField(labelWithString: "")
|
||||
field.font = .monospacedSystemFont(ofSize: 11, weight: .regular)
|
||||
field.lineBreakMode = .byClipping
|
||||
field.translatesAutoresizingMaskIntoConstraints = false
|
||||
cell.addSubview(field)
|
||||
cell.textField = field
|
||||
NSLayoutConstraint.activate([
|
||||
field.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 8),
|
||||
field.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: -4),
|
||||
field.topAnchor.constraint(equalTo: cell.topAnchor), field.bottomAnchor.constraint(equalTo: cell.bottomAnchor)
|
||||
])
|
||||
createdCells += 1
|
||||
}
|
||||
update(cell, row: row)
|
||||
return cell
|
||||
}
|
||||
func update(_ cell: NSTableCellView, row: Int) {
|
||||
guard row >= 0, row < lines.count + rows.count else { return }
|
||||
let value = row < lines.count ? lines[row] : TextReportHost.processLine(rows[row - lines.count])
|
||||
if cell.textField?.stringValue != value { cell.textField?.stringValue = value }
|
||||
}
|
||||
}
|
||||
final class ReportScrollView: NSScrollView {
|
||||
var choice = AppAppearance.system { didSet { apply() } }
|
||||
override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); apply() }
|
||||
private func apply() {
|
||||
let target = choice.windowAppearance
|
||||
if window?.appearance?.name != target?.name { window?.appearance = target }
|
||||
}
|
||||
}
|
||||
private static func number(_ value: Double?) -> String { value.map { String(format: "%.3f", $0) } ?? "--" }
|
||||
private static func bytes(_ value: UInt64?) -> String { value.map(String.init) ?? "--" }
|
||||
private static func resourceText(_ s: MetricsSnapshot) -> String {
|
||||
var lines = ["Kymo — plain text comparison (no charts, icons or animation)", "Resource timestamp: \(s.date.timeIntervalSince1970)"]
|
||||
lines += ["CPU total/user/system fraction: \(number(s.cpu?.usage)) / \(number(s.cpu?.user)) / \(number(s.cpu?.system))",
|
||||
"CPU cores: \(s.cpu?.cores.map { number($0) }.joined(separator: " ") ?? "--")",
|
||||
"CPU/GPU temperature °C: \(number(s.cpuTemperature)) / \(number(s.gpuTemperature))",
|
||||
"Fans RPM: \(s.fans?.map { "\($0.id)=\(number($0.rpm))" }.joined(separator: " ") ?? "--")",
|
||||
"GPU usage/renderer/tiler/cores: \(number(s.gpu?.usage)) / \(number(s.gpu?.renderer)) / \(number(s.gpu?.tiler)) / \(s.gpu?.coreCount.map(String.init) ?? "--")",
|
||||
"GPU in-use/allocated bytes: \(bytes(s.gpu?.inUseMemory)) / \(bytes(s.gpu?.allocatedMemory))",
|
||||
"Memory total/used/available/cached/wired/compressed/swap bytes: \(bytes(s.memory?.total)) / \(bytes(s.memory?.used)) / \(bytes(s.memory?.available)) / \(bytes(s.memory?.cached)) / \(bytes(s.memory?.wired)) / \(bytes(s.memory?.compressed)) / \(bytes(s.memory?.swapUsed))",
|
||||
"Memory pressure: \(s.memory?.pressure.map(String.init) ?? "--")",
|
||||
"Disk total/available bytes: \(bytes(s.disk?.total)) / \(bytes(s.disk?.available))",
|
||||
"Disk IO read/write B/s: \(number(s.diskIO?.read)) / \(number(s.diskIO?.written))",
|
||||
"SMART remaining/hour: \(number(s.diskHealth?.remainingLife)) / \(bytes(s.diskHealth?.powerOnHours))",
|
||||
"Battery charge/health/power W/cycles: \(number(s.battery?.charge)) / \(number(s.battery?.health)) / \(number(s.battery?.power)) / \(s.battery?.cycles.map(String.init) ?? "--")",
|
||||
"Battery charging/external/minutes/state: \(String(describing: s.battery?.charging)) / \(String(describing: s.battery?.externalPower)) / \(s.battery?.minutesRemaining.map(String.init) ?? "--") / \(s.batteryState)",
|
||||
"Uptime/load: \(number(s.uptime)) / \(s.load.map { number($0) }.joined(separator: " "))",
|
||||
"Network path/default interface: \(String(describing: s.networkPath)) / \(s.defaultNetworkInterface ?? "--")"]
|
||||
for i in s.network ?? [] { lines.append("\(i.name) active=\(i.active) received/sent=\(i.received)/\(i.sent) B, down/up=\(number(i.download))/\(number(i.upload)) B/s, addresses=\(i.addresses.joined(separator: ","))") }
|
||||
for v in s.volumes ?? [] { lines.append("Volume \(v.name) \(v.path): total/available \(v.capacity.total)/\(v.capacity.available) B") }
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
private static func energyText(_ energy: ProcessEnergySnapshot?) -> String {
|
||||
guard let energy else { return "CPU energy: waiting\n" }
|
||||
return "CPU energy: \(energy.state), measured/readable/enumerated=\(energy.measured)/\(energy.readable)/\(energy.candidates)\n" + energy.rows.map { "\($0.id.pid) \($0.process.name): \($0.formattedPower), interval \(number($0.seconds)) s" }.joined(separator: "\n") + "\n"
|
||||
}
|
||||
private static func processLine(_ process: ProcessMetrics) -> String {
|
||||
"\(process.id.pid)\t\(number(process.cpu.map { $0 * 100 }))\t\(bytes(process.residentBytes))\t\(process.threads.map(String.init) ?? "--")\t\(process.restricted)\t\(process.name)\t\(process.path ?? "--")"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#else
|
||||
/// The diagnostic renderer is excluded from distribution builds.
|
||||
struct TextMonitoringAuditView: View {
|
||||
let metrics: MetricsStore
|
||||
let appearance: AppearancePreferences
|
||||
var body: some View { EmptyView() }
|
||||
}
|
||||
#endif
|
||||
@@ -748,6 +748,7 @@
|
||||
}
|
||||
},
|
||||
"battery.cpuUsage" : {
|
||||
"extractionState" : "stale",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
@@ -836,29 +837,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"battery.energyProxyHelp" : {
|
||||
"extractionState" : "stale",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Ranked by current process CPU utilization; this is not the system energy impact score."
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "按当前进程 CPU 利用率排序,不代表系统能耗影响评分。"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "依目前處理程序 CPU 使用率排序,不代表系統能耗影響評分。"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"battery.external" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
@@ -905,6 +883,7 @@
|
||||
}
|
||||
},
|
||||
"battery.highestEnergyProcess" : {
|
||||
"extractionState" : "stale",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
@@ -1577,6 +1556,213 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"energy.averagePower" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Average power"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "平均功率"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "平均功率"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"energy.coverage %lld %lld" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Measured intervals / enumerated processes: %1$lld / %2$lld"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "有效区间进程数 / 枚举数:%1$lld / %2$lld"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "有效區間程序數 / 列舉數:%1$lld / %2$lld"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"energy.cpuProcesses" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Energy processes (CPU)"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "耗电进程(CPU)"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "耗電程序(CPU)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"energy.partial" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Partial"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "部分可测"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "部分可測"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"energy.scopeHelp" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Ranked by system CPU energy counter deltas among measurable processes. Not total app/device power; GPU, display, network and helper processes are not aggregated. Bars are relative to this list."
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "在可测进程中按系统 CPU 归属能量差值排序,不代表应用或整机完整功耗;不聚合 GPU、屏幕、网络或辅助进程。条形图仅为列表内相对值。"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "在可測程序中依系統 CPU 歸屬能量差值排序,不代表應用程式或整機完整功耗;不彙總 GPU、螢幕、網路或輔助程序。長條僅為清單內相對值。"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"energy.unavailable" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Energy counter unavailable"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "能量计数不可用或受限"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "能量計數不可用或受限"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"energy.unsupported" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Energy counter unsupported"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "系统不支持能量计数"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "系統不支援能量計數"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"energy.waiting" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Waiting for energy interval…"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "等待能量区间采样…"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "等待能量區間取樣…"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"energy.window %@" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Measured interval: %@ s"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "实际统计窗口:%@ 秒"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "實際統計區間:%@ 秒"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"gpu.allocatedMemory" : {
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
@@ -3870,6 +4056,29 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"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" : "隱藏時記錄趨勢"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"sampling.backgroundHelp" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
@@ -4166,30 +4375,7 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -19,8 +19,8 @@ extension AppAppearance {
|
||||
struct AppearanceStyle: ViewModifier {
|
||||
let preferences: AppearancePreferences
|
||||
var refreshContentOnChange = false
|
||||
@State private var system = SystemAppearanceObserver()
|
||||
private var resolved: AppAppearance { preferences.appearance.resolved(systemIsDark: system.isDark) }
|
||||
@State private var system: SystemAppearanceObserver?
|
||||
private var resolved: AppAppearance { preferences.appearance.resolved(systemIsDark: system?.isDark ?? SystemAppearanceObserver.isDark(globalDomain: UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain))) }
|
||||
private var scheme: ColorScheme { resolved == .dark ? .dark : .light }
|
||||
func body(content: Content) -> some View {
|
||||
content
|
||||
@@ -31,6 +31,7 @@ struct AppearanceStyle: ViewModifier {
|
||||
.preferredColorScheme(scheme)
|
||||
.environment(\.colorScheme, scheme)
|
||||
.tint(.blue)
|
||||
.onAppear { if system == nil { system = SystemAppearanceObserver() } }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user