commit 594bf796f14ef34080ae801db9ca25a9be4b1691
parent 414892113f35692ea7cf0f8d79233f6eba52ee76
Author: Michael Camilleri <[email protected]>
Date: Sat, 17 Oct 2026 11:01:20 +0900
Run prompt scheduling one refresh at a time
Changing several settings in quick succession could leave prompts
missing. Each change started its own refresh, and the refreshes ran
concurrently, so one that read the pending notifications after a newer
refresh had added to them would remove the newer prompts as stale.
This commit queues refreshes so each waits for the one before it to
finish. The settings are read when a refresh starts rather than when it
is requested, so the last one always schedules from the latest settings.
Debug builds also list the pending notifications at the bottom of the
Settings tab, soonest first, with each one's kind and fire time, so
what the scheduler has done can be checked on a device.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Reportage/Services/Prompts/PromptScheduler.swift | | | 27 | +++++++++++++++++++++++++-- |
| M | Reportage/Views/Settings/SettingsView.swift | | | 78 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- |
| M | Tests/Unit/PromptSchedulerTests.swift | | | 32 | ++++++++++++++++++++++++++++++++ |
3 files changed, 134 insertions(+), 3 deletions(-)
diff --git a/Reportage/Services/Prompts/PromptScheduler.swift b/Reportage/Services/Prompts/PromptScheduler.swift
@@ -33,9 +33,15 @@ struct PromptScheduler: Sendable {
private static let logger = Logger(subsystem: "net.inqk.reportage", category: "Prompts")
- /// Schedules from the saved settings.
+ /// Schedules from the saved settings, once any refresh already under
+ /// way has finished. Overlapping runs could otherwise remove each
+ /// other's prompts: a run that read the pending list after a newer one
+ /// added to it would delete the newer prompts as stale. The settings are
+ /// read when the run starts, so the last run uses the latest ones.
func refresh() async {
- await reschedule(settings: .load(), secret: PromptSecret.value())
+ await PromptRefreshQueue.shared.run {
+ await reschedule(settings: .load(), secret: PromptSecret.value())
+ }
}
func reschedule(
@@ -63,3 +69,20 @@ struct PromptScheduler: Sendable {
}
}
}
+
+/// Runs refreshes one after another, in the order they were asked for.
+actor PromptRefreshQueue {
+ static let shared = PromptRefreshQueue()
+
+ private var last: Task<Void, Never>?
+
+ func run(_ operation: @escaping @Sendable () async -> Void) async {
+ let previous = last
+ let task = Task {
+ await previous?.value
+ await operation()
+ }
+ last = task
+ await task.value
+ }
+}
diff --git a/Reportage/Views/Settings/SettingsView.swift b/Reportage/Views/Settings/SettingsView.swift
@@ -11,6 +11,9 @@ struct SettingsView: View {
@State private var isExplainingLocation = false
/// Held while iOS asks to upgrade location to 'Always'.
@State private var locationSession: CLServiceSession?
+ /// Counts finished reschedules, so the debug list of pending
+ /// notifications reloads after each.
+ @State private var scheduleGeneration = 0
private static let gaps = [0, 15, 30, 45, 60, 90, 120]
private static let snoozes = [5, 10, 15, 20, 30, 60]
@@ -73,6 +76,9 @@ struct SettingsView: View {
SettingsHeading("Timing")
}
}
+ #if DEBUG
+ ScheduledPrompts(generation: scheduleGeneration)
+ #endif
}
.listStyle(.plain)
.scrollContentBackground(.hidden)
@@ -86,7 +92,10 @@ struct SettingsView: View {
}
.onChange(of: settings) { _, settings in
settings.save()
- Task { await PromptScheduler().refresh() }
+ Task {
+ await PromptScheduler().refresh()
+ scheduleGeneration += 1
+ }
}
.alert("Record Location from Notifications?", isPresented: $isExplainingLocation) {
Button("Continue") { locationSession = LocationAuthorization.requestAlways() }
@@ -241,6 +250,73 @@ extension View {
}
}
+#if DEBUG
+ /// The notifications waiting to be delivered, soonest first, to check
+ /// what the scheduler has done. Debug builds only.
+ private struct ScheduledPrompts: View {
+ let generation: Int
+
+ @State private var pending: [Pending] = []
+
+ private static let shown = 12
+
+ struct Pending: Identifiable {
+ let id: String
+ let date: Date?
+ }
+
+ var body: some View {
+ Section {
+ if pending.isEmpty {
+ SettingsNote { Text(verbatim: "Nothing scheduled.") }
+ }
+ ForEach(pending.prefix(Self.shown)) { item in
+ LabeledContent {
+ if let date = item.date {
+ Text(date, format: .dateTime.weekday(.abbreviated).hour().minute().second())
+ .monospacedDigit()
+ }
+ } label: {
+ Text(verbatim: item.id.split(separator: ".").first.map(String.init) ?? item.id)
+ }
+ .font(.footnote)
+ .settingsRow()
+ }
+ if pending.count > Self.shown {
+ SettingsNote { Text(verbatim: "and \(pending.count - Self.shown) more") }
+ }
+ } header: {
+ HStack {
+ SettingsHeading("Scheduled (\(pending.count))")
+ Button("Reload", systemImage: "arrow.clockwise") {
+ Task { await load() }
+ }
+ .labelStyle(.iconOnly)
+ .font(.footnote)
+ .padding(.trailing, Theme.margin)
+ }
+ .background(Theme.paper)
+ }
+ .task(id: generation) { await load() }
+ }
+
+ private func load() async {
+ let requests = await UNUserNotificationCenter.current().pendingNotificationRequests()
+ pending = requests
+ .map { request in
+ let date =
+ switch request.trigger {
+ case let trigger as UNCalendarNotificationTrigger: trigger.nextTriggerDate()
+ case let trigger as UNTimeIntervalNotificationTrigger: trigger.nextTriggerDate()
+ default: nil as Date?
+ }
+ return Pending(id: request.identifier, date: date)
+ }
+ .sorted { ($0.date ?? .distantFuture) < ($1.date ?? .distantFuture) }
+ }
+ }
+#endif
+
/// A number of minutes, such as '30 min' or '1 hr, 30 min'.
private struct MinutesText: View {
let minutes: Int
diff --git a/Tests/Unit/PromptSchedulerTests.swift b/Tests/Unit/PromptSchedulerTests.swift
@@ -217,3 +217,35 @@ struct PromptResponderTests {
#expect(try await ReportStore(persistence: persistence).passiveCount() == 0)
}
}
+
+@Suite("PromptRefreshQueue")
+struct PromptRefreshQueueTests {
+
+ /// Records when each run starts and ends.
+ private actor Log {
+ var events: [String] = []
+ func record(_ event: String) { events.append(event) }
+ }
+
+ @Test("Runs never overlap, and each waits for the one before")
+ func serial() async {
+ let queue = PromptRefreshQueue()
+ let log = Log()
+ // Started in order, the first taking longest, so overlapping runs
+ // would interleave or finish out of order.
+ await withTaskGroup(of: Void.self) { group in
+ for (index, delay) in [30, 10, 0].enumerated() {
+ group.addTask {
+ await queue.run {
+ await log.record("start \(index)")
+ try? await Task.sleep(for: .milliseconds(delay))
+ await log.record("end \(index)")
+ }
+ }
+ // Lets each run reach the queue before the next is started.
+ try? await Task.sleep(for: .milliseconds(5))
+ }
+ }
+ #expect(await log.events == ["start 0", "end 0", "start 1", "end 1", "start 2", "end 2"])
+ }
+}