Files
Kymo/kymoTests/SamplingIntervalChecks.swift
wangairnan 4b8deb2e48 feat(power): 展示电池实际充放电功率并及时响应电源切换
保留电量百分比和连续趋势,按历史采样展示电池、适配器和系统功率。面板可见时读取电池实时功率,插拔电源后立即刷新并复读。
2026-11-15 23:54:19 +08:00

195 lines
11 KiB
Swift

import Foundation
import Observation
@main struct SamplingIntervalChecks {
@MainActor static func main() async throws {
let suite = "kymo-interval-checks-" + UUID().uuidString
let defaults = UserDefaults(suiteName: suite)!
defer { defaults.removePersistentDomain(forName: suite) }
let preferences = SamplingPreferences(defaults: defaults)
precondition(preferences.panelMilliseconds == 2000 && preferences.backgroundMilliseconds == 30000 && !preferences.backgroundEnabled)
for (input, expected) in [(Int.min, 500), (549, 500), (550, 600), (1501, 1500), (Int.max, 1_800_000)] {
preferences.panelMilliseconds = input
precondition(preferences.panelMilliseconds == expected)
}
preferences.backgroundMilliseconds = 1799900
let restored = SamplingPreferences(defaults: defaults)
precondition(restored.panelMilliseconds == 1_800_000 && restored.backgroundMilliseconds == 1799900)
precondition(restored.backgroundEnabled, "Existing explicit intervals retain background history")
restored.backgroundEnabled = false
precondition(!SamplingPreferences(defaults: defaults).backgroundEnabled, "Explicit opt-out overrides migration")
defaults.set(Double.nan, forKey: "sampling.panelMilliseconds")
defaults.set(true, forKey: "sampling.backgroundMilliseconds")
let invalid = SamplingPreferences(defaults: defaults)
precondition(invalid.panelMilliseconds == 2000 && invalid.backgroundMilliseconds == 30000 && !invalid.backgroundEnabled)
preferences.backgroundEnabled = true
preferences.panelMilliseconds = 500
preferences.backgroundMilliseconds = 1_800_000
let store = MetricsStore(sampling: preferences)
store.setDetailDemand(processes: true, slowMetrics: false)
store.setPanelVisible(true)
try await until { store.processSnapshot != nil }
precondition(store.effectiveMilliseconds == 500)
store.setPanelVisible(false)
precondition(store.processSnapshot == nil && store.effectiveMilliseconds == 1_800_000)
try await Task.sleep(for: .milliseconds(200))
let hiddenDate = store.snapshot.date
preferences.panelMilliseconds = 700
try await Task.sleep(for: .milliseconds(650))
precondition(store.snapshot.date == hiddenDate && store.processSnapshot == nil)
preferences.backgroundMilliseconds = 500
try await until { store.snapshot.date > hiddenDate }
precondition(store.history.samples.last?.breakBefore == false)
precondition(store.history.samples.last?.expectedInterval == 0.5)
let first = store.snapshot.date
try await until { store.snapshot.date > first }
precondition(store.snapshot.date.timeIntervalSince(first) >= 0.45)
store.togglePause()
let paused = store.snapshot.date
preferences.panelMilliseconds = 1_800_000
store.setPanelVisible(true)
preferences.backgroundMilliseconds = 800
try await Task.sleep(for: .milliseconds(650))
precondition(store.isPaused && store.snapshot.date == paused)
store.togglePause()
try await until { store.snapshot.date > paused && store.processSnapshot != nil }
precondition(store.effectiveMilliseconds == 1_800_000)
precondition(store.history.samples.last?.breakBefore == true)
store.togglePause()
let pausedCount = store.history.samples.count
store.powerSourceDidChange()
try await Task.sleep(for: .milliseconds(100))
precondition(store.history.samples.count == pausedCount)
store.togglePause()
try await until { store.history.samples.count > pausedCount }
let beforeEvent = store.history.samples.count
store.powerSourceDidChange()
try await until { store.history.samples.count >= beforeEvent + 2 }
precondition(store.effectiveMilliseconds == 1_800_000)
store.togglePause()
let probe = DelayedProcessRead()
let deferred = SystemSampler(processRead: { probe.read(&$0) })
await deferred.setProcessVisible(true)
_ = await deferred.sample()
await deferred.setProcessVisible(false)
await deferred.setProcessVisible(true)
let delivered = ProcessDelivery()
_ = await deferred.sample(processUpdate: { _ in Task { await delivered.received() } })
let deadline = ContinuousClock.now.advanced(by: .seconds(4))
while !(await delivered.value) && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) }
let didDeliver = await delivered.value
precondition(didDeliver, "Reopened process request must complete without another sample")
precondition(probe.count >= 2 && probe.peak == 1)
await deferred.setProcessVisible(false)
let slowRead = DelayedProcessRead(delay: 0.5)
let changing = SamplingPreferences(defaults: defaults)
changing.panelMilliseconds = 500
changing.backgroundMilliseconds = 1_800_000
let changingStore = MetricsStore(sampling: changing, sampler: SystemSampler(processRead: { slowRead.read(&$0) }))
changingStore.setDetailDemand(processes: true, slowMetrics: false)
changingStore.setPanelVisible(true)
try await until { !changingStore.history.samples.isEmpty }
precondition(changingStore.processSnapshot == nil)
let countBeforeChange = changingStore.history.samples.count
let resourceChanges = PublicationCount()
withObservationTracking { _ = changingStore.snapshot } onChange: { resourceChanges.increment() }
changing.panelMilliseconds = 1_800_000
try await until { changingStore.processSnapshot != nil }
precondition(changingStore.history.samples.count == countBeforeChange, "Rate changes must preserve in-flight process delivery without an extra quick sample")
precondition(resourceChanges.value == 0, "Process completion must not invalidate resource snapshot observers")
changingStore.togglePause()
let dormantPreferences = SamplingPreferences(defaults: defaults)
dormantPreferences.backgroundEnabled = false
dormantPreferences.panelMilliseconds = 500
let dormant = MetricsStore(sampling: dormantPreferences)
try await Task.sleep(for: .milliseconds(650))
precondition(dormant.history.samples.isEmpty && dormant.snapshot.memory == nil,
"Hidden without a consumer must not perform even an initial full sample")
dormant.setDetailDemand(processes: true, slowMetrics: false)
dormant.setPanelVisible(true)
try await until { dormant.processSnapshot != nil }
dormant.setPanelVisible(false)
let hiddenCount = dormant.history.samples.count
try await Task.sleep(for: .milliseconds(650))
precondition(dormant.history.samples.count == hiddenCount && dormant.processSnapshot == nil)
dormantPreferences.backgroundEnabled = true
dormantPreferences.backgroundMilliseconds = 500
try await until { dormant.history.samples.count > hiddenCount }
dormantPreferences.backgroundEnabled = false
let disabledCount = dormant.history.samples.count
try await Task.sleep(for: .milliseconds(650))
precondition(dormant.history.samples.count == disabledCount)
dormant.setPanelVisible(true)
try await until { dormant.history.samples.count > disabledCount }
precondition(dormant.history.samples.last?.breakBefore == true)
dormant.setDisplaySleeping(true)
let darkCount = dormant.history.samples.count
try await Task.sleep(for: .milliseconds(650))
precondition(dormant.history.samples.count == darkCount && dormant.processSnapshot == nil && dormant.energy == nil)
dormantPreferences.backgroundEnabled = true
dormantPreferences.backgroundMilliseconds = 500
try await until { dormant.history.samples.count > darkCount }
precondition(dormant.processSnapshot == nil && dormant.energy == nil,
"Explicit background trends may run with the display off, but process/energy scans must stay stopped")
dormantPreferences.backgroundEnabled = false
dormant.setDisplaySleeping(false)
try await until { dormant.processSnapshot != nil }
dormant.setSystemSleeping(true)
let sleepingCount = dormant.history.samples.count
try await Task.sleep(for: .milliseconds(650))
precondition(dormant.isSystemSleeping && dormant.history.samples.count == sleepingCount && dormant.energy == nil)
dormant.setSystemSleeping(false)
try await until { dormant.history.samples.count > sleepingCount }
precondition(dormant.history.samples.last?.breakBefore == true && dormant.snapshot.cpu == nil)
let staleProbe = DelayedProcessRead(delay: 0.01)
let stale = SystemSampler(processRead: { staleProbe.read(&$0) })
await stale.setProcessVisible(false, revision: 2)
_ = await stale.sample(includeProcesses: true, includeSlowMetrics: false, demandRevision: 1)
try await Task.sleep(for: .milliseconds(100))
precondition(staleProbe.count == 0, "A stale demand must not start any process work")
await stale.setProcessVisible(true, revision: 3)
await stale.setProcessVisible(false, revision: 2)
_ = await stale.sample(includeSlowMetrics: false, demandRevision: 3)
let liveDeadline = ContinuousClock.now.advanced(by: .seconds(2))
while staleProbe.count == 0 && ContinuousClock.now < liveDeadline { try await Task.sleep(for: .milliseconds(20)) }
precondition(staleProbe.count == 1, "A stale stop must not undo the newer visible demand")
await stale.setProcessVisible(false, revision: 4)
dormant.togglePause()
print("PASS: defaults, 100ms quantization/clamping, independent persistence, invalid defaults, active/background wake, pause precedence, slow-interval initial processes and history boundary")
}
@MainActor private static func until(_ predicate: () -> Bool) async throws {
let deadline = ContinuousClock.now.advanced(by: .seconds(4))
while !predicate() && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) }
precondition(predicate(), "Timed out waiting for schedule update")
}
}
private actor ProcessDelivery {
private(set) var value = false
func received() { value = true }
}
private final class DelayedProcessRead: @unchecked Sendable {
private let lock = NSLock()
private let delay: TimeInterval
init(delay: TimeInterval = 0.2) { self.delay = delay }
private var active = 0
private var reads = 0
private var maximum = 0
var count: Int { lock.lock(); defer { lock.unlock() }; return reads }
var peak: Int { lock.lock(); defer { lock.unlock() }; return maximum }
func read(_ monitor: inout ProcessMonitor) -> ProcessSnapshot {
lock.lock(); active += 1; reads += 1; maximum = max(maximum, active); lock.unlock()
defer { lock.lock(); active -= 1; lock.unlock() }
Thread.sleep(forTimeInterval: delay)
return monitor.sample()
}
}
private final class PublicationCount: @unchecked Sendable {
private let lock = NSLock()
private var count = 0
var value: Int { lock.lock(); defer { lock.unlock() }; return count }
func increment() { lock.lock(); count += 1; lock.unlock() }
}