import Foundation import Observation @MainActor @Observable final class MetricsStore { private(set) var snapshot = MetricsSnapshot() private(set) var history = MetricHistory() private(set) var isPaused = false @ObservationIgnored private var task: Task? @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 self?.history.append(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() } }