diff --git a/Normal/App/ContentView.swift b/Normal/App/ContentView.swift index 46a68ab..496348a 100644 --- a/Normal/App/ContentView.swift +++ b/Normal/App/ContentView.swift @@ -13,7 +13,6 @@ struct ContentView: View { @Query private var schedules: [BlockSchedule] @Query private var usageLimits: [UsageLimit] - @State private var selectedTab: AppTab = .home @State private var navigationCoordinator = NavigationCoordinator() private var settings: Settings? { @@ -22,20 +21,20 @@ struct ContentView: View { var body: some View { ZStack { - MainTabView(selectedTab: $selectedTab) + MainTabView(selectedTab: $navigationCoordinator.selectedTab) if onboardingService.isOnboardingActive { OnboardingOverlayView() } } - .environment(\.navigationCoordinator, navigationCoordinator) - .widgetActionResponder(coordinator: navigationCoordinator, selectedTab: $selectedTab) + .widgetActionResponder(coordinator: navigationCoordinator) .liveActivitySync() .sheet(isPresented: $navigationCoordinator.isSettingsPresented, onDismiss: navigationCoordinator.settingsDidDismiss) { SettingsView(initialTab: navigationCoordinator.settingsInitialTab) } + .environment(\.navigationCoordinator, navigationCoordinator) .onChange(of: onboardingService.requiredTab) { _, newTab in if let newTab { - selectedTab = newTab + navigationCoordinator.selectedTab = newTab } } .onChange(of: onboardingService.isOnboardingActive, onOnboardingCompleted) @@ -63,7 +62,7 @@ struct ContentView: View { if settings?.hasCompletedOnboarding == true { onboardingService.isOnboardingActive = false onboardingService.currentStep = .complete - selectedTab = settings?.defaultTab ?? .home + navigationCoordinator.selectedTab = settings?.defaultTab ?? .home } Task { await screenTimeService.checkAuthorizationStatus() @@ -91,7 +90,7 @@ struct ContentView: View { private func onOnboardingCompleted(_: Bool, _ isActive: Bool) { if !isActive, settings?.hasCompletedOnboarding != true { settings?.hasCompletedOnboarding = true - selectedTab = .appSelect + navigationCoordinator.selectedTab = .appSelect } } } diff --git a/Normal/Intents/AppBlockIntentPerformer.swift b/Normal/Intents/AppBlockIntentPerformer.swift index 4c840b0..ccf6f2e 100644 --- a/Normal/Intents/AppBlockIntentPerformer.swift +++ b/Normal/Intents/AppBlockIntentPerformer.swift @@ -31,7 +31,7 @@ final class AppBlockIntentPerformer: BlockIntentPerforming { func blockAll() throws -> BlockOutcome { logger.info("Block intent: all") - let settings = try intents.validatedSettings(requiringGlobalKey: true) + let settings = try intents.validatedSettings(requiringKey: true) let mainSelection = try intents.mainSelection(settings: settings) let wasAlreadyBlocked = intents.screenTimeService.blockStatus(of: .all(mainSelection), settings: settings) == .all && intents.timedUnblockService.activeUnblocks.isEmpty @@ -48,7 +48,7 @@ final class AppBlockIntentPerformer: BlockIntentPerforming { func blockGroup(id: UUID) throws -> BlockOutcome { logger.info("Block intent: group") - let settings = try intents.validatedSettings(requiringGlobalKey: true) + let settings = try intents.validatedSettings(requiringKey: true, groupID: id) let group = try intents.group(id: id) let wasAlreadyBlocked = intents.screenTimeService.blockStatus(of: .group(group), settings: settings) == .all && !intents.timedUnblockService.isGroupUnblockActive(groupId: id) diff --git a/Normal/Intents/AppUnblockIntentPerformer.swift b/Normal/Intents/AppUnblockIntentPerformer.swift index 5b7eb48..166a05e 100644 --- a/Normal/Intents/AppUnblockIntentPerformer.swift +++ b/Normal/Intents/AppUnblockIntentPerformer.swift @@ -100,7 +100,7 @@ final class AppUnblockIntentPerformer: UnblockIntentPerforming { } private func readiness(for request: UnblockRequest) throws -> Readiness { - let settings = try intents.validatedSettings(requiringGlobalKey: false) + let settings = try intents.validatedSettings(requiringKey: false) intents.timedUnblockService.refresh(screenTimeService: intents.screenTimeService) let target = try intents.target(groupID: request.groupID, settings: settings) let status = intents.screenTimeService.blockStatus(of: target, settings: settings) diff --git a/Normal/Intents/IntentContext.swift b/Normal/Intents/IntentContext.swift index d888a56..e95cd3e 100644 --- a/Normal/Intents/IntentContext.swift +++ b/Normal/Intents/IntentContext.swift @@ -10,14 +10,15 @@ struct IntentContext { container.mainContext } - func validatedSettings(requiringGlobalKey: Bool) throws -> Settings { + func validatedSettings(requiringKey: Bool, groupID: UUID? = nil) throws -> Settings { let settings = try context.fetch(FetchDescriptor()).first let hasCompletedOnboarding = settings?.hasCompletedOnboarding == true - if requiringGlobalKey { + if requiringKey { try BlockActions.validate( isAuthorized: screenTimeService.isAuthorizedNow, hasCompletedOnboarding: hasCompletedOnboarding, - keys: keys() + keys: keys(), + groupID: groupID ) } else { try BlockActions.validateSetup( diff --git a/Normal/Modifiers/WidgetActionResponder.swift b/Normal/Modifiers/WidgetActionResponder.swift index 6a94374..37c2c2e 100644 --- a/Normal/Modifiers/WidgetActionResponder.swift +++ b/Normal/Modifiers/WidgetActionResponder.swift @@ -13,7 +13,6 @@ private struct WidgetActionResponder: ViewModifier { @Query private var selectedApps: [SelectedApps] let coordinator: NavigationCoordinator - @Binding var selectedTab: AppTab @State private var authAction: ProtectedAction? @State private var active: ActiveRequest? @@ -124,7 +123,7 @@ private struct WidgetActionResponder: ViewModifier { } private func present(_ request: ActiveRequest) { - selectedTab = request.target.groupID == nil ? .home : .groups + coordinator.selectedTab = request.target.groupID == nil ? .home : .groups active = request } @@ -159,10 +158,7 @@ private struct WidgetActionResponder: ViewModifier { } extension View { - func widgetActionResponder( - coordinator: NavigationCoordinator, - selectedTab: Binding - ) -> some View { - modifier(WidgetActionResponder(coordinator: coordinator, selectedTab: selectedTab)) + func widgetActionResponder(coordinator: NavigationCoordinator) -> some View { + modifier(WidgetActionResponder(coordinator: coordinator)) } } diff --git a/Normal/Resources/Localizable.xcstrings b/Normal/Resources/Localizable.xcstrings index 87e07e2..4311ba0 100644 --- a/Normal/Resources/Localizable.xcstrings +++ b/Normal/Resources/Localizable.xcstrings @@ -235,16 +235,12 @@ "comment" : "A button to add a custom website domain.", "isCommentAutoGenerated" : true }, - "Add a key in Normal before blocking apps." : { - "comment" : "Error message when a key is not set up.", + "Add a Key First" : { + "comment" : "Title of an alert shown when an action needs a key the user hasn't added.", "isCommentAutoGenerated" : true }, - "Add a key in the Keys tab before blocking apps." : { - "comment" : "A message displayed in an alert when a user tries to trigger an action but has no keys added.", - "isCommentAutoGenerated" : true - }, - "Add a key in the Keys tab before blocking groups." : { - "comment" : "Footer message displayed when the user does not have a global key to block apps.", + "Add a key in Normal before blocking apps." : { + "comment" : "Error message when a key is not set up.", "isCommentAutoGenerated" : true }, "Add a key in the Keys tab before creating schedules." : { @@ -803,6 +799,10 @@ }, "Go to App Select to choose which apps to manage before creating schedules." : { + }, + "Go to Keys" : { + "comment" : "Button that opens the Keys tab.", + "isCommentAutoGenerated" : true }, "Grant Permission" : { "comment" : "A button that requests Screen Time permission.", @@ -820,6 +820,10 @@ "comment" : "A header label for a section that lists the group keys of a family member.", "isCommentAutoGenerated" : true }, + "Group keys only unblock their own group. Add a key in the Keys tab to block." : { + "comment" : "Message shown when the user tries to block with only group keys.", + "isCommentAutoGenerated" : true + }, "Group Name" : { "comment" : "A label for the name of a group.", "isCommentAutoGenerated" : true @@ -1081,10 +1085,6 @@ "comment" : "An alert title when a user has no keys added.", "isCommentAutoGenerated" : true }, - "No Keys Available" : { - "comment" : "A title for an alert that informs the user that they have no keys registered.", - "isCommentAutoGenerated" : true - }, "No Keys Yet" : { "comment" : "A title displayed in the header of the \"No Keys Yet\" view.", "isCommentAutoGenerated" : true @@ -1101,7 +1101,7 @@ "isCommentAutoGenerated" : true }, "None of your registered keys are supported on this device. Add a QR code or barcode key to use on iPad." : { - "comment" : "A message displayed in the \"No Keys Available\" alert when a user has no keys registered on their device.", + "comment" : "Message in the Add a Key First alert when none of the user's keys work on this device.", "isCommentAutoGenerated" : true }, "Normal" : { @@ -1154,6 +1154,10 @@ }, "Normal works fully offline. No internet connection is required to set up or enforce your screen time limits." : { + }, + "Not Now" : { + "comment" : "Button that closes the Add a Key First alert.", + "isCommentAutoGenerated" : true }, "Now you have a dumb phone with iPhone hardware, the best of both worlds." : { @@ -1835,6 +1839,14 @@ "comment" : "A description of the consequences of blocking without a key.", "isCommentAutoGenerated" : true }, + "You'll need a key to unblock these apps." : { + "comment" : "Message shown when the user tries to unblock without a key.", + "isCommentAutoGenerated" : true + }, + "You'll need a key to unblock your apps later." : { + "comment" : "Message shown when the user tries to block without any keys.", + "isCommentAutoGenerated" : true + }, "You're All Set" : { "comment" : "A title for the onboarding finish view.", "isCommentAutoGenerated" : true diff --git a/Normal/Services/BlockActions.swift b/Normal/Services/BlockActions.swift index 7bbe3e4..b4a425f 100644 --- a/Normal/Services/BlockActions.swift +++ b/Normal/Services/BlockActions.swift @@ -74,9 +74,9 @@ enum BlockActions { UIImpactFeedbackGenerator(style: .medium).impactOccurred() } - static func validate(isAuthorized: Bool, hasCompletedOnboarding: Bool, keys: [Key]) throws { + static func validate(isAuthorized: Bool, hasCompletedOnboarding: Bool, keys: [Key], groupID: UUID? = nil) throws { try validateSetup(isAuthorized: isAuthorized, hasCompletedOnboarding: hasCompletedOnboarding) - guard Key.hasGlobalKey(in: keys) else { throw BlockIntentError.noGlobalKey } + guard !Key.scoped(keys, toGroup: groupID).isEmpty else { throw BlockIntentError.noGlobalKey } } static func validateSetup(isAuthorized: Bool, hasCompletedOnboarding: Bool) throws { diff --git a/Normal/Services/Keys/KeyCheckFlow.swift b/Normal/Services/Keys/KeyCheckFlow.swift index 28db6e2..b4ffcde 100644 --- a/Normal/Services/Keys/KeyCheckFlow.swift +++ b/Normal/Services/Keys/KeyCheckFlow.swift @@ -6,15 +6,23 @@ final class KeyCheckFlow { struct Request { let id = UUID() let keys: [Key] + let hasAnyGroupKey: Bool let keyGroupID: UUID? let availableKeyTypes: [KeyType] let defaultKeyType: KeyType? var requestedKeyType: KeyType? } + enum MissingKey: Equatable { + case noKeys + case onlyGroupKeys + case noKeyToUnblock + case unsupportedOnDevice + } + enum Stage: Equatable { case idle - case noKeys + case missingKey(MissingKey) case choosing case confirmingBypass case scanningQR @@ -57,7 +65,7 @@ final class KeyCheckFlow { switch stage { case .choosing, .confirmingBypass, .scanningQR, .checkingLocation: true case .scanningNFC: nfcOverPicker - case .idle, .noKeys: false + case .idle, .missingKey: false } } @@ -80,6 +88,10 @@ final class KeyCheckFlow { self.request = request self.action = action allowsBypass = action.allowsBypass + if allowsBypass, request.keys.isEmpty { + stage = .missingKey(request.hasAnyGroupKey ? .onlyGroupKeys : .noKeys) + return + } switch KeySelectLogic.decide( availableKeyTypes: request.availableKeyTypes, allowBypass: allowsBypass, @@ -87,7 +99,7 @@ final class KeyCheckFlow { requestedKeyType: request.requestedKeyType ) { case .showNoKeysAlert: - stage = .noKeys + stage = .missingKey(request.keys.isEmpty ? .noKeyToUnblock : .unsupportedOnDevice) case let .autoSelect(keyType): begin(keyType, fromPicker: false) case .showSheet: diff --git a/Normal/Services/NavigationCoordinator.swift b/Normal/Services/NavigationCoordinator.swift index e7922b0..577b9ba 100644 --- a/Normal/Services/NavigationCoordinator.swift +++ b/Normal/Services/NavigationCoordinator.swift @@ -13,12 +13,18 @@ struct ActionRequest: Equatable { @MainActor @Observable final class NavigationCoordinator { + var selectedTab: AppTab = .home var isSettingsPresented = false private(set) var settingsInitialTab: SettingsTab = .general private(set) var pendingAction: ActionRequest? private var actionAfterSettings: ActionRequest? + func show(_ tab: AppTab) { + isSettingsPresented = false + selectedTab = tab + } + func presentSettings(tab: SettingsTab = .general) { settingsInitialTab = tab isSettingsPresented = true diff --git a/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift b/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift index 0a8c813..2150160 100644 --- a/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift +++ b/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift @@ -4,6 +4,7 @@ import SwiftUI struct KeySelectModifier: ViewModifier { @Environment(QRService.self) private var qrService @Environment(LocationService.self) private var locationService + @Environment(\.navigationCoordinator) private var navigation @Query private var keys: [Key] @Query private var allSettings: [Settings] @@ -60,14 +61,14 @@ struct KeySelectModifier: ViewModifier { } } } - .alert("No Keys Available", isPresented: noKeysAlert) { - Button("OK", role: .cancel) { flow.cancel() } - } message: { - Text( - flow.request?.keys.isEmpty ?? true - ? "Add a key in the Keys tab before blocking apps." - : "None of your registered keys are supported on this device. Add a QR code or barcode key to use on iPad." - ) + .alert("Add a Key First", isPresented: missingKeyAlert, presenting: missingKey) { _ in + Button("Not Now", role: .cancel) { flow.cancel() } + Button("Go to Keys") { + flow.cancel() + navigation.show(.keys) + } + } message: { missingKey in + Text(message(for: missingKey)) } .sheet(item: keySheet, onDismiss: flow.keySheetDismissed) { _ in keySelectSheet @@ -139,13 +140,33 @@ struct KeySelectModifier: ViewModifier { allowsMinimizedDetent ? [sheetDetent, Self.minimizedDetent] : [sheetDetent] } - private var noKeysAlert: Binding { + private var missingKey: KeyCheckFlow.MissingKey? { + if case let .missingKey(missingKey) = flow.stage { + return missingKey + } + return nil + } + + private var missingKeyAlert: Binding { Binding( - get: { flow.stage == .noKeys }, + get: { missingKey != nil }, set: { if !$0 { flow.cancel() } } ) } + private func message(for missingKey: KeyCheckFlow.MissingKey) -> LocalizedStringKey { + switch missingKey { + case .noKeys: + "You'll need a key to unblock your apps later." + case .onlyGroupKeys: + "Group keys only unblock their own group. Add a key in the Keys tab to block." + case .noKeyToUnblock: + "You'll need a key to unblock these apps." + case .unsupportedOnDevice: + "None of your registered keys are supported on this device. Add a QR code or barcode key to use on iPad." + } + } + private var keySheet: Binding { Binding( get: { flow.showsKeySheet ? flow.request.map { SheetID(id: $0.id) } : nil }, @@ -166,6 +187,7 @@ struct KeySelectModifier: ViewModifier { flow.start( KeyCheckFlow.Request( keys: scopedKeys, + hasAnyGroupKey: keys.contains { $0.groupID != nil }, keyGroupID: keyGroupID, availableKeyTypes: KeyType.selectable(registered: scopedKeys.map(\.type)), defaultKeyType: defaultKeyType, diff --git a/Normal/Views/Groups/GroupListCardView.swift b/Normal/Views/Groups/GroupListCardView.swift index 90d29c7..7d52ed6 100644 --- a/Normal/Views/Groups/GroupListCardView.swift +++ b/Normal/Views/Groups/GroupListCardView.swift @@ -35,10 +35,6 @@ struct GroupListCardView: View { screenTimeService.activeShieldCount() > 0 } - private var hasGlobalKey: Bool { - Key.hasGlobalKey(in: allKeys) - } - private var blockStatus: BlockStatus { screenTimeService.blockStatus(selection: appGroup.selection, customDomains: customDomains) } @@ -235,7 +231,6 @@ struct GroupListCardView: View { requestAction(.tighten(blockGroup)) } .accessibilityIdentifier("group.blockButton") - .disabled(!hasGlobalKey) } private var unblockButton: some View { diff --git a/Normal/Views/Groups/GroupsView.swift b/Normal/Views/Groups/GroupsView.swift index 407f20e..ee38cd3 100644 --- a/Normal/Views/Groups/GroupsView.swift +++ b/Normal/Views/Groups/GroupsView.swift @@ -7,7 +7,6 @@ struct GroupsView: View { @Query(sort: [SortDescriptor(\AppGroup.sortIndex)]) private var appGroups: [AppGroup] @Query private var selectedApps: [SelectedApps] - @Query private var keys: [Key] @Query private var allSettings: [Settings] @State private var isShowingSheet = false @@ -24,10 +23,6 @@ struct GroupsView: View { screenTimeService.activeShieldCount() > 0 } - private var hasGlobalKey: Bool { - Key.hasGlobalKey(in: keys) - } - var body: some View { NavigationStack { content @@ -64,8 +59,6 @@ struct GroupsView: View { .safeAreaInset(edge: .bottom) { if isBlocked { FooterMessage(text: BlockedMessage.groups) - } else if !hasGlobalKey { - FooterMessage(text: "Add a key in the Keys tab before blocking groups.") } } // Host the key prompt on the stable list, scoped to whichever card diff --git a/Normal/Views/Home/MainBlockButtonView.swift b/Normal/Views/Home/MainBlockButtonView.swift index a263c2d..15d3615 100644 --- a/Normal/Views/Home/MainBlockButtonView.swift +++ b/Normal/Views/Home/MainBlockButtonView.swift @@ -5,7 +5,6 @@ struct MainBlockButtonView: View { @Environment(ScreenTimeService.self) private var screenTimeService @Environment(TimedUnblockService.self) private var timedUnblockService @Query private var allSettings: [Settings] - @Query private var keys: [Key] let mainSelection: SelectedApps @Binding var authAction: ProtectedAction? @@ -32,10 +31,6 @@ struct MainBlockButtonView: View { blockStatus.canUnblockAll(timedUnblockActive: timedUnblockService.isMainUnblockActive) } - private var hasGlobalKey: Bool { - Key.hasGlobalKey(in: keys) - } - var body: some View { Section { if canShowBlock { @@ -44,10 +39,6 @@ struct MainBlockButtonView: View { if canShowUnblock { unblockRow } - } footer: { - if canShowBlock, !hasGlobalKey { - Text("Add a key in the Keys tab before blocking apps.") - } } } @@ -63,7 +54,6 @@ struct MainBlockButtonView: View { } .accessibilityIdentifier("home.blockAll") .padding(.vertical, DS.Spacing.sm) - .disabled(!hasGlobalKey) } private var unblockRow: some View { diff --git a/Normal/Views/Schedules/SchedulesView.swift b/Normal/Views/Schedules/SchedulesView.swift index 7b0b3db..20ba51a 100644 --- a/Normal/Views/Schedules/SchedulesView.swift +++ b/Normal/Views/Schedules/SchedulesView.swift @@ -4,6 +4,7 @@ import SwiftUI struct SchedulesView: View { @Environment(ScreenTimeService.self) private var screenTimeService @Environment(ScheduleService.self) private var scheduleService + @Environment(\.navigationCoordinator) private var navigation @Query(sort: [SortDescriptor(\BlockSchedule.sortIndex)]) private var schedules: [BlockSchedule] @@ -87,11 +88,14 @@ struct SchedulesView: View { description: Text("Go to App Select to choose which apps to manage before creating schedules.") ) } else if !hasGlobalKey { - ContentUnavailableView( - "No Keys", - systemImage: "key.viewfinder", - description: Text("Add a key in the Keys tab before creating schedules.") - ) + ContentUnavailableView { + Label("No Keys", systemImage: "key.viewfinder") + } description: { + Text("Add a key in the Keys tab before creating schedules.") + } actions: { + Button("Go to Keys") { navigation.show(.keys) } + .buttonStyle(.borderedProminent) + } } else if isBlocked { ContentUnavailableView( "Apps Blocked", diff --git a/NormalTests/Services/AppBlockIntentPerformerTests.swift b/NormalTests/Services/AppBlockIntentPerformerTests.swift index e9361c8..a1463b9 100644 --- a/NormalTests/Services/AppBlockIntentPerformerTests.swift +++ b/NormalTests/Services/AppBlockIntentPerformerTests.swift @@ -136,6 +136,30 @@ struct AppBlockIntentPerformerTests { #expect(screenTime.blockCustomDomains == ["x.com"]) } + @Test func blockGroupAcceptsItsOwnKey() throws { + try seed(globalKey: false) + let group = AppGroup(name: "Social", selection: FamilyActivitySelection()) + context.insert(group) + context.insert(Key(name: "group", type: .qr, rawValue: "a", groupID: group.id)) + try context.save() + + #expect(try performer.blockGroup(id: group.id) == BlockOutcome(name: "Social", wasAlreadyBlocked: false)) + #expect(screenTime.blockCalled) + } + + @Test func blockGroupRejectsAnotherGroupsKey() throws { + try seed(globalKey: false) + let group = AppGroup(name: "Social", selection: FamilyActivitySelection()) + context.insert(group) + context.insert(Key(name: "other", type: .qr, rawValue: "a", groupID: UUID())) + try context.save() + + #expect(throws: BlockIntentError.noGlobalKey) { + try performer.blockGroup(id: group.id) + } + #expect(!screenTime.blockCalled) + } + @Test func blockGroupThrowsForDeletedGroup() throws { try seed() diff --git a/NormalTests/Services/BlockActionsTests.swift b/NormalTests/Services/BlockActionsTests.swift index c2e5f94..41e9be9 100644 --- a/NormalTests/Services/BlockActionsTests.swift +++ b/NormalTests/Services/BlockActionsTests.swift @@ -281,4 +281,25 @@ struct BlockActionsTests { ) } } + + @Test func validateAcceptsAGroupsOwnKeyForThatGroup() throws { + let groupID = UUID() + try BlockActions.validate( + isAuthorized: true, + hasCompletedOnboarding: true, + keys: [Key(name: "group", type: .qr, rawValue: "a", groupID: groupID)], + groupID: groupID + ) + } + + @Test func validateRejectsAnotherGroupsKey() { + #expect(throws: BlockIntentError.noGlobalKey) { + try BlockActions.validate( + isAuthorized: true, + hasCompletedOnboarding: true, + keys: [Key(name: "group", type: .qr, rawValue: "a", groupID: UUID())], + groupID: UUID() + ) + } + } } diff --git a/NormalTests/Services/KeyCheckFlowTests.swift b/NormalTests/Services/KeyCheckFlowTests.swift index 3cf9452..aff179e 100644 --- a/NormalTests/Services/KeyCheckFlowTests.swift +++ b/NormalTests/Services/KeyCheckFlowTests.swift @@ -25,11 +25,13 @@ struct KeyCheckFlowTests { private func request( _ keys: [Key], available: [KeyType], + hasAnyGroupKey: Bool = false, keyGroupID: UUID? = nil, defaultKeyType: KeyType? = nil ) -> KeyCheckFlow.Request { KeyCheckFlow.Request( keys: keys, + hasAnyGroupKey: hasAnyGroupKey, keyGroupID: keyGroupID, availableKeyTypes: available, defaultKeyType: defaultKeyType @@ -58,7 +60,7 @@ struct KeyCheckFlowTests { @Test func noKeysShowsTheAlertUntilCancelled() { let request = request([], available: []) start(request) - #expect(flow.stage == .noKeys) + #expect(flow.stage == .missingKey(.noKeyToUnblock)) flow.cancel() @@ -67,6 +69,53 @@ struct KeyCheckFlowTests { #expect(counter.runs == 0) } + @Test func blockingWithNoKeysAsksForOne() { + start(request([], available: []), allowBypass: true) + + #expect(flow.stage == .missingKey(.noKeys)) + #expect(!flow.showsKeySheet) + } + + @Test func blockingAGroupWithItsOwnKeyOffersTheKeySheet() { + let groupID = UUID() + let groupKey = Key(name: "tag", type: .nfc, rawValue: "tag", groupID: groupID) + start(request([groupKey], available: [.nfc], hasAnyGroupKey: true, keyGroupID: groupID), allowBypass: true) + + #expect(flow.stage == .choosing) + #expect(counter.runs == 0) + } + + @Test func blockingAGroupWithOnlyOtherGroupsKeysAsksForAKey() { + start(request([], available: [], hasAnyGroupKey: true, keyGroupID: UUID()), allowBypass: true) + + #expect(flow.stage == .missingKey(.onlyGroupKeys)) + } + + @Test func blockingAllWithOnlyOtherGroupsKeysAsksForAKeyOutsideGroups() { + start(request([], available: [], hasAnyGroupKey: true), allowBypass: true) + + #expect(flow.stage == .missingKey(.onlyGroupKeys)) + } + + @Test func groupKeyStillUnblocksItsGroup() async { + let groupID = UUID() + let groupKey = Key(name: "tag", type: .nfc, rawValue: "tag", groupID: groupID) + start(request([groupKey], available: [.nfc], hasAnyGroupKey: true, keyGroupID: groupID)) + #expect(flow.stage == .scanningNFC) + await waitUntil { nfc.isScanning } + + nfc.present("tag") + await waitUntil { flow.stage == .idle } + + #expect(counter.proofs == [KeyProof(keyGroupID: groupID)]) + } + + @Test func keysThisDeviceCantReadAskForOneItCan() { + start(request([key(.nfc, "tag")], available: []), allowBypass: true) + + #expect(flow.stage == .missingKey(.unsupportedOnDevice)) + } + @Test func severalKeyTypesShowThePicker() { start(qrAndNFC) #expect(flow.stage == .choosing) diff --git a/NormalTests/Services/NavigationCoordinatorTests.swift b/NormalTests/Services/NavigationCoordinatorTests.swift index 5d7f95f..e15b3af 100644 --- a/NormalTests/Services/NavigationCoordinatorTests.swift +++ b/NormalTests/Services/NavigationCoordinatorTests.swift @@ -42,6 +42,16 @@ struct NavigationCoordinatorTests { #expect(c.pendingAction?.action == .unblock(request)) } + @Test func showingATabClosesSettings() { + let c = NavigationCoordinator() + c.presentSettings() + + c.show(.keys) + + #expect(c.selectedTab == .keys) + #expect(!c.isSettingsPresented) + } + @Test func dismissingSettingsWithoutARequestDoesNothing() { let c = NavigationCoordinator() c.presentSettings() diff --git a/NormalUITests/RecoveryUITests.swift b/NormalUITests/RecoveryUITests.swift index 5f0852d..6230030 100644 --- a/NormalUITests/RecoveryUITests.swift +++ b/NormalUITests/RecoveryUITests.swift @@ -64,9 +64,9 @@ final class RecoveryUITests: XCTestCase { require(app.staticTexts["All Selected Apps Blocked"], "Should start blocked") app.buttons["home.unblockAll"].tap() - let alert = app.alerts["No Keys Available"] + let alert = app.alerts["Add a Key First"] require(alert, "No-keys unblock attempt must surface a recoverable alert") - alert.buttons["OK"].tap() + alert.buttons["Not Now"].tap() XCTAssertTrue( app.staticTexts["All Selected Apps Blocked"].waitForExistence(timeout: timeout), @@ -74,6 +74,83 @@ final class RecoveryUITests: XCTestCase { ) } + func testBlockingWithoutKeysOffersTheKeysTab() { + let app = launch(["-uiTestNoKeys"]) + + let blockAll = app.buttons["home.blockAll"] + require(blockAll, "Block All should show without a key") + blockAll.tap() + + let alert = app.alerts["Add a Key First"] + require(alert, "Blocking without a key should explain why") + alert.buttons["Go to Keys"].tap() + + require(app.staticTexts["No Keys Yet"], "Go to Keys should open the Keys tab") + } + + func testBlockingAllWithOnlyGroupKeysExplainsWhy() { + let app = launch(["-uiTestNoKeys", "-uiTestSeedGroupKey"]) + + let blockAll = app.buttons["home.blockAll"] + require(blockAll, "Block All should show with only group keys") + blockAll.tap() + + let alert = app.alerts["Add a Key First"] + require(alert, "Blocking all apps with only group keys should explain why") + XCTAssertTrue( + alert.staticTexts["Group keys only unblock their own group. Add a key in the Keys tab to block."].exists, + "The alert should say group keys aren't enough" + ) + alert.buttons["Not Now"].tap() + + XCTAssertTrue(blockAll.waitForExistence(timeout: timeout), "Not Now should stay on Home") + } + + func testGroupWithItsOwnKeyCanBlock() { + let app = launch(["-uiTestNoKeys", "-uiTestSeedGroupKey"]) + + app.mainTab("Groups").tap() + let block = app.buttons["group.blockButton"] + require(block, "Seeded group should show a Block button") + block.tap() + + let bypass = app.buttons["keySelect.blockWithoutKey"] + require(bypass, "A group with its own key should offer the key sheet") + bypass.tap() + let confirm = app.buttons["keySelect.confirmBlockWithoutKey"] + require(confirm, "Blocking without scanning should ask to confirm") + confirm.tap() + + require(app.buttons["group.unblockButton"], "The group should be blocked") + } + + func testSchedulesWithoutKeysLinkToTheKeysTab() { + let app = launch(["-uiTestNoKeys"]) + + app.mainTab("Schedules").tap() + let goToKeys = app.buttons["Go to Keys"] + require(goToKeys, "The No Keys screen should link to the Keys tab") + goToKeys.tap() + + require(app.staticTexts["No Keys Yet"], "Go to Keys should open the Keys tab") + } + + func testGoToKeysFromSettingsClosesSettings() { + let app = launch(["-uiTestNoKeys"]) + + app.buttons["nav.settings"].tap() + let toggle = app.switches["settings.blockAdultContentToggle"] + require(toggle, "Settings should show the adult content toggle") + toggle.coordinate(withNormalizedOffset: CGVector(dx: 0.92, dy: 0.5)).tap() + + let alert = app.alerts["Add a Key First"] + require(alert, "Turning on a filter without a key should explain why") + alert.buttons["Go to Keys"].tap() + + XCTAssertTrue(toggle.waitForNonExistence(timeout: timeout), "Go to Keys should close Settings") + require(app.staticTexts["No Keys Yet"], "Go to Keys should open the Keys tab") + } + func testEmergencyUnblockDisablesAfterThreeUses() { let app = launch([])