From 3d1d1cc4502e3604cabef0276e0945a414721bfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Bj=C3=B6rkert?= Date: Sun, 22 Nov 2026 21:55:49 +0100 Subject: [PATCH 1/2] Check a profile save only in the schedules it changes and flag profiles outside the limits A remote save of an existing profile is checked against the shared limits only in the schedules it changes, as Loop and Trio check it, so one schedule that no longer fits does not keep the others from being corrected. Profiles that no longer fit the limits are marked in the list, the profile screen says why the app will not activate them, and the activation confirmation says when the active profile can't be activated again. --- .../Remote/Profiles/ProfileEditorSheet.swift | 9 ++- .../Remote/Profiles/ProfileReviewView.swift | 2 +- .../Remote/Profiles/ProfileValidation.swift | 57 ++++++++++++++----- .../Remote/Profiles/ProfileValuesEditor.swift | 7 ++- .../Remote/Profiles/TherapyProfilesView.swift | 34 +++++++++++ Tests/ProfileValidationTests.swift | 24 +++++++- 6 files changed, 112 insertions(+), 21 deletions(-) diff --git a/LoopFollow/Remote/Profiles/ProfileEditorSheet.swift b/LoopFollow/Remote/Profiles/ProfileEditorSheet.swift index b4deffa01..11fb8d7c1 100644 --- a/LoopFollow/Remote/Profiles/ProfileEditorSheet.swift +++ b/LoopFollow/Remote/Profiles/ProfileEditorSheet.swift @@ -91,9 +91,14 @@ struct ProfileEditorSheet: View { ?? ProfileValidation.nameProblem(name, existingNames: profileSet.profiles.map(\.name)) } + /// The schedules the draft changes; every schedule for a new profile. + private var changedSchedules: Set { + isNew ? Set(ProfileScheduleKind.allCases) : ProfileValidation.changedSchedules(from: source.values, to: draft.values, singleTarget: remote.hasSingleTarget) + } + private var problems: [String] { guard let limits = editableLimits else { return [] } - return ProfileValidation.problems(draft.values, limits: limits) + return ProfileValidation.problems(draft.values, limits: limits, schedules: changedSchedules) } private var hasChanges: Bool { @@ -150,7 +155,7 @@ struct ProfileEditorSheet: View { } ForEach(ProfileScheduleKind.allCases) { kind in - ProfileValuesEditor(kind: kind, segments: Binding(get: { draft[kind] }, set: { draft[kind] = $0 }), units: draft.units, limits: editableLimits, singleTarget: remote.hasSingleTarget) + ProfileValuesEditor(kind: kind, segments: Binding(get: { draft[kind] }, set: { draft[kind] = $0 }), units: draft.units, limits: editableLimits, singleTarget: remote.hasSingleTarget, isUnchanged: !changedSchedules.contains(kind)) } if !problems.isEmpty { diff --git a/LoopFollow/Remote/Profiles/ProfileReviewView.swift b/LoopFollow/Remote/Profiles/ProfileReviewView.swift index 6114e5d15..736552e4b 100644 --- a/LoopFollow/Remote/Profiles/ProfileReviewView.swift +++ b/LoopFollow/Remote/Profiles/ProfileReviewView.swift @@ -80,7 +80,7 @@ struct ProfileReviewView: View { private var problems: [String] { guard let limits else { return ["Profiles can not be changed without the limits from \(remote.appName)."] } - return ProfileValidation.problems(for: command, limits: limits) + return ProfileValidation.problems(for: command, limits: limits, singleTarget: remote.hasSingleTarget) } private static func computePushSize(_ command: ProfileCommand, remote: ProfileRemote) -> Int? { diff --git a/LoopFollow/Remote/Profiles/ProfileValidation.swift b/LoopFollow/Remote/Profiles/ProfileValidation.swift index a5b2630b0..bd5b05cc3 100644 --- a/LoopFollow/Remote/Profiles/ProfileValidation.swift +++ b/LoopFollow/Remote/Profiles/ProfileValidation.swift @@ -128,41 +128,68 @@ enum ProfileValidation { return nil } - /// Everything that keeps `values` from being sent within `limits`. Empty when the profile can be sent. - static func problems(_ values: TherapyProfileValues, limits: ProfileEditLimits) -> [String] { + /// Everything that keeps the `schedules` of `values` from being sent within `limits`. Empty when they can be sent. + static func problems( + _ values: TherapyProfileValues, + limits: ProfileEditLimits, + schedules: Set = Set(ProfileScheduleKind.allCases) + ) -> [String] { var problems: [String] = [] if values.units != limits.normalizedUnits { problems.append("The profile is in \(values.units), but the limits are in \(limits.normalizedUnits).") } - let schedules: [(ProfileScheduleKind, [Int])] = [ + let starts: [(ProfileScheduleKind, [Int])] = [ (.correctionRange, values.target.map(\.seconds)), (.carbRatio, values.carbRatio.map(\.seconds)), (.basal, values.basal.map(\.seconds)), (.sensitivity, values.sensitivity.map(\.seconds)), ] - for (kind, starts) in schedules { + for (kind, starts) in starts where schedules.contains(kind) { problems += scheduleProblems(starts, kind: kind, limits: limits) } - for (kind, items) in [(ProfileScheduleKind.carbRatio, values.carbRatio), (.basal, values.basal), (.sensitivity, values.sensitivity)] { + for (kind, items) in [(ProfileScheduleKind.carbRatio, values.carbRatio), (.basal, values.basal), (.sensitivity, values.sensitivity)] where schedules.contains(kind) { if items.contains(where: { limits.status(of: $0.value, in: kind) == .notAllowed }) { problems.append("\(kind.title): a value is outside what is allowed. \(limits.boundsText(for: kind))") } } - if values.target.contains(where: { limits.status(of: $0.low, in: .correctionRange) == .notAllowed || limits.status(of: $0.high, in: .correctionRange) == .notAllowed }) { - problems.append("Correction Range: a value is outside what is allowed. \(limits.boundsText(for: .correctionRange))") - } - if values.target.contains(where: { $0.low > $0.high + ProfileEditLimits.tolerance }) { - problems.append("Correction Range: the low value must not be above the high value.") + if schedules.contains(.correctionRange) { + if values.target.contains(where: { limits.status(of: $0.low, in: .correctionRange) == .notAllowed || limits.status(of: $0.high, in: .correctionRange) == .notAllowed }) { + problems.append("Correction Range: a value is outside what is allowed. \(limits.boundsText(for: .correctionRange))") + } + if values.target.contains(where: { $0.low > $0.high + ProfileEditLimits.tolerance }) { + problems.append("Correction Range: the low value must not be above the high value.") + } } return problems } - /// Everything that keeps `command` from being sent within `limits`. A save that keeps the values of the - /// profile it updates (a pure rename) is not checked against the limits, which may have changed since the - /// values were stored. - static func problems(for command: ProfileCommand, limits: ProfileEditLimits) -> [String] { + /// The schedules of `values` that differ from `original`. With `singleTarget`, a correction range also counts as + /// unchanged when it matches `original` with each high value set to its low value, as the editor shows it. + static func changedSchedules(from original: TherapyProfileValues, to values: TherapyProfileValues, singleTarget: Bool = false) -> Set { + var changed = Set() + if values.basal != original.basal { changed.insert(.basal) } + if values.carbRatio != original.carbRatio { changed.insert(.carbRatio) } + if values.sensitivity != original.sensitivity { changed.insert(.sensitivity) } + let editorTarget = ProfileDraft(original, singleTarget: singleTarget).values.target + if values.target != original.target, values.target != editorTarget { changed.insert(.correctionRange) } + return changed + } + + /// Everything that keeps `command` from being sent within `limits`. A save of an existing profile is checked only + /// in the schedules it changes, as Loop and Trio check it, so a schedule that no longer fits the limits does not + /// keep the others from being corrected. A pure rename is not checked against the limits. + static func problems(for command: ProfileCommand, limits: ProfileEditLimits, singleTarget: Bool = false) -> [String] { guard case let .save(_, original, values) = command else { return [] } - if let original, original.values == values { return [] } + guard let original else { return problems(values, limits: limits) } + let changed = changedSchedules(from: original.values, to: values, singleTarget: singleTarget) + if changed.isEmpty { return [] } + return problems(values, limits: limits, schedules: changed) + } + + /// Why Loop or Trio would refuse to activate `values` under `limits`, or empty when nothing in the limits stands in + /// the way. Empty when the profile and the limits are in different units, since they can't be compared. + static func activationProblems(_ values: TherapyProfileValues, limits: ProfileEditLimits?) -> [String] { + guard let limits, values.units == limits.normalizedUnits else { return [] } return problems(values, limits: limits) } diff --git a/LoopFollow/Remote/Profiles/ProfileValuesEditor.swift b/LoopFollow/Remote/Profiles/ProfileValuesEditor.swift index 727b0e1f7..ab0f1b682 100644 --- a/LoopFollow/Remote/Profiles/ProfileValuesEditor.swift +++ b/LoopFollow/Remote/Profiles/ProfileValuesEditor.swift @@ -67,6 +67,9 @@ struct ProfileValuesEditor: View { let limits: ProfileEditLimits? /// One target value per time, for Trio. var singleTarget = false + /// True while the schedule keeps the values of the stored profile, which may be saved unchanged although they + /// no longer fit the limits. + var isUnchanged = false private var isRange: Bool { kind.isRange && !singleTarget } @@ -121,7 +124,9 @@ struct ProfileValuesEditor: View { } switch status { case .notAllowed: - Text("Outside what is allowed. Change this value before sending.") + Text(isUnchanged + ? "Outside what is allowed now. The profile can't be activated until this value is changed." + : "Outside what is allowed. Change this value before sending.") .font(.caption) .foregroundColor(.red) case .outsideRecommended: diff --git a/LoopFollow/Remote/Profiles/TherapyProfilesView.swift b/LoopFollow/Remote/Profiles/TherapyProfilesView.swift index 892dcee0d..ac2fecc64 100644 --- a/LoopFollow/Remote/Profiles/TherapyProfilesView.swift +++ b/LoopFollow/Remote/Profiles/TherapyProfilesView.swift @@ -57,6 +57,11 @@ struct TherapyProfilesView: View { HStack { Text(profile.name) Spacer() + if !ProfileValidation.activationProblems(profile.values, limits: profileSet.limits).isEmpty { + Text("Outside Limits") + .font(.caption) + .foregroundColor(.orange) + } if profileSet.isActive(profile) { Text("Active") .font(.caption) @@ -187,6 +192,20 @@ struct TherapyProfilePreviewView: View { return increases.isEmpty ? nil : (active, increases) } + /// Why the app would refuse to activate this profile under the limits it shared. + private var activationProblems: [String] { + guard let profile else { return [] } + return ProfileValidation.activationProblems(profile.values, limits: profileSet?.limits) + } + + /// The note for the activation confirmation when the active profile itself no longer fits the limits. + private var switchBackText: String? { + guard !isActive, let active = profileSet?.activeProfile, + !ProfileValidation.activationProblems(active.values, limits: profileSet?.limits).isEmpty + else { return nil } + return "\(active.name) no longer fits the limits \(remote.appName) shared, so it can't be activated again until it is edited." + } + private var activateKey: String { remote.key(.activate, name: name) } private var deleteKey: String { remote.key(.delete, name: name) } @@ -241,6 +260,20 @@ struct TherapyProfilePreviewView: View { List { Section(footer: Text("\(remote.appName) writes the basal rates to the pump when the profile is activated.")) { Text(isActive ? "This is the active profile. \(remote.appName) doses insulin with these values." : "Review the profile before activating it in \(remote.appName).") + if !activationProblems.isEmpty { + VStack(alignment: .leading, spacing: 4) { + Label(isActive + ? "This profile no longer fits the limits \(remote.appName) shared. It stays active, but once another profile is activated it can't be activated again until it is edited." + : "\(remote.appName) will not activate this profile until it is edited to fit the limits it shared.", + systemImage: "exclamationmark.triangle") + .foregroundColor(.orange) + ForEach(activationProblems, id: \.self) { problem in + Text(problem) + .font(.footnote) + .foregroundColor(.secondary) + } + } + } if let activationIncreases { MoreInsulinWarning( increases: activationIncreases.increases, @@ -336,6 +369,7 @@ struct TherapyProfilePreviewView: View { title: Text("Activate \(name) in \(remote.appName)?"), message: Text("\(remote.appName) replaces its correction range, carb ratios, basal rates and insulin sensitivities with these values and writes the basal rates to the pump. Dosing changes right away." + (profileSet.flatMap { ScheduledSwitches.holdText($0.scheduledSwitches) }.map { " " + $0 } ?? "") + + (switchBackText.map { " " + $0 } ?? "") + MoreInsulinWarning.sentence(activationIncreases?.increases ?? [], comparedWith: activationIncreases?.active.name ?? "")), primaryButton: .default(Text("Activate")) { send(.activate, fingerprint: fingerprint) }, secondaryButton: .cancel() diff --git a/Tests/ProfileValidationTests.swift b/Tests/ProfileValidationTests.swift index ea9858bc4..40b790fb9 100644 --- a/Tests/ProfileValidationTests.swift +++ b/Tests/ProfileValidationTests.swift @@ -94,7 +94,7 @@ struct ProfileValidationTests { #expect(ProfileValidation.problems(values(basal: basal), limits: limits).count == 1) } - @Test("a pure rename is not checked against today's limits, a changed save is") + @Test("a save of an existing profile is checked only in the schedules it changes") func renameSkipsValueChecks() throws { let limits = try ProfileEditLimitsTests.limits() let json = """ @@ -112,9 +112,29 @@ struct ProfileValidationTests { var draft = ProfileDraft(stored.values) draft.carbRatio[0].value = 12 - #expect(ProfileValidation.problems(for: .save(name: "Old Sport", original: stored, values: draft.values), limits: limits).count == 2) + #expect(ProfileValidation.problems(for: .save(name: "Old Sport", original: stored, values: draft.values), limits: limits).isEmpty) + draft.carbRatio[0].value = 151 + #expect(ProfileValidation.problems(for: .save(name: "Old Sport", original: stored, values: draft.values), limits: limits).count == 1) + draft.carbRatio[0].value = 12 + draft.basal[0].value = 0.15 + #expect(ProfileValidation.problems(for: .save(name: "Old Sport", original: stored, values: draft.values), limits: limits).isEmpty) + draft.basal[0].value = 3.05 + #expect(ProfileValidation.problems(for: .save(name: "Old Sport", original: stored, values: draft.values), limits: limits).count == 1) #expect(ProfileValidation.problems(for: .save(name: "Copy", original: nil, values: stored.values), limits: limits).count == 2) #expect(ProfileValidation.problems(for: .activate(stored), limits: limits).isEmpty) + #expect(ProfileValidation.activationProblems(stored.values, limits: limits).count == 2) + #expect(ProfileValidation.activationProblems(draft.values, limits: nil).isEmpty) + } + + @Test("changed schedules are found per schedule, and a single-target range shown as low-only is unchanged") + func changedSchedules() { + let original = values(target: [(0, 100, 110)]) + #expect(ProfileValidation.changedSchedules(from: original, to: original).isEmpty) + #expect(ProfileValidation.changedSchedules(from: original, to: values(basal: [(0, 0.85)], target: [(0, 100, 110)])) == [.basal]) + #expect(ProfileValidation.changedSchedules(from: original, to: values(sens: [(0, 55)], target: [(0, 100, 110)])) == [.sensitivity]) + #expect(ProfileValidation.changedSchedules(from: original, to: values(target: [(0, 100, 100)])) == [.correctionRange]) + #expect(ProfileValidation.changedSchedules(from: original, to: values(target: [(0, 100, 100)]), singleTarget: true).isEmpty) + #expect(ProfileValidation.changedSchedules(from: original, to: values(target: [(0, 105, 105)]), singleTarget: true) == [.correctionRange]) } @Test("new segments go one step after the last, or into the first free slot") From 955330d0e2c5905fd65c5d882e0d0eda709aefaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Bj=C3=B6rkert?= Date: Sun, 22 Nov 2026 22:04:36 +0100 Subject: [PATCH 2/2] Judge activation only against usable limits and say when unchanged schedules stay outside them Profiles are flagged only when the shared limits are usable, the profile was read completely and both are in the same units. A schedule grid of zero seconds gives no segments. The review notes when the schedules a save leaves alone stay outside the limits, the activation confirmation says when the target is outside them, and the wording follows whether the profile can be edited from LoopFollow. --- .../Remote/Profiles/ProfileEditLimits.swift | 2 +- .../Remote/Profiles/ProfileEditorSheet.swift | 2 +- .../Remote/Profiles/ProfileReviewView.swift | 4 ++ .../Remote/Profiles/ProfileValidation.swift | 23 +++++-- .../Remote/Profiles/ProfileValuesEditor.swift | 10 ++- .../Remote/Profiles/TherapyProfilesView.swift | 24 ++++--- Tests/ProfileValidationTests.swift | 68 ++++++++++++++++++- 7 files changed, 110 insertions(+), 23 deletions(-) diff --git a/LoopFollow/Remote/Profiles/ProfileEditLimits.swift b/LoopFollow/Remote/Profiles/ProfileEditLimits.swift index b440a19b7..f3ff02f70 100644 --- a/LoopFollow/Remote/Profiles/ProfileEditLimits.swift +++ b/LoopFollow/Remote/Profiles/ProfileEditLimits.swift @@ -78,7 +78,7 @@ struct ProfileEditLimits: Decodable, Equatable { /// The most segments a schedule may have: the published maximum, never more than one per segment slot. var segmentLimit: Int { - min(maxSegments, 86400 / segmentSeconds) + segmentSeconds > 0 ? min(maxSegments, 86400 / segmentSeconds) : 0 } /// The most segments a schedule of `kind` may have; basal also stays within the pump's entry limit. diff --git a/LoopFollow/Remote/Profiles/ProfileEditorSheet.swift b/LoopFollow/Remote/Profiles/ProfileEditorSheet.swift index 11fb8d7c1..60b51dfe9 100644 --- a/LoopFollow/Remote/Profiles/ProfileEditorSheet.swift +++ b/LoopFollow/Remote/Profiles/ProfileEditorSheet.swift @@ -155,7 +155,7 @@ struct ProfileEditorSheet: View { } ForEach(ProfileScheduleKind.allCases) { kind in - ProfileValuesEditor(kind: kind, segments: Binding(get: { draft[kind] }, set: { draft[kind] = $0 }), units: draft.units, limits: editableLimits, singleTarget: remote.hasSingleTarget, isUnchanged: !changedSchedules.contains(kind)) + ProfileValuesEditor(kind: kind, segments: Binding(get: { draft[kind] }, set: { draft[kind] = $0 }), units: draft.units, limits: editableLimits, singleTarget: remote.hasSingleTarget, isUnchanged: !changedSchedules.contains(kind), isActiveProfile: isEditingActive) } if !problems.isEmpty { diff --git a/LoopFollow/Remote/Profiles/ProfileReviewView.swift b/LoopFollow/Remote/Profiles/ProfileReviewView.swift index 736552e4b..6d5870c60 100644 --- a/LoopFollow/Remote/Profiles/ProfileReviewView.swift +++ b/LoopFollow/Remote/Profiles/ProfileReviewView.swift @@ -108,6 +108,10 @@ struct ProfileReviewView: View { if appliesNow { ActiveProfileWarning(remote: remote) } + if !ProfileValidation.unchangedProblems(for: command, limits: limits, singleTarget: remote.hasSingleTarget).isEmpty { + Label("Schedules this change leaves alone stay outside the limits \(remote.appName) shared, so \(remote.appName) would refuse to activate this profile until they are changed too.", systemImage: "exclamationmark.triangle") + .foregroundColor(.orange) + } if !increases.isEmpty { MoreInsulinWarning( increases: increases, diff --git a/LoopFollow/Remote/Profiles/ProfileValidation.swift b/LoopFollow/Remote/Profiles/ProfileValidation.swift index bd5b05cc3..abe067ab3 100644 --- a/LoopFollow/Remote/Profiles/ProfileValidation.swift +++ b/LoopFollow/Remote/Profiles/ProfileValidation.swift @@ -186,11 +186,22 @@ enum ProfileValidation { return problems(values, limits: limits, schedules: changed) } - /// Why Loop or Trio would refuse to activate `values` under `limits`, or empty when nothing in the limits stands in - /// the way. Empty when the profile and the limits are in different units, since they can't be compared. - static func activationProblems(_ values: TherapyProfileValues, limits: ProfileEditLimits?) -> [String] { - guard let limits, values.units == limits.normalizedUnits else { return [] } - return problems(values, limits: limits) + /// Why Loop or Trio would refuse to activate `profile` under `limits`, or empty when nothing in the limits stands in + /// the way. Empty when the limits are not usable, the profile could not be read completely, or the two are in + /// different units, since the profile can't be judged then. + static func activationProblems(_ profile: TherapyProfile, limits: ProfileEditLimits?) -> [String] { + guard let limits, limits.isUsable, profile.isWellFormed, profile.values.units == limits.normalizedUnits else { return [] } + return problems(profile.values, limits: limits) + } + + /// The problems of the schedules a save of an existing profile leaves unchanged; they stay stored as they are. + static func unchangedProblems(for command: ProfileCommand, limits: ProfileEditLimits?, singleTarget: Bool = false) -> [String] { + guard case let .save(_, original?, values) = command, let limits, limits.isUsable, original.isWellFormed, + values.units == limits.normalizedUnits + else { return [] } + let unchanged = Set(ProfileScheduleKind.allCases).subtracting(changedSchedules(from: original.values, to: values, singleTarget: singleTarget)) + if unchanged.isEmpty { return [] } + return problems(values, limits: limits, schedules: unchanged) } static func scheduleProblems(_ starts: [Int], kind: ProfileScheduleKind, limits: ProfileEditLimits) -> [String] { @@ -200,7 +211,7 @@ enum ProfileValidation { if zip(starts, starts.dropFirst()).contains(where: { $0 >= $1 }) { problems.append("\(kind.title): each time must be later than the one before.") } - if starts.contains(where: { $0 < 0 || $0 >= 86400 || $0 % limits.segmentSeconds != 0 }) { + if starts.contains(where: { $0 < 0 || $0 >= 86400 || limits.segmentSeconds <= 0 || $0 % limits.segmentSeconds != 0 }) { problems.append("\(kind.title): times must be on the \(limits.segmentSeconds / 60)-minute grid.") } let segmentLimit = limits.segmentLimit(for: kind) diff --git a/LoopFollow/Remote/Profiles/ProfileValuesEditor.swift b/LoopFollow/Remote/Profiles/ProfileValuesEditor.swift index ab0f1b682..b0c4e8be8 100644 --- a/LoopFollow/Remote/Profiles/ProfileValuesEditor.swift +++ b/LoopFollow/Remote/Profiles/ProfileValuesEditor.swift @@ -70,6 +70,8 @@ struct ProfileValuesEditor: View { /// True while the schedule keeps the values of the stored profile, which may be saved unchanged although they /// no longer fit the limits. var isUnchanged = false + /// True when the schedule belongs to the active profile. + var isActiveProfile = false private var isRange: Bool { kind.isRange && !singleTarget } @@ -124,9 +126,11 @@ struct ProfileValuesEditor: View { } switch status { case .notAllowed: - Text(isUnchanged - ? "Outside what is allowed now. The profile can't be activated until this value is changed." - : "Outside what is allowed. Change this value before sending.") + Text(!isUnchanged + ? "Outside what is allowed. Change this value before sending." + : isActiveProfile + ? "Outside what is allowed now. Once another profile is activated, this one can't be activated again until this value is changed." + : "Outside what is allowed now. The profile can't be activated until this value is changed.") .font(.caption) .foregroundColor(.red) case .outsideRecommended: diff --git a/LoopFollow/Remote/Profiles/TherapyProfilesView.swift b/LoopFollow/Remote/Profiles/TherapyProfilesView.swift index ac2fecc64..90a4d8cd1 100644 --- a/LoopFollow/Remote/Profiles/TherapyProfilesView.swift +++ b/LoopFollow/Remote/Profiles/TherapyProfilesView.swift @@ -57,7 +57,7 @@ struct TherapyProfilesView: View { HStack { Text(profile.name) Spacer() - if !ProfileValidation.activationProblems(profile.values, limits: profileSet.limits).isEmpty { + if !ProfileValidation.activationProblems(profile, limits: profileSet.limits).isEmpty { Text("Outside Limits") .font(.caption) .foregroundColor(.orange) @@ -195,15 +195,21 @@ struct TherapyProfilePreviewView: View { /// Why the app would refuse to activate this profile under the limits it shared. private var activationProblems: [String] { guard let profile else { return [] } - return ProfileValidation.activationProblems(profile.values, limits: profileSet?.limits) + return ProfileValidation.activationProblems(profile, limits: profileSet?.limits) } - /// The note for the activation confirmation when the active profile itself no longer fits the limits. - private var switchBackText: String? { + /// The note for the activation confirmation: the target is outside the limits, or the active profile itself no + /// longer fits them. + private var activationLimitsText: String? { + if !activationProblems.isEmpty { + return "This profile is outside the limits \(remote.appName) shared, so \(remote.appName) will likely refuse it." + } guard !isActive, let active = profileSet?.activeProfile, - !ProfileValidation.activationProblems(active.values, limits: profileSet?.limits).isEmpty + !ProfileValidation.activationProblems(active, limits: profileSet?.limits).isEmpty else { return nil } - return "\(active.name) no longer fits the limits \(remote.appName) shared, so it can't be activated again until it is edited." + let blocked = ProfileEditing.blocker(for: active, limits: profileSet?.limits, remote: remote) != nil + return "\(active.name) no longer fits the limits \(remote.appName) shared, so \(remote.appName) would refuse to activate it again" + + (blocked ? "." : " until it is edited.") } private var activateKey: String { remote.key(.activate, name: name) } @@ -263,8 +269,8 @@ struct TherapyProfilePreviewView: View { if !activationProblems.isEmpty { VStack(alignment: .leading, spacing: 4) { Label(isActive - ? "This profile no longer fits the limits \(remote.appName) shared. It stays active, but once another profile is activated it can't be activated again until it is edited." - : "\(remote.appName) will not activate this profile until it is edited to fit the limits it shared.", + ? "This profile no longer fits the limits \(remote.appName) shared. It stays active, but once another profile is activated, \(remote.appName) would refuse to activate it again" + (editBlocker == nil ? " until it is edited." : ".") + : "\(remote.appName) would refuse to activate this profile under the limits it shared." + (editBlocker == nil ? " Edit it to fit them first." : ""), systemImage: "exclamationmark.triangle") .foregroundColor(.orange) ForEach(activationProblems, id: \.self) { problem in @@ -369,7 +375,7 @@ struct TherapyProfilePreviewView: View { title: Text("Activate \(name) in \(remote.appName)?"), message: Text("\(remote.appName) replaces its correction range, carb ratios, basal rates and insulin sensitivities with these values and writes the basal rates to the pump. Dosing changes right away." + (profileSet.flatMap { ScheduledSwitches.holdText($0.scheduledSwitches) }.map { " " + $0 } ?? "") - + (switchBackText.map { " " + $0 } ?? "") + + (activationLimitsText.map { " " + $0 } ?? "") + MoreInsulinWarning.sentence(activationIncreases?.increases ?? [], comparedWith: activationIncreases?.active.name ?? "")), primaryButton: .default(Text("Activate")) { send(.activate, fingerprint: fingerprint) }, secondaryButton: .cancel() diff --git a/Tests/ProfileValidationTests.swift b/Tests/ProfileValidationTests.swift index 40b790fb9..e2edb1c7e 100644 --- a/Tests/ProfileValidationTests.swift +++ b/Tests/ProfileValidationTests.swift @@ -95,7 +95,7 @@ struct ProfileValidationTests { } @Test("a save of an existing profile is checked only in the schedules it changes") - func renameSkipsValueChecks() throws { + func saveChecksChangedSchedulesOnly() throws { let limits = try ProfileEditLimitsTests.limits() let json = """ {"timezone": "UTC", "units": "mg/dL", @@ -122,8 +122,62 @@ struct ProfileValidationTests { #expect(ProfileValidation.problems(for: .save(name: "Old Sport", original: stored, values: draft.values), limits: limits).count == 1) #expect(ProfileValidation.problems(for: .save(name: "Copy", original: nil, values: stored.values), limits: limits).count == 2) #expect(ProfileValidation.problems(for: .activate(stored), limits: limits).isEmpty) - #expect(ProfileValidation.activationProblems(stored.values, limits: limits).count == 2) - #expect(ProfileValidation.activationProblems(draft.values, limits: nil).isEmpty) + #expect(ProfileValidation.activationProblems(stored, limits: limits).count == 2) + #expect(ProfileValidation.activationProblems(stored, limits: nil).isEmpty) + #expect(ProfileValidation.unchangedProblems(for: .save(name: "Old Sport", original: stored, values: draft.values), limits: limits).count == 1) + #expect(ProfileValidation.unchangedProblems(for: .save(name: "Copy", original: nil, values: stored.values), limits: limits).isEmpty) + } + + private func storedProfile(units: String = "mg/dL", basal: Double = 0.12, targetLow: Double = 80, targetHigh: Double = 110) throws -> TherapyProfile { + let json = """ + {"timezone": "UTC", "units": "\(units)", + "basal": [{"time": "00:00", "value": \(basal), "timeAsSeconds": 0}], + "carbratio": [{"time": "00:00", "value": 10, "timeAsSeconds": 0}], + "sens": [{"time": "00:00", "value": 50, "timeAsSeconds": 0}], + "target_low": [{"time": "00:00", "value": \(targetLow), "timeAsSeconds": 0}], + "target_high": [{"time": "00:00", "value": \(targetHigh), "timeAsSeconds": 0}]} + """ + return TherapyProfile(name: "Stored", store: try JSONDecoder().decode(NSProfile.Store.self, from: Data(json.utf8))) + } + + @Test("activation problems are left out for unusable limits, unit mismatches and profiles not read completely") + func activationProblemsNeedComparableLimits() throws { + let stored = try storedProfile() + let limits = try ProfileEditLimitsTests.limits() + #expect(ProfileValidation.activationProblems(stored, limits: limits).count == 2) + let badGrid = try ProfileEditLimitsTests.limits(ProfileEditLimitsTests.contractLimitsJSON.replacingOccurrences(of: "\"segmentSeconds\": 1800", with: "\"segmentSeconds\": 1700")) + let badStep = try ProfileEditLimitsTests.limits(ProfileEditLimitsTests.contractLimitsJSON.replacingOccurrences(of: "\"step\": 0.1", with: "\"step\": 0")) + let zeroGrid = try ProfileEditLimitsTests.limits(ProfileEditLimitsTests.contractLimitsJSON.replacingOccurrences(of: "\"segmentSeconds\": 1800", with: "\"segmentSeconds\": 0")) + #expect(ProfileValidation.activationProblems(stored, limits: badGrid).isEmpty) + #expect(ProfileValidation.activationProblems(stored, limits: badStep).isEmpty) + #expect(ProfileValidation.activationProblems(stored, limits: zeroGrid).isEmpty) + #expect(!zeroGrid.isUsable) + #expect(zeroGrid.segmentLimit == 0) + #expect(!ProfileValidation.scheduleProblems([0], kind: .basal, limits: zeroGrid).isEmpty) + let mmol = try storedProfile(units: "mmol/L", targetLow: 4.4, targetHigh: 6.1) + #expect(ProfileValidation.activationProblems(mmol, limits: limits).isEmpty) + let malformed = try JSONDecoder().decode(NSProfile.Store.self, from: Data(""" + {"timezone": "UTC", "units": "mg/dL", + "basal": [{"time": "00:00", "value": 0.12, "timeAsSeconds": 0}], + "carbratio": [{"time": "00:00", "value": 10, "timeAsSeconds": 0}], + "sens": [{"time": "00:00", "value": 50, "timeAsSeconds": 0}], + "target_low": [{"time": "00:00", "value": 100, "timeAsSeconds": 0}, {"time": "06:00", "value": 100, "timeAsSeconds": 21600}], + "target_high": [{"time": "00:00", "value": 110, "timeAsSeconds": 0}]} + """.utf8)) + let notReadable = TherapyProfile(name: "Broken", store: malformed) + #expect(!notReadable.isWellFormed) + #expect(ProfileValidation.activationProblems(notReadable, limits: limits).isEmpty) + } + + @Test("an unchanged out-of-limits Trio target is not checked while another schedule changes") + func singleTargetUnchangedTarget() throws { + let limits = try ProfileEditLimitsTests.limits() + let stored = try storedProfile(basal: 0.1, targetLow: 80, targetHigh: 120) + var draft = ProfileDraft(stored.values, singleTarget: true) + draft.sensitivity[0].value = 60 + #expect(ProfileValidation.changedSchedules(from: stored.values, to: draft.values, singleTarget: true) == [.sensitivity]) + #expect(ProfileValidation.problems(for: .save(name: "Stored", original: stored, values: draft.values), limits: limits, singleTarget: true).isEmpty) + #expect(ProfileValidation.problems(for: .save(name: "Stored", original: stored, values: draft.values), limits: limits).count == 1) } @Test("changed schedules are found per schedule, and a single-target range shown as low-only is unchanged") @@ -135,6 +189,14 @@ struct ProfileValidationTests { #expect(ProfileValidation.changedSchedules(from: original, to: values(target: [(0, 100, 100)])) == [.correctionRange]) #expect(ProfileValidation.changedSchedules(from: original, to: values(target: [(0, 100, 100)]), singleTarget: true).isEmpty) #expect(ProfileValidation.changedSchedules(from: original, to: values(target: [(0, 105, 105)]), singleTarget: true) == [.correctionRange]) + #expect(ProfileValidation.changedSchedules(from: original, to: values(carbRatio: [(0, 12)], target: [(0, 100, 110)])) == [.carbRatio]) + #expect(ProfileValidation.changedSchedules(from: original, to: values(basal: [(0, 0.85), (23400, 1.0)], target: [(0, 100, 110)])) == [.basal]) + #expect(ProfileValidation.changedSchedules(from: original, to: values(carbRatio: [(0, 10), (43200, 12)], target: [(0, 100, 110)])) == [.carbRatio]) + #expect(ProfileValidation.changedSchedules(from: original, to: values(target: [(0, 100, 110), (43200, 100, 120)])) == [.correctionRange]) + #expect(ProfileValidation.changedSchedules(from: original, to: values(basal: [(0, 0.9), (21600, 1.0)], sens: [(0, 45)], target: [(0, 95, 110)])) == [.basal, .sensitivity, .correctionRange]) + let mmol = values(units: "mmol/L", sens: [(0, 2.8)], target: [(0, 5.5, 6.1)]) + #expect(ProfileValidation.changedSchedules(from: mmol, to: mmol).isEmpty) + #expect(ProfileValidation.changedSchedules(from: mmol, to: values(units: "mmol/L", sens: [(0, 2.9)], target: [(0, 5.5, 6.1)])) == [.sensitivity]) } @Test("new segments go one step after the last, or into the first free slot")