diff --git a/Loop.xcodeproj/project.pbxproj b/Loop.xcodeproj/project.pbxproj index c3d66500dc..94ea573abf 100644 --- a/Loop.xcodeproj/project.pbxproj +++ b/Loop.xcodeproj/project.pbxproj @@ -450,6 +450,7 @@ A9C62D882331703100535612 /* Service.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9C62D852331703000535612 /* Service.swift */; }; A9C62D892331703100535612 /* LoggingServicesManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9C62D862331703000535612 /* LoggingServicesManager.swift */; }; A9C62D8A2331703100535612 /* ServicesManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9C62D872331703000535612 /* ServicesManager.swift */; }; + AC87CACC45C01E5FC5B62A08 /* RemoteCommandGuard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C633B93FCDD95990EF512A6 /* RemoteCommandGuard.swift */; }; A9C62D8E2331708700535612 /* AuthenticationTableViewCell+NibLoadable.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9C62D8D2331708700535612 /* AuthenticationTableViewCell+NibLoadable.swift */; }; A9CBE458248AB564008E7BA2 /* DoseStore+SimulatedCoreData.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CBE457248AB564008E7BA2 /* DoseStore+SimulatedCoreData.swift */; }; A9CBE45A248ACBE1008E7BA2 /* DosingDecisionStore+SimulatedCoreData.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CBE459248ACBE1008E7BA2 /* DosingDecisionStore+SimulatedCoreData.swift */; }; @@ -548,6 +549,7 @@ C1275E1C2E82269A0013B99D /* LoopKit.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = C1275E1A2E82269A0013B99D /* LoopKit.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; C1275E1F2E822CEE0013B99D /* DerivedAssets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A966152923EA5A37005D8B29 /* DerivedAssets.xcassets */; }; C129BF4A2B2791EE00DF15CB /* TemporaryPresetsManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C129BF492B2791EE00DF15CB /* TemporaryPresetsManagerTests.swift */; }; + D9E8D6887773403C8FD4AD37 /* RemoteCommandGuardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E343B6C171D669C639F11F8B /* RemoteCommandGuardTests.swift */; }; C129D3BF2B8697F100FEA6A9 /* TempBasalRecommendationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C129D3BE2B8697F100FEA6A9 /* TempBasalRecommendationTests.swift */; }; C12D72402E4FBC5F00BD628A /* WatchActionsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12D723F2E4FBC5D00BD628A /* WatchActionsView.swift */; }; D7A3000100000000000A0006 /* WatchSensorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7A3000100000000000A0005 /* WatchSensorView.swift */; }; @@ -1292,6 +1294,7 @@ A9C62D852331703000535612 /* Service.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Service.swift; sourceTree = ""; }; A9C62D862331703000535612 /* LoggingServicesManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LoggingServicesManager.swift; sourceTree = ""; }; A9C62D872331703000535612 /* ServicesManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ServicesManager.swift; sourceTree = ""; }; + 6C633B93FCDD95990EF512A6 /* RemoteCommandGuard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteCommandGuard.swift; sourceTree = ""; }; A9C62D8D2331708700535612 /* AuthenticationTableViewCell+NibLoadable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "AuthenticationTableViewCell+NibLoadable.swift"; sourceTree = ""; }; A9CBE457248AB564008E7BA2 /* DoseStore+SimulatedCoreData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DoseStore+SimulatedCoreData.swift"; sourceTree = ""; }; A9CBE459248ACBE1008E7BA2 /* DosingDecisionStore+SimulatedCoreData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DosingDecisionStore+SimulatedCoreData.swift"; sourceTree = ""; }; @@ -1405,6 +1408,7 @@ C1275E1A2E82269A0013B99D /* LoopKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = LoopKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; C1275E1D2E8227260013B99D /* LoopKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = LoopKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; C129BF492B2791EE00DF15CB /* TemporaryPresetsManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemporaryPresetsManagerTests.swift; sourceTree = ""; }; + E343B6C171D669C639F11F8B /* RemoteCommandGuardTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteCommandGuardTests.swift; sourceTree = ""; }; C129D3BE2B8697F100FEA6A9 /* TempBasalRecommendationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TempBasalRecommendationTests.swift; sourceTree = ""; }; C12CB9AC23106A3C00F84978 /* it */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = it; path = it.lproj/Intents.strings; sourceTree = ""; }; C12CB9AE23106A5C00F84978 /* fr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = fr; path = fr.lproj/Intents.strings; sourceTree = ""; }; @@ -1835,6 +1839,7 @@ 1D70C40026EC0F9D00C62570 /* SupportManagerTests.swift */, A7E1C0B12F8A4D2E00C0FFEE /* AnalyticsServicesManagerTests.swift */, C129BF492B2791EE00DF15CB /* TemporaryPresetsManagerTests.swift */, + E343B6C171D669C639F11F8B /* RemoteCommandGuardTests.swift */, A9F5F1F4251050EC00E7C8A4 /* ZipArchiveTests.swift */, ); path = Managers; @@ -2306,6 +2311,7 @@ 7E69CFFB2A16A77E00203CBD /* ResetLoopManager.swift */, A9C62D852331703000535612 /* Service.swift */, A9C62D872331703000535612 /* ServicesManager.swift */, + 6C633B93FCDD95990EF512A6 /* RemoteCommandGuard.swift */, C1F7822527CC056900C0919A /* SettingsManager.swift */, A96DAC2B2838F31200D94E38 /* SharedLogging.swift */, E9BB27AA23B85C3500FB4987 /* SleepStore.swift */, @@ -3792,6 +3798,7 @@ A96DAC242838325900D94E38 /* DiagnosticLog.swift in Sources */, A9CBE45A248ACBE1008E7BA2 /* DosingDecisionStore+SimulatedCoreData.swift in Sources */, A9C62D8A2331703100535612 /* ServicesManager.swift in Sources */, + AC87CACC45C01E5FC5B62A08 /* RemoteCommandGuard.swift in Sources */, 43DBF0531C93EC8200B3C386 /* DeviceDataManager.swift in Sources */, A9347F2F24E7508A00C99C34 /* WatchHistoricalCarbs.swift in Sources */, C10509792D8B636900118A37 /* Environment+TemporaryPresetsManager.swift in Sources */, @@ -4239,6 +4246,7 @@ A96DAC2A2838EF8A00D94E38 /* DiagnosticLogTests.swift in Sources */, A9DAE7D02332D77F006AE942 /* LoopTests.swift in Sources */, C129BF4A2B2791EE00DF15CB /* TemporaryPresetsManagerTests.swift in Sources */, + D9E8D6887773403C8FD4AD37 /* RemoteCommandGuardTests.swift in Sources */, E93E86B024DDE1BD00FF40C8 /* MockGlucoseStore.swift in Sources */, C18859A82AF292D90010F21F /* MockTrustedTimeChecker.swift in Sources */, C129D3BF2B8697F100FEA6A9 /* TempBasalRecommendationTests.swift in Sources */, diff --git a/Loop/Localizable.xcstrings b/Loop/Localizable.xcstrings index 92601ae0e8..119e214140 100644 --- a/Loop/Localizable.xcstrings +++ b/Loop/Localizable.xcstrings @@ -12,6 +12,27 @@ }, " -" : { + }, + "Bolus may have been delivered. Check the history before sending another bolus." : { + "comment" : "Remote bolus error description: the pump did not confirm whether the bolus was delivered." + }, + "Command rejected: %1$@ U of insulin has not been uploaded to Nightscout yet." : { + "comment" : "Remote bolus error description: insulin not yet uploaded. (1: units of insulin)" + }, + "Command rejected: %1$@ U of insulin was delivered after the command was sent (or after the newest treatment you had seen)." : { + "comment" : "Remote bolus error description: insulin the sender had not seen. (1: units of insulin)" + }, + "Command rejected: %1$d carb entries totaling %2$@ g were recorded that you had not seen." : { + "comment" : "Remote carb error description: several carb entries the sender had not seen. (1: number of entries, 2: total grams of carbs)" + }, + "Command rejected: a carb entry of %1$@ g was recorded that you had not seen." : { + "comment" : "Remote carb error description: one carb entry the sender had not seen. (1: grams of carbs)" + }, + "Command rejected: treatment history is not available." : { + "comment" : "Remote command error description: treatment history could not be checked." + }, + "Loop is not ready to deliver remote commands" : { + "comment" : "Remote command error description: the component that delivers remote boluses and carbs is not available." }, " - " : { diff --git a/Loop/Managers/DeviceDataManager.swift b/Loop/Managers/DeviceDataManager.swift index 4728ea9532..5e4e481496 100644 --- a/Loop/Managers/DeviceDataManager.swift +++ b/Loop/Managers/DeviceDataManager.swift @@ -828,18 +828,27 @@ extension DeviceDataManager { metadata.activationType = activationType let doseId = await newDoseId(for: metadata) + // A remote command reports the pump's error to its sender and sends its own failure notification + let rethrowsErrors = metadata.origin == .remote + do { try await pumpManager.enactBolus(doseId: doseId, units: units, activationType: activationType) } catch PumpManagerError.uncertainDelivery { // Do not generate notification on uncertain delivery error + if rethrowsErrors { + throw PumpManagerError.uncertainDelivery + } } catch { - if !activationType.isAutomatic, let error = error as? PumpManagerError { + if !activationType.isAutomatic, !rethrowsErrors, let error = error as? PumpManagerError { do { try await NotificationManager.sendBolusFailureNotification(for: error, units: units, at: Date(), decisionId: metadata.decisionId, activationType: activationType) } catch { log.error("Error sending bolus failure notification %{public}@", String(describing: error)) } } + if rethrowsErrors { + throw error + } } } diff --git a/Loop/Managers/LoopAppManager.swift b/Loop/Managers/LoopAppManager.swift index 8b12cac3ef..d52aea9af6 100644 --- a/Loop/Managers/LoopAppManager.swift +++ b/Loop/Managers/LoopAppManager.swift @@ -380,6 +380,7 @@ class LoopAppManager: NSObject { servicesManagerDelegate: loopDataManager, servicesManagerDosingDelegate: self ) + servicesManager.remoteCommandGate.treatmentSource = self statefulPluginManager = StatefulPluginManager(pluginManager: pluginManager, servicesManager: servicesManager) @@ -1104,6 +1105,29 @@ extension LoopAppManager: ServicesManagerDosingDelegate { } } +// MARK: - RemoteCommandTreatmentSource + +extension LoopAppManager: RemoteCommandTreatmentSource { + func bolusHistory(since start: Date) async throws -> [DoseEntry] { + try await doseStore.getBoluses(start: start) + } + + var bolusInProgress: DoseEntry? { + guard case .inProgress(let dose) = deviceDataManager?.bolusState else { + return nil + } + return dose + } + + func carbEntries(since start: Date) async throws -> [StoredCarbEntry] { + try await carbStore.getCarbEntries(start: start) + } + + func roundToSupportedBolusVolume(units: Double) -> Double { + deviceDataManager?.pumpManager?.roundToSupportedBolusVolume(units: units) ?? units + } +} + protocol DiagnosticReportGenerator: AnyObject { func generateDiagnosticReport() async -> String } diff --git a/Loop/Managers/RemoteCommandGuard.swift b/Loop/Managers/RemoteCommandGuard.swift new file mode 100644 index 0000000000..2d87bf34f8 --- /dev/null +++ b/Loop/Managers/RemoteCommandGuard.swift @@ -0,0 +1,318 @@ +// +// RemoteCommandGuard.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import Foundation +import LoopKit + +/// Rejects a remote command when insulin or carbs were recorded that its sender had not seen. +/// +/// A treatment is unknown to the sender when it is dated after the command was sent (carbs: and not after now), +/// when it was last edited after the command was sent or after the newest treatment the sender had fetched, +/// or, when the context lists the treatments the sender had seen and the treatment was created after the +/// service started recording uploads, when it is not among them. +struct RemoteCommandGuard { + + struct Treatment: Equatable { + var syncIdentifier: String? + var date: Date + /// Units for insulin, grams for carbs + var amount: Double + /// When the user created the entry, when known + var createdDate: Date? = nil + /// When the user last edited the entry; an edited entry keeps its Nightscout `_id` + var updatedDate: Date? = nil + } + + enum Kind { + case insulin + case carbs + } + + enum UnknownReason: Equatable { + case recordedAfterSend + case notSeen + case notUploaded + } + + /// How far back treatments are considered + static let lookbackInterval = TimeInterval(hours: 6) + + /// A bolus is rejected when unknown insulin is at least this fraction of the requested amount + static let unknownInsulinFraction = 0.2 + + /// Tolerance for comparing insulin amounts + static let insulinTolerance = 1e-6 + + let context: RemoteCommandContext + let now: Date + + func unknownReason(for treatment: Treatment, kind: Kind) -> UnknownReason? { + guard treatment.date >= now.addingTimeInterval(-Self.lookbackInterval) else { + return nil + } + if isAfterSend(treatment.date, kind: kind) || treatment.updatedDate.map({ $0 > editCutoff }) == true { + return .recordedAfterSend + } + if let known = context.knownTreatments, (treatment.createdDate ?? treatment.date) > known.recordedSince { + guard let syncIdentifier = treatment.syncIdentifier, known.uploadedSyncIdentifiers.contains(syncIdentifier) else { + return .notUploaded + } + if !known.syncIdentifiers.contains(syncIdentifier) { + return .notSeen + } + } + return nil + } + + /// Insulin dated after now counts, as the pump clock can be ahead; future-dated carbs are judged by the marker rule only + private func isAfterSend(_ date: Date, kind: Kind) -> Bool { + switch kind { + case .insulin: + return date > context.sentAt + case .carbs: + return date > context.sentAt && date <= now + } + } + + /// The send time, or the marker's time when it is earlier + private var editCutoff: Date { + guard let markerDate = context.knownTreatments?.markerDate else { + return context.sentAt + } + return min(context.sentAt, markerDate) + } + + func checkBolus(amountInUnits: Double, boluses: [Treatment]) throws { + let unknown = boluses.compactMap { bolus in unknownReason(for: bolus, kind: .insulin).map { (bolus, $0) } } + let unknownUnits = unknown.reduce(0) { $0 + $1.0.amount } + guard unknownUnits > 0, unknownUnits + Self.insulinTolerance >= amountInUnits * Self.unknownInsulinFraction else { + return + } + if unknown.allSatisfy({ $0.1 == .notUploaded }) { + throw RemoteCommandGuardError.insulinNotUploaded(units: unknownUnits) + } else { + throw RemoteCommandGuardError.unknownInsulin(units: unknownUnits) + } + } + + func checkCarbs(carbEntries: [Treatment]) throws { + let unknownGrams = carbEntries.filter { unknownReason(for: $0, kind: .carbs) != nil }.map { $0.amount } + if !unknownGrams.isEmpty { + throw RemoteCommandGuardError.unknownCarbs(grams: unknownGrams) + } + } + + /// Boluses whose start dates and programmed amounts are within these tolerances are the same bolus; Trio uses the same values + static let sameBolusDateTolerance = TimeInterval(10) + static let sameBolusUnitsTolerance = 0.025 + + /// A pump manager's bolus in progress can carry a different syncIdentifier, or none, than the stored entry for the same bolus + static func isSameBolus(_ a: DoseEntry, _ b: DoseEntry) -> Bool { + if let syncIdentifier = a.syncIdentifier, syncIdentifier == b.syncIdentifier { + return true + } + return abs(a.startDate.timeIntervalSince(b.startDate)) <= sameBolusDateTolerance + && abs(a.programmedUnits - b.programmedUnits) <= sameBolusUnitsTolerance + insulinTolerance + } + + /// Boluses from the dose history plus the pump's bolus in progress, when the history does not yet hold it + static func bolusCandidates(history: [DoseEntry], inProgress: DoseEntry?) -> [DoseEntry] { + var candidates = history + if let inProgress, !history.contains(where: { isSameBolus($0, inProgress) }) { + candidates.append(inProgress) + } + return candidates + } +} + +enum RemoteCommandGuardError: RemoteCommandRejection, Equatable { + case unknownInsulin(units: Double) + case insulinNotUploaded(units: Double) + case unknownCarbs(grams: [Double]) + case historyUnavailable + + var errorDescription: String? { + switch self { + case .unknownInsulin(let units): + return String(format: NSLocalizedString("Command rejected: %1$@ U of insulin was delivered after the command was sent (or after the newest treatment you had seen).", comment: "Remote bolus error description: insulin the sender had not seen. (1: units of insulin)"), Self.format(units, scale: 2)) + case .insulinNotUploaded(let units): + return String(format: NSLocalizedString("Command rejected: %1$@ U of insulin has not been uploaded to Nightscout yet.", comment: "Remote bolus error description: insulin not yet uploaded. (1: units of insulin)"), Self.format(units, scale: 2)) + case .unknownCarbs(let grams): + if grams.count == 1 { + return String(format: NSLocalizedString("Command rejected: a carb entry of %1$@ g was recorded that you had not seen.", comment: "Remote carb error description: one carb entry the sender had not seen. (1: grams of carbs)"), Self.format(grams[0], scale: 0)) + } else { + return String(format: NSLocalizedString("Command rejected: %1$d carb entries totaling %2$@ g were recorded that you had not seen.", comment: "Remote carb error description: several carb entries the sender had not seen. (1: number of entries, 2: total grams of carbs)"), grams.count, Self.format(grams.reduce(0, +), scale: 0)) + } + case .historyUnavailable: + return NSLocalizedString("Command rejected: treatment history is not available.", comment: "Remote command error description: treatment history could not be checked.") + } + } + + var replyText: String { + switch self { + case .unknownInsulin(let units): + return "Command rejected: \(Self.format(units, scale: 2)) U of insulin was delivered after the command was sent (or after the newest treatment you had seen)." + case .insulinNotUploaded(let units): + return "Command rejected: \(Self.format(units, scale: 2)) U of insulin has not been uploaded to Nightscout yet." + case .unknownCarbs(let grams): + if grams.count == 1 { + return "Command rejected: a carb entry of \(Self.format(grams[0], scale: 0)) g was recorded that you had not seen." + } else { + return "Command rejected: \(grams.count) carb entries totaling \(Self.format(grams.reduce(0, +), scale: 0)) g were recorded that you had not seen." + } + case .historyUnavailable: + return "Command rejected: treatment history is not available." + } + } + + /// `value` rounded half up to `scale` decimals from its shortest decimal representation, printed with "." and without trailing zeros, as Trio prints it + static func format(_ value: Double, scale: Int) -> String { + var input = Decimal(string: "\(value)", locale: Locale(identifier: "en_US_POSIX")) ?? Decimal(value) + var rounded = Decimal() + NSDecimalRound(&rounded, &input, scale, .plain) + return NSDecimalNumber(decimal: rounded).description(withLocale: Locale(identifier: "en_US_POSIX")) + } +} + +enum RemoteBolusDeliveryError: RemoteCommandRejection, Equatable { + case uncertainDelivery + + var errorDescription: String? { + switch self { + case .uncertainDelivery: + return NSLocalizedString("Bolus may have been delivered. Check the history before sending another bolus.", comment: "Remote bolus error description: the pump did not confirm whether the bolus was delivered.") + } + } + + var replyText: String { + switch self { + case .uncertainDelivery: + return "Bolus may have been delivered. Check the history before sending another bolus." + } + } +} + +extension RemoteCommandGuard.Treatment { + /// Uses programmed units while the bolus is in progress or has no delivered amount + init(bolus: DoseEntry) { + let units = bolus.isMutable ? bolus.programmedUnits : (bolus.deliveredUnits ?? bolus.programmedUnits) + self.init(syncIdentifier: bolus.syncIdentifier, date: bolus.startDate, amount: units) + } + + init(carbEntry: StoredCarbEntry) { + self.init( + syncIdentifier: carbEntry.syncIdentifier, + date: carbEntry.startDate, + amount: carbEntry.quantity.doubleValue(for: .gram), + createdDate: carbEntry.userCreatedDate, + updatedDate: carbEntry.userUpdatedDate + ) + } +} + +@MainActor +protocol RemoteCommandTreatmentSource: AnyObject { + func bolusHistory(since start: Date) async throws -> [DoseEntry] + var bolusInProgress: DoseEntry? { get } + func carbEntries(since start: Date) async throws -> [StoredCarbEntry] + /// The amount the pump delivers for a requested bolus + func roundToSupportedBolusVolume(units: Double) -> Double +} + +/// Runs remote bolus and carb commands one at a time, each checked by `RemoteCommandGuard` before delivery. +@MainActor +final class RemoteCommandGate { + + /// How long an accepted remote bolus is counted while it is missing from the dose history + static let acceptedBolusRetention = TimeInterval(minutes: 15) + + weak var treatmentSource: RemoteCommandTreatmentSource? + + private let now: () -> Date + + private var lastCommand: Task? + + /// The most recent remote bolus accepted, until the dose history or the pump shows it, or for `acceptedBolusRetention` + private(set) var acceptedRemoteBolus: DoseEntry? + + init(now: @escaping () -> Date = { Date() }) { + self.now = now + } + + func deliverBolus(amountInUnits: Double, context: RemoteCommandContext?, deliver: @escaping @MainActor () async throws -> Void) async throws { + try await serially { + if let context { + try await self.checkBolus(amountInUnits: amountInUnits, context: context) + } + let units = self.treatmentSource?.roundToSupportedBolusVolume(units: amountInUnits) ?? amountInUnits + let accepted = DoseEntry(type: .bolus, startDate: self.now(), value: units, unit: .units, isMutable: true) + do { + try await deliver() + } catch PumpManagerError.uncertainDelivery { + // The bolus may have been delivered, so later commands count it + self.acceptedRemoteBolus = accepted + throw RemoteBolusDeliveryError.uncertainDelivery + } + self.acceptedRemoteBolus = accepted + } + } + + func deliverCarbs(context: RemoteCommandContext?, deliver: @escaping @MainActor () async throws -> Void) async throws { + try await serially { + if let context { + try await self.checkCarbs(context: context) + } + try await deliver() + } + } + + private func checkBolus(amountInUnits: Double, context: RemoteCommandContext) async throws { + guard let treatmentSource else { + throw RemoteCommandGuardError.historyUnavailable + } + let now = now() + let history = try await treatmentSource.bolusHistory(since: now.addingTimeInterval(-RemoteCommandGuard.lookbackInterval)) + var candidates = RemoteCommandGuard.bolusCandidates(history: history, inProgress: treatmentSource.bolusInProgress) + if let accepted = acceptedRemoteBolus { + if now.timeIntervalSince(accepted.startDate) > Self.acceptedBolusRetention + || candidates.contains(where: { Self.shows($0, accepted: accepted) }) + { + acceptedRemoteBolus = nil + } else { + candidates.append(accepted) + } + } + try RemoteCommandGuard(context: context, now: now).checkBolus(amountInUnits: amountInUnits, boluses: candidates.map { RemoteCommandGuard.Treatment(bolus: $0) }) + } + + /// A bolus shows the accepted one when it is not automatic, starts at most `sameBolusDateTolerance` before it, + /// and has the same programmed units within `sameBolusUnitsTolerance`; Trio uses the same rule + static func shows(_ bolus: DoseEntry, accepted: DoseEntry) -> Bool { + bolus.automatic != true + && bolus.startDate >= accepted.startDate.addingTimeInterval(-RemoteCommandGuard.sameBolusDateTolerance) + && abs(bolus.programmedUnits - accepted.programmedUnits) <= RemoteCommandGuard.sameBolusUnitsTolerance + RemoteCommandGuard.insulinTolerance + } + + private func checkCarbs(context: RemoteCommandContext) async throws { + guard let treatmentSource else { + throw RemoteCommandGuardError.historyUnavailable + } + let now = now() + let entries = try await treatmentSource.carbEntries(since: now.addingTimeInterval(-RemoteCommandGuard.lookbackInterval)) + try RemoteCommandGuard(context: context, now: now).checkCarbs(carbEntries: entries.map { RemoteCommandGuard.Treatment(carbEntry: $0) }) + } + + private func serially(_ operation: @escaping @MainActor () async throws -> Void) async throws { + let previous = lastCommand + let task = Task { @MainActor in + await previous?.value + try await operation() + } + lastCommand = Task { _ = try? await task.value } + try await task.value + } +} diff --git a/Loop/Managers/ServicesManager.swift b/Loop/Managers/ServicesManager.swift index 847d170052..6d06b21459 100644 --- a/Loop/Managers/ServicesManager.swift +++ b/Loop/Managers/ServicesManager.swift @@ -35,6 +35,8 @@ class ServicesManager { private let servicesLock = UnfairLock() + let remoteCommandGate = RemoteCommandGate() + private let log = OSLog(category: "ServicesManager") lazy private var cancellables = Set() @@ -325,8 +327,17 @@ extension ServicesManager: ServiceDelegate { } func deliverRemoteCarbs(amountInGrams: Double, absorptionTime: TimeInterval?, foodType: String?, startDate: Date?) async throws { + try await deliverRemoteCarbs(amountInGrams: amountInGrams, absorptionTime: absorptionTime, foodType: foodType, startDate: startDate, context: nil) + } + + func deliverRemoteCarbs(amountInGrams: Double, absorptionTime: TimeInterval?, foodType: String?, startDate: Date?, context: RemoteCommandContext?) async throws { do { - try await servicesManagerDelegate?.deliverCarbs(amountInGrams: amountInGrams, absorptionTime: absorptionTime, foodType: foodType, startDate: startDate) + try await remoteCommandGate.deliverCarbs(context: context) { [weak self] in + guard let delegate = self?.servicesManagerDelegate else { + throw RemoteDeliveryError.unavailable + } + try await delegate.deliverCarbs(amountInGrams: amountInGrams, absorptionTime: absorptionTime, foodType: foodType, startDate: startDate) + } NotificationManager.sendRemoteCarbEntryNotification(amountInGrams: amountInGrams) await remoteDataServicesManager.performUpload(for: .carb) analyticsServicesManager.didAddCarbs(source: "Remote") @@ -341,6 +352,10 @@ extension ServicesManager: ServiceDelegate { } func deliverRemoteBolus(amountInUnits: Double, decisionId: UUID?, request: DoseMetadata.RemoteRequest?) async throws { + try await deliverRemoteBolus(amountInUnits: amountInUnits, decisionId: decisionId, request: request, context: nil) + } + + func deliverRemoteBolus(amountInUnits: Double, decisionId: UUID?, request: DoseMetadata.RemoteRequest?, context: RemoteCommandContext?) async throws { do { guard amountInUnits > 0 else { @@ -355,7 +370,12 @@ extension ServicesManager: ServiceDelegate { throw BolusActionError.exceedsMaxBolus } - try await servicesManagerDosingDelegate?.deliverBolus(amountInUnits: amountInUnits, decisionId: decisionId, request: request) + try await remoteCommandGate.deliverBolus(amountInUnits: amountInUnits, context: context) { [weak self] in + guard let dosingDelegate = self?.servicesManagerDosingDelegate else { + throw RemoteDeliveryError.unavailable + } + try await dosingDelegate.deliverBolus(amountInUnits: amountInUnits, decisionId: decisionId, request: request) + } NotificationManager.sendRemoteBolusNotification(amount: amountInUnits) await remoteDataServicesManager.performUpload(for: .dose) analyticsServicesManager.didBolus(source: "Remote") @@ -365,6 +385,18 @@ extension ServicesManager: ServiceDelegate { } } + enum RemoteDeliveryError: LocalizedError { + + case unavailable + + var errorDescription: String? { + switch self { + case .unavailable: + return NSLocalizedString("Loop is not ready to deliver remote commands", comment: "Remote command error description: the component that delivers remote boluses and carbs is not available.") + } + } + } + enum BolusActionError: LocalizedError { case invalidBolus diff --git a/LoopTests/Managers/DeviceDataManagerTests.swift b/LoopTests/Managers/DeviceDataManagerTests.swift index 1dbba29dfd..ec1c9bf8d8 100644 --- a/LoopTests/Managers/DeviceDataManagerTests.swift +++ b/LoopTests/Managers/DeviceDataManagerTests.swift @@ -118,6 +118,31 @@ final class DeviceDataManagerTests: XCTestCase { XCTAssertEqual(metadata, DoseMetadata(origin: .user, device: .watch, decisionId: decisionId, activationType: .manualRecommendationAccepted)) } + func testEnactBolusRethrowsPumpErrorsForRemoteOrigin() async throws { + pumpManager.enactBolusError = .uncertainDelivery + do { + try await deviceDataManager.enactBolus(units: 1, metadata: DoseMetadata(origin: .remote), activationType: .manualNoRecommendation) + XCTFail("Expected the pump error") + } catch PumpManagerError.uncertainDelivery { + } + + pumpManager.enactBolusError = .deviceState(nil) + do { + try await deviceDataManager.enactBolus(units: 1, metadata: DoseMetadata(origin: .remote), activationType: .manualNoRecommendation) + XCTFail("Expected the pump error") + } catch PumpManagerError.deviceState { + } + pumpManager.enactBolusError = nil + } + + func testEnactBolusDoesNotThrowPumpErrorsForOtherOrigins() async throws { + pumpManager.enactBolusError = .uncertainDelivery + try await deviceDataManager.enactBolus(units: 1, metadata: DoseMetadata(origin: .user), activationType: .manualRecommendationAccepted) + pumpManager.enactBolusError = .deviceState(nil) + try await deviceDataManager.enactBolus(units: 1, metadata: DoseMetadata(origin: .user), activationType: .manualRecommendationAccepted) + pumpManager.enactBolusError = nil + } + func testAutomaticDosesStoreMetadataWithTheDecision() async throws { let decisionId = UUID() pumpManager.enactedDoseIds = [] diff --git a/LoopTests/Managers/RemoteCommandGuardTests.swift b/LoopTests/Managers/RemoteCommandGuardTests.swift new file mode 100644 index 0000000000..6c12083e95 --- /dev/null +++ b/LoopTests/Managers/RemoteCommandGuardTests.swift @@ -0,0 +1,589 @@ +// +// RemoteCommandGuardTests.swift +// LoopTests +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import XCTest +import LoopKit + +@testable import Loop + +class RemoteCommandGuardTests: XCTestCase { + + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + private var sentAt: Date { now.addingTimeInterval(.minutes(-5)) } + + private func treatment(_ syncIdentifier: String?, minutesAgo: Double, amount: Double) -> RemoteCommandGuard.Treatment { + RemoteCommandGuard.Treatment(syncIdentifier: syncIdentifier, date: now.addingTimeInterval(.minutes(-minutesAgo)), amount: amount) + } + + /// `known` were seen by the sender; `uploaded` adds treatments uploaded after the marker, whose time is `markerDate` or the send time + private func commandGuard(known: Set?, uploaded: Set = [], recordedSince: Date? = nil, sentAt: Date? = nil, markerDate: Date? = nil) -> RemoteCommandGuard { + let sentAt = sentAt ?? self.sentAt + let knownTreatments = known.map { + RemoteCommandContext.KnownTreatments( + syncIdentifiers: $0, + uploadedSyncIdentifiers: $0.union(uploaded), + recordedSince: recordedSince ?? now.addingTimeInterval(.hours(-24)), + markerDate: markerDate ?? sentAt + ) + } + return RemoteCommandGuard(context: RemoteCommandContext(sentAt: sentAt, knownTreatments: knownTreatments), now: now) + } + + // MARK: Bolus + + func testBolus_UnknownInsulinBelowFraction_Accepted() { + let boluses = [ + treatment("known", minutesAgo: 30, amount: 3), + treatment("unknown", minutesAgo: 20, amount: 0.3) + ] + XCTAssertNoThrow(try commandGuard(known: ["known"], uploaded: ["unknown"]).checkBolus(amountInUnits: 2, boluses: boluses)) + } + + func testBolus_UnknownInsulinAtFraction_Rejected() { + let boluses = [treatment("unknown", minutesAgo: 20, amount: 0.4)] + XCTAssertThrowsError(try commandGuard(known: [], uploaded: ["unknown"]).checkBolus(amountInUnits: 2, boluses: boluses)) { error in + XCTAssertEqual(error as? RemoteCommandGuardError, .unknownInsulin(units: 0.4)) + } + } + + func testBolus_ThresholdWithoutFloatingPointError_Rejected() { + // 3 * 0.2 is 0.6000000000000001 in binary floating point + let boluses = [treatment("unknown", minutesAgo: 20, amount: 0.6)] + XCTAssertThrowsError(try commandGuard(known: [], uploaded: ["unknown"]).checkBolus(amountInUnits: 3, boluses: boluses)) + } + + func testBolus_UnknownInsulinSummedAboveFraction_Rejected() { + let boluses = [ + treatment("smb1", minutesAgo: 15, amount: 0.2), + treatment("smb2", minutesAgo: 10, amount: 0.25), + treatment("known", minutesAgo: 60, amount: 4) + ] + XCTAssertThrowsError(try commandGuard(known: ["known"], uploaded: ["smb1", "smb2"]).checkBolus(amountInUnits: 2, boluses: boluses)) + } + + func testBolus_InProgressBolusCountsProgrammedUnits() { + let inProgress = DoseEntry(type: .bolus, startDate: now.addingTimeInterval(.minutes(-1)), value: 2, unit: .units, deliveredUnits: nil, syncIdentifier: "in-progress", isMutable: true) + let candidate = RemoteCommandGuard.Treatment(bolus: inProgress) + XCTAssertEqual(candidate.amount, 2) + XCTAssertThrowsError(try commandGuard(known: nil).checkBolus(amountInUnits: 2, boluses: [candidate])) + } + + func testBolus_FinalizedBolusCountsDeliveredUnits() { + let interrupted = DoseEntry(type: .bolus, startDate: now.addingTimeInterval(.minutes(-30)), value: 2, unit: .units, deliveredUnits: 0.5, syncIdentifier: "interrupted") + XCTAssertEqual(RemoteCommandGuard.Treatment(bolus: interrupted).amount, 0.5) + } + + func testBolusCandidates_IncludePumpBolusInProgressOnce() { + let history = [DoseEntry(type: .bolus, startDate: now.addingTimeInterval(.minutes(-60)), value: 1, unit: .units, deliveredUnits: 1, syncIdentifier: "old")] + let inProgress = DoseEntry(type: .bolus, startDate: now.addingTimeInterval(.minutes(-1)), value: 2, unit: .units, syncIdentifier: "pump", isMutable: true) + + XCTAssertEqual(RemoteCommandGuard.bolusCandidates(history: history, inProgress: inProgress).count, 2) + XCTAssertEqual(RemoteCommandGuard.bolusCandidates(history: history + [inProgress], inProgress: inProgress).count, 2) + } + + func testBolusCandidates_InProgressWithOtherIdentifierCountedOnce() { + // MockPumpManager reports its bolus in progress without a syncIdentifier; the stored entry has one + let startDate = now.addingTimeInterval(.minutes(-1)) + let stored = DoseEntry(type: .bolus, startDate: startDate, value: 2, unit: .units, syncIdentifier: "stored", isMutable: true) + let unidentified = DoseEntry(type: .bolus, startDate: startDate.addingTimeInterval(1), value: 2, unit: .units, isMutable: true) + let otherIdentifier = DoseEntry(type: .bolus, startDate: startDate, value: 2, unit: .units, syncIdentifier: "pump", isMutable: true) + let otherBolus = DoseEntry(type: .bolus, startDate: startDate.addingTimeInterval(1), value: 1, unit: .units, isMutable: true) + + XCTAssertEqual(RemoteCommandGuard.bolusCandidates(history: [stored], inProgress: unidentified).count, 1) + XCTAssertEqual(RemoteCommandGuard.bolusCandidates(history: [stored], inProgress: otherIdentifier).count, 1) + XCTAssertEqual(RemoteCommandGuard.bolusCandidates(history: [stored], inProgress: otherBolus).count, 2) + } + + func testIsSameBolus_ToleranceEdges() { + let startDate = now.addingTimeInterval(.minutes(-1)) + func bolus(secondsLater: TimeInterval, units: Double, syncIdentifier: String? = nil) -> DoseEntry { + DoseEntry(type: .bolus, startDate: startDate.addingTimeInterval(secondsLater), value: units, unit: .units, syncIdentifier: syncIdentifier, isMutable: true) + } + let reference = bolus(secondsLater: 0, units: 0.3) + + XCTAssertTrue(RemoteCommandGuard.isSameBolus(reference, bolus(secondsLater: 10, units: 0.3))) + XCTAssertTrue(RemoteCommandGuard.isSameBolus(reference, bolus(secondsLater: -10, units: 0.3))) + XCTAssertFalse(RemoteCommandGuard.isSameBolus(reference, bolus(secondsLater: 10.5, units: 0.3))) + + // 0.325 - 0.3 is slightly above 0.025 in binary floating point + XCTAssertTrue(RemoteCommandGuard.isSameBolus(reference, bolus(secondsLater: 0, units: 0.325))) + XCTAssertTrue(RemoteCommandGuard.isSameBolus(reference, bolus(secondsLater: 0, units: 0.275))) + XCTAssertFalse(RemoteCommandGuard.isSameBolus(reference, bolus(secondsLater: 0, units: 0.35))) + XCTAssertFalse(RemoteCommandGuard.isSameBolus(reference, bolus(secondsLater: 10.5, units: 0.325))) + + let identified = bolus(secondsLater: 0, units: 0.3, syncIdentifier: "same") + XCTAssertTrue(RemoteCommandGuard.isSameBolus(identified, bolus(secondsLater: 60, units: 1, syncIdentifier: "same"))) + XCTAssertFalse(RemoteCommandGuard.isSameBolus(identified, bolus(secondsLater: 60, units: 1, syncIdentifier: "other"))) + } + + func testBolus_DatedAfterNow_Rejected() { + // The pump clock is ahead of the phone + let boluses = [treatment("pump-ahead", minutesAgo: -3, amount: 2)] + XCTAssertThrowsError(try commandGuard(known: nil).checkBolus(amountInUnits: 2, boluses: boluses)) { error in + XCTAssertEqual(error as? RemoteCommandGuardError, .unknownInsulin(units: 2)) + } + XCTAssertThrowsError(try commandGuard(known: ["pump-ahead"]).checkBolus(amountInUnits: 2, boluses: boluses)) + + let beforeSend = [treatment("before-send", minutesAgo: 10, amount: 2)] + XCTAssertNoThrow(try commandGuard(known: nil).checkBolus(amountInUnits: 2, boluses: beforeSend)) + } + + func testBolus_BolusOlderThanLookback_Ignored() { + let boluses = [treatment("old", minutesAgo: 6 * 60 + 1, amount: 5)] + XCTAssertNoThrow(try commandGuard(known: []).checkBolus(amountInUnits: 1, boluses: boluses)) + } + + func testBolus_OnlyMissingNightscoutIds_NotUploadedMessage() { + let boluses = [treatment("not-uploaded", minutesAgo: 20, amount: 1)] + XCTAssertThrowsError(try commandGuard(known: []).checkBolus(amountInUnits: 2, boluses: boluses)) { error in + XCTAssertEqual(error as? RemoteCommandGuardError, .insulinNotUploaded(units: 1)) + } + } + + func testBolus_MixedReasons_UnknownInsulinMessage() { + let boluses = [ + treatment("not-uploaded", minutesAgo: 20, amount: 0.5), + treatment("after-marker", minutesAgo: 15, amount: 0.5) + ] + XCTAssertThrowsError(try commandGuard(known: [], uploaded: ["after-marker"]).checkBolus(amountInUnits: 2, boluses: boluses)) { error in + XCTAssertEqual(error as? RemoteCommandGuardError, .unknownInsulin(units: 1)) + } + } + + // MARK: Carbs + + func testCarbs_AllKnown_Accepted() { + let entries = [treatment("a", minutesAgo: 90, amount: 40), treatment("b", minutesAgo: 30, amount: 10)] + XCTAssertNoThrow(try commandGuard(known: ["a", "b"]).checkCarbs(carbEntries: entries)) + } + + func testCarbs_BackdatedEntryUploadedAfterMarker_Rejected() { + // Dated before the send time, but its Nightscout _id is newer than the marker + let entries = [treatment("backdated", minutesAgo: 60, amount: 20)] + XCTAssertThrowsError(try commandGuard(known: [], uploaded: ["backdated"]).checkCarbs(carbEntries: entries)) { error in + XCTAssertEqual(error as? RemoteCommandGuardError, .unknownCarbs(grams: [20])) + } + } + + func testCarbs_FutureDatedKnownEntry_Accepted() { + let entries = [treatment("future", minutesAgo: -30, amount: 15)] + XCTAssertNoThrow(try commandGuard(known: ["future"]).checkCarbs(carbEntries: entries)) + } + + func testCarbs_FutureDatedUnknownEntry_Rejected() { + let entries = [treatment("future", minutesAgo: -30, amount: 15)] + XCTAssertThrowsError(try commandGuard(known: [], uploaded: ["future"]).checkCarbs(carbEntries: entries)) + } + + func testCarbs_EntryWithoutNightscoutId_Rejected() { + // Not uploaded, or uploaded without an _id ("NA"): not in the uploaded set + let entries = [treatment("not-uploaded", minutesAgo: 30, amount: 10)] + XCTAssertThrowsError(try commandGuard(known: ["other"]).checkCarbs(carbEntries: entries)) + } + + func testCarbs_EntryWithoutSyncIdentifier_RejectedWhenMarkerPresent() { + let entries = [treatment(nil, minutesAgo: 30, amount: 10)] + XCTAssertThrowsError(try commandGuard(known: []).checkCarbs(carbEntries: entries)) + XCTAssertNoThrow(try commandGuard(known: nil).checkCarbs(carbEntries: entries)) + } + + func testEditedCarbEntry_UpdatedAfterSend_Rejected() { + // Dated and seen before the send time; the edit keeps its Nightscout _id + var edited = treatment("edited", minutesAgo: 40, amount: 30) + edited.updatedDate = now.addingTimeInterval(.minutes(-2)) + XCTAssertThrowsError(try commandGuard(known: ["edited"]).checkCarbs(carbEntries: [edited])) { error in + XCTAssertEqual(error as? RemoteCommandGuardError, .unknownCarbs(grams: [30])) + } + XCTAssertThrowsError(try commandGuard(known: nil).checkCarbs(carbEntries: [edited])) + + edited.updatedDate = now.addingTimeInterval(.minutes(-10)) + XCTAssertNoThrow(try commandGuard(known: ["edited"]).checkCarbs(carbEntries: [edited])) + } + + func testEditedCarbEntry_EditedAfterMarkerBeforeSend_Rejected() { + let markerDate = now.addingTimeInterval(.minutes(-20)) + var edited = treatment("edited", minutesAgo: 40, amount: 30) + edited.updatedDate = now.addingTimeInterval(.minutes(-10)) + XCTAssertThrowsError(try commandGuard(known: ["edited"], markerDate: markerDate).checkCarbs(carbEntries: [edited])) { error in + XCTAssertEqual(error as? RemoteCommandGuardError, .unknownCarbs(grams: [30])) + } + // Without a marker only edits after the send time count + XCTAssertNoThrow(try commandGuard(known: nil).checkCarbs(carbEntries: [edited])) + + edited.updatedDate = now.addingTimeInterval(.minutes(-25)) + XCTAssertNoThrow(try commandGuard(known: ["edited"], markerDate: markerDate).checkCarbs(carbEntries: [edited])) + + // A marker after the send time leaves the send time as the limit + edited.updatedDate = now.addingTimeInterval(.minutes(-4)) + XCTAssertThrowsError(try commandGuard(known: ["edited"], markerDate: now.addingTimeInterval(.minutes(-1))).checkCarbs(carbEntries: [edited])) + } + + func testMarkerRule_JudgesByCreationDate() { + let recordedSince = now.addingTimeInterval(.minutes(-60)) + + // Future-dated entry created before recording started, never uploaded with an _id + var createdBefore = treatment("future", minutesAgo: -60, amount: 30) + createdBefore.createdDate = now.addingTimeInterval(.minutes(-90)) + XCTAssertNoThrow(try commandGuard(known: [], recordedSince: recordedSince).checkCarbs(carbEntries: [createdBefore])) + + var createdAfter = createdBefore + createdAfter.createdDate = now.addingTimeInterval(.minutes(-30)) + XCTAssertThrowsError(try commandGuard(known: [], recordedSince: recordedSince).checkCarbs(carbEntries: [createdAfter])) + + // Backdated entry created after recording started + var backdated = treatment("backdated", minutesAgo: 90, amount: 20) + backdated.createdDate = now.addingTimeInterval(.minutes(-30)) + XCTAssertThrowsError(try commandGuard(known: [], recordedSince: recordedSince).checkCarbs(carbEntries: [backdated])) + } + + func testMarkerRule_SkippedForEntriesDatedBeforeRecordingStarted() { + let entries = [treatment("before-recording", minutesAgo: 90, amount: 30)] + let recordedSince = now.addingTimeInterval(.minutes(-60)) + XCTAssertNoThrow(try commandGuard(known: [], recordedSince: recordedSince).checkCarbs(carbEntries: entries)) + + let laterEntries = [treatment("after-recording", minutesAgo: 30, amount: 30)] + XCTAssertThrowsError(try commandGuard(known: [], recordedSince: recordedSince).checkCarbs(carbEntries: laterEntries)) + } + + // MARK: Without a marker + + func testNoMarker_SendTimeRuleOnly() { + let carbs = [treatment("before", minutesAgo: 10, amount: 30)] + XCTAssertNoThrow(try commandGuard(known: nil).checkCarbs(carbEntries: carbs)) + + let laterCarbs = [treatment("after", minutesAgo: 2, amount: 30)] + XCTAssertThrowsError(try commandGuard(known: nil).checkCarbs(carbEntries: laterCarbs)) + + let futureCarbs = [treatment("future", minutesAgo: -30, amount: 30)] + XCTAssertNoThrow(try commandGuard(known: nil).checkCarbs(carbEntries: futureCarbs)) + + let laterBolus = [treatment("after", minutesAgo: 2, amount: 1)] + XCTAssertThrowsError(try commandGuard(known: nil).checkBolus(amountInUnits: 2, boluses: laterBolus)) + } + + func testInvalidMarker_TreatedAsAbsent() { + // NightscoutService passes no known treatments for an invalid marker + let entries = [treatment("not-uploaded", minutesAgo: 30, amount: 10)] + XCTAssertNoThrow(try commandGuard(known: nil).checkCarbs(carbEntries: entries)) + } + + func testMarkerOlderThanSendTime_EntryBetweenMarkerAndSendTime_Rejected() { + // The sender's last fetch was before an entry that is still dated before the send time + let entries = [ + treatment("seen", minutesAgo: 40, amount: 20), + treatment("recorded-after-fetch", minutesAgo: 8, amount: 15) + ] + XCTAssertThrowsError(try commandGuard(known: ["seen"], uploaded: ["recorded-after-fetch"]).checkCarbs(carbEntries: entries)) { error in + XCTAssertEqual(error as? RemoteCommandGuardError, .unknownCarbs(grams: [15])) + } + } + + func testTwoCaregivers_SecondCommandRejected() { + // Caregiver A's 2 U bolus was delivered after caregiver B sent the same command + let firstBolusDate = now.addingTimeInterval(.minutes(-1)) + let boluses = [RemoteCommandGuard.Treatment(syncIdentifier: "caregiver-a", date: firstBolusDate, amount: 2)] + let guardB = commandGuard(known: ["older"], uploaded: ["caregiver-a"], sentAt: now.addingTimeInterval(.minutes(-3))) + XCTAssertThrowsError(try guardB.checkBolus(amountInUnits: 2, boluses: boluses)) + + // Caregiver B sends again after seeing the bolus in Nightscout + let guardBAgain = commandGuard(known: ["older", "caregiver-a"], sentAt: now) + XCTAssertNoThrow(try guardBAgain.checkBolus(amountInUnits: 2, boluses: boluses)) + } + + // MARK: Messages + + func testErrorMessages() { + XCTAssertEqual(RemoteCommandGuardError.unknownInsulin(units: 0.4).replyText, "Command rejected: 0.4 U of insulin was delivered after the command was sent (or after the newest treatment you had seen).") + XCTAssertEqual(RemoteCommandGuardError.unknownInsulin(units: 1.2345).replyText, "Command rejected: 1.23 U of insulin was delivered after the command was sent (or after the newest treatment you had seen).") + XCTAssertEqual(RemoteCommandGuardError.unknownInsulin(units: 0.125).replyText, "Command rejected: 0.13 U of insulin was delivered after the command was sent (or after the newest treatment you had seen).") + XCTAssertEqual(RemoteCommandGuardError.unknownCarbs(grams: [12.5]).replyText, "Command rejected: a carb entry of 13 g was recorded that you had not seen.") + XCTAssertEqual(RemoteCommandGuardError.insulinNotUploaded(units: 1.5).replyText, "Command rejected: 1.5 U of insulin has not been uploaded to Nightscout yet.") + XCTAssertEqual(RemoteCommandGuardError.unknownCarbs(grams: [20]).replyText, "Command rejected: a carb entry of 20 g was recorded that you had not seen.") + XCTAssertEqual(RemoteCommandGuardError.unknownCarbs(grams: [20.4, 15]).replyText, "Command rejected: 2 carb entries totaling 35 g were recorded that you had not seen.") + XCTAssertEqual(RemoteBolusDeliveryError.uncertainDelivery.replyText, "Bolus may have been delivered. Check the history before sending another bolus.") + } + + func testFormat_RoundsHalfUpFromDecimalRepresentation() { + XCTAssertEqual(RemoteCommandGuardError.format(1.005, scale: 2), "1.01") + XCTAssertEqual(RemoteCommandGuardError.format(2.675, scale: 2), "2.68") + XCTAssertEqual(RemoteCommandGuardError.format(0.1 + 0.2, scale: 2), "0.3") + XCTAssertEqual(RemoteCommandGuardError.format(2, scale: 2), "2") + XCTAssertEqual(RemoteCommandGuardError.format(0.004, scale: 2), "0") + XCTAssertEqual(RemoteCommandGuardError.format(12.5, scale: 0), "13") + XCTAssertEqual(RemoteCommandGuardError.format(1234.5, scale: 0), "1235") + XCTAssertEqual(RemoteCommandGuardError.unknownInsulin(units: 1.005).replyText, "Command rejected: 1.01 U of insulin was delivered after the command was sent (or after the newest treatment you had seen).") + } + + func testDescriptionMatchesReplyInDevelopmentLanguage() { + let errors: [RemoteCommandRejection] = [ + RemoteCommandGuardError.unknownInsulin(units: 1.005), + RemoteCommandGuardError.insulinNotUploaded(units: 1.5), + RemoteCommandGuardError.unknownCarbs(grams: [20]), + RemoteCommandGuardError.unknownCarbs(grams: [20.4, 15]), + RemoteCommandGuardError.historyUnavailable, + RemoteBolusDeliveryError.uncertainDelivery + ] + for error in errors { + XCTAssertEqual(error.errorDescription, error.replyText) + } + } + + func testRepliesAreRejections() { + XCTAssertTrue(RemoteCommandGuardError.unknownInsulin(units: 1) as Error is RemoteCommandRejection) + XCTAssertTrue(RemoteBolusDeliveryError.uncertainDelivery as Error is RemoteCommandRejection) + } +} + +@MainActor +class RemoteCommandGateTests: XCTestCase { + + private final class MockTreatmentSource: RemoteCommandTreatmentSource { + var boluses: [DoseEntry] = [] + var bolusInProgress: DoseEntry? + var carbs: [StoredCarbEntry] = [] + var bolusIncrement: Double? + + func bolusHistory(since start: Date) async throws -> [DoseEntry] { boluses } + func carbEntries(since start: Date) async throws -> [StoredCarbEntry] { carbs } + func roundToSupportedBolusVolume(units: Double) -> Double { + guard let bolusIncrement else { return units } + return (units / bolusIncrement).rounded() * bolusIncrement + } + } + + private final class Counter { + var count = 0 + } + + private var source: MockTreatmentSource! + private var gate: RemoteCommandGate! + + override func setUp() async throws { + source = MockTreatmentSource() + gate = RemoteCommandGate() + gate.treatmentSource = source + } + + private func context(sentAt: Date) -> RemoteCommandContext { + RemoteCommandContext(sentAt: sentAt) + } + + func testConcurrentBoluses_SecondRejected() async throws { + let sentAt = Date().addingTimeInterval(-60) + let deliveries = Counter() + let deliver: @MainActor () async throws -> Void = { + try await Task.sleep(nanoseconds: 50_000_000) + deliveries.count += 1 + } + + async let first: Void = gate.deliverBolus(amountInUnits: 2, context: context(sentAt: sentAt), deliver: deliver) + async let second: Void = gate.deliverBolus(amountInUnits: 2, context: context(sentAt: sentAt), deliver: deliver) + var errors: [Error] = [] + do { try await first } catch { errors.append(error) } + do { try await second } catch { errors.append(error) } + + XCTAssertEqual(deliveries.count, 1) + XCTAssertEqual(errors.compactMap { $0 as? RemoteCommandGuardError }, [.unknownInsulin(units: 2)]) + } + + func testAcceptedBolus_DroppedOnceInHistory() async throws { + try await gate.deliverBolus(amountInUnits: 2, context: context(sentAt: Date().addingTimeInterval(-60))) {} + XCTAssertNotNil(gate.acceptedRemoteBolus) + + source.boluses = [DoseEntry(type: .bolus, startDate: Date(), value: 2, unit: .units, deliveredUnits: 2, syncIdentifier: "remote")] + try await gate.deliverBolus(amountInUnits: 1, context: context(sentAt: Date().addingTimeInterval(1))) {} + XCTAssertEqual(gate.acceptedRemoteBolus?.programmedUnits, 1) + } + + func testPumpBolusInProgress_Rejects() async throws { + source.bolusInProgress = DoseEntry(type: .bolus, startDate: Date().addingTimeInterval(-10), value: 3, unit: .units, syncIdentifier: "pump", isMutable: true) + var delivered = false + do { + try await gate.deliverBolus(amountInUnits: 2, context: context(sentAt: Date().addingTimeInterval(-60))) { delivered = true } + XCTFail("Expected rejection") + } catch { + XCTAssertEqual(error as? RemoteCommandGuardError, .unknownInsulin(units: 3)) + } + XCTAssertFalse(delivered) + } + + func testAcceptedBolusAndInProgressBolus_CountedOnce() async throws { + let sentAt = Date().addingTimeInterval(-60) + try await gate.deliverBolus(amountInUnits: 1, context: context(sentAt: sentAt)) {} + let acceptedAt = try XCTUnwrap(gate.acceptedRemoteBolus?.startDate) + + // The pump dates the bolus slightly before acceptance, stores it, and reports it in progress without a syncIdentifier + source.boluses = [DoseEntry(type: .bolus, startDate: acceptedAt.addingTimeInterval(-2), value: 1, unit: .units, syncIdentifier: "stored", isMutable: true)] + source.bolusInProgress = DoseEntry(type: .bolus, startDate: acceptedAt.addingTimeInterval(-2), value: 1, unit: .units, isMutable: true) + + // 1 U counted once is below 20 % of 6 U; counted twice or three times it would reject + try await gate.deliverBolus(amountInUnits: 6, context: context(sentAt: sentAt)) {} + } + + func testNoTreatmentSource_Rejects() async throws { + gate.treatmentSource = nil + var delivered = false + do { + try await gate.deliverCarbs(context: context(sentAt: Date())) { delivered = true } + XCTFail("Expected rejection") + } catch { + XCTAssertEqual(error as? RemoteCommandGuardError, .historyUnavailable) + } + do { + try await gate.deliverBolus(amountInUnits: 1, context: context(sentAt: Date())) { delivered = true } + XCTFail("Expected rejection") + } catch { + XCTAssertEqual(error as? RemoteCommandGuardError, .historyUnavailable) + } + XCTAssertFalse(delivered) + } + + func testFailedDelivery_NotHeldAsAccepted() async throws { + struct DeliveryError: Error {} + do { + try await gate.deliverBolus(amountInUnits: 2, context: context(sentAt: Date())) { throw DeliveryError() } + } catch {} + XCTAssertNil(gate.acceptedRemoteBolus) + } + + func testUncertainDelivery_HeldAsAcceptedAndReported() async throws { + do { + try await gate.deliverBolus(amountInUnits: 2, context: context(sentAt: Date())) { throw PumpManagerError.uncertainDelivery } + XCTFail("Expected the delivery error") + } catch RemoteBolusDeliveryError.uncertainDelivery { + } + XCTAssertEqual(gate.acceptedRemoteBolus?.programmedUnits, 2) + } + + private final class Clock { + var now = Date() + } + + func testAcceptedBolus_CountedUntilRetentionExpires() async throws { + let clock = Clock() + gate = RemoteCommandGate(now: { clock.now }) + gate.treatmentSource = source + let acceptedAt = clock.now + let sentAt = acceptedAt.addingTimeInterval(-60) + try await gate.deliverBolus(amountInUnits: 2, context: context(sentAt: sentAt)) {} + + clock.now = acceptedAt.addingTimeInterval(RemoteCommandGate.acceptedBolusRetention) + do { + try await gate.deliverBolus(amountInUnits: 2, context: context(sentAt: sentAt)) {} + XCTFail("Expected rejection") + } catch { + XCTAssertEqual(error as? RemoteCommandGuardError, .unknownInsulin(units: 2)) + } + XCTAssertNotNil(gate.acceptedRemoteBolus) + + clock.now = acceptedAt.addingTimeInterval(RemoteCommandGate.acceptedBolusRetention + 1) + try await gate.deliverBolus(amountInUnits: 1, context: context(sentAt: clock.now)) {} + XCTAssertEqual(gate.acceptedRemoteBolus?.programmedUnits, 1) + XCTAssertEqual(gate.acceptedRemoteBolus?.startDate, clock.now) + } + + func testAcceptedBolus_KeptWhenHistoryShowsOnlyAnUnrelatedLaterBolus() async throws { + let clock = Clock() + gate = RemoteCommandGate(now: { clock.now }) + gate.treatmentSource = source + let acceptedAt = clock.now + let sentAt = acceptedAt.addingTimeInterval(-60) + do { + try await gate.deliverBolus(amountInUnits: 2, context: context(sentAt: sentAt)) { throw PumpManagerError.uncertainDelivery } + } catch RemoteBolusDeliveryError.uncertainDelivery { + } + XCTAssertNotNil(gate.acceptedRemoteBolus) + + // An automatic bolus after the accepted one, with a different amount + source.boluses = [DoseEntry(type: .bolus, startDate: acceptedAt.addingTimeInterval(.minutes(3)), value: 0.3, unit: .units, deliveredUnits: 0.3, syncIdentifier: "smb", automatic: true)] + clock.now = acceptedAt.addingTimeInterval(.minutes(5)) + + do { + try await gate.deliverBolus(amountInUnits: 2, context: context(sentAt: sentAt)) {} + XCTFail("Expected rejection") + } catch { + XCTAssertEqual(error as? RemoteCommandGuardError, .unknownInsulin(units: 2.3)) + } + XCTAssertEqual(gate.acceptedRemoteBolus?.programmedUnits, 2) + } + + func testShows_LaterBolusWithSameUnits() { + let acceptedAt = Date() + let accepted = DoseEntry(type: .bolus, startDate: acceptedAt, value: 2, unit: .units, isMutable: true) + func bolus(secondsLater: TimeInterval, units: Double) -> DoseEntry { + DoseEntry(type: .bolus, startDate: acceptedAt.addingTimeInterval(secondsLater), value: units, unit: .units, deliveredUnits: units, syncIdentifier: "stored") + } + + XCTAssertTrue(RemoteCommandGate.shows(bolus(secondsLater: 30, units: 2), accepted: accepted)) + XCTAssertTrue(RemoteCommandGate.shows(bolus(secondsLater: 30, units: 2.025), accepted: accepted)) + XCTAssertTrue(RemoteCommandGate.shows(bolus(secondsLater: 30, units: 1.975), accepted: accepted)) + XCTAssertFalse(RemoteCommandGate.shows(bolus(secondsLater: 30, units: 2.03), accepted: accepted)) + XCTAssertTrue(RemoteCommandGate.shows(bolus(secondsLater: -5, units: 2), accepted: accepted)) + XCTAssertTrue(RemoteCommandGate.shows(bolus(secondsLater: -10, units: 2), accepted: accepted)) + XCTAssertFalse(RemoteCommandGate.shows(bolus(secondsLater: -11, units: 2), accepted: accepted)) + XCTAssertFalse(RemoteCommandGate.shows(bolus(secondsLater: 30, units: 0.3), accepted: accepted)) + XCTAssertFalse(RemoteCommandGate.shows(bolus(secondsLater: -60, units: 2), accepted: accepted)) + } + + func testShows_IgnoresAutomaticBolus() { + let acceptedAt = Date() + let accepted = DoseEntry(type: .bolus, startDate: acceptedAt, value: 0.5, unit: .units, isMutable: true) + let automatic = DoseEntry(type: .bolus, startDate: acceptedAt.addingTimeInterval(60), value: 0.5, unit: .units, deliveredUnits: 0.5, syncIdentifier: "smb", automatic: true) + let manual = DoseEntry(type: .bolus, startDate: acceptedAt.addingTimeInterval(60), value: 0.5, unit: .units, deliveredUnits: 0.5, syncIdentifier: "manual", automatic: false) + XCTAssertFalse(RemoteCommandGate.shows(automatic, accepted: accepted)) + XCTAssertTrue(RemoteCommandGate.shows(manual, accepted: accepted)) + } + + func testAcceptedBolus_KeptWhenOnlyAnAutomaticBolusMatches() async throws { + let clock = Clock() + gate = RemoteCommandGate(now: { clock.now }) + gate.treatmentSource = source + let acceptedAt = clock.now + let sentAt = acceptedAt.addingTimeInterval(-60) + try await gate.deliverBolus(amountInUnits: 0.5, context: context(sentAt: sentAt)) {} + + source.boluses = [DoseEntry(type: .bolus, startDate: acceptedAt.addingTimeInterval(.minutes(3)), value: 0.5, unit: .units, deliveredUnits: 0.5, syncIdentifier: "smb", automatic: true)] + clock.now = acceptedAt.addingTimeInterval(.minutes(5)) + + // 0.5 U automatic alone is below 20 % of 4 U; with the accepted 0.5 U it is not + do { + try await gate.deliverBolus(amountInUnits: 4, context: context(sentAt: sentAt)) {} + XCTFail("Expected rejection") + } catch { + XCTAssertEqual(error as? RemoteCommandGuardError, .unknownInsulin(units: 1)) + } + XCTAssertEqual(gate.acceptedRemoteBolus?.programmedUnits, 0.5) + } + + func testAcceptedBolus_DroppedWhenPumpShowsItInProgress() async throws { + let clock = Clock() + gate = RemoteCommandGate(now: { clock.now }) + gate.treatmentSource = source + let acceptedAt = clock.now + let sentAt = acceptedAt.addingTimeInterval(-60) + try await gate.deliverBolus(amountInUnits: 2, context: context(sentAt: sentAt)) {} + + source.bolusInProgress = DoseEntry(type: .bolus, startDate: acceptedAt.addingTimeInterval(-3), value: 2.02, unit: .units, isMutable: true) + clock.now = acceptedAt.addingTimeInterval(30) + + // 2.02 U in progress alone is below 20 % of 15 U; with the accepted 2 U it is not + try await gate.deliverBolus(amountInUnits: 15, context: context(sentAt: sentAt)) {} + XCTAssertEqual(gate.acceptedRemoteBolus?.programmedUnits, 15) + } + + func testAcceptedBolus_HeldAtPumpRoundedAmount() async throws { + source.bolusIncrement = 0.05 + try await gate.deliverBolus(amountInUnits: 1.03, context: context(sentAt: Date().addingTimeInterval(-60))) {} + XCTAssertEqual(try XCTUnwrap(gate.acceptedRemoteBolus?.programmedUnits), 1.05, accuracy: 1e-9) + + // The pump records the rounded amount, which shows the accepted bolus + let acceptedAt = try XCTUnwrap(gate.acceptedRemoteBolus?.startDate) + source.boluses = [DoseEntry(type: .bolus, startDate: acceptedAt, value: 1.05, unit: .units, deliveredUnits: 1.05, syncIdentifier: "stored")] + XCTAssertTrue(RemoteCommandGate.shows(source.boluses[0], accepted: try XCTUnwrap(gate.acceptedRemoteBolus))) + } +} diff --git a/LoopTests/Mocks/MockPumpManager.swift b/LoopTests/Mocks/MockPumpManager.swift index 2f62593be5..cccadb6dcd 100644 --- a/LoopTests/Mocks/MockPumpManager.swift +++ b/LoopTests/Mocks/MockPumpManager.swift @@ -23,6 +23,8 @@ class MockPumpManager: PumpManager { var enactTempBasalError: PumpManagerError? + var enactBolusError: PumpManagerError? + init() { } @@ -87,7 +89,7 @@ class MockPumpManager: PumpManager { func enactBolus(doseId: UUID, units: Double, activationType: BolusActivationType, completion: @escaping (PumpManagerError?) -> Void) { enactedDoseIds.append(doseId) enactBolusCalled?(units, activationType) - completion(nil) + completion(enactBolusError) } func cancelBolus(completion: @escaping (PumpManagerResult) -> Void) {