From 5257f5521a521eac23a13e9a676ffd86526519c6 Mon Sep 17 00:00:00 2001 From: Ivan Magda Date: Mon, 12 Oct 2026 17:18:10 +0300 Subject: [PATCH] Defer session history loading until monitoring starts --- CLAUDE.md | 3 ++- MiniWatts/Core/PowerMonitor.swift | 8 +++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 5faf621..4e8f35e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -104,7 +104,8 @@ foreground. Three things make that work and they are easy to undo by accident: way to keep the tick alive is the floating meter, which runs through a locked screen. `SessionStore` encodes and writes on its own serial queue, coalescing bursts, and the -load in `PowerMonitor.init` is a `Task`. At the ceiling — 60 sessions × 1,500 samples — +load starts once in `PowerMonitor.start()` as a `Task`, so a background-only Shortcut +does not load unused history. At the ceiling — 60 sessions × 1,500 samples — the file is several megabytes, and doing that inline was a stall before the first frame and again every thirty seconds during a charge. `persist()` is a no-op until `isLoaded`, or a save landing before the load would truncate the history to nothing. diff --git a/MiniWatts/Core/PowerMonitor.swift b/MiniWatts/Core/PowerMonitor.swift index e6553e2..ecb9069 100644 --- a/MiniWatts/Core/PowerMonitor.swift +++ b/MiniWatts/Core/PowerMonitor.swift @@ -114,6 +114,7 @@ final class PowerMonitor { private let store = SessionStore() private var task: Task? + private var hasRequestedStoredSessions = false private var tick = 0 private var lastSampleWrite: Date = .distantPast private var lastPersist: Date = .distantPast @@ -154,7 +155,6 @@ final class PowerMonitor { .flatMap(LiveActivityMetric.init(rawValue:)) ?? .chargingPower sensorServiceCount = probeService.initialServiceCount collectDiagnostics() - Task { await loadStoredSessions() } } /// Reads the session file off the main thread and merges it in. @@ -189,6 +189,12 @@ final class PowerMonitor { func start() { guard task == nil else { return } + // A background Shortcut needs only a fresh reading, not session history. + // Remember the request across pauses, even while the file is still loading. + if !hasRequestedStoredSessions { + hasRequestedStoredSessions = true + Task { await loadStoredSessions() } + } task = Task { [weak self] in while let self, !Task.isCancelled { await self.refresh()