From 0c76e4af31a58222860855ad91306e12bec79613 Mon Sep 17 00:00:00 2001 From: ykisana Date: Sun, 15 Nov 2026 15:34:54 -0600 Subject: [PATCH] fix: start timed unblocks at iOS's activity limit and show unblock errors At iOS's 20 schedules-and-timers limit, a timed unblock now starts without its own timer and the monitor re-blocks it at the next :00/:30 heartbeat. The app says it may end up to 30 minutes late. This only applies when the heartbeat is registered; without it (a phone that filled every slot before 1.6) nothing would re-block the unblock, so it still fails. Other failures to start an unblock with the default duration now show "Couldn't Unblock" instead of failing silently. --- Normal/App/UITestDeviceActivityCenter.swift | 8 ++ Normal/App/UITestSupport.swift | 6 ++ Normal/Extensions/View+UnblockAlert.swift | 44 +++++++++ Normal/Modifiers/WidgetActionResponder.swift | 23 +++-- Normal/Resources/Localizable.xcstrings | 12 +++ Normal/Services/BlockActions.swift | 6 +- Normal/Services/QRService.swift | 3 + Normal/Services/TimedUnblockService.swift | 39 +++++--- Normal/Services/UnblockTarget.swift | 7 +- .../TimedUnlock/UnblockDurationSheet.swift | 6 +- Normal/Views/Groups/GroupListCardView.swift | 20 ++-- Normal/Views/Groups/GroupsView.swift | 7 +- Normal/Views/Home/HomeView.swift | 14 ++- .../AppUnblockIntentPerformerTests.swift | 30 +++++- .../Services/BlockingScenarioTests.swift | 36 +++++++ .../Services/TimedUnblockServiceTests.swift | 38 ++++++++ NormalTests/TestSupport/BlockingHarness.swift | 3 +- NormalUITests/BlockingUITests.swift | 94 +++++++++++++++++++ 18 files changed, 355 insertions(+), 41 deletions(-) create mode 100644 Normal/Extensions/View+UnblockAlert.swift diff --git a/Normal/App/UITestDeviceActivityCenter.swift b/Normal/App/UITestDeviceActivityCenter.swift index 1f27dfc..74751b6 100644 --- a/Normal/App/UITestDeviceActivityCenter.swift +++ b/Normal/App/UITestDeviceActivityCenter.swift @@ -13,6 +13,14 @@ final class UITestDeviceActivityCenter: DeviceActivityProviding { during schedule: DeviceActivitySchedule, events _: [DeviceActivityEvent.Name: DeviceActivityEvent] ) throws { + if activityName.rawValue.hasPrefix("timedUnblock_") { + if UITestSupport.timedUnblockFails { + throw DeviceActivityCenter.MonitoringError.unauthorized + } + if UITestSupport.timerLimitReached { + throw DeviceActivityCenter.MonitoringError.excessiveActivities + } + } schedules[activityName.rawValue] = schedule } diff --git a/Normal/App/UITestSupport.swift b/Normal/App/UITestSupport.swift index 9504fbf..98e1ef9 100644 --- a/Normal/App/UITestSupport.swift +++ b/Normal/App/UITestSupport.swift @@ -22,6 +22,12 @@ enum UITestSupport { static let websitesOnly = arguments.contains("-uiTestWebsitesOnly") + static let timedUnblockFails = arguments.contains("-uiTestTimedUnblockFails") + + static let timerLimitReached = arguments.contains("-uiTestTimerLimitReached") + + static let slowScan = arguments.contains("-uiTestSlowScan") + static let seedGroupKey = arguments.contains("-uiTestSeedGroupKey") static let seedLocationKey = arguments.contains("-uiTestSeedLocationKey") diff --git a/Normal/Extensions/View+UnblockAlert.swift b/Normal/Extensions/View+UnblockAlert.swift new file mode 100644 index 0000000..3b4a015 --- /dev/null +++ b/Normal/Extensions/View+UnblockAlert.swift @@ -0,0 +1,44 @@ +import SwiftUI + +enum UnblockAlert { + case failed(any Error) + case mayEndLate + + init?(_ timing: UnblockTiming) { + guard timing == .mayEndLate else { return nil } + self = .mayEndLate + } + + var title: LocalizedStringKey { + switch self { + case .failed: "Couldn't Unblock" + case .mayEndLate: "Unblocked" + } + } + + var message: Text { + switch self { + case let .failed(error): + Text(error.localizedDescription) + case .mayEndLate: + Text("iOS only tracks 20 schedules and timers at once, so this unblock may end up to 30 minutes late.") + } + } +} + +extension View { + func unblockAlert(_ alert: Binding) -> some View { + self.alert( + alert.wrappedValue?.title ?? "", + isPresented: Binding( + get: { alert.wrappedValue != nil }, + set: { if !$0 { alert.wrappedValue = nil } } + ), + presenting: alert.wrappedValue + ) { _ in + Button("OK", role: .cancel) {} + } message: { alert in + alert.message + } + } +} diff --git a/Normal/Modifiers/WidgetActionResponder.swift b/Normal/Modifiers/WidgetActionResponder.swift index f0cdb3b..6a94374 100644 --- a/Normal/Modifiers/WidgetActionResponder.swift +++ b/Normal/Modifiers/WidgetActionResponder.swift @@ -19,6 +19,7 @@ private struct WidgetActionResponder: ViewModifier { @State private var active: ActiveRequest? @State private var heldRequest: ActionRequest? @State private var durationGrant: UnblockGrant? + @State private var unblockAlert: UnblockAlert? private struct ActiveRequest { let token: UUID @@ -39,8 +40,9 @@ private struct WidgetActionResponder: ViewModifier { requestID: active?.token ) .sheet(item: $durationGrant, onDismiss: durationSheetDismissed) { grant in - UnblockDurationSheet(grant: grant) + UnblockDurationSheet(grant: grant) { unblockAlert = UnblockAlert($0) } } + .unblockAlert($unblockAlert) .onOpenURL { coordinator.handle(url: $0) } .onChange(of: coordinator.pendingAction) { _, request in resolve(request) } .onChange(of: unlockInbox.pending, initial: true) { _, _ in takeInboxRequest() } @@ -132,13 +134,18 @@ private struct WidgetActionResponder: ViewModifier { durationGrant = grant return } - try? BlockActions.unblock( - grant, - for: length, - settings: settings, - screenTimeService: screenTimeService, - timedUnblockService: timedUnblockService - ) + do { + let timing = try BlockActions.unblock( + grant, + for: length, + settings: settings, + screenTimeService: screenTimeService, + timedUnblockService: timedUnblockService + ) + unblockAlert = UnblockAlert(timing) + } catch { + unblockAlert = .failed(error) + } } private func block(_ group: AppGroup) { diff --git a/Normal/Resources/Localizable.xcstrings b/Normal/Resources/Localizable.xcstrings index 6762e36..87e07e2 100644 --- a/Normal/Resources/Localizable.xcstrings +++ b/Normal/Resources/Localizable.xcstrings @@ -574,6 +574,10 @@ "comment" : "Error when unblocking an app fails.", "isCommentAutoGenerated" : true }, + "Couldn't Unblock" : { + "comment" : "Title of an alert shown when an unblock with the default duration fails.", + "isCommentAutoGenerated" : true + }, "Create a schedule to automatically block or unblock apps at set times." : { "comment" : "A footer message in the Schedules view that instructs the user on how to create schedules.", "isCommentAutoGenerated" : true @@ -903,6 +907,10 @@ }, "Invalid Key" : { + }, + "iOS only tracks 20 schedules and timers at once, so this unblock may end up to 30 minutes late." : { + "comment" : "Message shown after a timed unblock starts without its own iOS timer because too many schedules and timers are registered.", + "isCommentAutoGenerated" : true }, "It provides both a dummy Apple ID and a random passcode. This can be made near impossible to recover." : { "comment" : "A description of a service that can be used to generate a passcode and Apple ID for the Screen Time bypass.", @@ -1661,6 +1669,10 @@ "comment" : "A heading for the NFC tag unblocking process.", "isCommentAutoGenerated" : true }, + "Unblocked" : { + "comment" : "Title of an alert shown after a timed unblock starts without its own iOS timer.", + "isCommentAutoGenerated" : true + }, "Unblocking" : { "comment" : "A section header that lists unblocking-related settings.", "isCommentAutoGenerated" : true diff --git a/Normal/Services/BlockActions.swift b/Normal/Services/BlockActions.swift index 88020ae..0aabe3c 100644 --- a/Normal/Services/BlockActions.swift +++ b/Normal/Services/BlockActions.swift @@ -28,16 +28,17 @@ enum BlockActions { screenTimeService.block(selection: group.selection, customDomains: customDomains) } + @discardableResult static func unblock( _ grant: UnblockGrant, for length: UnblockLength, settings: Settings, screenTimeService: any ScreenTimeProviding, timedUnblockService: TimedUnblockService - ) throws { + ) throws -> UnblockTiming { switch length { case let .timed(duration): - try timedUnblockService.start( + return try timedUnblockService.start( grant, duration: duration, settings: settings, @@ -45,6 +46,7 @@ enum BlockActions { ) case .permanent: screenTimeService.unblockPermanently(grant, settings: settings) + return .exact } } diff --git a/Normal/Services/QRService.swift b/Normal/Services/QRService.swift index cc09956..fd2a6f9 100644 --- a/Normal/Services/QRService.swift +++ b/Normal/Services/QRService.swift @@ -29,6 +29,9 @@ final class QRService { func scan(validate: ((String) -> Bool)?) async throws -> String { if UITestSupport.isActive { + if UITestSupport.slowScan { + try? await Task.sleep(for: .seconds(1)) + } if let validate, !validate(UITestSupport.stubScanValue) { throw ScanError.invalidKey } diff --git a/Normal/Services/TimedUnblockService.swift b/Normal/Services/TimedUnblockService.swift index aee7035..35a3f4b 100644 --- a/Normal/Services/TimedUnblockService.swift +++ b/Normal/Services/TimedUnblockService.swift @@ -53,19 +53,20 @@ final class TimedUnblockService { activeUnblocks[groupId.uuidString] } + @discardableResult func startMain( duration: TimedUnblockDuration, selection: FamilyActivitySelection, customDomains: [String] = [], screenTimeService: any ScreenTimeProviding, blockAllPreventsAppDelete: Bool = false - ) throws { + ) throws -> UnblockTiming { let activityName = SharedConstants.mainTimedUnblockActivityName cancelMonitoring(activityName: activityName) let start = clock() let endDate = Self.endDate(of: duration, from: start) - try scheduleActivity(name: activityName, start: start, endDate: endDate) + let timing = try scheduleActivity(name: activityName, start: start, endDate: endDate) try persist( id: Self.mainID, @@ -81,22 +82,24 @@ final class TimedUnblockService { cancelAllGroupUnblocks() syncHeartbeat() screenTimeService.reconcile() + return timing } + @discardableResult func startGroup( duration: TimedUnblockDuration, groupId: UUID, selection: FamilyActivitySelection, customDomains: [String] = [], screenTimeService: any ScreenTimeProviding - ) throws { + ) throws -> UnblockTiming { let id = groupId.uuidString let activityName = SharedConstants.groupTimedUnblockActivityName(for: groupId) cancelMonitoring(activityName: activityName) let start = clock() let endDate = Self.endDate(of: duration, from: start) - try scheduleActivity(name: activityName, start: start, endDate: endDate) + let timing = try scheduleActivity(name: activityName, start: start, endDate: endDate) try persist( id: id, @@ -110,6 +113,7 @@ final class TimedUnblockService { syncHeartbeat() screenTimeService.reconcile() + return timing } func cancelMain( @@ -285,13 +289,20 @@ final class TimedUnblockService { return Date(timeIntervalSinceReferenceDate: end.rounded(.down)) } - private func scheduleActivity(name: String, start: Date, endDate: Date) throws { + private func scheduleActivity(name: String, start: Date, endDate: Date) throws -> UnblockTiming { let schedule = DeviceActivityScheduleFactory.window(from: start, to: endDate) - try activityCenter.startMonitoring( - DeviceActivityName(name), - during: schedule, - events: [:] - ) + do { + try activityCenter.startMonitoring( + DeviceActivityName(name), + during: schedule, + events: [:] + ) + return .exact + } catch DeviceActivityCenter.MonitoringError.excessiveActivities + where activityCenter.monitoredActivityNames.contains(SharedConstants.reblockHeartbeatActivityName) + { + return .mayEndLate + } } private func syncHeartbeat() { @@ -329,12 +340,13 @@ final class TimedUnblockService { } extension TimedUnblockService { + @discardableResult func startMain( duration: TimedUnblockDuration, mainSelection: SelectedApps, settings: Settings, screenTimeService: any ScreenTimeProviding - ) throws { + ) throws -> UnblockTiming { try startMain( duration: duration, selection: mainSelection.selection, @@ -344,3 +356,8 @@ extension TimedUnblockService { ) } } + +enum UnblockTiming: Equatable { + case exact + case mayEndLate +} diff --git a/Normal/Services/UnblockTarget.swift b/Normal/Services/UnblockTarget.swift index 86c4f00..de5154d 100644 --- a/Normal/Services/UnblockTarget.swift +++ b/Normal/Services/UnblockTarget.swift @@ -52,23 +52,24 @@ enum UnblockTarget: Identifiable { } extension TimedUnblockService { + @discardableResult func start( _ grant: UnblockGrant, duration: TimedUnblockDuration, settings: Settings, screenTimeService: any ScreenTimeProviding - ) throws { + ) throws -> UnblockTiming { let target = grant.target switch target { case let .all(mainSelection): - try startMain( + return try startMain( duration: duration, mainSelection: mainSelection, settings: settings, screenTimeService: screenTimeService ) case let .group(group): - try startGroup( + return try startGroup( duration: duration, groupId: group.id, selection: group.selection, diff --git a/Normal/Views/BlockUnblockViews/TimedUnlock/UnblockDurationSheet.swift b/Normal/Views/BlockUnblockViews/TimedUnlock/UnblockDurationSheet.swift index 0e206ca..d48f65c 100644 --- a/Normal/Views/BlockUnblockViews/TimedUnlock/UnblockDurationSheet.swift +++ b/Normal/Views/BlockUnblockViews/TimedUnlock/UnblockDurationSheet.swift @@ -7,7 +7,7 @@ struct UnblockDurationSheet: View { @Query private var allSettings: [Settings] let grant: UnblockGrant - var onUnblock: () -> Void = {} + var onUnblock: (UnblockTiming) -> Void = { _ in } private var settings: Settings { allSettings.unwrapped @@ -26,14 +26,14 @@ struct UnblockDurationSheet: View { durations: settings.unblockDurations, initialDuration: settings.defaultDuration, onConfirm: { length in - try BlockActions.unblock( + let timing = try BlockActions.unblock( grant, for: length, settings: settings, screenTimeService: screenTimeService, timedUnblockService: timedUnblockService ) - onUnblock() + onUnblock(timing) } ) } diff --git a/Normal/Views/Groups/GroupListCardView.swift b/Normal/Views/Groups/GroupListCardView.swift index c6b9b87..90d29c7 100644 --- a/Normal/Views/Groups/GroupListCardView.swift +++ b/Normal/Views/Groups/GroupListCardView.swift @@ -17,6 +17,7 @@ struct GroupListCardView: View { @Binding var authAction: ProtectedAction? @Binding var pendingGroupID: UUID? @Binding var durationGrant: UnblockGrant? + @Binding var unblockAlert: UnblockAlert? @State private var isEditing = false @State private var isReselecting = false @@ -254,12 +255,17 @@ struct GroupListCardView: View { durationGrant = grant return } - try? BlockActions.unblock( - grant, - for: .timed(duration), - settings: settings, - screenTimeService: screenTimeService, - timedUnblockService: timedUnblockService - ) + do { + let timing = try BlockActions.unblock( + grant, + for: .timed(duration), + settings: settings, + screenTimeService: screenTimeService, + timedUnblockService: timedUnblockService + ) + unblockAlert = UnblockAlert(timing) + } catch { + unblockAlert = .failed(error) + } } } diff --git a/Normal/Views/Groups/GroupsView.swift b/Normal/Views/Groups/GroupsView.swift index ea090ae..407f20e 100644 --- a/Normal/Views/Groups/GroupsView.swift +++ b/Normal/Views/Groups/GroupsView.swift @@ -14,6 +14,7 @@ struct GroupsView: View { @State private var authAction: ProtectedAction? @State private var pendingGroupID: UUID? @State private var durationGrant: UnblockGrant? + @State private var unblockAlert: UnblockAlert? private var hasSelection: Bool { selectedApps.first?.selection.isEmpty == false @@ -56,7 +57,8 @@ struct GroupsView: View { appGroup: group, authAction: $authAction, pendingGroupID: $pendingGroupID, - durationGrant: $durationGrant + durationGrant: $durationGrant, + unblockAlert: $unblockAlert ) }, onMove: move) .safeAreaInset(edge: .bottom) { @@ -74,8 +76,9 @@ struct GroupsView: View { keyGroupID: pendingGroupID ) .sheet(item: $durationGrant) { grant in - UnblockDurationSheet(grant: grant) + UnblockDurationSheet(grant: grant) { unblockAlert = UnblockAlert($0) } } + .unblockAlert($unblockAlert) } } diff --git a/Normal/Views/Home/HomeView.swift b/Normal/Views/Home/HomeView.swift index b9ecdd9..5fa0efa 100644 --- a/Normal/Views/Home/HomeView.swift +++ b/Normal/Views/Home/HomeView.swift @@ -14,6 +14,7 @@ struct HomeView: View { @State private var authAction: ProtectedAction? @State private var durationGrant: UnblockGrant? + @State private var unblockAlert: UnblockAlert? private var mainSelection: SelectedApps? { selectedApps.first @@ -53,8 +54,12 @@ struct HomeView: View { } .protectedAction($authAction, defaultKeyType: settings.defaultKeyType) .sheet(item: $durationGrant) { grant in - UnblockDurationSheet(grant: grant, onUnblock: recordUnblockForReview) + UnblockDurationSheet(grant: grant) { timing in + recordUnblockForReview() + unblockAlert = UnblockAlert(timing) + } } + .unblockAlert($unblockAlert) .navigationTitle("Home") .settingsToolbar() } @@ -76,7 +81,7 @@ struct HomeView: View { return } do { - try BlockActions.unblock( + let timing = try BlockActions.unblock( grant, for: .timed(duration), settings: settings, @@ -84,7 +89,10 @@ struct HomeView: View { timedUnblockService: timedUnblockService ) recordUnblockForReview() - } catch {} + unblockAlert = UnblockAlert(timing) + } catch { + unblockAlert = .failed(error) + } } private func recordUnblockForReview() { diff --git a/NormalTests/Services/AppUnblockIntentPerformerTests.swift b/NormalTests/Services/AppUnblockIntentPerformerTests.swift index 7efc3e4..e47f6f6 100644 --- a/NormalTests/Services/AppUnblockIntentPerformerTests.swift +++ b/NormalTests/Services/AppUnblockIntentPerformerTests.swift @@ -382,11 +382,39 @@ struct AppUnblockIntentPerformerTests { try seed() context.insert(locationKey()) screenTime.stubBlockStatus = .all - activity.startError = DeviceActivityCenter.MonitoringError.excessiveActivities + activity.startError = DeviceActivityCenter.MonitoringError.unauthorized await #expect(throws: UnblockIntentError.unblockFailed) { try await performer.unblock(locationRequest()) } #expect(!timedUnblock.isMainUnblockActive) } + + @Test func unblockAtTheActivityLimitStillStarts() async throws { + try seed() + context.insert(locationKey()) + screenTime.stubBlockStatus = .all + let schedule = try ScheduleDTO( + id: UUID(), + name: "S", + selectionData: FamilyActivitySelection().toData(), + startHour: 20, + startMinute: 0, + durationMinutes: 60, + weekdays: Set(1 ... 7), + shouldBlock: true, + isTimed: true, + isEnabled: true + ) + store.saveSchedules([schedule]) + try activity.startMonitoring( + DeviceActivityName(SharedConstants.reblockHeartbeatActivityName), + during: DeviceActivityScheduleFactory.heartbeat(), + events: [:] + ) + activity.startError = DeviceActivityCenter.MonitoringError.excessiveActivities + + #expect(try await performer.unblock(locationRequest()) == .unblocked(name: "All Apps", length: .timed(.oneHour))) + #expect(timedUnblock.isMainUnblockActive) + } } diff --git a/NormalTests/Services/BlockingScenarioTests.swift b/NormalTests/Services/BlockingScenarioTests.swift index d101766..3473895 100644 --- a/NormalTests/Services/BlockingScenarioTests.swift +++ b/NormalTests/Services/BlockingScenarioTests.swift @@ -1,3 +1,4 @@ +import DeviceActivity import FamilyControls import Foundation import ManagedSettings @@ -285,6 +286,41 @@ struct BlockingScenarioTests { #expect(h.blocked == h.apps(1, 2, 3)) } + @Test func timedUnblockAllAtTheActivityLimitReblocksAtTheNextHeartbeat() throws { + let h = BlockingHarness() + try h.addSchedule([4], from: (20, 0), minutes: 60, block: true) + h.blockAll() + h.activity.activityLimit = h.activity.monitoredActivityNames.count + h.passTime(to: h.at(10, 1)) + + #expect(try h.unblockAllTimed(.fifteenMinutes) == .mayEndLate) + #expect(h.blocked.isEmpty) + #expect(h.activity.registeredSchedule(for: DeviceActivityName(SharedConstants.mainTimedUnblockActivityName)) == nil) + #expect(h.activity.registeredSchedule(for: DeviceActivityName(SharedConstants.reblockHeartbeatActivityName)) != nil) + + h.wake(at: h.at(10, 30)) + #expect(h.blocked == h.apps(1, 2, 3)) + } + + @Test func timedUnblockAllAtTheActivityLimitWithoutAHeartbeatStaysBlocked() throws { + let h = BlockingHarness() + for minute in 0 ..< 20 { + try h.addSchedule([4], from: (20, minute), minutes: 60, block: true) + } + let heartbeat = DeviceActivityName(SharedConstants.reblockHeartbeatActivityName) + h.activity.stopMonitoring([heartbeat]) + h.activity.activityLimit = 20 + h.openApp(at: h.at(9, 0)) + #expect(h.activity.registeredSchedule(for: heartbeat) == nil) + h.blockAll() + h.passTime(to: h.at(10, 1)) + + #expect(throws: DeviceActivityCenter.MonitoringError.self) { + try h.unblockAllTimed(.fifteenMinutes) + } + #expect(h.blocked == h.apps(1, 2, 3)) + } + @Test func groupTimedUnblockStartedMidSecondReblocksAtItsRegisteredEnd() throws { let h = BlockingHarness() h.blockAll() diff --git a/NormalTests/Services/TimedUnblockServiceTests.swift b/NormalTests/Services/TimedUnblockServiceTests.swift index 2c47805..893c4b9 100644 --- a/NormalTests/Services/TimedUnblockServiceTests.swift +++ b/NormalTests/Services/TimedUnblockServiceTests.swift @@ -109,6 +109,44 @@ struct TimedUnblockServiceTests { #expect(store.timedUnblocks.isEmpty) } + @Test func startMainAtTheActivityLimitStillUnblocksButMayEndLate() throws { + let (service, activity, store) = makeService() + let screenTime = FakeScreenTimeService() + try activity.startMonitoring( + DeviceActivityName(SharedConstants.reblockHeartbeatActivityName), + during: DeviceActivityScheduleFactory.heartbeat(), + events: [:] + ) + activity.activityLimit = 1 + + let timing = try service.startMain( + duration: .fifteenMinutes, + selection: FamilyActivitySelection(), + screenTimeService: screenTime + ) + + #expect(timing == .mayEndLate) + #expect(service.isMainUnblockActive) + #expect(store.timedUnblocks.count == 1) + #expect(activity.registeredSchedule(for: DeviceActivityName(SharedConstants.mainTimedUnblockActivityName)) == nil) + } + + @Test func startMainAtTheActivityLimitWithoutTheHeartbeatFails() { + let (service, activity, store) = makeService() + let screenTime = FakeScreenTimeService() + activity.activityLimit = 0 + + #expect(throws: DeviceActivityCenter.MonitoringError.self) { + try service.startMain( + duration: .fifteenMinutes, + selection: FamilyActivitySelection(), + screenTimeService: screenTime + ) + } + #expect(!service.isMainUnblockActive) + #expect(store.timedUnblocks.isEmpty) + } + @Test func customDurationSetsEndDateAndPersistsStartDate() throws { let (service, _, store) = makeService() let custom = try #require(TimedUnblockDuration(validating: 5700)) diff --git a/NormalTests/TestSupport/BlockingHarness.swift b/NormalTests/TestSupport/BlockingHarness.swift index 8880fae..b6cc8d5 100644 --- a/NormalTests/TestSupport/BlockingHarness.swift +++ b/NormalTests/TestSupport/BlockingHarness.swift @@ -129,7 +129,8 @@ final class BlockingHarness { screenTime.unblock(selection: group.selection, customDomains: group.customDomains) } - func unblockAllTimed(_ duration: TimedUnblockDuration) throws { + @discardableResult + func unblockAllTimed(_ duration: TimedUnblockDuration) throws -> UnblockTiming { try timedUnblock.startMain( duration: duration, mainSelection: main, diff --git a/NormalUITests/BlockingUITests.swift b/NormalUITests/BlockingUITests.swift index b23c5fa..55a834e 100644 --- a/NormalUITests/BlockingUITests.swift +++ b/NormalUITests/BlockingUITests.swift @@ -226,6 +226,100 @@ final class BlockingUITests: XCTestCase { require(app.buttons["group.blockButton"], "Group should be unblocked again") } + func testFailedDefaultDurationUnblockShowsError() { + let app = launch(["-uiTestDefaultDuration", "900", "-uiTestTimedUnblockFails"]) + blockViaBypass(app) + + app.buttons["home.unblockAll"].tap() + let keyRow = app.buttons["keySelect.row.QR"] + require(keyRow, "Unblock should require choosing the registered key") + keyRow.tap() + + let alert = app.alerts["Couldn't Unblock"] + require(alert, "A failed unblock should say so") + alert.buttons["OK"].tap() + require(app.buttons["home.unblockAll"], "Apps should stay blocked") + } + + func testDefaultDurationUnblockAtTheTimerLimitSaysItMayEndLate() { + let app = launch(["-uiTestDefaultDuration", "900", "-uiTestTimerLimitReached", "-uiTestSeedSchedule"]) + blockViaBypass(app) + + app.buttons["home.unblockAll"].tap() + let keyRow = app.buttons["keySelect.row.QR"] + require(keyRow, "Unblock should require choosing the registered key") + keyRow.tap() + + requireMayEndLateAlert(app) + require(app.staticTexts["Timed Unblock Active"], "The timed unblock should still start") + } + + func testDurationSheetUnblockAtTheTimerLimitSaysItMayEndLate() { + let app = launch(["-uiTestTimerLimitReached", "-uiTestSeedSchedule"]) + blockViaBypass(app) + + app.buttons["home.unblockAll"].tap() + let keyRow = app.buttons["keySelect.row.QR"] + require(keyRow, "Unblock should require choosing the registered key") + keyRow.tap() + let confirm = app.buttons["timedUnblock.confirm"] + require(confirm, "Timed unblock sheet should appear") + confirm.tap() + + requireMayEndLateAlert(app) + require(app.staticTexts["Timed Unblock Active"], "The timed unblock should still start") + } + + private func requireMayEndLateAlert(_ app: XCUIApplication) { + let alert = app.alerts["Unblocked"] + require(alert, "An unblock without its own iOS timer should say so") + XCTAssertTrue( + alert.staticTexts[ + "iOS only tracks 20 schedules and timers at once, so this unblock may end up to 30 minutes late." + ].exists, + "The alert should explain why the unblock may end late" + ) + alert.buttons["OK"].tap() + } + + func testFailedDefaultDurationGroupUnblockShowsError() { + let app = launch(["-uiTestSeedGroupKey", "-uiTestDefaultDuration", "900", "-uiTestTimedUnblockFails"]) + app.mainTab("Groups").tap() + + let blockButton = app.buttons["group.blockButton"] + require(blockButton, "Group block button should render") + blockButton.tap() + let bypass = app.buttons["keySelect.blockWithoutKey"] + require(bypass, "Group block should offer bypass") + bypass.tap() + confirmBypass(app) + + let unblockButton = app.buttons["group.unblockButton"] + require(unblockButton, "Group unblock button should render after blocking") + unblockButton.tap() + let keyRow = app.buttons["keySelect.row.QR"] + require(keyRow, "Unblocking the group should ask for a key") + keyRow.tap() + + require(app.alerts["Couldn't Unblock"], "A failed group unblock should say so") + } + + func testFailedUnlockLinkShowsError() throws { + let app = launch(["-uiTestSeedGroupKey", "-uiTestTimedUnblockFails", "-uiTestSlowScan"]) + let groupID = "6E0A1C9B-2D4F-4B7A-9C3E-5F8D1A2B3C4D" + + app.open(try XCTUnwrap(URL(string: "normal://block?group=\(groupID)"))) + let bypass = app.buttons["keySelect.blockWithoutKey"] + require(bypass, "Block link should offer bypass") + bypass.tap() + confirmBypass(app) + require(app.buttons["group.unblockButton"], "Group should be blocked") + + app.open(try XCTUnwrap(URL(string: "normal://unlock?group=\(groupID)&duration=3600&key=QR"))) + + require(app.alerts["Couldn't Unblock"], "A failed unlock from a link should say so") + } + func testUnlockLinkDuringBypassConfirmationFallsBackToKeySelection() throws { let app = launch(["-uiTestSeedGroupKey"]) let groupID = "6E0A1C9B-2D4F-4B7A-9C3E-5F8D1A2B3C4D"